/* Minification failed. Returning unminified contents.
(2,1): run-time error CSS1019: Unexpected token, found '!'
(2,2): run-time error CSS1019: Unexpected token, found 'function('
(2,14): run-time error CSS1031: Expected selector, found ')'
(2,14): run-time error CSS1025: Expected comma or open brace, found ')'
(2,212): run-time error CSS1019: Unexpected token, found '('
(2,213): run-time error CSS1019: Unexpected token, found '"undefined"'
(2,224): run-time error CSS1019: Unexpected token, found '!'
(2,225): run-time error CSS1019: Unexpected token, found '='
(2,239): run-time error CSS1031: Expected selector, found '?'
(2,239): run-time error CSS1025: Expected comma or open brace, found '?'
: error : L'index se trouve en dehors des limites du tableau.
 */
/*! jQuery v2.1.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.1",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+Math.random()}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)
},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||l,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=l),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?Z:$):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=Z,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(g in a)this.on(g,b,c,a[g],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return n().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=$),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var ab=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ib={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(ob(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(ob(c,"script"),kb),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(hb,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function tb(a){var b=l,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qb[0].contentDocument,b.write(),b.close(),c=sb(a,b),qb.detach()),rb[a]=c),c}var ub=/^margin/,vb=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)};function xb(a,b,c){var d,e,f,g,h=a.style;return c=c||wb(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),vb.test(g)&&ub.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function yb(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),b}})}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var zb=/^(none|table(?!-c[ea]).+)/,Ab=new RegExp("^("+Q+")(.*)$","i"),Bb=new RegExp("^([+-])=("+Q+")","i"),Cb={position:"absolute",visibility:"hidden",display:"block"},Db={letterSpacing:"0",fontWeight:"400"},Eb=["Webkit","O","Moz","ms"];function Fb(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Eb.length;while(e--)if(b=Eb[e]+c,b in a)return b;return d}function Gb(a,b,c){var d=Ab.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Hb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ib(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wb(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xb(a,b,f),(0>e||null==e)&&(e=a.style[b]),vb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Hb(a,b,c||(g?"border":"content"),d,f)+"px"}function Jb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",tb(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Bb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xb(a,b,d)),"normal"===e&&b in Db&&(e=Db[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?zb.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Cb,function(){return Ib(a,b,d)}):Ib(a,b,d):void 0},set:function(a,c,d){var e=d&&wb(a);return Gb(a,c,d?Hb(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=yb(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ub.test(a)||(n.cssHooks[a+b].set=Gb)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Jb(this,!0)},hide:function(){return Jb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Kb(a,b,c,d,e){return new Kb.prototype.init(a,b,c,d,e)}n.Tween=Kb,Kb.prototype={constructor:Kb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Kb.propHooks[this.prop];return a&&a.get?a.get(this):Kb.propHooks._default.get(this)},run:function(a){var b,c=Kb.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Kb.propHooks._default.set(this),this}},Kb.prototype.init.prototype=Kb.prototype,Kb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Kb.propHooks.scrollTop=Kb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Kb.prototype.init,n.fx.step={};var Lb,Mb,Nb=/^(?:toggle|show|hide)$/,Ob=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pb=/queueHooks$/,Qb=[Vb],Rb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Ob.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Ob.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sb(){return setTimeout(function(){Lb=void 0}),Lb=n.now()}function Tb(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ub(a,b,c){for(var d,e=(Rb[b]||[]).concat(Rb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Vb(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||tb(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Nb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?tb(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ub(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xb(a,b,c){var d,e,f=0,g=Qb.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Lb||Sb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Lb||Sb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wb(k,j.opts.specialEasing);g>f;f++)if(d=Qb[f].call(j,a,k,j.opts))return d;return n.map(k,Ub,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(Xb,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Rb[c]=Rb[c]||[],Rb[c].unshift(b)},prefilter:function(a,b){b?Qb.unshift(a):Qb.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xb(this,n.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Tb(b,!0),a,d,e)}}),n.each({slideDown:Tb("show"),slideUp:Tb("hide"),slideToggle:Tb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Lb=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Lb=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Mb||(Mb=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Mb),Mb=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a=l.createElement("input"),b=l.createElement("select"),c=b.appendChild(l.createElement("option"));a.type="checkbox",k.checkOn=""!==a.value,k.optSelected=c.selected,b.disabled=!0,k.optDisabled=!c.disabled,a=l.createElement("input"),a.value="t",a.type="radio",k.radioValue="t"===a.value}();var Yb,Zb,$b=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Zb:Yb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))
},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Zb={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$b[b]||n.find.attr;$b[b]=function(a,b,d){var e,f;return d||(f=$b[b],$b[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$b[b]=f),e}});var _b=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_b.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ac=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ac," ").indexOf(b)>=0)return!0;return!1}});var bc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cc=n.now(),dc=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var ec,fc,gc=/#.*$/,hc=/([?&])_=[^&]*/,ic=/^(.*?):[ \t]*([^\r\n]*)$/gm,jc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,kc=/^(?:GET|HEAD)$/,lc=/^\/\//,mc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,nc={},oc={},pc="*/".concat("*");try{fc=location.href}catch(qc){fc=l.createElement("a"),fc.href="",fc=fc.href}ec=mc.exec(fc.toLowerCase())||[];function rc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function sc(a,b,c,d){var e={},f=a===oc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function tc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function uc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function vc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:fc,type:"GET",isLocal:jc.test(ec[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":pc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?tc(tc(a,n.ajaxSettings),b):tc(n.ajaxSettings,a)},ajaxPrefilter:rc(nc),ajaxTransport:rc(oc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=ic.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||fc)+"").replace(gc,"").replace(lc,ec[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=mc.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===ec[1]&&h[2]===ec[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(ec[3]||("http:"===ec[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),sc(nc,k,b,v),2===t)return v;i=k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!kc.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(dc.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=hc.test(d)?d.replace(hc,"$1_="+cc++):d+(dc.test(d)?"&":"?")+"_="+cc++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+pc+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=sc(oc,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=uc(k,v,f)),u=vc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var wc=/%20/g,xc=/\[\]$/,yc=/\r?\n/g,zc=/^(?:submit|button|image|reset|file)$/i,Ac=/^(?:input|select|textarea|keygen)/i;function Bc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||xc.test(a)?d(a,e):Bc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Bc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Bc(c,a[c],b,e);return d.join("&").replace(wc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Ac.test(this.nodeName)&&!zc.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(yc,"\r\n")}}):{name:b.name,value:c.replace(yc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Cc=0,Dc={},Ec={0:200,1223:204},Fc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Dc)Dc[a]()}),k.cors=!!Fc&&"withCredentials"in Fc,k.ajax=Fc=!!Fc,n.ajaxTransport(function(a){var b;return k.cors||Fc&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Cc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Dc[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Ec[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Dc[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),l.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Gc=[],Hc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Gc.pop()||n.expando+"_"+cc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Hc.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Hc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Hc,"$1"+e):b.jsonp!==!1&&(b.url+=(dc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Gc.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||l;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var Ic=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Ic)return Ic.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Jc=a.document.documentElement;function Kc(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Kc(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Jc;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Jc})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;n.fn[b]=function(e){return J(this,function(b,e,f){var g=Kc(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=yb(k.pixelPosition,function(a,c){return c?(c=xb(a,b),vb.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Lc=a.jQuery,Mc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Mc),b&&a.jQuery===n&&(a.jQuery=Lc),n},typeof b===U&&(a.jQuery=a.$=n),n});

/*! jQuery UI - v1.10.3 - 2013-06-06
* http://jqueryui.com
* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js
* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */

(function(e,t){function i(t,i){var a,n,r,o=t.nodeName.toLowerCase();return"area"===o?(a=t.parentNode,n=a.name,t.href&&n&&"map"===a.nodeName.toLowerCase()?(r=e("img[usemap=#"+n+"]")[0],!!r&&s(r)):!1):(/input|select|textarea|button|object/.test(o)?!t.disabled:"a"===o?t.href||i:i)&&s(t)}function s(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var a=0,n=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.3",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var s,a,n=e(this[0]);n.length&&n[0]!==document;){if(s=n.css("position"),("absolute"===s||"relative"===s||"fixed"===s)&&(a=parseInt(n.css("zIndex"),10),!isNaN(a)&&0!==a))return a;n=n.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++a)})},removeUniqueId:function(){return this.each(function(){n.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var s=e.attr(t,"tabindex"),a=isNaN(s);return(a||s>=0)&&i(t,!a)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,s){function a(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===s?["Left","Right"]:["Top","Bottom"],r=s.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+s]=function(i){return i===t?o["inner"+s].call(this):this.each(function(){e(this).css(r,a(this,i)+"px")})},e.fn["outer"+s]=function(t,i){return"number"!=typeof t?o["outer"+s].call(this,t):this.each(function(){e(this).css(r,a(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,s){var a,n=e.ui[t].prototype;for(a in s)n.plugins[a]=n.plugins[a]||[],n.plugins[a].push([i,s[a]])},call:function(e,t,i){var s,a=e.plugins[t];if(a&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(s=0;a.length>s;s++)e.options[a[s][0]]&&a[s][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",a=!1;return t[s]>0?!0:(t[s]=1,a=t[s]>0,t[s]=0,a)}})})(jQuery);(function(e,t){var i=0,s=Array.prototype.slice,n=e.cleanData;e.cleanData=function(t){for(var i,s=0;null!=(i=t[s]);s++)try{e(i).triggerHandler("remove")}catch(a){}n(t)},e.widget=function(i,s,n){var a,r,o,h,l={},u=i.split(".")[0];i=i.split(".")[1],a=u+"-"+i,n||(n=s,s=e.Widget),e.expr[":"][a.toLowerCase()]=function(t){return!!e.data(t,a)},e[u]=e[u]||{},r=e[u][i],o=e[u][i]=function(e,i){return this._createWidget?(arguments.length&&this._createWidget(e,i),t):new o(e,i)},e.extend(o,r,{version:n.version,_proto:e.extend({},n),_childConstructors:[]}),h=new s,h.options=e.widget.extend({},h.options),e.each(n,function(i,n){return e.isFunction(n)?(l[i]=function(){var e=function(){return s.prototype[i].apply(this,arguments)},t=function(e){return s.prototype[i].apply(this,e)};return function(){var i,s=this._super,a=this._superApply;return this._super=e,this._superApply=t,i=n.apply(this,arguments),this._super=s,this._superApply=a,i}}(),t):(l[i]=n,t)}),o.prototype=e.widget.extend(h,{widgetEventPrefix:r?h.widgetEventPrefix:i},l,{constructor:o,namespace:u,widgetName:i,widgetFullName:a}),r?(e.each(r._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete r._childConstructors):s._childConstructors.push(o),e.widget.bridge(i,o)},e.widget.extend=function(i){for(var n,a,r=s.call(arguments,1),o=0,h=r.length;h>o;o++)for(n in r[o])a=r[o][n],r[o].hasOwnProperty(n)&&a!==t&&(i[n]=e.isPlainObject(a)?e.isPlainObject(i[n])?e.widget.extend({},i[n],a):e.widget.extend({},a):a);return i},e.widget.bridge=function(i,n){var a=n.prototype.widgetFullName||i;e.fn[i]=function(r){var o="string"==typeof r,h=s.call(arguments,1),l=this;return r=!o&&h.length?e.widget.extend.apply(null,[r].concat(h)):r,o?this.each(function(){var s,n=e.data(this,a);return n?e.isFunction(n[r])&&"_"!==r.charAt(0)?(s=n[r].apply(n,h),s!==n&&s!==t?(l=s&&s.jquery?l.pushStack(s.get()):s,!1):t):e.error("no such method '"+r+"' for "+i+" widget instance"):e.error("cannot call methods on "+i+" prior to initialization; "+"attempted to call method '"+r+"'")}):this.each(function(){var t=e.data(this,a);t?t.option(r||{})._init():e.data(this,a,new n(r,this))}),l}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,s){s=e(s||this.defaultElement||this)[0],this.element=e(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),s!==this&&(e.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===s&&this.destroy()}}),this.document=e(s.style?s.ownerDocument:s.document||s),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(i,s){var n,a,r,o=i;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof i)if(o={},n=i.split("."),i=n.shift(),n.length){for(a=o[i]=e.widget.extend({},this.options[i]),r=0;n.length-1>r;r++)a[n[r]]=a[n[r]]||{},a=a[n[r]];if(i=n.pop(),s===t)return a[i]===t?null:a[i];a[i]=s}else{if(s===t)return this.options[i]===t?null:this.options[i];o[i]=s}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(i,s,n){var a,r=this;"boolean"!=typeof i&&(n=s,s=i,i=!1),n?(s=a=e(s),this.bindings=this.bindings.add(s)):(n=s,s=this.element,a=this.widget()),e.each(n,function(n,o){function h(){return i||r.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?r[o]:o).apply(r,arguments):t}"string"!=typeof o&&(h.guid=o.guid=o.guid||h.guid||e.guid++);var l=n.match(/^(\w+)\s*(.*)$/),u=l[1]+r.eventNamespace,c=l[2];c?a.delegate(c,u,h):s.bind(u,h)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,r=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(r)&&r.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var r,o=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),r=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),r&&e.effects&&e.effects.effect[o]?s[t](n):o!==t&&s[o]?s[o](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}})})(jQuery);(function(e){var t=!1;e(document).mouseup(function(){t=!1}),e.widget("ui.mouse",{version:"1.10.3",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(i){return!0===e.data(i.target,t.widgetName+".preventClickEvent")?(e.removeData(i.target,t.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):undefined}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(i){if(!t){this._mouseStarted&&this._mouseUp(i),this._mouseDownEvent=i;var s=this,n=1===i.which,a="string"==typeof this.options.cancel&&i.target.nodeName?e(i.target).closest(this.options.cancel).length:!1;return n&&!a&&this._mouseCapture(i)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){s.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(i)&&this._mouseDelayMet(i)&&(this._mouseStarted=this._mouseStart(i)!==!1,!this._mouseStarted)?(i.preventDefault(),!0):(!0===e.data(i.target,this.widgetName+".preventClickEvent")&&e.removeData(i.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return s._mouseMove(e)},this._mouseUpDelegate=function(e){return s._mouseUp(e)},e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),i.preventDefault(),t=!0,!0)):!0}},_mouseMove:function(t){return e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button?this._mouseUp(t):this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){return e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(jQuery);(function(e){e.widget("ui.draggable",e.ui.mouse,{version:"1.10.3",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){"original"!==this.options.helper||/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var i=this.options;return this.helper||i.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(e(i.iframeFix===!0?"iframe":i.iframeFix).each(function(){e("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>").css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var i=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offsetParent=this.helper.offsetParent(),this.offsetParentCssPosition=this.offsetParent.css("position"),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},this.offset.scroll=!1,e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,i){if("fixed"===this.offsetParentCssPosition&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),!i){var s=this._uiHash();if(this._trigger("drag",t,s)===!1)return this._mouseUp({}),!1;this.position=s.position}return this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var i=this,s=!1;return e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),"original"!==this.options.helper||e.contains(this.element[0].ownerDocument,this.element[0])?("invalid"===this.options.revert&&!s||"valid"===this.options.revert&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){i._trigger("stop",t)!==!1&&i._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!1):!1},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){return this.options.handle?!!e(t.target).closest(this.element.find(this.options.handle)).length:!0},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return s.parents("body").length||s.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s[0]===this.element[0]||/(fixed|absolute)/.test(s.css("position"))||s.css("position","absolute"),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,i,s,n=this.options;return n.containment?"window"===n.containment?(this.containment=[e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,e(window).scrollLeft()+e(window).width()-this.helperProportions.width-this.margins.left,e(window).scrollTop()+(e(window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):"document"===n.containment?(this.containment=[0,0,e(document).width()-this.helperProportions.width-this.margins.left,(e(document).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],undefined):n.containment.constructor===Array?(this.containment=n.containment,undefined):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=e(n.containment),s=i[0],s&&(t="hidden"!==i.css("overflow"),this.containment=[(parseInt(i.css("borderLeftWidth"),10)||0)+(parseInt(i.css("paddingLeft"),10)||0),(parseInt(i.css("borderTopWidth"),10)||0)+(parseInt(i.css("paddingTop"),10)||0),(t?Math.max(s.scrollWidth,s.offsetWidth):s.offsetWidth)-(parseInt(i.css("borderRightWidth"),10)||0)-(parseInt(i.css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(s.scrollHeight,s.offsetHeight):s.offsetHeight)-(parseInt(i.css("borderBottomWidth"),10)||0)-(parseInt(i.css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=i),undefined):(this.containment=null,undefined)},_convertPositionTo:function(t,i){i||(i=this.position);var s="absolute"===t?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent;return this.offset.scroll||(this.offset.scroll={top:n.scrollTop(),left:n.scrollLeft()}),{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top)*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)*s}},_generatePosition:function(t){var i,s,n,a,o=this.options,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=t.pageX,l=t.pageY;return this.offset.scroll||(this.offset.scroll={top:r.scrollTop(),left:r.scrollLeft()}),this.originalPosition&&(this.containment&&(this.relative_container?(s=this.relative_container.offset(),i=[this.containment[0]+s.left,this.containment[1]+s.top,this.containment[2]+s.left,this.containment[3]+s.top]):i=this.containment,t.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),t.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),t.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),t.pageY-this.offset.click.top>i[3]&&(l=i[3]+this.offset.click.top)),o.grid&&(n=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=i?n-this.offset.click.top>=i[1]||n-this.offset.click.top>i[3]?n:n-this.offset.click.top>=i[1]?n-o.grid[1]:n+o.grid[1]:n,a=o.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,h=i?a-this.offset.click.left>=i[0]||a-this.offset.click.left>i[2]?a:a-this.offset.click.left>=i[0]?a-o.grid[0]:a+o.grid[0]:a)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():this.offset.scroll.left)}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]===this.element[0]||this.cancelHelperRemoval||this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(t,i,s){return s=s||this._uiHash(),e.ui.plugin.call(this,t,[i,s]),"drag"===t&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,i,s)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,i){var s=e(this).data("ui-draggable"),n=s.options,a=e.extend({},i,{item:s.element});s.sortables=[],e(n.connectToSortable).each(function(){var i=e.data(this,"ui-sortable");i&&!i.options.disabled&&(s.sortables.push({instance:i,shouldRevert:i.options.revert}),i.refreshPositions(),i._trigger("activate",t,a))})},stop:function(t,i){var s=e(this).data("ui-draggable"),n=e.extend({},i,{item:s.element});e.each(s.sortables,function(){this.instance.isOver?(this.instance.isOver=0,s.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=this.shouldRevert),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,"original"===s.options.helper&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,n))})},drag:function(t,i){var s=e(this).data("ui-draggable"),n=this;e.each(s.sortables,function(){var a=!1,o=this;this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(a=!0,e.each(s.sortables,function(){return this.instance.positionAbs=s.positionAbs,this.instance.helperProportions=s.helperProportions,this.instance.offset.click=s.offset.click,this!==o&&this.instance._intersectsWith(this.instance.containerCache)&&e.contains(o.instance.element[0],this.instance.element[0])&&(a=!1),a})),a?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(n).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return i.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=s.offset.click.top,this.instance.offset.click.left=s.offset.click.left,this.instance.offset.parent.left-=s.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=s.offset.parent.top-this.instance.offset.parent.top,s._trigger("toSortable",t),s.dropped=this.instance.element,s.currentItem=s.element,this.instance.fromOutside=s),this.instance.currentItem&&this.instance._mouseDrag(t)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),s._trigger("fromSortable",t),s.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(){var t=e("body"),i=e(this).data("ui-draggable").options;t.css("cursor")&&(i._cursor=t.css("cursor")),t.css("cursor",i.cursor)},stop:function(){var t=e(this).data("ui-draggable").options;t._cursor&&e("body").css("cursor",t._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,i){var s=e(i.helper),n=e(this).data("ui-draggable").options;s.css("opacity")&&(n._opacity=s.css("opacity")),s.css("opacity",n.opacity)},stop:function(t,i){var s=e(this).data("ui-draggable").options;s._opacity&&e(i.helper).css("opacity",s._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(){var t=e(this).data("ui-draggable");t.scrollParent[0]!==document&&"HTML"!==t.scrollParent[0].tagName&&(t.overflowOffset=t.scrollParent.offset())},drag:function(t){var i=e(this).data("ui-draggable"),s=i.options,n=!1;i.scrollParent[0]!==document&&"HTML"!==i.scrollParent[0].tagName?(s.axis&&"x"===s.axis||(i.overflowOffset.top+i.scrollParent[0].offsetHeight-t.pageY<s.scrollSensitivity?i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop+s.scrollSpeed:t.pageY-i.overflowOffset.top<s.scrollSensitivity&&(i.scrollParent[0].scrollTop=n=i.scrollParent[0].scrollTop-s.scrollSpeed)),s.axis&&"y"===s.axis||(i.overflowOffset.left+i.scrollParent[0].offsetWidth-t.pageX<s.scrollSensitivity?i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft+s.scrollSpeed:t.pageX-i.overflowOffset.left<s.scrollSensitivity&&(i.scrollParent[0].scrollLeft=n=i.scrollParent[0].scrollLeft-s.scrollSpeed))):(s.axis&&"x"===s.axis||(t.pageY-e(document).scrollTop()<s.scrollSensitivity?n=e(document).scrollTop(e(document).scrollTop()-s.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<s.scrollSensitivity&&(n=e(document).scrollTop(e(document).scrollTop()+s.scrollSpeed))),s.axis&&"y"===s.axis||(t.pageX-e(document).scrollLeft()<s.scrollSensitivity?n=e(document).scrollLeft(e(document).scrollLeft()-s.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<s.scrollSensitivity&&(n=e(document).scrollLeft(e(document).scrollLeft()+s.scrollSpeed)))),n!==!1&&e.ui.ddmanager&&!s.dropBehaviour&&e.ui.ddmanager.prepareOffsets(i,t)}}),e.ui.plugin.add("draggable","snap",{start:function(){var t=e(this).data("ui-draggable"),i=t.options;t.snapElements=[],e(i.snap.constructor!==String?i.snap.items||":data(ui-draggable)":i.snap).each(function(){var i=e(this),s=i.offset();this!==t.element[0]&&t.snapElements.push({item:this,width:i.outerWidth(),height:i.outerHeight(),top:s.top,left:s.left})})},drag:function(t,i){var s,n,a,o,r,h,l,u,c,d,p=e(this).data("ui-draggable"),f=p.options,m=f.snapTolerance,g=i.offset.left,v=g+p.helperProportions.width,b=i.offset.top,y=b+p.helperProportions.height;for(c=p.snapElements.length-1;c>=0;c--)r=p.snapElements[c].left,h=r+p.snapElements[c].width,l=p.snapElements[c].top,u=l+p.snapElements[c].height,r-m>v||g>h+m||l-m>y||b>u+m||!e.contains(p.snapElements[c].item.ownerDocument,p.snapElements[c].item)?(p.snapElements[c].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=!1):("inner"!==f.snapMode&&(s=m>=Math.abs(l-y),n=m>=Math.abs(u-b),a=m>=Math.abs(r-v),o=m>=Math.abs(h-g),s&&(i.position.top=p._convertPositionTo("relative",{top:l-p.helperProportions.height,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:u,left:0}).top-p.margins.top),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r-p.helperProportions.width}).left-p.margins.left),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:h}).left-p.margins.left)),d=s||n||a||o,"outer"!==f.snapMode&&(s=m>=Math.abs(l-b),n=m>=Math.abs(u-y),a=m>=Math.abs(r-g),o=m>=Math.abs(h-v),s&&(i.position.top=p._convertPositionTo("relative",{top:l,left:0}).top-p.margins.top),n&&(i.position.top=p._convertPositionTo("relative",{top:u-p.helperProportions.height,left:0}).top-p.margins.top),a&&(i.position.left=p._convertPositionTo("relative",{top:0,left:r}).left-p.margins.left),o&&(i.position.left=p._convertPositionTo("relative",{top:0,left:h-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[c].snapping&&(s||n||a||o||d)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=s||n||a||o||d)}}),e.ui.plugin.add("draggable","stack",{start:function(){var t,i=this.data("ui-draggable").options,s=e.makeArray(e(i.stack)).sort(function(t,i){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(i).css("zIndex"),10)||0)});s.length&&(t=parseInt(e(s[0]).css("zIndex"),10)||0,e(s).each(function(i){e(this).css("zIndex",t+i)}),this.css("zIndex",t+s.length))}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,i){var s=e(i.helper),n=e(this).data("ui-draggable").options;s.css("zIndex")&&(n._zIndex=s.css("zIndex")),s.css("zIndex",n.zIndex)},stop:function(t,i){var s=e(this).data("ui-draggable").options;s._zIndex&&e(i.helper).css("zIndex",s._zIndex)}})})(jQuery);(function(e){function t(e,t,i){return e>t&&t+i>e}e.widget("ui.droppable",{version:"1.10.3",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t=this.options,i=t.accept;this.isover=!1,this.isout=!0,this.accept=e.isFunction(i)?i:function(e){return e.is(i)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},e.ui.ddmanager.droppables[t.scope]=e.ui.ddmanager.droppables[t.scope]||[],e.ui.ddmanager.droppables[t.scope].push(this),t.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){for(var t=0,i=e.ui.ddmanager.droppables[this.options.scope];i.length>t;t++)i[t]===this&&i.splice(t,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,i){"accept"===t&&(this.accept=e.isFunction(i)?i:function(e){return e.is(i)}),e.Widget.prototype._setOption.apply(this,arguments)},_activate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),i&&this._trigger("activate",t,this.ui(i))},_deactivate:function(t){var i=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),i&&this._trigger("deactivate",t,this.ui(i))},_over:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(i)))},_out:function(t){var i=e.ui.ddmanager.current;i&&(i.currentItem||i.element)[0]!==this.element[0]&&this.accept.call(this.element[0],i.currentItem||i.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(i)))},_drop:function(t,i){var s=i||e.ui.ddmanager.current,n=!1;return s&&(s.currentItem||s.element)[0]!==this.element[0]?(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var t=e.data(this,"ui-droppable");return t.options.greedy&&!t.options.disabled&&t.options.scope===s.options.scope&&t.accept.call(t.element[0],s.currentItem||s.element)&&e.ui.intersect(s,e.extend(t,{offset:t.element.offset()}),t.options.tolerance)?(n=!0,!1):undefined}),n?!1:this.accept.call(this.element[0],s.currentItem||s.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",t,this.ui(s)),this.element):!1):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(e,i,s){if(!i.offset)return!1;var n,a,o=(e.positionAbs||e.position.absolute).left,r=o+e.helperProportions.width,h=(e.positionAbs||e.position.absolute).top,l=h+e.helperProportions.height,u=i.offset.left,c=u+i.proportions.width,d=i.offset.top,p=d+i.proportions.height;switch(s){case"fit":return o>=u&&c>=r&&h>=d&&p>=l;case"intersect":return o+e.helperProportions.width/2>u&&c>r-e.helperProportions.width/2&&h+e.helperProportions.height/2>d&&p>l-e.helperProportions.height/2;case"pointer":return n=(e.positionAbs||e.position.absolute).left+(e.clickOffset||e.offset.click).left,a=(e.positionAbs||e.position.absolute).top+(e.clickOffset||e.offset.click).top,t(a,d,i.proportions.height)&&t(n,u,i.proportions.width);case"touch":return(h>=d&&p>=h||l>=d&&p>=l||d>h&&l>p)&&(o>=u&&c>=o||r>=u&&c>=r||u>o&&r>c);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,i){var s,n,a=e.ui.ddmanager.droppables[t.options.scope]||[],o=i?i.type:null,r=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(s=0;a.length>s;s++)if(!(a[s].options.disabled||t&&!a[s].accept.call(a[s].element[0],t.currentItem||t.element))){for(n=0;r.length>n;n++)if(r[n]===a[s].element[0]){a[s].proportions.height=0;continue e}a[s].visible="none"!==a[s].element.css("display"),a[s].visible&&("mousedown"===o&&a[s]._activate.call(a[s],i),a[s].offset=a[s].element.offset(),a[s].proportions={width:a[s].element[0].offsetWidth,height:a[s].element[0].offsetHeight})}},drop:function(t,i){var s=!1;return e.each((e.ui.ddmanager.droppables[t.options.scope]||[]).slice(),function(){this.options&&(!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance)&&(s=this._drop.call(this,i)||s),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,i)))}),s},dragStart:function(t,i){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)})},drag:function(t,i){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,i),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var s,n,a,o=e.ui.intersect(t,this,this.options.tolerance),r=!o&&this.isover?"isout":o&&!this.isover?"isover":null;r&&(this.options.greedy&&(n=this.options.scope,a=this.element.parents(":data(ui-droppable)").filter(function(){return e.data(this,"ui-droppable").options.scope===n}),a.length&&(s=e.data(a[0],"ui-droppable"),s.greedyChild="isover"===r)),s&&"isover"===r&&(s.isover=!1,s.isout=!0,s._out.call(s,i)),this[r]=!0,this["isout"===r?"isover":"isout"]=!1,this["isover"===r?"_over":"_out"].call(this,i),s&&"isout"===r&&(s.isout=!1,s.isover=!0,s._over.call(s,i)))}})},dragStop:function(t,i){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,i)}}})(jQuery);
/*! jQuery UI - v1.11.4 - 2015-03-11
* http://jqueryui.com
* Includes: core.js, widget.js, mouse.js, position.js, accordion.js, autocomplete.js, button.js, datepicker.js, dialog.js, draggable.js, droppable.js, effect.js, effect-blind.js, effect-bounce.js, effect-clip.js, effect-drop.js, effect-explode.js, effect-fade.js, effect-fold.js, effect-highlight.js, effect-puff.js, effect-pulsate.js, effect-scale.js, effect-shake.js, effect-size.js, effect-slide.js, effect-transfer.js, menu.js, progressbar.js, resizable.js, selectable.js, selectmenu.js, slider.js, sortable.js, spinner.js, tabs.js, tooltip.js
* Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */

(function( factory ) {
	if ( typeof define === "function" && define.amd ) {

		// AMD. Register as an anonymous module.
		define([ "jquery" ], factory );
	} else {

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {
/*!
 * jQuery UI Core 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/category/ui-core/
 */


// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};

$.extend( $.ui, {
	version: "1.11.4",

	keyCode: {
		BACKSPACE: 8,
		COMMA: 188,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		LEFT: 37,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
});

// plugins
$.fn.extend({
	scrollParent: function( includeHidden ) {
		var position = this.css( "position" ),
			excludeStaticParent = position === "absolute",
			overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/,
			scrollParent = this.parents().filter( function() {
				var parent = $( this );
				if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
					return false;
				}
				return overflowRegex.test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
			}).eq( 0 );

		return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
	},

	uniqueId: (function() {
		var uuid = 0;

		return function() {
			return this.each(function() {
				if ( !this.id ) {
					this.id = "ui-id-" + ( ++uuid );
				}
			});
		};
	})(),

	removeUniqueId: function() {
		return this.each(function() {
			if ( /^ui-id-\d+$/.test( this.id ) ) {
				$( this ).removeAttr( "id" );
			}
		});
	}
});

// selectors
function focusable( element, isTabIndexNotNaN ) {
	var map, mapName, img,
		nodeName = element.nodeName.toLowerCase();
	if ( "area" === nodeName ) {
		map = element.parentNode;
		mapName = map.name;
		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
			return false;
		}
		img = $( "img[usemap='#" + mapName + "']" )[ 0 ];
		return !!img && visible( img );
	}
	return ( /^(input|select|textarea|button|object)$/.test( nodeName ) ?
		!element.disabled :
		"a" === nodeName ?
			element.href || isTabIndexNotNaN :
			isTabIndexNotNaN) &&
		// the element and all of its ancestors must be visible
		visible( element );
}

function visible( element ) {
	return $.expr.filters.visible( element ) &&
		!$( element ).parents().addBack().filter(function() {
			return $.css( this, "visibility" ) === "hidden";
		}).length;
}

$.extend( $.expr[ ":" ], {
	data: $.expr.createPseudo ?
		$.expr.createPseudo(function( dataName ) {
			return function( elem ) {
				return !!$.data( elem, dataName );
			};
		}) :
		// support: jQuery <1.8
		function( elem, i, match ) {
			return !!$.data( elem, match[ 3 ] );
		},

	focusable: function( element ) {
		return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
	},

	tabbable: function( element ) {
		var tabIndex = $.attr( element, "tabindex" ),
			isTabIndexNaN = isNaN( tabIndex );
		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
	}
});

// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
	$.each( [ "Width", "Height" ], function( i, name ) {
		var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
			type = name.toLowerCase(),
			orig = {
				innerWidth: $.fn.innerWidth,
				innerHeight: $.fn.innerHeight,
				outerWidth: $.fn.outerWidth,
				outerHeight: $.fn.outerHeight
			};

		function reduce( elem, size, border, margin ) {
			$.each( side, function() {
				size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
				if ( border ) {
					size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
				}
				if ( margin ) {
					size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
				}
			});
			return size;
		}

		$.fn[ "inner" + name ] = function( size ) {
			if ( size === undefined ) {
				return orig[ "inner" + name ].call( this );
			}

			return this.each(function() {
				$( this ).css( type, reduce( this, size ) + "px" );
			});
		};

		$.fn[ "outer" + name] = function( size, margin ) {
			if ( typeof size !== "number" ) {
				return orig[ "outer" + name ].call( this, size );
			}

			return this.each(function() {
				$( this).css( type, reduce( this, size, true, margin ) + "px" );
			});
		};
	});
}

// support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
	$.fn.removeData = (function( removeData ) {
		return function( key ) {
			if ( arguments.length ) {
				return removeData.call( this, $.camelCase( key ) );
			} else {
				return removeData.call( this );
			}
		};
	})( $.fn.removeData );
}

// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );

$.fn.extend({
	focus: (function( orig ) {
		return function( delay, fn ) {
			return typeof delay === "number" ?
				this.each(function() {
					var elem = this;
					setTimeout(function() {
						$( elem ).focus();
						if ( fn ) {
							fn.call( elem );
						}
					}, delay );
				}) :
				orig.apply( this, arguments );
		};
	})( $.fn.focus ),

	disableSelection: (function() {
		var eventType = "onselectstart" in document.createElement( "div" ) ?
			"selectstart" :
			"mousedown";

		return function() {
			return this.bind( eventType + ".ui-disableSelection", function( event ) {
				event.preventDefault();
			});
		};
	})(),

	enableSelection: function() {
		return this.unbind( ".ui-disableSelection" );
	},

	zIndex: function( zIndex ) {
		if ( zIndex !== undefined ) {
			return this.css( "zIndex", zIndex );
		}

		if ( this.length ) {
			var elem = $( this[ 0 ] ), position, value;
			while ( elem.length && elem[ 0 ] !== document ) {
				// Ignore z-index if position is set to a value where z-index is ignored by the browser
				// This makes behavior of this function consistent across browsers
				// WebKit always returns auto if the element is positioned
				position = elem.css( "position" );
				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
					// IE returns 0 when zIndex is not specified
					// other browsers return a string
					// we ignore the case of nested elements with an explicit value of 0
					// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
					value = parseInt( elem.css( "zIndex" ), 10 );
					if ( !isNaN( value ) && value !== 0 ) {
						return value;
					}
				}
				elem = elem.parent();
			}
		}

		return 0;
	}
});

// $.ui.plugin is deprecated. Use $.widget() extensions instead.
$.ui.plugin = {
	add: function( module, option, set ) {
		var i,
			proto = $.ui[ module ].prototype;
		for ( i in set ) {
			proto.plugins[ i ] = proto.plugins[ i ] || [];
			proto.plugins[ i ].push( [ option, set[ i ] ] );
		}
	},
	call: function( instance, name, args, allowDisconnected ) {
		var i,
			set = instance.plugins[ name ];

		if ( !set ) {
			return;
		}

		if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
			return;
		}

		for ( i = 0; i < set.length; i++ ) {
			if ( instance.options[ set[ i ][ 0 ] ] ) {
				set[ i ][ 1 ].apply( instance.element, args );
			}
		}
	}
};


/*!
 * jQuery UI Widget 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/jQuery.widget/
 */


var widget_uuid = 0,
	widget_slice = Array.prototype.slice;

$.cleanData = (function( orig ) {
	return function( elems ) {
		var events, elem, i;
		for ( i = 0; (elem = elems[i]) != null; i++ ) {
			try {

				// Only trigger remove when necessary to save time
				events = $._data( elem, "events" );
				if ( events && events.remove ) {
					$( elem ).triggerHandler( "remove" );
				}

			// http://bugs.jquery.com/ticket/8235
			} catch ( e ) {}
		}
		orig( elems );
	};
})( $.cleanData );

$.widget = function( name, base, prototype ) {
	var fullName, existingConstructor, constructor, basePrototype,
		// proxiedPrototype allows the provided prototype to remain unmodified
		// so that it can be used as a mixin for multiple widgets (#8876)
		proxiedPrototype = {},
		namespace = name.split( "." )[ 0 ];

	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
		prototype = base;
		base = $.Widget;
	}

	// create selector for plugin
	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
		return !!$.data( elem, fullName );
	};

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};
	// extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,
		// copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),
		// track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	});

	basePrototype = new base();
	// we need to make the options hash a property directly on the new instance
	// otherwise we'll modify the options hash on the prototype that we're
	// inheriting from
	basePrototype.options = $.widget.extend( {}, basePrototype.options );
	$.each( prototype, function( prop, value ) {
		if ( !$.isFunction( value ) ) {
			proxiedPrototype[ prop ] = value;
			return;
		}
		proxiedPrototype[ prop ] = (function() {
			var _super = function() {
					return base.prototype[ prop ].apply( this, arguments );
				},
				_superApply = function( args ) {
					return base.prototype[ prop ].apply( this, args );
				};
			return function() {
				var __super = this._super,
					__superApply = this._superApply,
					returnValue;

				this._super = _super;
				this._superApply = _superApply;

				returnValue = value.apply( this, arguments );

				this._super = __super;
				this._superApply = __superApply;

				return returnValue;
			};
		})();
	});
	constructor.prototype = $.widget.extend( basePrototype, {
		// TODO: remove support for widgetEventPrefix
		// always use the name + a colon as the prefix, e.g., draggable:start
		// don't prefix for widgets that aren't DOM-based
		widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name
	}, proxiedPrototype, {
		constructor: constructor,
		namespace: namespace,
		widgetName: name,
		widgetFullName: fullName
	});

	// If this widget is being redefined then we need to find all widgets that
	// are inheriting from it and redefine all of them so that they inherit from
	// the new version of this widget. We're essentially trying to replace one
	// level in the prototype chain.
	if ( existingConstructor ) {
		$.each( existingConstructor._childConstructors, function( i, child ) {
			var childPrototype = child.prototype;

			// redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
		});
		// remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widget_slice.call( arguments, 1 ),
		inputIndex = 0,
		inputLength = input.length,
		key,
		value;
	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :
						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );
				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

$.widget.bridge = function( name, object ) {
	var fullName = object.prototype.widgetFullName || name;
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = widget_slice.call( arguments, 1 ),
			returnValue = this;

		if ( isMethodCall ) {
			this.each(function() {
				var methodValue,
					instance = $.data( this, fullName );
				if ( options === "instance" ) {
					returnValue = instance;
					return false;
				}
				if ( !instance ) {
					return $.error( "cannot call methods on " + name + " prior to initialization; " +
						"attempted to call method '" + options + "'" );
				}
				if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
					return $.error( "no such method '" + options + "' for " + name + " widget instance" );
				}
				methodValue = instance[ options ].apply( instance, args );
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue && methodValue.jquery ?
						returnValue.pushStack( methodValue.get() ) :
						methodValue;
					return false;
				}
			});
		} else {

			// Allow multiple hashes to be passed on init
			if ( args.length ) {
				options = $.widget.extend.apply( null, [ options ].concat(args) );
			}

			this.each(function() {
				var instance = $.data( this, fullName );
				if ( instance ) {
					instance.option( options || {} );
					if ( instance._init ) {
						instance._init();
					}
				} else {
					$.data( this, fullName, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];

$.Widget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	defaultElement: "<div>",
	options: {
		disabled: false,

		// callbacks
		create: null
	},
	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widget_uuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			});
			this.document = $( element.style ?
				// element within the document
				element.ownerDocument :
				// element is window or document
				element.document || element );
			this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
		}

		this.options = $.widget.extend( {},
			this.options,
			this._getCreateOptions(),
			options );

		this._create();
		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},
	_getCreateOptions: $.noop,
	_getCreateEventData: $.noop,
	_create: $.noop,
	_init: $.noop,

	destroy: function() {
		this._destroy();
		// we can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.unbind( this.eventNamespace )
			.removeData( this.widgetFullName )
			// support: jquery <1.6.3
			// http://bugs.jquery.com/ticket/9413
			.removeData( $.camelCase( this.widgetFullName ) );
		this.widget()
			.unbind( this.eventNamespace )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetFullName + "-disabled " +
				"ui-state-disabled" );

		// clean up events and states
		this.bindings.unbind( this.eventNamespace );
		this.hoverable.removeClass( "ui-state-hover" );
		this.focusable.removeClass( "ui-state-focus" );
	},
	_destroy: $.noop,

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key,
			parts,
			curOption,
			i;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {
			// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
			options = {};
			parts = key.split( "." );
			key = parts.shift();
			if ( parts.length ) {
				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
				for ( i = 0; i < parts.length - 1; i++ ) {
					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
					curOption = curOption[ parts[ i ] ];
				}
				key = parts.pop();
				if ( arguments.length === 1 ) {
					return curOption[ key ] === undefined ? null : curOption[ key ];
				}
				curOption[ key ] = value;
			} else {
				if ( arguments.length === 1 ) {
					return this.options[ key ] === undefined ? null : this.options[ key ];
				}
				options[ key ] = value;
			}
		}

		this._setOptions( options );

		return this;
	},
	_setOptions: function( options ) {
		var key;

		for ( key in options ) {
			this._setOption( key, options[ key ] );
		}

		return this;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				.toggleClass( this.widgetFullName + "-disabled", !!value );

			// If the widget is becoming disabled, then nothing is interactive
			if ( value ) {
				this.hoverable.removeClass( "ui-state-hover" );
				this.focusable.removeClass( "ui-state-focus" );
			}
		}

		return this;
	},

	enable: function() {
		return this._setOptions({ disabled: false });
	},
	disable: function() {
		return this._setOptions({ disabled: true });
	},

	_on: function( suppressDisabledCheck, element, handlers ) {
		var delegateElement,
			instance = this;

		// no suppressDisabledCheck flag, shuffle arguments
		if ( typeof suppressDisabledCheck !== "boolean" ) {
			handlers = element;
			element = suppressDisabledCheck;
			suppressDisabledCheck = false;
		}

		// no element argument, shuffle and use this.element
		if ( !handlers ) {
			handlers = element;
			element = this.element;
			delegateElement = this.widget();
		} else {
			element = delegateElement = $( element );
			this.bindings = this.bindings.add( element );
		}

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {
				// allow widgets to customize the disabled handling
				// - disabled as an array instead of boolean
				// - disabled class as method for disabling individual parts
				if ( !suppressDisabledCheck &&
						( instance.options.disabled === true ||
							$( this ).hasClass( "ui-state-disabled" ) ) ) {
					return;
				}
				return ( typeof handler === "string" ? instance[ handler ] : handler )
					.apply( instance, arguments );
			}

			// copy the guid so direct unbinding works
			if ( typeof handler !== "string" ) {
				handlerProxy.guid = handler.guid =
					handler.guid || handlerProxy.guid || $.guid++;
			}

			var match = event.match( /^([\w:-]*)\s*(.*)$/ ),
				eventName = match[1] + instance.eventNamespace,
				selector = match[2];
			if ( selector ) {
				delegateElement.delegate( selector, eventName, handlerProxy );
			} else {
				element.bind( eventName, handlerProxy );
			}
		});
	},

	_off: function( element, eventName ) {
		eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) +
			this.eventNamespace;
		element.unbind( eventName ).undelegate( eventName );

		// Clear the stack to avoid memory leaks (#10056)
		this.bindings = $( this.bindings.not( element ).get() );
		this.focusable = $( this.focusable.not( element ).get() );
		this.hoverable = $( this.hoverable.not( element ).get() );
	},

	_delay: function( handler, delay ) {
		function handlerProxy() {
			return ( typeof handler === "string" ? instance[ handler ] : handler )
				.apply( instance, arguments );
		}
		var instance = this;
		return setTimeout( handlerProxy, delay || 0 );
	},

	_hoverable: function( element ) {
		this.hoverable = this.hoverable.add( element );
		this._on( element, {
			mouseenter: function( event ) {
				$( event.currentTarget ).addClass( "ui-state-hover" );
			},
			mouseleave: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-hover" );
			}
		});
	},

	_focusable: function( element ) {
		this.focusable = this.focusable.add( element );
		this._on( element, {
			focusin: function( event ) {
				$( event.currentTarget ).addClass( "ui-state-focus" );
			},
			focusout: function( event ) {
				$( event.currentTarget ).removeClass( "ui-state-focus" );
			}
		});
	},

	_trigger: function( type, event, data ) {
		var prop, orig,
			callback = this.options[ type ];

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		// the original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

		// copy original event properties over to the new event
		orig = event.originalEvent;
		if ( orig ) {
			for ( prop in orig ) {
				if ( !( prop in event ) ) {
					event[ prop ] = orig[ prop ];
				}
			}
		}

		this.element.trigger( event, data );
		return !( $.isFunction( callback ) &&
			callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
			event.isDefaultPrevented() );
	}
};

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}
		var hasOptions,
			effectName = !options ?
				method :
				options === true || typeof options === "number" ?
					defaultEffect :
					options.effect || defaultEffect;
		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}
		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;
		if ( options.delay ) {
			element.delay( options.delay );
		}
		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue(function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			});
		}
	};
});

var widget = $.widget;


/*!
 * jQuery UI Mouse 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/mouse/
 */


var mouseHandled = false;
$( document ).mouseup( function() {
	mouseHandled = false;
});

var mouse = $.widget("ui.mouse", {
	version: "1.11.4",
	options: {
		cancel: "input,textarea,button,select,option",
		distance: 1,
		delay: 0
	},
	_mouseInit: function() {
		var that = this;

		this.element
			.bind("mousedown." + this.widgetName, function(event) {
				return that._mouseDown(event);
			})
			.bind("click." + this.widgetName, function(event) {
				if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
					$.removeData(event.target, that.widgetName + ".preventClickEvent");
					event.stopImmediatePropagation();
					return false;
				}
			});

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind("." + this.widgetName);
		if ( this._mouseMoveDelegate ) {
			this.document
				.unbind("mousemove." + this.widgetName, this._mouseMoveDelegate)
				.unbind("mouseup." + this.widgetName, this._mouseUpDelegate);
		}
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		if ( mouseHandled ) {
			return;
		}

		this._mouseMoved = false;

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = (event.which === 1),
			// event.target.nodeName works around a bug in IE 8 with
			// disabled inputs (#7620)
			elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				that.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// Click event may never have fired (Gecko & Opera)
		if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
			$.removeData(event.target, this.widgetName + ".preventClickEvent");
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return that._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return that._mouseUp(event);
		};

		this.document
			.bind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.bind( "mouseup." + this.widgetName, this._mouseUpDelegate );

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {
			// IE mouseup check - mouseup happened when mouse was out of window
			if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
				return this._mouseUp(event);

			// Iframe mouseup check - mouseup occurred in another document
			} else if ( !event.which ) {
				return this._mouseUp( event );
			}
		}

		if ( event.which || event.button ) {
			this._mouseMoved = true;
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		this.document
			.unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate )
			.unbind( "mouseup." + this.widgetName, this._mouseUpDelegate );

		if (this._mouseStarted) {
			this._mouseStarted = false;

			if (event.target === this._mouseDownEvent.target) {
				$.data(event.target, this.widgetName + ".preventClickEvent", true);
			}

			this._mouseStop(event);
		}

		mouseHandled = false;
		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(/* event */) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(/* event */) {},
	_mouseDrag: function(/* event */) {},
	_mouseStop: function(/* event */) {},
	_mouseCapture: function(/* event */) { return true; }
});


/*!
 * jQuery UI Position 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/position/
 */

(function() {

$.ui = $.ui || {};

var cachedScrollbarWidth, supportsOffsetFractions,
	max = Math.max,
	abs = Math.abs,
	round = Math.round,
	rhorizontal = /left|center|right/,
	rvertical = /top|center|bottom/,
	roffset = /[\+\-]\d+(\.[\d]+)?%?/,
	rposition = /^\w+/,
	rpercent = /%$/,
	_position = $.fn.position;

function getOffsets( offsets, width, height ) {
	return [
		parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
		parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
	];
}

function parseCss( element, property ) {
	return parseInt( $.css( element, property ), 10 ) || 0;
}

function getDimensions( elem ) {
	var raw = elem[0];
	if ( raw.nodeType === 9 ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: 0, left: 0 }
		};
	}
	if ( $.isWindow( raw ) ) {
		return {
			width: elem.width(),
			height: elem.height(),
			offset: { top: elem.scrollTop(), left: elem.scrollLeft() }
		};
	}
	if ( raw.preventDefault ) {
		return {
			width: 0,
			height: 0,
			offset: { top: raw.pageY, left: raw.pageX }
		};
	}
	return {
		width: elem.outerWidth(),
		height: elem.outerHeight(),
		offset: elem.offset()
	};
}

$.position = {
	scrollbarWidth: function() {
		if ( cachedScrollbarWidth !== undefined ) {
			return cachedScrollbarWidth;
		}
		var w1, w2,
			div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
			innerDiv = div.children()[0];

		$( "body" ).append( div );
		w1 = innerDiv.offsetWidth;
		div.css( "overflow", "scroll" );

		w2 = innerDiv.offsetWidth;

		if ( w1 === w2 ) {
			w2 = div[0].clientWidth;
		}

		div.remove();

		return (cachedScrollbarWidth = w1 - w2);
	},
	getScrollInfo: function( within ) {
		var overflowX = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-x" ),
			overflowY = within.isWindow || within.isDocument ? "" :
				within.element.css( "overflow-y" ),
			hasOverflowX = overflowX === "scroll" ||
				( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
			hasOverflowY = overflowY === "scroll" ||
				( overflowY === "auto" && within.height < within.element[0].scrollHeight );
		return {
			width: hasOverflowY ? $.position.scrollbarWidth() : 0,
			height: hasOverflowX ? $.position.scrollbarWidth() : 0
		};
	},
	getWithinInfo: function( element ) {
		var withinElement = $( element || window ),
			isWindow = $.isWindow( withinElement[0] ),
			isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9;
		return {
			element: withinElement,
			isWindow: isWindow,
			isDocument: isDocument,
			offset: withinElement.offset() || { left: 0, top: 0 },
			scrollLeft: withinElement.scrollLeft(),
			scrollTop: withinElement.scrollTop(),

			// support: jQuery 1.6.x
			// jQuery 1.6 doesn't support .outerWidth/Height() on documents or windows
			width: isWindow || isDocument ? withinElement.width() : withinElement.outerWidth(),
			height: isWindow || isDocument ? withinElement.height() : withinElement.outerHeight()
		};
	}
};

$.fn.position = function( options ) {
	if ( !options || !options.of ) {
		return _position.apply( this, arguments );
	}

	// make a copy, we don't want to modify arguments
	options = $.extend( {}, options );

	var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions,
		target = $( options.of ),
		within = $.position.getWithinInfo( options.within ),
		scrollInfo = $.position.getScrollInfo( within ),
		collision = ( options.collision || "flip" ).split( " " ),
		offsets = {};

	dimensions = getDimensions( target );
	if ( target[0].preventDefault ) {
		// force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;
	// clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

	// force my and at to have valid horizontal and vertical positions
	// if a value is missing or invalid, it will be converted to center
	$.each( [ "my", "at" ], function() {
		var pos = ( options[ this ] || "" ).split( " " ),
			horizontalOffset,
			verticalOffset;

		if ( pos.length === 1) {
			pos = rhorizontal.test( pos[ 0 ] ) ?
				pos.concat( [ "center" ] ) :
				rvertical.test( pos[ 0 ] ) ?
					[ "center" ].concat( pos ) :
					[ "center", "center" ];
		}
		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";

		// calculate offsets
		horizontalOffset = roffset.exec( pos[ 0 ] );
		verticalOffset = roffset.exec( pos[ 1 ] );
		offsets[ this ] = [
			horizontalOffset ? horizontalOffset[ 0 ] : 0,
			verticalOffset ? verticalOffset[ 0 ] : 0
		];

		// reduce to just the positions without the offsets
		options[ this ] = [
			rposition.exec( pos[ 0 ] )[ 0 ],
			rposition.exec( pos[ 1 ] )[ 0 ]
		];
	});

	// normalize collision option
	if ( collision.length === 1 ) {
		collision[ 1 ] = collision[ 0 ];
	}

	if ( options.at[ 0 ] === "right" ) {
		basePosition.left += targetWidth;
	} else if ( options.at[ 0 ] === "center" ) {
		basePosition.left += targetWidth / 2;
	}

	if ( options.at[ 1 ] === "bottom" ) {
		basePosition.top += targetHeight;
	} else if ( options.at[ 1 ] === "center" ) {
		basePosition.top += targetHeight / 2;
	}

	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
	basePosition.left += atOffset[ 0 ];
	basePosition.top += atOffset[ 1 ];

	return this.each(function() {
		var collisionPosition, using,
			elem = $( this ),
			elemWidth = elem.outerWidth(),
			elemHeight = elem.outerHeight(),
			marginLeft = parseCss( this, "marginLeft" ),
			marginTop = parseCss( this, "marginTop" ),
			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
			position = $.extend( {}, basePosition ),
			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );

		if ( options.my[ 0 ] === "right" ) {
			position.left -= elemWidth;
		} else if ( options.my[ 0 ] === "center" ) {
			position.left -= elemWidth / 2;
		}

		if ( options.my[ 1 ] === "bottom" ) {
			position.top -= elemHeight;
		} else if ( options.my[ 1 ] === "center" ) {
			position.top -= elemHeight / 2;
		}

		position.left += myOffset[ 0 ];
		position.top += myOffset[ 1 ];

		// if the browser doesn't support fractions, then round for consistent results
		if ( !supportsOffsetFractions ) {
			position.left = round( position.left );
			position.top = round( position.top );
		}

		collisionPosition = {
			marginLeft: marginLeft,
			marginTop: marginTop
		};

		$.each( [ "left", "top" ], function( i, dir ) {
			if ( $.ui.position[ collision[ i ] ] ) {
				$.ui.position[ collision[ i ] ][ dir ]( position, {
					targetWidth: targetWidth,
					targetHeight: targetHeight,
					elemWidth: elemWidth,
					elemHeight: elemHeight,
					collisionPosition: collisionPosition,
					collisionWidth: collisionWidth,
					collisionHeight: collisionHeight,
					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
					my: options.my,
					at: options.at,
					within: within,
					elem: elem
				});
			}
		});

		if ( options.using ) {
			// adds feedback as second argument to using callback, if present
			using = function( props ) {
				var left = targetOffset.left - position.left,
					right = left + targetWidth - elemWidth,
					top = targetOffset.top - position.top,
					bottom = top + targetHeight - elemHeight,
					feedback = {
						target: {
							element: target,
							left: targetOffset.left,
							top: targetOffset.top,
							width: targetWidth,
							height: targetHeight
						},
						element: {
							element: elem,
							left: position.left,
							top: position.top,
							width: elemWidth,
							height: elemHeight
						},
						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
					};
				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
					feedback.horizontal = "center";
				}
				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
					feedback.vertical = "middle";
				}
				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
					feedback.important = "horizontal";
				} else {
					feedback.important = "vertical";
				}
				options.using.call( this, props, feedback );
			};
		}

		elem.offset( $.extend( position, { using: using } ) );
	});
};

$.ui.position = {
	fit: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
				outerWidth = within.width,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = withinOffset - collisionPosLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
				newOverRight;

			// element is wider than within
			if ( data.collisionWidth > outerWidth ) {
				// element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
					position.left += overLeft - newOverRight;
				// element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;
				// element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}
			// too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;
			// too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;
			// adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// element is taller than within
			if ( data.collisionHeight > outerHeight ) {
				// element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
					position.top += overTop - newOverBottom;
				// element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;
				// element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}
			// too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;
			// too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;
			// adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

			if ( overLeft < 0 ) {
				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
					position.left += myOffset + atOffset + offset;
				}
			} else if ( overRight > 0 ) {
				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
					position.left += myOffset + atOffset + offset;
				}
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.top + within.scrollTop,
				outerHeight = within.height,
				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = collisionPosTop - offsetTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
				top = data.my[ 1 ] === "top",
				myOffset = top ?
					-data.elemHeight :
					data.my[ 1 ] === "bottom" ?
						data.elemHeight :
						0,
				atOffset = data.at[ 1 ] === "top" ?
					data.targetHeight :
					data.at[ 1 ] === "bottom" ?
						-data.targetHeight :
						0,
				offset = -2 * data.offset[ 1 ],
				newOverTop,
				newOverBottom;
			if ( overTop < 0 ) {
				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
				if ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) {
					position.top += myOffset + atOffset + offset;
				}
			} else if ( overBottom > 0 ) {
				newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
				if ( newOverTop > 0 || abs( newOverTop ) < overBottom ) {
					position.top += myOffset + atOffset + offset;
				}
			}
		}
	},
	flipfit: {
		left: function() {
			$.ui.position.flip.left.apply( this, arguments );
			$.ui.position.fit.left.apply( this, arguments );
		},
		top: function() {
			$.ui.position.flip.top.apply( this, arguments );
			$.ui.position.fit.top.apply( this, arguments );
		}
	}
};

// fraction support test
(function() {
	var testElement, testElementParent, testElementStyle, offsetLeft, i,
		body = document.getElementsByTagName( "body" )[ 0 ],
		div = document.createElement( "div" );

	//Create a "fake body" for testing based on method used in jQuery.support
	testElement = document.createElement( body ? "div" : "body" );
	testElementStyle = {
		visibility: "hidden",
		width: 0,
		height: 0,
		border: 0,
		margin: 0,
		background: "none"
	};
	if ( body ) {
		$.extend( testElementStyle, {
			position: "absolute",
			left: "-1000px",
			top: "-1000px"
		});
	}
	for ( i in testElementStyle ) {
		testElement.style[ i ] = testElementStyle[ i ];
	}
	testElement.appendChild( div );
	testElementParent = body || document.documentElement;
	testElementParent.insertBefore( testElement, testElementParent.firstChild );

	div.style.cssText = "position: absolute; left: 10.7432222px;";

	offsetLeft = $( div ).offset().left;
	supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11;

	testElement.innerHTML = "";
	testElementParent.removeChild( testElement );
})();

})();

var position = $.ui.position;


/*!
 * jQuery UI Accordion 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/accordion/
 */


var accordion = $.widget( "ui.accordion", {
	version: "1.11.4",
	options: {
		active: 0,
		animate: {},
		collapsible: false,
		event: "click",
		header: "> li > :first-child,> :not(li):even",
		heightStyle: "auto",
		icons: {
			activeHeader: "ui-icon-triangle-1-s",
			header: "ui-icon-triangle-1-e"
		},

		// callbacks
		activate: null,
		beforeActivate: null
	},

	hideProps: {
		borderTopWidth: "hide",
		borderBottomWidth: "hide",
		paddingTop: "hide",
		paddingBottom: "hide",
		height: "hide"
	},

	showProps: {
		borderTopWidth: "show",
		borderBottomWidth: "show",
		paddingTop: "show",
		paddingBottom: "show",
		height: "show"
	},

	_create: function() {
		var options = this.options;
		this.prevShow = this.prevHide = $();
		this.element.addClass( "ui-accordion ui-widget ui-helper-reset" )
			// ARIA
			.attr( "role", "tablist" );

		// don't allow collapsible: false and active: false / null
		if ( !options.collapsible && (options.active === false || options.active == null) ) {
			options.active = 0;
		}

		this._processPanels();
		// handle negative values
		if ( options.active < 0 ) {
			options.active += this.headers.length;
		}
		this._refresh();
	},

	_getCreateEventData: function() {
		return {
			header: this.active,
			panel: !this.active.length ? $() : this.active.next()
		};
	},

	_createIcons: function() {
		var icons = this.options.icons;
		if ( icons ) {
			$( "<span>" )
				.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
				.prependTo( this.headers );
			this.active.children( ".ui-accordion-header-icon" )
				.removeClass( icons.header )
				.addClass( icons.activeHeader );
			this.headers.addClass( "ui-accordion-icons" );
		}
	},

	_destroyIcons: function() {
		this.headers
			.removeClass( "ui-accordion-icons" )
			.children( ".ui-accordion-header-icon" )
				.remove();
	},

	_destroy: function() {
		var contents;

		// clean up main element
		this.element
			.removeClass( "ui-accordion ui-widget ui-helper-reset" )
			.removeAttr( "role" );

		// clean up headers
		this.headers
			.removeClass( "ui-accordion-header ui-accordion-header-active ui-state-default " +
				"ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
			.removeAttr( "role" )
			.removeAttr( "aria-expanded" )
			.removeAttr( "aria-selected" )
			.removeAttr( "aria-controls" )
			.removeAttr( "tabIndex" )
			.removeUniqueId();

		this._destroyIcons();

		// clean up content panels
		contents = this.headers.next()
			.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom " +
				"ui-accordion-content ui-accordion-content-active ui-state-disabled" )
			.css( "display", "" )
			.removeAttr( "role" )
			.removeAttr( "aria-hidden" )
			.removeAttr( "aria-labelledby" )
			.removeUniqueId();

		if ( this.options.heightStyle !== "content" ) {
			contents.css( "height", "" );
		}
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {
			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		if ( key === "event" ) {
			if ( this.options.event ) {
				this._off( this.headers, this.options.event );
			}
			this._setupEvents( value );
		}

		this._super( key, value );

		// setting collapsible: false while collapsed; open first panel
		if ( key === "collapsible" && !value && this.options.active === false ) {
			this._activate( 0 );
		}

		if ( key === "icons" ) {
			this._destroyIcons();
			if ( value ) {
				this._createIcons();
			}
		}

		// #5332 - opacity doesn't cascade to positioned elements in IE
		// so we need to add the disabled class to the headers and panels
		if ( key === "disabled" ) {
			this.element
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
			this.headers.add( this.headers.next() )
				.toggleClass( "ui-state-disabled", !!value );
		}
	},

	_keydown: function( event ) {
		if ( event.altKey || event.ctrlKey ) {
			return;
		}

		var keyCode = $.ui.keyCode,
			length = this.headers.length,
			currentIndex = this.headers.index( event.target ),
			toFocus = false;

		switch ( event.keyCode ) {
			case keyCode.RIGHT:
			case keyCode.DOWN:
				toFocus = this.headers[ ( currentIndex + 1 ) % length ];
				break;
			case keyCode.LEFT:
			case keyCode.UP:
				toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
				break;
			case keyCode.SPACE:
			case keyCode.ENTER:
				this._eventHandler( event );
				break;
			case keyCode.HOME:
				toFocus = this.headers[ 0 ];
				break;
			case keyCode.END:
				toFocus = this.headers[ length - 1 ];
				break;
		}

		if ( toFocus ) {
			$( event.target ).attr( "tabIndex", -1 );
			$( toFocus ).attr( "tabIndex", 0 );
			toFocus.focus();
			event.preventDefault();
		}
	},

	_panelKeyDown: function( event ) {
		if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
			$( event.currentTarget ).prev().focus();
		}
	},

	refresh: function() {
		var options = this.options;
		this._processPanels();

		// was collapsed or no panel
		if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) {
			options.active = false;
			this.active = $();
		// active false only when collapsible is true
		} else if ( options.active === false ) {
			this._activate( 0 );
		// was active, but active panel is gone
		} else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			// all remaining panel are disabled
			if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) {
				options.active = false;
				this.active = $();
			// activate previous panel
			} else {
				this._activate( Math.max( 0, options.active - 1 ) );
			}
		// was active, active panel still exists
		} else {
			// make sure active index is correct
			options.active = this.headers.index( this.active );
		}

		this._destroyIcons();

		this._refresh();
	},

	_processPanels: function() {
		var prevHeaders = this.headers,
			prevPanels = this.panels;

		this.headers = this.element.find( this.options.header )
			.addClass( "ui-accordion-header ui-state-default ui-corner-all" );

		this.panels = this.headers.next()
			.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
			.filter( ":not(.ui-accordion-content-active)" )
			.hide();

		// Avoid memory leaks (#10056)
		if ( prevPanels ) {
			this._off( prevHeaders.not( this.headers ) );
			this._off( prevPanels.not( this.panels ) );
		}
	},

	_refresh: function() {
		var maxHeight,
			options = this.options,
			heightStyle = options.heightStyle,
			parent = this.element.parent();

		this.active = this._findActive( options.active )
			.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" )
			.removeClass( "ui-corner-all" );
		this.active.next()
			.addClass( "ui-accordion-content-active" )
			.show();

		this.headers
			.attr( "role", "tab" )
			.each(function() {
				var header = $( this ),
					headerId = header.uniqueId().attr( "id" ),
					panel = header.next(),
					panelId = panel.uniqueId().attr( "id" );
				header.attr( "aria-controls", panelId );
				panel.attr( "aria-labelledby", headerId );
			})
			.next()
				.attr( "role", "tabpanel" );

		this.headers
			.not( this.active )
			.attr({
				"aria-selected": "false",
				"aria-expanded": "false",
				tabIndex: -1
			})
			.next()
				.attr({
					"aria-hidden": "true"
				})
				.hide();

		// make sure at least one header is in the tab order
		if ( !this.active.length ) {
			this.headers.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active.attr({
				"aria-selected": "true",
				"aria-expanded": "true",
				tabIndex: 0
			})
			.next()
				.attr({
					"aria-hidden": "false"
				});
		}

		this._createIcons();

		this._setupEvents( options.event );

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			this.element.siblings( ":visible" ).each(function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			});

			this.headers.each(function() {
				maxHeight -= $( this ).outerHeight( true );
			});

			this.headers.next()
				.each(function() {
					$( this ).height( Math.max( 0, maxHeight -
						$( this ).innerHeight() + $( this ).height() ) );
				})
				.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.headers.next()
				.each(function() {
					maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
				})
				.height( maxHeight );
		}
	},

	_activate: function( index ) {
		var active = this._findActive( index )[ 0 ];

		// trying to activate the already active panel
		if ( active === this.active[ 0 ] ) {
			return;
		}

		// trying to collapse, simulate a click on the currently active header
		active = active || this.active[ 0 ];

		this._eventHandler({
			target: active,
			currentTarget: active,
			preventDefault: $.noop
		});
	},

	_findActive: function( selector ) {
		return typeof selector === "number" ? this.headers.eq( selector ) : $();
	},

	_setupEvents: function( event ) {
		var events = {
			keydown: "_keydown"
		};
		if ( event ) {
			$.each( event.split( " " ), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			});
		}

		this._off( this.headers.add( this.headers.next() ) );
		this._on( this.headers, events );
		this._on( this.headers.next(), { keydown: "_panelKeyDown" });
		this._hoverable( this.headers );
		this._focusable( this.headers );
	},

	_eventHandler: function( event ) {
		var options = this.options,
			active = this.active,
			clicked = $( event.currentTarget ),
			clickedIsActive = clicked[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : clicked.next(),
			toHide = active.next(),
			eventData = {
				oldHeader: active,
				oldPanel: toHide,
				newHeader: collapsing ? $() : clicked,
				newPanel: toShow
			};

		event.preventDefault();

		if (
				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||
				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.headers.index( clicked );

		// when the call to ._toggle() comes after the class changes
		// it causes a very odd bug in IE 8 (see #6720)
		this.active = clickedIsActive ? $() : clicked;
		this._toggle( eventData );

		// switch classes
		// corner classes on the previously active header stay after the animation
		active.removeClass( "ui-accordion-header-active ui-state-active" );
		if ( options.icons ) {
			active.children( ".ui-accordion-header-icon" )
				.removeClass( options.icons.activeHeader )
				.addClass( options.icons.header );
		}

		if ( !clickedIsActive ) {
			clicked
				.removeClass( "ui-corner-all" )
				.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
			if ( options.icons ) {
				clicked.children( ".ui-accordion-header-icon" )
					.removeClass( options.icons.header )
					.addClass( options.icons.activeHeader );
			}

			clicked
				.next()
				.addClass( "ui-accordion-content-active" );
		}
	},

	_toggle: function( data ) {
		var toShow = data.newPanel,
			toHide = this.prevShow.length ? this.prevShow : data.oldPanel;

		// handle activating a panel during the animation for another activation
		this.prevShow.add( this.prevHide ).stop( true, true );
		this.prevShow = toShow;
		this.prevHide = toHide;

		if ( this.options.animate ) {
			this._animate( toShow, toHide, data );
		} else {
			toHide.hide();
			toShow.show();
			this._toggleComplete( data );
		}

		toHide.attr({
			"aria-hidden": "true"
		});
		toHide.prev().attr({
			"aria-selected": "false",
			"aria-expanded": "false"
		});
		// if we're switching panels, remove the old header from the tab order
		// if we're opening from collapsed state, remove the previous header from the tab order
		// if we're collapsing, then keep the collapsing header in the tab order
		if ( toShow.length && toHide.length ) {
			toHide.prev().attr({
				"tabIndex": -1,
				"aria-expanded": "false"
			});
		} else if ( toShow.length ) {
			this.headers.filter(function() {
				return parseInt( $( this ).attr( "tabIndex" ), 10 ) === 0;
			})
			.attr( "tabIndex", -1 );
		}

		toShow
			.attr( "aria-hidden", "false" )
			.prev()
				.attr({
					"aria-selected": "true",
					"aria-expanded": "true",
					tabIndex: 0
				});
	},

	_animate: function( toShow, toHide, data ) {
		var total, easing, duration,
			that = this,
			adjust = 0,
			boxSizing = toShow.css( "box-sizing" ),
			down = toShow.length &&
				( !toHide.length || ( toShow.index() < toHide.index() ) ),
			animate = this.options.animate || {},
			options = down && animate.down || animate,
			complete = function() {
				that._toggleComplete( data );
			};

		if ( typeof options === "number" ) {
			duration = options;
		}
		if ( typeof options === "string" ) {
			easing = options;
		}
		// fall back from options to animation in case of partial down settings
		easing = easing || options.easing || animate.easing;
		duration = duration || options.duration || animate.duration;

		if ( !toHide.length ) {
			return toShow.animate( this.showProps, duration, easing, complete );
		}
		if ( !toShow.length ) {
			return toHide.animate( this.hideProps, duration, easing, complete );
		}

		total = toShow.show().outerHeight();
		toHide.animate( this.hideProps, {
			duration: duration,
			easing: easing,
			step: function( now, fx ) {
				fx.now = Math.round( now );
			}
		});
		toShow
			.hide()
			.animate( this.showProps, {
				duration: duration,
				easing: easing,
				complete: complete,
				step: function( now, fx ) {
					fx.now = Math.round( now );
					if ( fx.prop !== "height" ) {
						if ( boxSizing === "content-box" ) {
							adjust += fx.now;
						}
					} else if ( that.options.heightStyle !== "content" ) {
						fx.now = Math.round( total - toHide.outerHeight() - adjust );
						adjust = 0;
					}
				}
			});
	},

	_toggleComplete: function( data ) {
		var toHide = data.oldPanel;

		toHide
			.removeClass( "ui-accordion-content-active" )
			.prev()
				.removeClass( "ui-corner-top" )
				.addClass( "ui-corner-all" );

		// Work around for rendering bug in IE (#5421)
		if ( toHide.length ) {
			toHide.parent()[ 0 ].className = toHide.parent()[ 0 ].className;
		}
		this._trigger( "activate", null, data );
	}
});


/*!
 * jQuery UI Menu 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/menu/
 */


var menu = $.widget( "ui.menu", {
	version: "1.11.4",
	defaultElement: "<ul>",
	delay: 300,
	options: {
		icons: {
			submenu: "ui-icon-carat-1-e"
		},
		items: "> *",
		menus: "ul",
		position: {
			my: "left-1 top",
			at: "right top"
		},
		role: "menu",

		// callbacks
		blur: null,
		focus: null,
		select: null
	},

	_create: function() {
		this.activeMenu = this.element;

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.element
			.uniqueId()
			.addClass( "ui-menu ui-widget ui-widget-content" )
			.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
			.attr({
				role: this.options.role,
				tabIndex: 0
			});

		if ( this.options.disabled ) {
			this.element
				.addClass( "ui-state-disabled" )
				.attr( "aria-disabled", "true" );
		}

		this._on({
			// Prevent focus from sticking to links inside menu after clicking
			// them (focus should always stay on UL during navigation).
			"mousedown .ui-menu-item": function( event ) {
				event.preventDefault();
			},
			"click .ui-menu-item": function( event ) {
				var target = $( event.target );
				if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) {
					this.select( event );

					// Only set the mouseHandled flag if the event will bubble, see #9469.
					if ( !event.isPropagationStopped() ) {
						this.mouseHandled = true;
					}

					// Open submenu on click
					if ( target.has( ".ui-menu" ).length ) {
						this.expand( event );
					} else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) {

						// Redirect focus to the menu
						this.element.trigger( "focus", [ true ] );

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": function( event ) {
				// Ignore mouse events while typeahead is active, see #10458.
				// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
				// is over an item in the menu
				if ( this.previousFilter ) {
					return;
				}
				var target = $( event.currentTarget );
				// Remove ui-state-active class from siblings of the newly focused menu item
				// to avoid a jump caused by adjacent elements both having a class with a border
				target.siblings( ".ui-state-active" ).removeClass( "ui-state-active" );
				this.focus( event, target );
			},
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {
				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this.element.find( this.options.items ).eq( 0 );

				if ( !keepActiveItem ) {
					this.focus( event, item );
				}
			},
			blur: function( event ) {
				this._delay(function() {
					if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
						this.collapseAll( event );
					}
				});
			},
			keydown: "_keydown"
		});

		this.refresh();

		// Clicks outside of a menu collapse any open menus
		this._on( this.document, {
			click: function( event ) {
				if ( this._closeOnDocumentClick( event ) ) {
					this.collapseAll( event );
				}

				// Reset the mouseHandled flag
				this.mouseHandled = false;
			}
		});
	},

	_destroy: function() {
		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeClass( "ui-menu ui-widget ui-widget-content ui-menu-icons ui-front" )
				.removeAttr( "role" )
				.removeAttr( "tabIndex" )
				.removeAttr( "aria-labelledby" )
				.removeAttr( "aria-expanded" )
				.removeAttr( "aria-hidden" )
				.removeAttr( "aria-disabled" )
				.removeUniqueId()
				.show();

		// Destroy menu items
		this.element.find( ".ui-menu-item" )
			.removeClass( "ui-menu-item" )
			.removeAttr( "role" )
			.removeAttr( "aria-disabled" )
			.removeUniqueId()
			.removeClass( "ui-state-hover" )
			.removeAttr( "tabIndex" )
			.removeAttr( "role" )
			.removeAttr( "aria-haspopup" )
			.children().each( function() {
				var elem = $( this );
				if ( elem.data( "ui-menu-submenu-carat" ) ) {
					elem.remove();
				}
			});

		// Destroy menu dividers
		this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
	},

	_keydown: function( event ) {
		var match, prev, character, skip,
			preventDefault = true;

		switch ( event.keyCode ) {
		case $.ui.keyCode.PAGE_UP:
			this.previousPage( event );
			break;
		case $.ui.keyCode.PAGE_DOWN:
			this.nextPage( event );
			break;
		case $.ui.keyCode.HOME:
			this._move( "first", "first", event );
			break;
		case $.ui.keyCode.END:
			this._move( "last", "last", event );
			break;
		case $.ui.keyCode.UP:
			this.previous( event );
			break;
		case $.ui.keyCode.DOWN:
			this.next( event );
			break;
		case $.ui.keyCode.LEFT:
			this.collapse( event );
			break;
		case $.ui.keyCode.RIGHT:
			if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
				this.expand( event );
			}
			break;
		case $.ui.keyCode.ENTER:
		case $.ui.keyCode.SPACE:
			this._activate( event );
			break;
		case $.ui.keyCode.ESCAPE:
			this.collapse( event );
			break;
		default:
			preventDefault = false;
			prev = this.previousFilter || "";
			character = String.fromCharCode( event.keyCode );
			skip = false;

			clearTimeout( this.filterTimer );

			if ( character === prev ) {
				skip = true;
			} else {
				character = prev + character;
			}

			match = this._filterMenuItems( character );
			match = skip && match.index( this.active.next() ) !== -1 ?
				this.active.nextAll( ".ui-menu-item" ) :
				match;

			// If no matches on the current filter, reset to the last character pressed
			// to move down the menu to the first item that starts with that character
			if ( !match.length ) {
				character = String.fromCharCode( event.keyCode );
				match = this._filterMenuItems( character );
			}

			if ( match.length ) {
				this.focus( event, match );
				this.previousFilter = character;
				this.filterTimer = this._delay(function() {
					delete this.previousFilter;
				}, 1000 );
			} else {
				delete this.previousFilter;
			}
		}

		if ( preventDefault ) {
			event.preventDefault();
		}
	},

	_activate: function( event ) {
		if ( !this.active.is( ".ui-state-disabled" ) ) {
			if ( this.active.is( "[aria-haspopup='true']" ) ) {
				this.expand( event );
			} else {
				this.select( event );
			}
		}
	},

	refresh: function() {
		var menus, items,
			that = this,
			icon = this.options.icons.submenu,
			submenus = this.element.find( this.options.menus );

		this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length );

		// Initialize nested menus
		submenus.filter( ":not(.ui-menu)" )
			.addClass( "ui-menu ui-widget ui-widget-content ui-front" )
			.hide()
			.attr({
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			})
			.each(function() {
				var menu = $( this ),
					item = menu.parent(),
					submenuCarat = $( "<span>" )
						.addClass( "ui-menu-icon ui-icon " + icon )
						.data( "ui-menu-submenu-carat", true );

				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCarat );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			});

		menus = submenus.add( this.element );
		items = menus.find( this.options.items );

		// Initialize menu-items containing spaces and/or dashes only as dividers
		items.not( ".ui-menu-item" ).each(function() {
			var item = $( this );
			if ( that._isDivider( item ) ) {
				item.addClass( "ui-widget-content ui-menu-divider" );
			}
		});

		// Don't refresh list items that are already adapted
		items.not( ".ui-menu-item, .ui-menu-divider" )
			.addClass( "ui-menu-item" )
			.uniqueId()
			.attr({
				tabIndex: -1,
				role: this._itemRole()
			});

		// Add aria-disabled attribute to any disabled menu item
		items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" );

		// If the active item has been removed, blur the menu
		if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
			this.blur();
		}
	},

	_itemRole: function() {
		return {
			menu: "menuitem",
			listbox: "option"
		}[ this.options.role ];
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.element.find( ".ui-menu-icon" )
				.removeClass( this.options.icons.submenu )
				.addClass( value.submenu );
		}
		if ( key === "disabled" ) {
			this.element
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
		}
		this._super( key, value );
	},

	focus: function( event, item ) {
		var nested, focused;
		this.blur( event, event && event.type === "focus" );

		this._scrollIntoView( item );

		this.active = item.first();
		focused = this.active.addClass( "ui-state-focus" ).removeClass( "ui-state-active" );
		// Only update aria-activedescendant if there's a role
		// otherwise we assume focus is managed elsewhere
		if ( this.options.role ) {
			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
		}

		// Highlight active parent menu item, if any
		this.active
			.parent()
			.closest( ".ui-menu-item" )
			.addClass( "ui-state-active" );

		if ( event && event.type === "keydown" ) {
			this._close();
		} else {
			this.timer = this._delay(function() {
				this._close();
			}, this.delay );
		}

		nested = item.children( ".ui-menu" );
		if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) {
			this._startOpening(nested);
		}
		this.activeMenu = item.parent();

		this._trigger( "focus", event, { item: item } );
	},

	_scrollIntoView: function( item ) {
		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
		if ( this._hasScroll() ) {
			borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
			paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
			scroll = this.activeMenu.scrollTop();
			elementHeight = this.activeMenu.height();
			itemHeight = item.outerHeight();

			if ( offset < 0 ) {
				this.activeMenu.scrollTop( scroll + offset );
			} else if ( offset + itemHeight > elementHeight ) {
				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
			}
		}
	},

	blur: function( event, fromFocus ) {
		if ( !fromFocus ) {
			clearTimeout( this.timer );
		}

		if ( !this.active ) {
			return;
		}

		this.active.removeClass( "ui-state-focus" );
		this.active = null;

		this._trigger( "blur", event, { item: this.active } );
	},

	_startOpening: function( submenu ) {
		clearTimeout( this.timer );

		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
		// shift in the submenu position when mousing over the carat icon
		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
			return;
		}

		this.timer = this._delay(function() {
			this._close();
			this._open( submenu );
		}, this.delay );
	},

	_open: function( submenu ) {
		var position = $.extend({
			of: this.active
		}, this.options.position );

		clearTimeout( this.timer );
		this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
			.hide()
			.attr( "aria-hidden", "true" );

		submenu
			.show()
			.removeAttr( "aria-hidden" )
			.attr( "aria-expanded", "true" )
			.position( position );
	},

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay(function() {
			// If we were passed an event, look for the submenu that contains the event
			var currentMenu = all ? this.element :
				$( event && event.target ).closest( this.element.find( ".ui-menu" ) );

			// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
			if ( !currentMenu.length ) {
				currentMenu = this.element;
			}

			this._close( currentMenu );

			this.blur( event );
			this.activeMenu = currentMenu;
		}, this.delay );
	},

	// With no arguments, closes the currently active menu - if nothing is active
	// it closes all menus.  If passed an argument, it will search for menus BELOW
	_close: function( startMenu ) {
		if ( !startMenu ) {
			startMenu = this.active ? this.active.parent() : this.element;
		}

		startMenu
			.find( ".ui-menu" )
				.hide()
				.attr( "aria-hidden", "true" )
				.attr( "aria-expanded", "false" )
			.end()
			.find( ".ui-state-active" ).not( ".ui-state-focus" )
				.removeClass( "ui-state-active" );
	},

	_closeOnDocumentClick: function( event ) {
		return !$( event.target ).closest( ".ui-menu" ).length;
	},

	_isDivider: function( item ) {

		// Match hyphen, em dash, en dash
		return !/[^\-\u2014\u2013\s]/.test( item.text() );
	},

	collapse: function( event ) {
		var newItem = this.active &&
			this.active.parent().closest( ".ui-menu-item", this.element );
		if ( newItem && newItem.length ) {
			this._close();
			this.focus( event, newItem );
		}
	},

	expand: function( event ) {
		var newItem = this.active &&
			this.active
				.children( ".ui-menu " )
				.find( this.options.items )
				.first();

		if ( newItem && newItem.length ) {
			this._open( newItem.parent() );

			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
			this._delay(function() {
				this.focus( event, newItem );
			});
		}
	},

	next: function( event ) {
		this._move( "next", "first", event );
	},

	previous: function( event ) {
		this._move( "prev", "last", event );
	},

	isFirstItem: function() {
		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
	},

	isLastItem: function() {
		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
	},

	_move: function( direction, filter, event ) {
		var next;
		if ( this.active ) {
			if ( direction === "first" || direction === "last" ) {
				next = this.active
					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
					.eq( -1 );
			} else {
				next = this.active
					[ direction + "All" ]( ".ui-menu-item" )
					.eq( 0 );
			}
		}
		if ( !next || !next.length || !this.active ) {
			next = this.activeMenu.find( this.options.items )[ filter ]();
		}

		this.focus( event, next );
	},

	nextPage: function( event ) {
		var item, base, height;

		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isLastItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.nextAll( ".ui-menu-item" ).each(function() {
				item = $( this );
				return item.offset().top - base - height < 0;
			});

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items )
				[ !this.active ? "first" : "last" ]() );
		}
	},

	previousPage: function( event ) {
		var item, base, height;
		if ( !this.active ) {
			this.next( event );
			return;
		}
		if ( this.isFirstItem() ) {
			return;
		}
		if ( this._hasScroll() ) {
			base = this.active.offset().top;
			height = this.element.height();
			this.active.prevAll( ".ui-menu-item" ).each(function() {
				item = $( this );
				return item.offset().top - base + height > 0;
			});

			this.focus( event, item );
		} else {
			this.focus( event, this.activeMenu.find( this.options.items ).first() );
		}
	},

	_hasScroll: function() {
		return this.element.outerHeight() < this.element.prop( "scrollHeight" );
	},

	select: function( event ) {
		// TODO: It should never be possible to not have an active item at this
		// point, but the tests don't trigger mouseenter before click.
		this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
		var ui = { item: this.active };
		if ( !this.active.has( ".ui-menu" ).length ) {
			this.collapseAll( event, true );
		}
		this._trigger( "select", event, ui );
	},

	_filterMenuItems: function(character) {
		var escapedCharacter = character.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ),
			regex = new RegExp( "^" + escapedCharacter, "i" );

		return this.activeMenu
			.find( this.options.items )

			// Only match on items, not dividers or other content (#10571)
			.filter( ".ui-menu-item" )
			.filter(function() {
				return regex.test( $.trim( $( this ).text() ) );
			});
	}
});


/*!
 * jQuery UI Autocomplete 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/autocomplete/
 */


$.widget( "ui.autocomplete", {
	version: "1.11.4",
	defaultElement: "<input>",
	options: {
		appendTo: null,
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	requestIndex: 0,
	pending: 0,

	_create: function() {
		// Some browsers only repeat keydown events, not keypress events,
		// so we use the suppressKeyPress flag to determine if we've already
		// handled the keydown event. #7269
		// Unfortunately the code for & in keypress is the same as the up arrow,
		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
		// events when we know the keydown event was used to modify the
		// search term. #7799
		var suppressKeyPress, suppressKeyPressRepeat, suppressInput,
			nodeName = this.element[ 0 ].nodeName.toLowerCase(),
			isTextarea = nodeName === "textarea",
			isInput = nodeName === "input";

		this.isMultiLine =
			// Textareas are always multi-line
			isTextarea ? true :
			// Inputs are always single-line, even if inside a contentEditable element
			// IE also treats inputs as contentEditable
			isInput ? false :
			// All other element types are determined by whether or not they're contentEditable
			this.element.prop( "isContentEditable" );

		this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ];
		this.isNewMenu = true;

		this.element
			.addClass( "ui-autocomplete-input" )
			.attr( "autocomplete", "off" );

		this._on( this.element, {
			keydown: function( event ) {
				if ( this.element.prop( "readOnly" ) ) {
					suppressKeyPress = true;
					suppressInput = true;
					suppressKeyPressRepeat = true;
					return;
				}

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:
					// when menu is open and has focus
					if ( this.menu.active ) {
						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );
						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;
					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

				// replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					this._keyEvent( "next", event );
					break;
				}
			},
			input: function( event ) {
				if ( suppressInput ) {
					suppressInput = false;
					event.preventDefault();
					return;
				}
				this._searchTimeout( event );
			},
			focus: function() {
				this.selectedItem = null;
				this.previous = this._value();
			},
			blur: function( event ) {
				if ( this.cancelBlur ) {
					delete this.cancelBlur;
					return;
				}

				clearTimeout( this.searching );
				this.close( event );
				this._change( event );
			}
		});

		this._initSource();
		this.menu = $( "<ul>" )
			.addClass( "ui-autocomplete ui-front" )
			.appendTo( this._appendTo() )
			.menu({
				// disable ARIA support, the live region takes care of that
				role: null
			})
			.hide()
			.menu( "instance" );

		this._on( this.menu.element, {
			mousedown: function( event ) {
				// prevent moving focus out of the text field
				event.preventDefault();

				// IE doesn't prevent moving focus even with event.preventDefault()
				// so we set a flag to know when we should ignore the blur event
				this.cancelBlur = true;
				this._delay(function() {
					delete this.cancelBlur;
				});

				// clicking on the scrollbar causes focus to shift to the body
				// but we can't detect a mouseup or a click immediately afterward
				// so we have to track the next mousedown and close the menu if
				// the user clicks somewhere outside of the autocomplete
				var menuElement = this.menu.element[ 0 ];
				if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
					this._delay(function() {
						var that = this;
						this.document.one( "mousedown", function( event ) {
							if ( event.target !== that.element[ 0 ] &&
									event.target !== menuElement &&
									!$.contains( menuElement, event.target ) ) {
								that.close();
							}
						});
					});
				}
			},
			menufocus: function( event, ui ) {
				var label, item;
				// support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

						this.document.one( "mousemove", function() {
							$( event.target ).trigger( event.originalEvent );
						});

						return;
					}
				}

				item = ui.item.data( "ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {
					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

				// Announce the value in the liveRegion
				label = ui.item.attr( "aria-label" ) || item.value;
				if ( label && $.trim( label ).length ) {
					this.liveRegion.children().hide();
					$( "<div>" ).text( label ).appendTo( this.liveRegion );
				}
			},
			menuselect: function( event, ui ) {
				var item = ui.item.data( "ui-autocomplete-item" ),
					previous = this.previous;

				// only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) {
					this.element.focus();
					this.previous = previous;
					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay(function() {
						this.previous = previous;
						this.selectedItem = item;
					});
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}
				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

				this.close( event );
				this.selectedItem = item;
			}
		});

		this.liveRegion = $( "<span>", {
				role: "status",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			})
			.addClass( "ui-helper-hidden-accessible" )
			.appendTo( this.document[ 0 ].body );

		// turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		});
	},

	_destroy: function() {
		clearTimeout( this.searching );
		this.element
			.removeClass( "ui-autocomplete-input" )
			.removeAttr( "autocomplete" );
		this.menu.element.remove();
		this.liveRegion.remove();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( this._appendTo() );
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_initSource: function() {
		var array, url,
			that = this;
		if ( $.isArray( this.options.source ) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter( array, request.term ) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( that.xhr ) {
					that.xhr.abort();
				}
				that.xhr = $.ajax({
					url: url,
					data: request,
					dataType: "json",
					success: function( data ) {
						response( data );
					},
					error: function() {
						response([]);
					}
				});
			};
		} else {
			this.source = this.options.source;
		}
	},

	_searchTimeout: function( event ) {
		clearTimeout( this.searching );
		this.searching = this._delay(function() {

			// Search if the value has changed, or if the user retypes the same value (see #7434)
			var equalValues = this.term === this._value(),
				menuVisible = this.menu.element.is( ":visible" ),
				modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;

			if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) {
				this.selectedItem = null;
				this.search( null, event );
			}
		}, this.options.delay );
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this.element.addClass( "ui-autocomplete-loading" );
		this.cancelSearch = false;

		this.source( { term: value }, this._response() );
	},

	_response: function() {
		var index = ++this.requestIndex;

		return $.proxy(function( content ) {
			if ( index === this.requestIndex ) {
				this.__response( content );
			}

			this.pending--;
			if ( !this.pending ) {
				this.element.removeClass( "ui-autocomplete-loading" );
			}
		}, this );
	},

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {
			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

	close: function( event ) {
		this.cancelSearch = true;
		this._close( event );
	},

	_close: function( event ) {
		if ( this.menu.element.is( ":visible" ) ) {
			this.menu.element.hide();
			this.menu.blur();
			this.isNewMenu = true;
			this._trigger( "close", event );
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {
		// assume all items have the right format when the first item is complete
		if ( items.length && items[ 0 ].label && items[ 0 ].value ) {
			return items;
		}
		return $.map( items, function( item ) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend( {}, item, {
				label: item.label || item.value,
				value: item.value || item.label
			});
		});
	},

	_suggest: function( items ) {
		var ul = this.menu.element.empty();
		this._renderMenu( ul, items );
		this.isNewMenu = true;
		this.menu.refresh();

		// size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend({
			of: this.element
		}, this.options.position ) );

		if ( this.options.autoFocus ) {
			this.menu.next();
		}
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(
			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var that = this;
		$.each( items, function( index, item ) {
			that._renderItemData( ul, item );
		});
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
	},

	_renderItem: function( ul, item ) {
		return $( "<li>" ).text( item.label ).appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is( ":visible" ) ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
				this.menu.isLastItem() && /^next/.test( direction ) ) {

			if ( !this.isMultiLine ) {
				this._value( this.term );
			}

			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function() {
		return this.valueMethod.apply( this.element, arguments );
	},

	_keyEvent: function( keyEvent, event ) {
		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
			this._move( keyEvent, event );

			// prevents moving cursor to beginning/end of the text field in some browsers
			event.preventDefault();
		}
	}
});

$.extend( $.ui.autocomplete, {
	escapeRegex: function( value ) {
		return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
	},
	filter: function( array, term ) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" );
		return $.grep( array, function( value ) {
			return matcher.test( value.label || value.value || value );
		});
	}
});

// live region extension, adding a `messages` option
// NOTE: This is an experimental API. We are still investigating
// a full solution for string manipulation and internationalization.
$.widget( "ui.autocomplete", $.ui.autocomplete, {
	options: {
		messages: {
			noResults: "No search results.",
			results: function( amount ) {
				return amount + ( amount > 1 ? " results are" : " result is" ) +
					" available, use up and down arrow keys to navigate.";
			}
		}
	},

	__response: function( content ) {
		var message;
		this._superApply( arguments );
		if ( this.options.disabled || this.cancelSearch ) {
			return;
		}
		if ( content && content.length ) {
			message = this.options.messages.results( content.length );
		} else {
			message = this.options.messages.noResults;
		}
		this.liveRegion.children().hide();
		$( "<div>" ).text( message ).appendTo( this.liveRegion );
	}
});

var autocomplete = $.ui.autocomplete;


/*!
 * jQuery UI Button 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/button/
 */


var lastActive,
	baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
	typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
	formResetHandler = function() {
		var form = $( this );
		setTimeout(function() {
			form.find( ":ui-button" ).button( "refresh" );
		}, 1 );
	},
	radioGroup = function( radio ) {
		var name = radio.name,
			form = radio.form,
			radios = $( [] );
		if ( name ) {
			name = name.replace( /'/g, "\\'" );
			if ( form ) {
				radios = $( form ).find( "[name='" + name + "'][type=radio]" );
			} else {
				radios = $( "[name='" + name + "'][type=radio]", radio.ownerDocument )
					.filter(function() {
						return !this.form;
					});
			}
		}
		return radios;
	};

$.widget( "ui.button", {
	version: "1.11.4",
	defaultElement: "<button>",
	options: {
		disabled: null,
		text: true,
		label: null,
		icons: {
			primary: null,
			secondary: null
		}
	},
	_create: function() {
		this.element.closest( "form" )
			.unbind( "reset" + this.eventNamespace )
			.bind( "reset" + this.eventNamespace, formResetHandler );

		if ( typeof this.options.disabled !== "boolean" ) {
			this.options.disabled = !!this.element.prop( "disabled" );
		} else {
			this.element.prop( "disabled", this.options.disabled );
		}

		this._determineButtonType();
		this.hasTitle = !!this.buttonElement.attr( "title" );

		var that = this,
			options = this.options,
			toggleButton = this.type === "checkbox" || this.type === "radio",
			activeClass = !toggleButton ? "ui-state-active" : "";

		if ( options.label === null ) {
			options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
		}

		this._hoverable( this.buttonElement );

		this.buttonElement
			.addClass( baseClasses )
			.attr( "role", "button" )
			.bind( "mouseenter" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return;
				}
				if ( this === lastActive ) {
					$( this ).addClass( "ui-state-active" );
				}
			})
			.bind( "mouseleave" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return;
				}
				$( this ).removeClass( activeClass );
			})
			.bind( "click" + this.eventNamespace, function( event ) {
				if ( options.disabled ) {
					event.preventDefault();
					event.stopImmediatePropagation();
				}
			});

		// Can't use _focusable() because the element that receives focus
		// and the element that gets the ui-state-focus class are different
		this._on({
			focus: function() {
				this.buttonElement.addClass( "ui-state-focus" );
			},
			blur: function() {
				this.buttonElement.removeClass( "ui-state-focus" );
			}
		});

		if ( toggleButton ) {
			this.element.bind( "change" + this.eventNamespace, function() {
				that.refresh();
			});
		}

		if ( this.type === "checkbox" ) {
			this.buttonElement.bind( "click" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return false;
				}
			});
		} else if ( this.type === "radio" ) {
			this.buttonElement.bind( "click" + this.eventNamespace, function() {
				if ( options.disabled ) {
					return false;
				}
				$( this ).addClass( "ui-state-active" );
				that.buttonElement.attr( "aria-pressed", "true" );

				var radio = that.element[ 0 ];
				radioGroup( radio )
					.not( radio )
					.map(function() {
						return $( this ).button( "widget" )[ 0 ];
					})
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", "false" );
			});
		} else {
			this.buttonElement
				.bind( "mousedown" + this.eventNamespace, function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).addClass( "ui-state-active" );
					lastActive = this;
					that.document.one( "mouseup", function() {
						lastActive = null;
					});
				})
				.bind( "mouseup" + this.eventNamespace, function() {
					if ( options.disabled ) {
						return false;
					}
					$( this ).removeClass( "ui-state-active" );
				})
				.bind( "keydown" + this.eventNamespace, function(event) {
					if ( options.disabled ) {
						return false;
					}
					if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
						$( this ).addClass( "ui-state-active" );
					}
				})
				// see #8559, we bind to blur here in case the button element loses
				// focus between keydown and keyup, it would be left in an "active" state
				.bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() {
					$( this ).removeClass( "ui-state-active" );
				});

			if ( this.buttonElement.is("a") ) {
				this.buttonElement.keyup(function(event) {
					if ( event.keyCode === $.ui.keyCode.SPACE ) {
						// TODO pass through original event correctly (just as 2nd argument doesn't work)
						$( this ).click();
					}
				});
			}
		}

		this._setOption( "disabled", options.disabled );
		this._resetButton();
	},

	_determineButtonType: function() {
		var ancestor, labelSelector, checked;

		if ( this.element.is("[type=checkbox]") ) {
			this.type = "checkbox";
		} else if ( this.element.is("[type=radio]") ) {
			this.type = "radio";
		} else if ( this.element.is("input") ) {
			this.type = "input";
		} else {
			this.type = "button";
		}

		if ( this.type === "checkbox" || this.type === "radio" ) {
			// we don't search against the document in case the element
			// is disconnected from the DOM
			ancestor = this.element.parents().last();
			labelSelector = "label[for='" + this.element.attr("id") + "']";
			this.buttonElement = ancestor.find( labelSelector );
			if ( !this.buttonElement.length ) {
				ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
				this.buttonElement = ancestor.filter( labelSelector );
				if ( !this.buttonElement.length ) {
					this.buttonElement = ancestor.find( labelSelector );
				}
			}
			this.element.addClass( "ui-helper-hidden-accessible" );

			checked = this.element.is( ":checked" );
			if ( checked ) {
				this.buttonElement.addClass( "ui-state-active" );
			}
			this.buttonElement.prop( "aria-pressed", checked );
		} else {
			this.buttonElement = this.element;
		}
	},

	widget: function() {
		return this.buttonElement;
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-helper-hidden-accessible" );
		this.buttonElement
			.removeClass( baseClasses + " ui-state-active " + typeClasses )
			.removeAttr( "role" )
			.removeAttr( "aria-pressed" )
			.html( this.buttonElement.find(".ui-button-text").html() );

		if ( !this.hasTitle ) {
			this.buttonElement.removeAttr( "title" );
		}
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "disabled" ) {
			this.widget().toggleClass( "ui-state-disabled", !!value );
			this.element.prop( "disabled", !!value );
			if ( value ) {
				if ( this.type === "checkbox" || this.type === "radio" ) {
					this.buttonElement.removeClass( "ui-state-focus" );
				} else {
					this.buttonElement.removeClass( "ui-state-focus ui-state-active" );
				}
			}
			return;
		}
		this._resetButton();
	},

	refresh: function() {
		//See #8237 & #8828
		var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );

		if ( isDisabled !== this.options.disabled ) {
			this._setOption( "disabled", isDisabled );
		}
		if ( this.type === "radio" ) {
			radioGroup( this.element[0] ).each(function() {
				if ( $( this ).is( ":checked" ) ) {
					$( this ).button( "widget" )
						.addClass( "ui-state-active" )
						.attr( "aria-pressed", "true" );
				} else {
					$( this ).button( "widget" )
						.removeClass( "ui-state-active" )
						.attr( "aria-pressed", "false" );
				}
			});
		} else if ( this.type === "checkbox" ) {
			if ( this.element.is( ":checked" ) ) {
				this.buttonElement
					.addClass( "ui-state-active" )
					.attr( "aria-pressed", "true" );
			} else {
				this.buttonElement
					.removeClass( "ui-state-active" )
					.attr( "aria-pressed", "false" );
			}
		}
	},

	_resetButton: function() {
		if ( this.type === "input" ) {
			if ( this.options.label ) {
				this.element.val( this.options.label );
			}
			return;
		}
		var buttonElement = this.buttonElement.removeClass( typeClasses ),
			buttonText = $( "<span></span>", this.document[0] )
				.addClass( "ui-button-text" )
				.html( this.options.label )
				.appendTo( buttonElement.empty() )
				.text(),
			icons = this.options.icons,
			multipleIcons = icons.primary && icons.secondary,
			buttonClasses = [];

		if ( icons.primary || icons.secondary ) {
			if ( this.options.text ) {
				buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
			}

			if ( icons.primary ) {
				buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
			}

			if ( icons.secondary ) {
				buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
			}

			if ( !this.options.text ) {
				buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );

				if ( !this.hasTitle ) {
					buttonElement.attr( "title", $.trim( buttonText ) );
				}
			}
		} else {
			buttonClasses.push( "ui-button-text-only" );
		}
		buttonElement.addClass( buttonClasses.join( " " ) );
	}
});

$.widget( "ui.buttonset", {
	version: "1.11.4",
	options: {
		items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)"
	},

	_create: function() {
		this.element.addClass( "ui-buttonset" );
	},

	_init: function() {
		this.refresh();
	},

	_setOption: function( key, value ) {
		if ( key === "disabled" ) {
			this.buttons.button( "option", key, value );
		}

		this._super( key, value );
	},

	refresh: function() {
		var rtl = this.element.css( "direction" ) === "rtl",
			allButtons = this.element.find( this.options.items ),
			existingButtons = allButtons.filter( ":ui-button" );

		// Initialize new buttons
		allButtons.not( ":ui-button" ).button();

		// Refresh existing buttons
		existingButtons.button( "refresh" );

		this.buttons = allButtons
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
				.filter( ":first" )
					.addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
				.end()
				.filter( ":last" )
					.addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
				.end()
			.end();
	},

	_destroy: function() {
		this.element.removeClass( "ui-buttonset" );
		this.buttons
			.map(function() {
				return $( this ).button( "widget" )[ 0 ];
			})
				.removeClass( "ui-corner-left ui-corner-right" )
			.end()
			.button( "destroy" );
	}
});

var button = $.ui.button;


/*!
 * jQuery UI Datepicker 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/datepicker/
 */


$.extend($.ui, { datepicker: { version: "1.11.4" } });

var datepicker_instActive;

function datepicker_getZindex( elem ) {
	var position, value;
	while ( elem.length && elem[ 0 ] !== document ) {
		// Ignore z-index if position is set to a value where z-index is ignored by the browser
		// This makes behavior of this function consistent across browsers
		// WebKit always returns auto if the element is positioned
		position = elem.css( "position" );
		if ( position === "absolute" || position === "relative" || position === "fixed" ) {
			// IE returns 0 when zIndex is not specified
			// other browsers return a string
			// we ignore the case of nested elements with an explicit value of 0
			// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
			value = parseInt( elem.css( "zIndex" ), 10 );
			if ( !isNaN( value ) && value !== 0 ) {
				return value;
			}
		}
		elem = elem.parent();
	}

	return 0;
}
/* Date picker manager.
   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
   Settings for (groups of) date pickers are maintained in an instance object,
   allowing multiple different settings on the same page. */

function Datepicker() {
	this._curInst = null; // The current instance in use
	this._keyEvent = false; // If the last event was a key event
	this._disabledInputs = []; // List of date picker inputs that have been disabled
	this._datepickerShowing = false; // True if the popup picker is showing , false if not
	this._inDialog = false; // True if showing within a "dialog", false if not
	this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
	this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
	this._appendClass = "ui-datepicker-append"; // The name of the append marker class
	this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
	this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
	this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
	this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
	this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
	this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
	this.regional = []; // Available regional settings, indexed by language code
	this.regional[""] = { // Default regional settings
		closeText: "Done", // Display text for close link
		prevText: "Prev", // Display text for previous month link
		nextText: "Next", // Display text for next month link
		currentText: "Today", // Display text for current month link
		monthNames: ["January","February","March","April","May","June",
			"July","August","September","October","November","December"], // Names of months for drop-down and formatting
		monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
		dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
		dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
		dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
		weekHeader: "Wk", // Column header for week of the year
		dateFormat: "mm/dd/yy", // See format options on parseDate
		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
		isRTL: false, // True if right-to-left language, false if left-to-right
		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
		yearSuffix: "" // Additional text to append to the year in the month headers
	};
	this._defaults = { // Global defaults for all the date picker instances
		showOn: "focus", // "focus" for popup on focus,
			// "button" for trigger button, or "both" for either
		showAnim: "fadeIn", // Name of jQuery animation for popup
		showOptions: {}, // Options for enhanced animations
		defaultDate: null, // Used when field is blank: actual date,
			// +/-number for offset from today, null for today
		appendText: "", // Display text following the input box, e.g. showing the format
		buttonText: "...", // Text for trigger button
		buttonImage: "", // URL for trigger button image
		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
		hideIfNoPrevNext: false, // True to hide next/previous month links
			// if not applicable, false to just disable them
		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
		gotoCurrent: false, // True if today link goes back to current selection instead
		changeMonth: false, // True if month can be selected directly, false if only prev/next
		changeYear: false, // True if year can be selected directly, false if only prev/next
		yearRange: "c-10:c+10", // Range of years to display in drop-down,
			// either relative to today's year (-nn:+nn), relative to currently displayed year
			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
		showOtherMonths: false, // True to show dates in other months, false to leave blank
		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
		showWeek: false, // True to show week of the year, false to not show it
		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
			// takes a Date and returns the number of the week for it
		shortYearCutoff: "+10", // Short year values < this are in the current century,
			// > this are in the previous century,
			// string value starting with "+" for current year + value
		minDate: null, // The earliest selectable date, or null for no limit
		maxDate: null, // The latest selectable date, or null for no limit
		duration: "fast", // Duration of display/closure
		beforeShowDay: null, // Function that takes a date and returns an array with
			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
		beforeShow: null, // Function that takes an input field and
			// returns a set of custom settings for the date picker
		onSelect: null, // Define a callback function when a date is selected
		onChangeMonthYear: null, // Define a callback function when the month or year is changed
		onClose: null, // Define a callback function when the datepicker is closed
		numberOfMonths: 1, // Number of months to show at a time
		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
		stepMonths: 1, // Number of months to step back/forward
		stepBigMonths: 12, // Number of months to step back/forward for the big links
		altField: "", // Selector for an alternate field to store selected dates into
		altFormat: "", // The date format to use for the alternate field
		constrainInput: true, // The input is constrained by the current date format
		showButtonPanel: false, // True to show button panel, false to not show it
		autoSize: false, // True to size the input for the date format, false to leave as is
		disabled: false // The initial disabled state
	};
	$.extend(this._defaults, this.regional[""]);
	this.regional.en = $.extend( true, {}, this.regional[ "" ]);
	this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
	this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}

$.extend(Datepicker.prototype, {
	/* Class name added to elements to indicate already configured with a date picker. */
	markerClassName: "hasDatepicker",

	//Keep track of the maximum number of rows displayed (see #7043)
	maxRows: 4,

	// TODO rename to "widget" when switching to widget factory
	_widgetDatepicker: function() {
		return this.dpDiv;
	},

	/* Override the default settings for all instances of the date picker.
	 * @param  settings  object - the new settings to use as defaults (anonymous object)
	 * @return the manager object
	 */
	setDefaults: function(settings) {
		datepicker_extendRemove(this._defaults, settings || {});
		return this;
	},

	/* Attach the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 * @param  settings  object - the new settings to use for this date picker instance (anonymous)
	 */
	_attachDatepicker: function(target, settings) {
		var nodeName, inline, inst;
		nodeName = target.nodeName.toLowerCase();
		inline = (nodeName === "div" || nodeName === "span");
		if (!target.id) {
			this.uuid += 1;
			target.id = "dp" + this.uuid;
		}
		inst = this._newInst($(target), inline);
		inst.settings = $.extend({}, settings || {});
		if (nodeName === "input") {
			this._connectDatepicker(target, inst);
		} else if (inline) {
			this._inlineDatepicker(target, inst);
		}
	},

	/* Create a new instance object. */
	_newInst: function(target, inline) {
		var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
		return {id: id, input: target, // associated target
			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
			drawMonth: 0, drawYear: 0, // month being drawn
			inline: inline, // is datepicker inline or not
			dpDiv: (!inline ? this.dpDiv : // presentation div
			datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
	},

	/* Attach the date picker to an input field. */
	_connectDatepicker: function(target, inst) {
		var input = $(target);
		inst.append = $([]);
		inst.trigger = $([]);
		if (input.hasClass(this.markerClassName)) {
			return;
		}
		this._attachments(input, inst);
		input.addClass(this.markerClassName).keydown(this._doKeyDown).
			keypress(this._doKeyPress).keyup(this._doKeyUp);
		this._autoSize(inst);
		$.data(target, "datepicker", inst);
		//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
		if( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
	},

	/* Make attachments based on settings. */
	_attachments: function(input, inst) {
		var showOn, buttonText, buttonImage,
			appendText = this._get(inst, "appendText"),
			isRTL = this._get(inst, "isRTL");

		if (inst.append) {
			inst.append.remove();
		}
		if (appendText) {
			inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
			input[isRTL ? "before" : "after"](inst.append);
		}

		input.unbind("focus", this._showDatepicker);

		if (inst.trigger) {
			inst.trigger.remove();
		}

		showOn = this._get(inst, "showOn");
		if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
			input.focus(this._showDatepicker);
		}
		if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
			buttonText = this._get(inst, "buttonText");
			buttonImage = this._get(inst, "buttonImage");
			inst.trigger = $(this._get(inst, "buttonImageOnly") ?
				$("<img/>").addClass(this._triggerClass).
					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
				$("<button type='button'></button>").addClass(this._triggerClass).
					html(!buttonImage ? buttonText : $("<img/>").attr(
					{ src:buttonImage, alt:buttonText, title:buttonText })));
			input[isRTL ? "before" : "after"](inst.trigger);
			inst.trigger.click(function() {
				if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
					$.datepicker._hideDatepicker();
				} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
					$.datepicker._hideDatepicker();
					$.datepicker._showDatepicker(input[0]);
				} else {
					$.datepicker._showDatepicker(input[0]);
				}
				return false;
			});
		}
	},

	/* Apply the maximum length for the date format. */
	_autoSize: function(inst) {
		if (this._get(inst, "autoSize") && !inst.inline) {
			var findMax, max, maxI, i,
				date = new Date(2009, 12 - 1, 20), // Ensure double digits
				dateFormat = this._get(inst, "dateFormat");

			if (dateFormat.match(/[DM]/)) {
				findMax = function(names) {
					max = 0;
					maxI = 0;
					for (i = 0; i < names.length; i++) {
						if (names[i].length > max) {
							max = names[i].length;
							maxI = i;
						}
					}
					return maxI;
				};
				date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
					"monthNames" : "monthNamesShort"))));
				date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
					"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
			}
			inst.input.attr("size", this._formatDate(inst, date).length);
		}
	},

	/* Attach an inline date picker to a div. */
	_inlineDatepicker: function(target, inst) {
		var divSpan = $(target);
		if (divSpan.hasClass(this.markerClassName)) {
			return;
		}
		divSpan.addClass(this.markerClassName).append(inst.dpDiv);
		$.data(target, "datepicker", inst);
		this._setDate(inst, this._getDefaultDate(inst), true);
		this._updateDatepicker(inst);
		this._updateAlternate(inst);
		//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
		if( inst.settings.disabled ) {
			this._disableDatepicker( target );
		}
		// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
		// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
		inst.dpDiv.css( "display", "block" );
	},

	/* Pop-up the date picker in a "dialog" box.
	 * @param  input element - ignored
	 * @param  date	string or Date - the initial date to display
	 * @param  onSelect  function - the function to call when a date is selected
	 * @param  settings  object - update the dialog date picker instance's settings (anonymous object)
	 * @param  pos int[2] - coordinates for the dialog's position within the screen or
	 *					event - with x/y coordinates or
	 *					leave empty for default (screen centre)
	 * @return the manager object
	 */
	_dialogDatepicker: function(input, date, onSelect, settings, pos) {
		var id, browserWidth, browserHeight, scrollX, scrollY,
			inst = this._dialogInst; // internal instance

		if (!inst) {
			this.uuid += 1;
			id = "dp" + this.uuid;
			this._dialogInput = $("<input type='text' id='" + id +
				"' style='position: absolute; top: -100px; width: 0px;'/>");
			this._dialogInput.keydown(this._doKeyDown);
			$("body").append(this._dialogInput);
			inst = this._dialogInst = this._newInst(this._dialogInput, false);
			inst.settings = {};
			$.data(this._dialogInput[0], "datepicker", inst);
		}
		datepicker_extendRemove(inst.settings, settings || {});
		date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
		this._dialogInput.val(date);

		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
		if (!this._pos) {
			browserWidth = document.documentElement.clientWidth;
			browserHeight = document.documentElement.clientHeight;
			scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
			scrollY = document.documentElement.scrollTop || document.body.scrollTop;
			this._pos = // should use actual width/height below
				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
		}

		// move input on screen for focus, but hidden behind dialog
		this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
		inst.settings.onSelect = onSelect;
		this._inDialog = true;
		this.dpDiv.addClass(this._dialogClass);
		this._showDatepicker(this._dialogInput[0]);
		if ($.blockUI) {
			$.blockUI(this.dpDiv);
		}
		$.data(this._dialogInput[0], "datepicker", inst);
		return this;
	},

	/* Detach a datepicker from its control.
	 * @param  target	element - the target input field or division or span
	 */
	_destroyDatepicker: function(target) {
		var nodeName,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		$.removeData(target, "datepicker");
		if (nodeName === "input") {
			inst.append.remove();
			inst.trigger.remove();
			$target.removeClass(this.markerClassName).
				unbind("focus", this._showDatepicker).
				unbind("keydown", this._doKeyDown).
				unbind("keypress", this._doKeyPress).
				unbind("keyup", this._doKeyUp);
		} else if (nodeName === "div" || nodeName === "span") {
			$target.removeClass(this.markerClassName).empty();
		}

		if ( datepicker_instActive === inst ) {
			datepicker_instActive = null;
		}
	},

	/* Enable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_enableDatepicker: function(target) {
		var nodeName, inline,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if (nodeName === "input") {
			target.disabled = false;
			inst.trigger.filter("button").
				each(function() { this.disabled = false; }).end().
				filter("img").css({opacity: "1.0", cursor: ""});
		} else if (nodeName === "div" || nodeName === "span") {
			inline = $target.children("." + this._inlineClass);
			inline.children().removeClass("ui-state-disabled");
			inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
				prop("disabled", false);
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value === target ? null : value); }); // delete entry
	},

	/* Disable the date picker to a jQuery selection.
	 * @param  target	element - the target input field or division or span
	 */
	_disableDatepicker: function(target) {
		var nodeName, inline,
			$target = $(target),
			inst = $.data(target, "datepicker");

		if (!$target.hasClass(this.markerClassName)) {
			return;
		}

		nodeName = target.nodeName.toLowerCase();
		if (nodeName === "input") {
			target.disabled = true;
			inst.trigger.filter("button").
				each(function() { this.disabled = true; }).end().
				filter("img").css({opacity: "0.5", cursor: "default"});
		} else if (nodeName === "div" || nodeName === "span") {
			inline = $target.children("." + this._inlineClass);
			inline.children().addClass("ui-state-disabled");
			inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
				prop("disabled", true);
		}
		this._disabledInputs = $.map(this._disabledInputs,
			function(value) { return (value === target ? null : value); }); // delete entry
		this._disabledInputs[this._disabledInputs.length] = target;
	},

	/* Is the first field in a jQuery collection disabled as a datepicker?
	 * @param  target	element - the target input field or division or span
	 * @return boolean - true if disabled, false if enabled
	 */
	_isDisabledDatepicker: function(target) {
		if (!target) {
			return false;
		}
		for (var i = 0; i < this._disabledInputs.length; i++) {
			if (this._disabledInputs[i] === target) {
				return true;
			}
		}
		return false;
	},

	/* Retrieve the instance data for the target control.
	 * @param  target  element - the target input field or division or span
	 * @return  object - the associated instance data
	 * @throws  error if a jQuery problem getting data
	 */
	_getInst: function(target) {
		try {
			return $.data(target, "datepicker");
		}
		catch (err) {
			throw "Missing instance data for this datepicker";
		}
	},

	/* Update or retrieve the settings for a date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 * @param  name	object - the new settings to update or
	 *				string - the name of the setting to change or retrieve,
	 *				when retrieving also "all" for all instance settings or
	 *				"defaults" for all global defaults
	 * @param  value   any - the new value for the setting
	 *				(omit if above is an object or to retrieve a value)
	 */
	_optionDatepicker: function(target, name, value) {
		var settings, date, minDate, maxDate,
			inst = this._getInst(target);

		if (arguments.length === 2 && typeof name === "string") {
			return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
				(inst ? (name === "all" ? $.extend({}, inst.settings) :
				this._get(inst, name)) : null));
		}

		settings = name || {};
		if (typeof name === "string") {
			settings = {};
			settings[name] = value;
		}

		if (inst) {
			if (this._curInst === inst) {
				this._hideDatepicker();
			}

			date = this._getDateDatepicker(target, true);
			minDate = this._getMinMaxDate(inst, "min");
			maxDate = this._getMinMaxDate(inst, "max");
			datepicker_extendRemove(inst.settings, settings);
			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
			if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
				inst.settings.minDate = this._formatDate(inst, minDate);
			}
			if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
				inst.settings.maxDate = this._formatDate(inst, maxDate);
			}
			if ( "disabled" in settings ) {
				if ( settings.disabled ) {
					this._disableDatepicker(target);
				} else {
					this._enableDatepicker(target);
				}
			}
			this._attachments($(target), inst);
			this._autoSize(inst);
			this._setDate(inst, date);
			this._updateAlternate(inst);
			this._updateDatepicker(inst);
		}
	},

	// change method deprecated
	_changeDatepicker: function(target, name, value) {
		this._optionDatepicker(target, name, value);
	},

	/* Redraw the date picker attached to an input field or division.
	 * @param  target  element - the target input field or division or span
	 */
	_refreshDatepicker: function(target) {
		var inst = this._getInst(target);
		if (inst) {
			this._updateDatepicker(inst);
		}
	},

	/* Set the dates for a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  date	Date - the new date
	 */
	_setDateDatepicker: function(target, date) {
		var inst = this._getInst(target);
		if (inst) {
			this._setDate(inst, date);
			this._updateDatepicker(inst);
			this._updateAlternate(inst);
		}
	},

	/* Get the date(s) for the first entry in a jQuery selection.
	 * @param  target element - the target input field or division or span
	 * @param  noDefault boolean - true if no default date is to be used
	 * @return Date - the current date
	 */
	_getDateDatepicker: function(target, noDefault) {
		var inst = this._getInst(target);
		if (inst && !inst.inline) {
			this._setDateFromField(inst, noDefault);
		}
		return (inst ? this._getDate(inst) : null);
	},

	/* Handle keystrokes. */
	_doKeyDown: function(event) {
		var onSelect, dateStr, sel,
			inst = $.datepicker._getInst(event.target),
			handled = true,
			isRTL = inst.dpDiv.is(".ui-datepicker-rtl");

		inst._keyEvent = true;
		if ($.datepicker._datepickerShowing) {
			switch (event.keyCode) {
				case 9: $.datepicker._hideDatepicker();
						handled = false;
						break; // hide on tab out
				case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
									$.datepicker._currentClass + ")", inst.dpDiv);
						if (sel[0]) {
							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
						}

						onSelect = $.datepicker._get(inst, "onSelect");
						if (onSelect) {
							dateStr = $.datepicker._formatDate(inst);

							// trigger custom callback
							onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
						} else {
							$.datepicker._hideDatepicker();
						}

						return false; // don't submit the form
				case 27: $.datepicker._hideDatepicker();
						break; // hide on escape
				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							-$.datepicker._get(inst, "stepBigMonths") :
							-$.datepicker._get(inst, "stepMonths")), "M");
						break; // previous month/year on page up/+ ctrl
				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
							+$.datepicker._get(inst, "stepBigMonths") :
							+$.datepicker._get(inst, "stepMonths")), "M");
						break; // next month/year on page down/+ ctrl
				case 35: if (event.ctrlKey || event.metaKey) {
							$.datepicker._clearDate(event.target);
						}
						handled = event.ctrlKey || event.metaKey;
						break; // clear on ctrl or command +end
				case 36: if (event.ctrlKey || event.metaKey) {
							$.datepicker._gotoToday(event.target);
						}
						handled = event.ctrlKey || event.metaKey;
						break; // current on ctrl or command +home
				case 37: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
						}
						handled = event.ctrlKey || event.metaKey;
						// -1 day on ctrl or command +left
						if (event.originalEvent.altKey) {
							$.datepicker._adjustDate(event.target, (event.ctrlKey ?
								-$.datepicker._get(inst, "stepBigMonths") :
								-$.datepicker._get(inst, "stepMonths")), "M");
						}
						// next month/year on alt +left on Mac
						break;
				case 38: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, -7, "D");
						}
						handled = event.ctrlKey || event.metaKey;
						break; // -1 week on ctrl or command +up
				case 39: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
						}
						handled = event.ctrlKey || event.metaKey;
						// +1 day on ctrl or command +right
						if (event.originalEvent.altKey) {
							$.datepicker._adjustDate(event.target, (event.ctrlKey ?
								+$.datepicker._get(inst, "stepBigMonths") :
								+$.datepicker._get(inst, "stepMonths")), "M");
						}
						// next month/year on alt +right
						break;
				case 40: if (event.ctrlKey || event.metaKey) {
							$.datepicker._adjustDate(event.target, +7, "D");
						}
						handled = event.ctrlKey || event.metaKey;
						break; // +1 week on ctrl or command +down
				default: handled = false;
			}
		} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
			$.datepicker._showDatepicker(this);
		} else {
			handled = false;
		}

		if (handled) {
			event.preventDefault();
			event.stopPropagation();
		}
	},

	/* Filter entered characters - based on date format. */
	_doKeyPress: function(event) {
		var chars, chr,
			inst = $.datepicker._getInst(event.target);

		if ($.datepicker._get(inst, "constrainInput")) {
			chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
			chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
			return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
		}
	},

	/* Synchronise manual entry and field/alternate field. */
	_doKeyUp: function(event) {
		var date,
			inst = $.datepicker._getInst(event.target);

		if (inst.input.val() !== inst.lastVal) {
			try {
				date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
					(inst.input ? inst.input.val() : null),
					$.datepicker._getFormatConfig(inst));

				if (date) { // only if valid
					$.datepicker._setDateFromField(inst);
					$.datepicker._updateAlternate(inst);
					$.datepicker._updateDatepicker(inst);
				}
			}
			catch (err) {
			}
		}
		return true;
	},

	/* Pop-up the date picker for a given input field.
	 * If false returned from beforeShow event handler do not show.
	 * @param  input  element - the input field attached to the date picker or
	 *					event - if triggered by focus
	 */
	_showDatepicker: function(input) {
		input = input.target || input;
		if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
			input = $("input", input.parentNode)[0];
		}

		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
			return;
		}

		var inst, beforeShow, beforeShowSettings, isFixed,
			offset, showAnim, duration;

		inst = $.datepicker._getInst(input);
		if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
			$.datepicker._curInst.dpDiv.stop(true, true);
			if ( inst && $.datepicker._datepickerShowing ) {
				$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
			}
		}

		beforeShow = $.datepicker._get(inst, "beforeShow");
		beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
		if(beforeShowSettings === false){
			return;
		}
		datepicker_extendRemove(inst.settings, beforeShowSettings);

		inst.lastVal = null;
		$.datepicker._lastInput = input;
		$.datepicker._setDateFromField(inst);

		if ($.datepicker._inDialog) { // hide cursor
			input.value = "";
		}
		if (!$.datepicker._pos) { // position below input
			$.datepicker._pos = $.datepicker._findPos(input);
			$.datepicker._pos[1] += input.offsetHeight; // add the height
		}

		isFixed = false;
		$(input).parents().each(function() {
			isFixed |= $(this).css("position") === "fixed";
			return !isFixed;
		});

		offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
		$.datepicker._pos = null;
		//to avoid flashes on Firefox
		inst.dpDiv.empty();
		// determine sizing offscreen
		inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
		$.datepicker._updateDatepicker(inst);
		// fix width for dynamic number of date pickers
		// and adjust position before showing
		offset = $.datepicker._checkOffset(inst, offset, isFixed);
		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
			"static" : (isFixed ? "fixed" : "absolute")), display: "none",
			left: offset.left + "px", top: offset.top + "px"});

		if (!inst.inline) {
			showAnim = $.datepicker._get(inst, "showAnim");
			duration = $.datepicker._get(inst, "duration");
			inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
			$.datepicker._datepickerShowing = true;

			if ( $.effects && $.effects.effect[ showAnim ] ) {
				inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
			} else {
				inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
			}

			if ( $.datepicker._shouldFocusInput( inst ) ) {
				inst.input.focus();
			}

			$.datepicker._curInst = inst;
		}
	},

	/* Generate the date picker content. */
	_updateDatepicker: function(inst) {
		this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
		datepicker_instActive = inst; // for delegate hover events
		inst.dpDiv.empty().append(this._generateHTML(inst));
		this._attachHandlers(inst);

		var origyearshtml,
			numMonths = this._getNumberOfMonths(inst),
			cols = numMonths[1],
			width = 17,
			activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );

		if ( activeCell.length > 0 ) {
			datepicker_handleMouseover.apply( activeCell.get( 0 ) );
		}

		inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
		if (cols > 1) {
			inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
		}
		inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
			"Class"]("ui-datepicker-multi");
		inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
			"Class"]("ui-datepicker-rtl");

		if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
			inst.input.focus();
		}

		// deffered render of the years select (to avoid flashes on Firefox)
		if( inst.yearshtml ){
			origyearshtml = inst.yearshtml;
			setTimeout(function(){
				//assure that inst.yearshtml didn't change.
				if( origyearshtml === inst.yearshtml && inst.yearshtml ){
					inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
				}
				origyearshtml = inst.yearshtml = null;
			}, 0);
		}
	},

	// #6694 - don't focus the input if it's already focused
	// this breaks the change event in IE
	// Support: IE and jQuery <1.9
	_shouldFocusInput: function( inst ) {
		return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
	},

	/* Check positioning to remain on screen. */
	_checkOffset: function(inst, offset, isFixed) {
		var dpWidth = inst.dpDiv.outerWidth(),
			dpHeight = inst.dpDiv.outerHeight(),
			inputWidth = inst.input ? inst.input.outerWidth() : 0,
			inputHeight = inst.input ? inst.input.outerHeight() : 0,
			viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
			viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());

		offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
		offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
		offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;

		// now check if datepicker is showing outside window viewport - move to a better place if so.
		offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
			Math.abs(offset.left + dpWidth - viewWidth) : 0);
		offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
			Math.abs(dpHeight + inputHeight) : 0);

		return offset;
	},

	/* Find an object's position on the screen. */
	_findPos: function(obj) {
		var position,
			inst = this._getInst(obj),
			isRTL = this._get(inst, "isRTL");

		while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
			obj = obj[isRTL ? "previousSibling" : "nextSibling"];
		}

		position = $(obj).offset();
		return [position.left, position.top];
	},

	/* Hide the date picker from view.
	 * @param  input  element - the input field attached to the date picker
	 */
	_hideDatepicker: function(input) {
		var showAnim, duration, postProcess, onClose,
			inst = this._curInst;

		if (!inst || (input && inst !== $.data(input, "datepicker"))) {
			return;
		}

		if (this._datepickerShowing) {
			showAnim = this._get(inst, "showAnim");
			duration = this._get(inst, "duration");
			postProcess = function() {
				$.datepicker._tidyDialog(inst);
			};

			// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
			if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
			} else {
				inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
					(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
			}

			if (!showAnim) {
				postProcess();
			}
			this._datepickerShowing = false;

			onClose = this._get(inst, "onClose");
			if (onClose) {
				onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
			}

			this._lastInput = null;
			if (this._inDialog) {
				this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
				if ($.blockUI) {
					$.unblockUI();
					$("body").append(this.dpDiv);
				}
			}
			this._inDialog = false;
		}
	},

	/* Tidy up after a dialog display. */
	_tidyDialog: function(inst) {
		inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
	},

	/* Close date picker if clicked elsewhere. */
	_checkExternalClick: function(event) {
		if (!$.datepicker._curInst) {
			return;
		}

		var $target = $(event.target),
			inst = $.datepicker._getInst($target[0]);

		if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
				$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
				!$target.hasClass($.datepicker.markerClassName) &&
				!$target.closest("." + $.datepicker._triggerClass).length &&
				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
			( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
				$.datepicker._hideDatepicker();
		}
	},

	/* Adjust one of the date sub-fields. */
	_adjustDate: function(id, offset, period) {
		var target = $(id),
			inst = this._getInst(target[0]);

		if (this._isDisabledDatepicker(target[0])) {
			return;
		}
		this._adjustInstDate(inst, offset +
			(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
			period);
		this._updateDatepicker(inst);
	},

	/* Action for current link. */
	_gotoToday: function(id) {
		var date,
			target = $(id),
			inst = this._getInst(target[0]);

		if (this._get(inst, "gotoCurrent") && inst.currentDay) {
			inst.selectedDay = inst.currentDay;
			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
			inst.drawYear = inst.selectedYear = inst.currentYear;
		} else {
			date = new Date();
			inst.selectedDay = date.getDate();
			inst.drawMonth = inst.selectedMonth = date.getMonth();
			inst.drawYear = inst.selectedYear = date.getFullYear();
		}
		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a new month/year. */
	_selectMonthYear: function(id, select, period) {
		var target = $(id),
			inst = this._getInst(target[0]);

		inst["selected" + (period === "M" ? "Month" : "Year")] =
		inst["draw" + (period === "M" ? "Month" : "Year")] =
			parseInt(select.options[select.selectedIndex].value,10);

		this._notifyChange(inst);
		this._adjustDate(target);
	},

	/* Action for selecting a day. */
	_selectDay: function(id, month, year, td) {
		var inst,
			target = $(id);

		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
			return;
		}

		inst = this._getInst(target[0]);
		inst.selectedDay = inst.currentDay = $("a", td).html();
		inst.selectedMonth = inst.currentMonth = month;
		inst.selectedYear = inst.currentYear = year;
		this._selectDate(id, this._formatDate(inst,
			inst.currentDay, inst.currentMonth, inst.currentYear));
	},

	/* Erase the input field and hide the date picker. */
	_clearDate: function(id) {
		var target = $(id);
		this._selectDate(target, "");
	},

	/* Update the input field with the selected date. */
	_selectDate: function(id, dateStr) {
		var onSelect,
			target = $(id),
			inst = this._getInst(target[0]);

		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
		if (inst.input) {
			inst.input.val(dateStr);
		}
		this._updateAlternate(inst);

		onSelect = this._get(inst, "onSelect");
		if (onSelect) {
			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
		} else if (inst.input) {
			inst.input.trigger("change"); // fire the change event
		}

		if (inst.inline){
			this._updateDatepicker(inst);
		} else {
			this._hideDatepicker();
			this._lastInput = inst.input[0];
			if (typeof(inst.input[0]) !== "object") {
				inst.input.focus(); // restore focus
			}
			this._lastInput = null;
		}
	},

	/* Update any alternate field to synchronise with the main field. */
	_updateAlternate: function(inst) {
		var altFormat, date, dateStr,
			altField = this._get(inst, "altField");

		if (altField) { // update alternate field too
			altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
			date = this._getDate(inst);
			dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
			$(altField).each(function() { $(this).val(dateStr); });
		}
	},

	/* Set as beforeShowDay function to prevent selection of weekends.
	 * @param  date  Date - the date to customise
	 * @return [boolean, string] - is this date selectable?, what is its CSS class?
	 */
	noWeekends: function(date) {
		var day = date.getDay();
		return [(day > 0 && day < 6), ""];
	},

	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
	 * @param  date  Date - the date to get the week for
	 * @return  number - the number of the week within the year that contains this date
	 */
	iso8601Week: function(date) {
		var time,
			checkDate = new Date(date.getTime());

		// Find Thursday of this week starting on Monday
		checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));

		time = checkDate.getTime();
		checkDate.setMonth(0); // Compare with Jan 1
		checkDate.setDate(1);
		return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
	},

	/* Parse a string value into a date object.
	 * See formatDate below for the possible formats.
	 *
	 * @param  format string - the expected format of the date
	 * @param  value string - the date in the above format
	 * @param  settings Object - attributes include:
	 *					shortYearCutoff  number - the cutoff year for determining the century (optional)
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  Date - the extracted date value or null if value is blank
	 */
	parseDate: function (format, value, settings) {
		if (format == null || value == null) {
			throw "Invalid arguments";
		}

		value = (typeof value === "object" ? value.toString() : value + "");
		if (value === "") {
			return null;
		}

		var iFormat, dim, extra,
			iValue = 0,
			shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
			shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
				new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
			dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
			dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
			monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
			monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
			year = -1,
			month = -1,
			day = -1,
			doy = -1,
			literal = false,
			date,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			},
			// Extract a number from the string value
			getNumber = function(match) {
				var isDoubled = lookAhead(match),
					size = (match === "@" ? 14 : (match === "!" ? 20 :
					(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
					minSize = (match === "y" ? size : 1),
					digits = new RegExp("^\\d{" + minSize + "," + size + "}"),
					num = value.substring(iValue).match(digits);
				if (!num) {
					throw "Missing number at position " + iValue;
				}
				iValue += num[0].length;
				return parseInt(num[0], 10);
			},
			// Extract a name from the string value and convert to an index
			getName = function(match, shortNames, longNames) {
				var index = -1,
					names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
						return [ [k, v] ];
					}).sort(function (a, b) {
						return -(a[1].length - b[1].length);
					});

				$.each(names, function (i, pair) {
					var name = pair[1];
					if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
						index = pair[0];
						iValue += name.length;
						return false;
					}
				});
				if (index !== -1) {
					return index + 1;
				} else {
					throw "Unknown name at position " + iValue;
				}
			},
			// Confirm that a literal character matches the string value
			checkLiteral = function() {
				if (value.charAt(iValue) !== format.charAt(iFormat)) {
					throw "Unexpected literal at position " + iValue;
				}
				iValue++;
			};

		for (iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal) {
				if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
					literal = false;
				} else {
					checkLiteral();
				}
			} else {
				switch (format.charAt(iFormat)) {
					case "d":
						day = getNumber("d");
						break;
					case "D":
						getName("D", dayNamesShort, dayNames);
						break;
					case "o":
						doy = getNumber("o");
						break;
					case "m":
						month = getNumber("m");
						break;
					case "M":
						month = getName("M", monthNamesShort, monthNames);
						break;
					case "y":
						year = getNumber("y");
						break;
					case "@":
						date = new Date(getNumber("@"));
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "!":
						date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
						year = date.getFullYear();
						month = date.getMonth() + 1;
						day = date.getDate();
						break;
					case "'":
						if (lookAhead("'")){
							checkLiteral();
						} else {
							literal = true;
						}
						break;
					default:
						checkLiteral();
				}
			}
		}

		if (iValue < value.length){
			extra = value.substr(iValue);
			if (!/^\s+/.test(extra)) {
				throw "Extra/unparsed characters found in date: " + extra;
			}
		}

		if (year === -1) {
			year = new Date().getFullYear();
		} else if (year < 100) {
			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
				(year <= shortYearCutoff ? 0 : -100);
		}

		if (doy > -1) {
			month = 1;
			day = doy;
			do {
				dim = this._getDaysInMonth(year, month - 1);
				if (day <= dim) {
					break;
				}
				month++;
				day -= dim;
			} while (true);
		}

		date = this._daylightSavingAdjust(new Date(year, month - 1, day));
		if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
			throw "Invalid date"; // E.g. 31/02/00
		}
		return date;
	},

	/* Standard date formats. */
	ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
	COOKIE: "D, dd M yy",
	ISO_8601: "yy-mm-dd",
	RFC_822: "D, d M y",
	RFC_850: "DD, dd-M-y",
	RFC_1036: "D, d M y",
	RFC_1123: "D, d M yy",
	RFC_2822: "D, d M yy",
	RSS: "D, d M y", // RFC 822
	TICKS: "!",
	TIMESTAMP: "@",
	W3C: "yy-mm-dd", // ISO 8601

	_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
		Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),

	/* Format a date object into a string value.
	 * The format can be combinations of the following:
	 * d  - day of month (no leading zero)
	 * dd - day of month (two digit)
	 * o  - day of year (no leading zeros)
	 * oo - day of year (three digit)
	 * D  - day name short
	 * DD - day name long
	 * m  - month of year (no leading zero)
	 * mm - month of year (two digit)
	 * M  - month name short
	 * MM - month name long
	 * y  - year (two digit)
	 * yy - year (four digit)
	 * @ - Unix timestamp (ms since 01/01/1970)
	 * ! - Windows ticks (100ns since 01/01/0001)
	 * "..." - literal text
	 * '' - single quote
	 *
	 * @param  format string - the desired format of the date
	 * @param  date Date - the date value to format
	 * @param  settings Object - attributes include:
	 *					dayNamesShort	string[7] - abbreviated names of the days from Sunday (optional)
	 *					dayNames		string[7] - names of the days from Sunday (optional)
	 *					monthNamesShort string[12] - abbreviated names of the months (optional)
	 *					monthNames		string[12] - names of the months (optional)
	 * @return  string - the date in the above format
	 */
	formatDate: function (format, date, settings) {
		if (!date) {
			return "";
		}

		var iFormat,
			dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
			dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
			monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
			monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			},
			// Format a number, with leading zero if necessary
			formatNumber = function(match, value, len) {
				var num = "" + value;
				if (lookAhead(match)) {
					while (num.length < len) {
						num = "0" + num;
					}
				}
				return num;
			},
			// Format a name, short or long as requested
			formatName = function(match, value, shortNames, longNames) {
				return (lookAhead(match) ? longNames[value] : shortNames[value]);
			},
			output = "",
			literal = false;

		if (date) {
			for (iFormat = 0; iFormat < format.length; iFormat++) {
				if (literal) {
					if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
						literal = false;
					} else {
						output += format.charAt(iFormat);
					}
				} else {
					switch (format.charAt(iFormat)) {
						case "d":
							output += formatNumber("d", date.getDate(), 2);
							break;
						case "D":
							output += formatName("D", date.getDay(), dayNamesShort, dayNames);
							break;
						case "o":
							output += formatNumber("o",
								Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
							break;
						case "m":
							output += formatNumber("m", date.getMonth() + 1, 2);
							break;
						case "M":
							output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
							break;
						case "y":
							output += (lookAhead("y") ? date.getFullYear() :
								(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
							break;
						case "@":
							output += date.getTime();
							break;
						case "!":
							output += date.getTime() * 10000 + this._ticksTo1970;
							break;
						case "'":
							if (lookAhead("'")) {
								output += "'";
							} else {
								literal = true;
							}
							break;
						default:
							output += format.charAt(iFormat);
					}
				}
			}
		}
		return output;
	},

	/* Extract all possible characters from the date format. */
	_possibleChars: function (format) {
		var iFormat,
			chars = "",
			literal = false,
			// Check whether a format character is doubled
			lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
				if (matches) {
					iFormat++;
				}
				return matches;
			};

		for (iFormat = 0; iFormat < format.length; iFormat++) {
			if (literal) {
				if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
					literal = false;
				} else {
					chars += format.charAt(iFormat);
				}
			} else {
				switch (format.charAt(iFormat)) {
					case "d": case "m": case "y": case "@":
						chars += "0123456789";
						break;
					case "D": case "M":
						return null; // Accept anything
					case "'":
						if (lookAhead("'")) {
							chars += "'";
						} else {
							literal = true;
						}
						break;
					default:
						chars += format.charAt(iFormat);
				}
			}
		}
		return chars;
	},

	/* Get a setting value, defaulting if necessary. */
	_get: function(inst, name) {
		return inst.settings[name] !== undefined ?
			inst.settings[name] : this._defaults[name];
	},

	/* Parse existing date and initialise date picker. */
	_setDateFromField: function(inst, noDefault) {
		if (inst.input.val() === inst.lastVal) {
			return;
		}

		var dateFormat = this._get(inst, "dateFormat"),
			dates = inst.lastVal = inst.input ? inst.input.val() : null,
			defaultDate = this._getDefaultDate(inst),
			date = defaultDate,
			settings = this._getFormatConfig(inst);

		try {
			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
		} catch (event) {
			dates = (noDefault ? "" : dates);
		}
		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		inst.currentDay = (dates ? date.getDate() : 0);
		inst.currentMonth = (dates ? date.getMonth() : 0);
		inst.currentYear = (dates ? date.getFullYear() : 0);
		this._adjustInstDate(inst);
	},

	/* Retrieve the default date shown on opening. */
	_getDefaultDate: function(inst) {
		return this._restrictMinMax(inst,
			this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
	},

	/* A date may be specified as an exact value or a relative one. */
	_determineDate: function(inst, date, defaultDate) {
		var offsetNumeric = function(offset) {
				var date = new Date();
				date.setDate(date.getDate() + offset);
				return date;
			},
			offsetString = function(offset) {
				try {
					return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
						offset, $.datepicker._getFormatConfig(inst));
				}
				catch (e) {
					// Ignore
				}

				var date = (offset.toLowerCase().match(/^c/) ?
					$.datepicker._getDate(inst) : null) || new Date(),
					year = date.getFullYear(),
					month = date.getMonth(),
					day = date.getDate(),
					pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
					matches = pattern.exec(offset);

				while (matches) {
					switch (matches[2] || "d") {
						case "d" : case "D" :
							day += parseInt(matches[1],10); break;
						case "w" : case "W" :
							day += parseInt(matches[1],10) * 7; break;
						case "m" : case "M" :
							month += parseInt(matches[1],10);
							day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
							break;
						case "y": case "Y" :
							year += parseInt(matches[1],10);
							day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
							break;
					}
					matches = pattern.exec(offset);
				}
				return new Date(year, month, day);
			},
			newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
				(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));

		newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
		if (newDate) {
			newDate.setHours(0);
			newDate.setMinutes(0);
			newDate.setSeconds(0);
			newDate.setMilliseconds(0);
		}
		return this._daylightSavingAdjust(newDate);
	},

	/* Handle switch to/from daylight saving.
	 * Hours may be non-zero on daylight saving cut-over:
	 * > 12 when midnight changeover, but then cannot generate
	 * midnight datetime, so jump to 1AM, otherwise reset.
	 * @param  date  (Date) the date to check
	 * @return  (Date) the corrected date
	 */
	_daylightSavingAdjust: function(date) {
		if (!date) {
			return null;
		}
		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
		return date;
	},

	/* Set the date(s) directly. */
	_setDate: function(inst, date, noChange) {
		var clear = !date,
			origMonth = inst.selectedMonth,
			origYear = inst.selectedYear,
			newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));

		inst.selectedDay = inst.currentDay = newDate.getDate();
		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
		if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
			this._notifyChange(inst);
		}
		this._adjustInstDate(inst);
		if (inst.input) {
			inst.input.val(clear ? "" : this._formatDate(inst));
		}
	},

	/* Retrieve the date(s) directly. */
	_getDate: function(inst) {
		var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
			this._daylightSavingAdjust(new Date(
			inst.currentYear, inst.currentMonth, inst.currentDay)));
			return startDate;
	},

	/* Attach the onxxx handlers.  These are declared statically so
	 * they work with static code transformers like Caja.
	 */
	_attachHandlers: function(inst) {
		var stepMonths = this._get(inst, "stepMonths"),
			id = "#" + inst.id.replace( /\\\\/g, "\\" );
		inst.dpDiv.find("[data-handler]").map(function () {
			var handler = {
				prev: function () {
					$.datepicker._adjustDate(id, -stepMonths, "M");
				},
				next: function () {
					$.datepicker._adjustDate(id, +stepMonths, "M");
				},
				hide: function () {
					$.datepicker._hideDatepicker();
				},
				today: function () {
					$.datepicker._gotoToday(id);
				},
				selectDay: function () {
					$.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
					return false;
				},
				selectMonth: function () {
					$.datepicker._selectMonthYear(id, this, "M");
					return false;
				},
				selectYear: function () {
					$.datepicker._selectMonthYear(id, this, "Y");
					return false;
				}
			};
			$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
		});
	},

	/* Generate the HTML for the current state of the date picker. */
	_generateHTML: function(inst) {
		var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
			controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
			monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
			selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
			cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
			printDate, dRow, tbody, daySettings, otherMonth, unselectable,
			tempDate = new Date(),
			today = this._daylightSavingAdjust(
				new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
			isRTL = this._get(inst, "isRTL"),
			showButtonPanel = this._get(inst, "showButtonPanel"),
			hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
			navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
			numMonths = this._getNumberOfMonths(inst),
			showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
			stepMonths = this._get(inst, "stepMonths"),
			isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
			currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
				new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
			minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			drawMonth = inst.drawMonth - showCurrentAtPos,
			drawYear = inst.drawYear;

		if (drawMonth < 0) {
			drawMonth += 12;
			drawYear--;
		}
		if (maxDate) {
			maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
				maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
				drawMonth--;
				if (drawMonth < 0) {
					drawMonth = 11;
					drawYear--;
				}
			}
		}
		inst.drawMonth = drawMonth;
		inst.drawYear = drawYear;

		prevText = this._get(inst, "prevText");
		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
			this._getFormatConfig(inst)));

		prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
			"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
			" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
			(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));

		nextText = this._get(inst, "nextText");
		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
			this._getFormatConfig(inst)));

		next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
			"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
			" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
			(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));

		currentText = this._get(inst, "currentText");
		gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
		currentText = (!navigationAsDateFormat ? currentText :
			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));

		controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
			this._get(inst, "closeText") + "</button>" : "");

		buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
			(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
			">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";

		firstDay = parseInt(this._get(inst, "firstDay"),10);
		firstDay = (isNaN(firstDay) ? 0 : firstDay);

		showWeek = this._get(inst, "showWeek");
		dayNames = this._get(inst, "dayNames");
		dayNamesMin = this._get(inst, "dayNamesMin");
		monthNames = this._get(inst, "monthNames");
		monthNamesShort = this._get(inst, "monthNamesShort");
		beforeShowDay = this._get(inst, "beforeShowDay");
		showOtherMonths = this._get(inst, "showOtherMonths");
		selectOtherMonths = this._get(inst, "selectOtherMonths");
		defaultDate = this._getDefaultDate(inst);
		html = "";
		dow;
		for (row = 0; row < numMonths[0]; row++) {
			group = "";
			this.maxRows = 4;
			for (col = 0; col < numMonths[1]; col++) {
				selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
				cornerClass = " ui-corner-all";
				calender = "";
				if (isMultiMonth) {
					calender += "<div class='ui-datepicker-group";
					if (numMonths[1] > 1) {
						switch (col) {
							case 0: calender += " ui-datepicker-group-first";
								cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
							case numMonths[1]-1: calender += " ui-datepicker-group-last";
								cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
							default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
						}
					}
					calender += "'>";
				}
				calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
					(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
					(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
					row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
					"</div><table class='ui-datepicker-calendar'><thead>" +
					"<tr>";
				thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
				for (dow = 0; dow < 7; dow++) { // days of the week
					day = (dow + firstDay) % 7;
					thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
						"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
				}
				calender += thead + "</tr></thead><tbody>";
				daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
				if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
				}
				leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
				curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
				numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
				this.maxRows = numRows;
				printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
				for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
					calender += "<tr>";
					tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
						this._get(inst, "calculateWeek")(printDate) + "</td>");
					for (dow = 0; dow < 7; dow++) { // create date picker days
						daySettings = (beforeShowDay ?
							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
						otherMonth = (printDate.getMonth() !== drawMonth);
						unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
						tbody += "<td class='" +
							((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
							(otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
							((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
							(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
							// or defaultDate is current printedDate and defaultDate is selectedDate
							" " + this._dayOverClass : "") + // highlight selected day
							(unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") +  // highlight unselectable days
							(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
							(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
							(printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
							((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "&#39;") + "'" : "") + // cell title
							(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
							(otherMonth && !showOtherMonths ? "&#xa0;" : // display for other months
							(unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
							(printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
							(printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
							(otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
							"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
						printDate.setDate(printDate.getDate() + 1);
						printDate = this._daylightSavingAdjust(printDate);
					}
					calender += tbody + "</tr>";
				}
				drawMonth++;
				if (drawMonth > 11) {
					drawMonth = 0;
					drawYear++;
				}
				calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
							((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
				group += calender;
			}
			html += group;
		}
		html += buttonPanel;
		inst._keyEvent = false;
		return html;
	},

	/* Generate the month and year header. */
	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
			secondary, monthNames, monthNamesShort) {

		var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
			changeMonth = this._get(inst, "changeMonth"),
			changeYear = this._get(inst, "changeYear"),
			showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
			html = "<div class='ui-datepicker-title'>",
			monthHtml = "";

		// month selection
		if (secondary || !changeMonth) {
			monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
		} else {
			inMinYear = (minDate && minDate.getFullYear() === drawYear);
			inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
			monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
			for ( month = 0; month < 12; month++) {
				if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
					monthHtml += "<option value='" + month + "'" +
						(month === drawMonth ? " selected='selected'" : "") +
						">" + monthNamesShort[month] + "</option>";
				}
			}
			monthHtml += "</select>";
		}

		if (!showMonthAfterYear) {
			html += monthHtml + (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "");
		}

		// year selection
		if ( !inst.yearshtml ) {
			inst.yearshtml = "";
			if (secondary || !changeYear) {
				html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
			} else {
				// determine range of years to display
				years = this._get(inst, "yearRange").split(":");
				thisYear = new Date().getFullYear();
				determineYear = function(value) {
					var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
						(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
						parseInt(value, 10)));
					return (isNaN(year) ? thisYear : year);
				};
				year = determineYear(years[0]);
				endYear = Math.max(year, determineYear(years[1] || ""));
				year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
				endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
				inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
				for (; year <= endYear; year++) {
					inst.yearshtml += "<option value='" + year + "'" +
						(year === drawYear ? " selected='selected'" : "") +
						">" + year + "</option>";
				}
				inst.yearshtml += "</select>";

				html += inst.yearshtml;
				inst.yearshtml = null;
			}
		}

		html += this._get(inst, "yearSuffix");
		if (showMonthAfterYear) {
			html += (secondary || !(changeMonth && changeYear) ? "&#xa0;" : "") + monthHtml;
		}
		html += "</div>"; // Close datepicker_header
		return html;
	},

	/* Adjust one of the date sub-fields. */
	_adjustInstDate: function(inst, offset, period) {
		var year = inst.drawYear + (period === "Y" ? offset : 0),
			month = inst.drawMonth + (period === "M" ? offset : 0),
			day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
			date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));

		inst.selectedDay = date.getDate();
		inst.drawMonth = inst.selectedMonth = date.getMonth();
		inst.drawYear = inst.selectedYear = date.getFullYear();
		if (period === "M" || period === "Y") {
			this._notifyChange(inst);
		}
	},

	/* Ensure a date is within any min/max bounds. */
	_restrictMinMax: function(inst, date) {
		var minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			newDate = (minDate && date < minDate ? minDate : date);
		return (maxDate && newDate > maxDate ? maxDate : newDate);
	},

	/* Notify change of month/year. */
	_notifyChange: function(inst) {
		var onChange = this._get(inst, "onChangeMonthYear");
		if (onChange) {
			onChange.apply((inst.input ? inst.input[0] : null),
				[inst.selectedYear, inst.selectedMonth + 1, inst]);
		}
	},

	/* Determine the number of months to show. */
	_getNumberOfMonths: function(inst) {
		var numMonths = this._get(inst, "numberOfMonths");
		return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
	},

	/* Determine the current maximum date - ensure no time components are set. */
	_getMinMaxDate: function(inst, minMax) {
		return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
	},

	/* Find the number of days in a given month. */
	_getDaysInMonth: function(year, month) {
		return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
	},

	/* Find the day of the week of the first of a month. */
	_getFirstDayOfMonth: function(year, month) {
		return new Date(year, month, 1).getDay();
	},

	/* Determines if we should allow a "next/prev" month display change. */
	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
		var numMonths = this._getNumberOfMonths(inst),
			date = this._daylightSavingAdjust(new Date(curYear,
			curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));

		if (offset < 0) {
			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
		}
		return this._isInRange(inst, date);
	},

	/* Is the given date in the accepted range? */
	_isInRange: function(inst, date) {
		var yearSplit, currentYear,
			minDate = this._getMinMaxDate(inst, "min"),
			maxDate = this._getMinMaxDate(inst, "max"),
			minYear = null,
			maxYear = null,
			years = this._get(inst, "yearRange");
			if (years){
				yearSplit = years.split(":");
				currentYear = new Date().getFullYear();
				minYear = parseInt(yearSplit[0], 10);
				maxYear = parseInt(yearSplit[1], 10);
				if ( yearSplit[0].match(/[+\-].*/) ) {
					minYear += currentYear;
				}
				if ( yearSplit[1].match(/[+\-].*/) ) {
					maxYear += currentYear;
				}
			}

		return ((!minDate || date.getTime() >= minDate.getTime()) &&
			(!maxDate || date.getTime() <= maxDate.getTime()) &&
			(!minYear || date.getFullYear() >= minYear) &&
			(!maxYear || date.getFullYear() <= maxYear));
	},

	/* Provide the configuration settings for formatting/parsing. */
	_getFormatConfig: function(inst) {
		var shortYearCutoff = this._get(inst, "shortYearCutoff");
		shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
		return {shortYearCutoff: shortYearCutoff,
			dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
			monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
	},

	/* Format the given date for display. */
	_formatDate: function(inst, day, month, year) {
		if (!day) {
			inst.currentDay = inst.selectedDay;
			inst.currentMonth = inst.selectedMonth;
			inst.currentYear = inst.selectedYear;
		}
		var date = (day ? (typeof day === "object" ? day :
			this._daylightSavingAdjust(new Date(year, month, day))) :
			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
		return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
	}
});

/*
 * Bind hover events for datepicker elements.
 * Done via delegate so the binding only occurs once in the lifetime of the parent div.
 * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
 */
function datepicker_bindHover(dpDiv) {
	var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
	return dpDiv.delegate(selector, "mouseout", function() {
			$(this).removeClass("ui-state-hover");
			if (this.className.indexOf("ui-datepicker-prev") !== -1) {
				$(this).removeClass("ui-datepicker-prev-hover");
			}
			if (this.className.indexOf("ui-datepicker-next") !== -1) {
				$(this).removeClass("ui-datepicker-next-hover");
			}
		})
		.delegate( selector, "mouseover", datepicker_handleMouseover );
}

function datepicker_handleMouseover() {
	if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? datepicker_instActive.dpDiv.parent()[0] : datepicker_instActive.input[0])) {
		$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
		$(this).addClass("ui-state-hover");
		if (this.className.indexOf("ui-datepicker-prev") !== -1) {
			$(this).addClass("ui-datepicker-prev-hover");
		}
		if (this.className.indexOf("ui-datepicker-next") !== -1) {
			$(this).addClass("ui-datepicker-next-hover");
		}
	}
}

/* jQuery extend now ignores nulls! */
function datepicker_extendRemove(target, props) {
	$.extend(target, props);
	for (var name in props) {
		if (props[name] == null) {
			target[name] = props[name];
		}
	}
	return target;
}

/* Invoke the datepicker functionality.
   @param  options  string - a command, optionally followed by additional parameters or
					Object - settings for attaching new datepicker functionality
   @return  jQuery object */
$.fn.datepicker = function(options){

	/* Verify an empty collection wasn't passed - Fixes #6976 */
	if ( !this.length ) {
		return this;
	}

	/* Initialise the date picker. */
	if (!$.datepicker.initialized) {
		$(document).mousedown($.datepicker._checkExternalClick);
		$.datepicker.initialized = true;
	}

	/* Append datepicker main container to body if not exist. */
	if ($("#"+$.datepicker._mainDivId).length === 0) {
		$("body").append($.datepicker.dpDiv);
	}

	var otherArgs = Array.prototype.slice.call(arguments, 1);
	if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
		return $.datepicker["_" + options + "Datepicker"].
			apply($.datepicker, [this[0]].concat(otherArgs));
	}
	if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
		return $.datepicker["_" + options + "Datepicker"].
			apply($.datepicker, [this[0]].concat(otherArgs));
	}
	return this.each(function() {
		typeof options === "string" ?
			$.datepicker["_" + options + "Datepicker"].
				apply($.datepicker, [this].concat(otherArgs)) :
			$.datepicker._attachDatepicker(this, options);
	});
};

$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.11.4";

var datepicker = $.datepicker;


/*!
 * jQuery UI Draggable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/draggable/
 */


$.widget("ui.draggable", $.ui.mouse, {
	version: "1.11.4",
	widgetEventPrefix: "drag",
	options: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false,

		// callbacks
		drag: null,
		start: null,
		stop: null
	},
	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if (this.options.addClasses){
			this.element.addClass("ui-draggable");
		}
		if (this.options.disabled){
			this.element.addClass("ui-draggable-disabled");
		}
		this._setHandleClassName();

		this._mouseInit();
	},

	_setOption: function( key, value ) {
		this._super( key, value );
		if ( key === "handle" ) {
			this._removeHandleClassName();
			this._setHandleClassName();
		}
	},

	_destroy: function() {
		if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) {
			this.destroyOnClear = true;
			return;
		}
		this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
		this._removeHandleClassName();
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {
		var o = this.options;

		this._blurActiveElement( event );

		// among others, prevent a drag on a resizable-handle
		if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
			return false;
		}

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle) {
			return false;
		}

		this._blockFrames( o.iframeFix === true ? "iframe" : o.iframeFix );

		return true;

	},

	_blockFrames: function( selector ) {
		this.iframeBlocks = this.document.find( selector ).map(function() {
			var iframe = $( this );

			return $( "<div>" )
				.css( "position", "absolute" )
				.appendTo( iframe.parent() )
				.outerWidth( iframe.outerWidth() )
				.outerHeight( iframe.outerHeight() )
				.offset( iframe.offset() )[ 0 ];
		});
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_blurActiveElement: function( event ) {
		var document = this.document[ 0 ];

		// Only need to blur if the event occurred on the draggable itself, see #10527
		if ( !this.handleElement.is( event.target ) ) {
			return;
		}

		// support: IE9
		// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
		try {

			// Support: IE9, IE10
			// If the <body> is blurred, IE will switch windows, see #9520
			if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) {

				// Blur any element that currently has focus, see #4261
				$( document.activeElement ).blur();
			}
		} catch ( error ) {}
	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		this.helper.addClass("ui-draggable-dragging");

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if ($.ui.ddmanager) {
			$.ui.ddmanager.current = this;
		}

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css( "position" );
		this.scrollParent = this.helper.scrollParent( true );
		this.offsetParent = this.helper.offsetParent();
		this.hasFixedAncestor = this.helper.parents().filter(function() {
				return $( this ).css( "position" ) === "fixed";
			}).length > 0;

		//The element's absolute position on the page minus margins
		this.positionAbs = this.element.offset();
		this._refreshOffsets( event );

		//Generate the original position
		this.originalPosition = this.position = this._generatePosition( event, false );
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Set a containment if given in the options
		this._setContainment();

		//Trigger event + callbacks
		if (this._trigger("start", event) === false) {
			this._clear();
			return false;
		}

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(this, event);
		}

		// Reset helper's right/bottom css if they're set and set explicit width/height instead
		// as this prevents resizing of elements with right/bottom set (see #7772)
		this._normalizeRightBottom();

		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position

		//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStart(this, event);
		}

		return true;
	},

	_refreshOffsets: function( event ) {
		this.offset = {
			top: this.positionAbs.top - this.margins.top,
			left: this.positionAbs.left - this.margins.left,
			scroll: false,
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset()
		};

		this.offset.click = {
			left: event.pageX - this.offset.left,
			top: event.pageY - this.offset.top
		};
	},

	_mouseDrag: function(event, noPropagation) {
		// reset any necessary cached properties (see #5009)
		if ( this.hasFixedAncestor ) {
			this.offset.parent = this._getParentOffset();
		}

		//Compute the helpers position
		this.position = this._generatePosition( event, true );
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			if (this._trigger("drag", event, ui) === false) {
				this._mouseUp({});
				return false;
			}
			this.position = ui.position;
		}

		this.helper[ 0 ].style.left = this.position.left + "px";
		this.helper[ 0 ].style.top = this.position.top + "px";

		if ($.ui.ddmanager) {
			$.ui.ddmanager.drag(this, event);
		}

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var that = this,
			dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour) {
			dropped = $.ui.ddmanager.drop(this, event);
		}

		//if a drop comes from outside (a sortable)
		if (this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				if (that._trigger("stop", event) !== false) {
					that._clear();
				}
			});
		} else {
			if (this._trigger("stop", event) !== false) {
				this._clear();
			}
		}

		return false;
	},

	_mouseUp: function( event ) {
		this._unblockFrames();

		//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
		if ( $.ui.ddmanager ) {
			$.ui.ddmanager.dragStop(this, event);
		}

		// Only need to focus if the event occurred on the draggable itself, see #10527
		if ( this.handleElement.is( event.target ) ) {
			// The interaction is over; whether or not the click resulted in a drag, focus the element
			this.element.focus();
		}

		return $.ui.mouse.prototype._mouseUp.call(this, event);
	},

	cancel: function() {

		if (this.helper.is(".ui-draggable-dragging")) {
			this._mouseUp({});
		} else {
			this._clear();
		}

		return this;

	},

	_getHandle: function(event) {
		return this.options.handle ?
			!!$( event.target ).closest( this.element.find( this.options.handle ) ).length :
			true;
	},

	_setHandleClassName: function() {
		this.handleElement = this.options.handle ?
			this.element.find( this.options.handle ) : this.element;
		this.handleElement.addClass( "ui-draggable-handle" );
	},

	_removeHandleClassName: function() {
		this.handleElement.removeClass( "ui-draggable-handle" );
	},

	_createHelper: function(event) {

		var o = this.options,
			helperIsFunction = $.isFunction( o.helper ),
			helper = helperIsFunction ?
				$( o.helper.apply( this.element[ 0 ], [ event ] ) ) :
				( o.helper === "clone" ?
					this.element.clone().removeAttr( "id" ) :
					this.element );

		if (!helper.parents("body").length) {
			helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
		}

		// http://bugs.jqueryui.com/ticket/9446
		// a helper function can return the original element
		// which wouldn't have been set to relative in _create
		if ( helperIsFunction && helper[ 0 ] === this.element[ 0 ] ) {
			this._setPositionRelative();
		}

		if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
			helper.css("position", "absolute");
		}

		return helper;

	},

	_setPositionRelative: function() {
		if ( !( /^(?:r|a|f)/ ).test( this.element.css( "position" ) ) ) {
			this.element[ 0 ].style.position = "relative";
		}
	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj === "string") {
			obj = obj.split(" ");
		}
		if ($.isArray(obj)) {
			obj = { left: +obj[0], top: +obj[1] || 0 };
		}
		if ("left" in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ("right" in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ("top" in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ("bottom" in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_isRootNode: function( element ) {
		return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ];
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		var po = this.offsetParent.offset(),
			document = this.document[ 0 ];

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if ( this._isRootNode( this.offsetParent[ 0 ] ) ) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"), 10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"), 10) || 0)
		};

	},

	_getRelativeOffset: function() {
		if ( this.cssPosition !== "relative" ) {
			return { top: 0, left: 0 };
		}

		var p = this.element.position(),
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ),
			left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 )
		};

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"), 10) || 0),
			top: (parseInt(this.element.css("marginTop"), 10) || 0),
			right: (parseInt(this.element.css("marginRight"), 10) || 0),
			bottom: (parseInt(this.element.css("marginBottom"), 10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var isUserScrollable, c, ce,
			o = this.options,
			document = this.document[ 0 ];

		this.relativeContainer = null;

		if ( !o.containment ) {
			this.containment = null;
			return;
		}

		if ( o.containment === "window" ) {
			this.containment = [
				$( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
				$( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top,
				$( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left,
				$( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment === "document") {
			this.containment = [
				0,
				0,
				$( document ).width() - this.helperProportions.width - this.margins.left,
				( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top
			];
			return;
		}

		if ( o.containment.constructor === Array ) {
			this.containment = o.containment;
			return;
		}

		if ( o.containment === "parent" ) {
			o.containment = this.helper[ 0 ].parentNode;
		}

		c = $( o.containment );
		ce = c[ 0 ];

		if ( !ce ) {
			return;
		}

		isUserScrollable = /(scroll|auto)/.test( c.css( "overflow" ) );

		this.containment = [
			( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ),
			( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ),
			( isUserScrollable ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) -
				( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) -
				this.helperProportions.width -
				this.margins.left -
				this.margins.right,
			( isUserScrollable ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) -
				( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) -
				( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) -
				this.helperProportions.height -
				this.margins.top -
				this.margins.bottom
		];
		this.relativeContainer = c;
	},

	_convertPositionTo: function(d, pos) {

		if (!pos) {
			pos = this.position;
		}

		var mod = d === "absolute" ? 1 : -1,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] );

		return {
			top: (
				pos.top	+																// The absolute mouse position
				this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top * mod -										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod)
			),
			left: (
				pos.left +																// The absolute mouse position
				this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left * mod	-										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod)
			)
		};

	},

	_generatePosition: function( event, constrainPosition ) {

		var containment, co, top, left,
			o = this.options,
			scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ),
			pageX = event.pageX,
			pageY = event.pageY;

		// Cache the scroll
		if ( !scrollIsRootNode || !this.offset.scroll ) {
			this.offset.scroll = {
				top: this.scrollParent.scrollTop(),
				left: this.scrollParent.scrollLeft()
			};
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		// If we are not dragging yet, we won't check for options
		if ( constrainPosition ) {
			if ( this.containment ) {
				if ( this.relativeContainer ){
					co = this.relativeContainer.offset();
					containment = [
						this.containment[ 0 ] + co.left,
						this.containment[ 1 ] + co.top,
						this.containment[ 2 ] + co.left,
						this.containment[ 3 ] + co.top
					];
				} else {
					containment = this.containment;
				}

				if (event.pageX - this.offset.click.left < containment[0]) {
					pageX = containment[0] + this.offset.click.left;
				}
				if (event.pageY - this.offset.click.top < containment[1]) {
					pageY = containment[1] + this.offset.click.top;
				}
				if (event.pageX - this.offset.click.left > containment[2]) {
					pageX = containment[2] + this.offset.click.left;
				}
				if (event.pageY - this.offset.click.top > containment[3]) {
					pageY = containment[3] + this.offset.click.top;
				}
			}

			if (o.grid) {
				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
				top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
				pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
				pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

			if ( o.axis === "y" ) {
				pageX = this.originalPageX;
			}

			if ( o.axis === "x" ) {
				pageY = this.originalPageY;
			}
		}

		return {
			top: (
				pageY -																	// The absolute mouse position
				this.offset.click.top	-												// Click offset (relative to the element)
				this.offset.relative.top -												// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
				( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) )
			),
			left: (
				pageX -																	// The absolute mouse position
				this.offset.click.left -												// Click offset (relative to the element)
				this.offset.relative.left -												// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
				( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) )
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
			this.helper.remove();
		}
		this.helper = null;
		this.cancelHelperRemoval = false;
		if ( this.destroyOnClear ) {
			this.destroy();
		}
	},

	_normalizeRightBottom: function() {
		if ( this.options.axis !== "y" && this.helper.css( "right" ) !== "auto" ) {
			this.helper.width( this.helper.width() );
			this.helper.css( "right", "auto" );
		}
		if ( this.options.axis !== "x" && this.helper.css( "bottom" ) !== "auto" ) {
			this.helper.height( this.helper.height() );
			this.helper.css( "bottom", "auto" );
		}
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function( type, event, ui ) {
		ui = ui || this._uiHash();
		$.ui.plugin.call( this, type, [ event, ui, this ], true );

		// Absolute position and offset (see #6884 ) have to be recalculated after plugins
		if ( /^(drag|start|stop)/.test( type ) ) {
			this.positionAbs = this._convertPositionTo( "absolute" );
			ui.offset = this.positionAbs;
		}
		return $.Widget.prototype._trigger.call( this, type, event, ui );
	},

	plugins: {},

	_uiHash: function() {
		return {
			helper: this.helper,
			position: this.position,
			originalPosition: this.originalPosition,
			offset: this.positionAbs
		};
	}

});

$.ui.plugin.add( "draggable", "connectToSortable", {
	start: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		});

		draggable.sortables = [];
		$( draggable.options.connectToSortable ).each(function() {
			var sortable = $( this ).sortable( "instance" );

			if ( sortable && !sortable.options.disabled ) {
				draggable.sortables.push( sortable );

				// refreshPositions is called at drag start to refresh the containerCache
				// which is used in drag. This ensures it's initialized and synchronized
				// with any changes that might have happened on the page since initialization.
				sortable.refreshPositions();
				sortable._trigger("activate", event, uiSortable);
			}
		});
	},
	stop: function( event, ui, draggable ) {
		var uiSortable = $.extend( {}, ui, {
			item: draggable.element
		});

		draggable.cancelHelperRemoval = false;

		$.each( draggable.sortables, function() {
			var sortable = this;

			if ( sortable.isOver ) {
				sortable.isOver = 0;

				// Allow this sortable to handle removing the helper
				draggable.cancelHelperRemoval = true;
				sortable.cancelHelperRemoval = false;

				// Use _storedCSS To restore properties in the sortable,
				// as this also handles revert (#9675) since the draggable
				// may have modified them in unexpected ways (#8809)
				sortable._storedCSS = {
					position: sortable.placeholder.css( "position" ),
					top: sortable.placeholder.css( "top" ),
					left: sortable.placeholder.css( "left" )
				};

				sortable._mouseStop(event);

				// Once drag has ended, the sortable should return to using
				// its original helper, not the shared helper from draggable
				sortable.options.helper = sortable.options._helper;
			} else {
				// Prevent this Sortable from removing the helper.
				// However, don't set the draggable to remove the helper
				// either as another connected Sortable may yet handle the removal.
				sortable.cancelHelperRemoval = true;

				sortable._trigger( "deactivate", event, uiSortable );
			}
		});
	},
	drag: function( event, ui, draggable ) {
		$.each( draggable.sortables, function() {
			var innermostIntersecting = false,
				sortable = this;

			// Copy over variables that sortable's _intersectsWith uses
			sortable.positionAbs = draggable.positionAbs;
			sortable.helperProportions = draggable.helperProportions;
			sortable.offset.click = draggable.offset.click;

			if ( sortable._intersectsWith( sortable.containerCache ) ) {
				innermostIntersecting = true;

				$.each( draggable.sortables, function() {
					// Copy over variables that sortable's _intersectsWith uses
					this.positionAbs = draggable.positionAbs;
					this.helperProportions = draggable.helperProportions;
					this.offset.click = draggable.offset.click;

					if ( this !== sortable &&
							this._intersectsWith( this.containerCache ) &&
							$.contains( sortable.element[ 0 ], this.element[ 0 ] ) ) {
						innermostIntersecting = false;
					}

					return innermostIntersecting;
				});
			}

			if ( innermostIntersecting ) {
				// If it intersects, we use a little isOver variable and set it once,
				// so that the move-in stuff gets fired only once.
				if ( !sortable.isOver ) {
					sortable.isOver = 1;

					// Store draggable's parent in case we need to reappend to it later.
					draggable._parent = ui.helper.parent();

					sortable.currentItem = ui.helper
						.appendTo( sortable.element )
						.data( "ui-sortable-item", true );

					// Store helper option to later restore it
					sortable.options._helper = sortable.options.helper;

					sortable.options.helper = function() {
						return ui.helper[ 0 ];
					};

					// Fire the start events of the sortable with our passed browser event,
					// and our own helper (so it doesn't create a new one)
					event.target = sortable.currentItem[ 0 ];
					sortable._mouseCapture( event, true );
					sortable._mouseStart( event, true, true );

					// Because the browser event is way off the new appended portlet,
					// modify necessary variables to reflect the changes
					sortable.offset.click.top = draggable.offset.click.top;
					sortable.offset.click.left = draggable.offset.click.left;
					sortable.offset.parent.left -= draggable.offset.parent.left -
						sortable.offset.parent.left;
					sortable.offset.parent.top -= draggable.offset.parent.top -
						sortable.offset.parent.top;

					draggable._trigger( "toSortable", event );

					// Inform draggable that the helper is in a valid drop zone,
					// used solely in the revert option to handle "valid/invalid".
					draggable.dropped = sortable.element;

					// Need to refreshPositions of all sortables in the case that
					// adding to one sortable changes the location of the other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					});

					// hack so receive/update callbacks work (mostly)
					draggable.currentItem = draggable.element;
					sortable.fromOutside = draggable;
				}

				if ( sortable.currentItem ) {
					sortable._mouseDrag( event );
					// Copy the sortable's position because the draggable's can potentially reflect
					// a relative position, while sortable is always absolute, which the dragged
					// element has now become. (#8809)
					ui.position = sortable.position;
				}
			} else {
				// If it doesn't intersect with the sortable, and it intersected before,
				// we fake the drag stop of the sortable, but make sure it doesn't remove
				// the helper by using cancelHelperRemoval.
				if ( sortable.isOver ) {

					sortable.isOver = 0;
					sortable.cancelHelperRemoval = true;

					// Calling sortable's mouseStop would trigger a revert,
					// so revert must be temporarily false until after mouseStop is called.
					sortable.options._revert = sortable.options.revert;
					sortable.options.revert = false;

					sortable._trigger( "out", event, sortable._uiHash( sortable ) );
					sortable._mouseStop( event, true );

					// restore sortable behaviors that were modfied
					// when the draggable entered the sortable area (#9481)
					sortable.options.revert = sortable.options._revert;
					sortable.options.helper = sortable.options._helper;

					if ( sortable.placeholder ) {
						sortable.placeholder.remove();
					}

					// Restore and recalculate the draggable's offset considering the sortable
					// may have modified them in unexpected ways. (#8809, #10669)
					ui.helper.appendTo( draggable._parent );
					draggable._refreshOffsets( event );
					ui.position = draggable._generatePosition( event, true );

					draggable._trigger( "fromSortable", event );

					// Inform draggable that the helper is no longer in a valid drop zone
					draggable.dropped = false;

					// Need to refreshPositions of all sortables just in case removing
					// from one sortable changes the location of other sortables (#9675)
					$.each( draggable.sortables, function() {
						this.refreshPositions();
					});
				}
			}
		});
	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function( event, ui, instance ) {
		var t = $( "body" ),
			o = instance.options;

		if (t.css("cursor")) {
			o._cursor = t.css("cursor");
		}
		t.css("cursor", o.cursor);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if (o._cursor) {
			$("body").css("cursor", o._cursor);
		}
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;
		if (t.css("opacity")) {
			o._opacity = t.css("opacity");
		}
		t.css("opacity", o.opacity);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;
		if (o._opacity) {
			$(ui.helper).css("opacity", o._opacity);
		}
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function( event, ui, i ) {
		if ( !i.scrollParentNotHidden ) {
			i.scrollParentNotHidden = i.helper.scrollParent( false );
		}

		if ( i.scrollParentNotHidden[ 0 ] !== i.document[ 0 ] && i.scrollParentNotHidden[ 0 ].tagName !== "HTML" ) {
			i.overflowOffset = i.scrollParentNotHidden.offset();
		}
	},
	drag: function( event, ui, i  ) {

		var o = i.options,
			scrolled = false,
			scrollParent = i.scrollParentNotHidden[ 0 ],
			document = i.document[ 0 ];

		if ( scrollParent !== document && scrollParent.tagName !== "HTML" ) {
			if ( !o.axis || o.axis !== "x" ) {
				if ( ( i.overflowOffset.top + scrollParent.offsetHeight ) - event.pageY < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop + o.scrollSpeed;
				} else if ( event.pageY - i.overflowOffset.top < o.scrollSensitivity ) {
					scrollParent.scrollTop = scrolled = scrollParent.scrollTop - o.scrollSpeed;
				}
			}

			if ( !o.axis || o.axis !== "y" ) {
				if ( ( i.overflowOffset.left + scrollParent.offsetWidth ) - event.pageX < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft + o.scrollSpeed;
				} else if ( event.pageX - i.overflowOffset.left < o.scrollSensitivity ) {
					scrollParent.scrollLeft = scrolled = scrollParent.scrollLeft - o.scrollSpeed;
				}
			}

		} else {

			if (!o.axis || o.axis !== "x") {
				if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				} else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
				}
			}

			if (!o.axis || o.axis !== "y") {
				if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				} else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
				}
			}

		}

		if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(i, event);
		}

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function( event, ui, i ) {

		var o = i.options;

		i.snapElements = [];

		$(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
			var $t = $(this),
				$o = $t.offset();
			if (this !== i.element[0]) {
				i.snapElements.push({
					item: this,
					width: $t.outerWidth(), height: $t.outerHeight(),
					top: $o.top, left: $o.left
				});
			}
		});

	},
	drag: function( event, ui, inst ) {

		var ts, bs, ls, rs, l, r, t, b, i, first,
			o = inst.options,
			d = o.snapTolerance,
			x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (i = inst.snapElements.length - 1; i >= 0; i--){

			l = inst.snapElements[i].left - inst.margins.left;
			r = l + inst.snapElements[i].width;
			t = inst.snapElements[i].top - inst.margins.top;
			b = t + inst.snapElements[i].height;

			if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) {
				if (inst.snapElements[i].snapping) {
					(inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				}
				inst.snapElements[i].snapping = false;
				continue;
			}

			if (o.snapMode !== "inner") {
				ts = Math.abs(t - y2) <= d;
				bs = Math.abs(b - y1) <= d;
				ls = Math.abs(l - x2) <= d;
				rs = Math.abs(r - x1) <= d;
				if (ts) {
					ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top;
				}
				if (bs) {
					ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top;
				}
				if (ls) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left;
				}
				if (rs) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left;
				}
			}

			first = (ts || bs || ls || rs);

			if (o.snapMode !== "outer") {
				ts = Math.abs(t - y1) <= d;
				bs = Math.abs(b - y2) <= d;
				ls = Math.abs(l - x1) <= d;
				rs = Math.abs(r - x2) <= d;
				if (ts) {
					ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top;
				}
				if (bs) {
					ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top;
				}
				if (ls) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left;
				}
				if (rs) {
					ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left;
				}
			}

			if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			}
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		}

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function( event, ui, instance ) {
		var min,
			o = instance.options,
			group = $.makeArray($(o.stack)).sort(function(a, b) {
				return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0);
			});

		if (!group.length) { return; }

		min = parseInt($(group[0]).css("zIndex"), 10) || 0;
		$(group).each(function(i) {
			$(this).css("zIndex", min + i);
		});
		this.css("zIndex", (min + group.length));
	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function( event, ui, instance ) {
		var t = $( ui.helper ),
			o = instance.options;

		if (t.css("zIndex")) {
			o._zIndex = t.css("zIndex");
		}
		t.css("zIndex", o.zIndex);
	},
	stop: function( event, ui, instance ) {
		var o = instance.options;

		if (o._zIndex) {
			$(ui.helper).css("zIndex", o._zIndex);
		}
	}
});

var draggable = $.ui.draggable;


/*!
 * jQuery UI Resizable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/resizable/
 */


$.widget("ui.resizable", $.ui.mouse, {
	version: "1.11.4",
	widgetEventPrefix: "resize",
	options: {
		alsoResize: false,
		animate: false,
		animateDuration: "slow",
		animateEasing: "swing",
		aspectRatio: false,
		autoHide: false,
		containment: false,
		ghost: false,
		grid: false,
		handles: "e,s,se",
		helper: false,
		maxHeight: null,
		maxWidth: null,
		minHeight: 10,
		minWidth: 10,
		// See #7960
		zIndex: 90,

		// callbacks
		resize: null,
		start: null,
		stop: null
	},

	_num: function( value ) {
		return parseInt( value, 10 ) || 0;
	},

	_isNumber: function( value ) {
		return !isNaN( parseInt( value, 10 ) );
	},

	_hasScroll: function( el, a ) {

		if ( $( el ).css( "overflow" ) === "hidden") {
			return false;
		}

		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
			has = false;

		if ( el[ scroll ] > 0 ) {
			return true;
		}

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[ scroll ] = 1;
		has = ( el[ scroll ] > 0 );
		el[ scroll ] = 0;
		return has;
	},

	_create: function() {

		var n, i, handle, axis, hname,
			that = this,
			o = this.options;
		this.element.addClass("ui-resizable");

		$.extend(this, {
			_aspectRatio: !!(o.aspectRatio),
			aspectRatio: o.aspectRatio,
			originalElement: this.element,
			_proportionallyResizeElements: [],
			_helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null
		});

		// Wrap the element if it cannot hold child nodes
		if (this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)) {

			this.element.wrap(
				$("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({
					position: this.element.css("position"),
					width: this.element.outerWidth(),
					height: this.element.outerHeight(),
					top: this.element.css("top"),
					left: this.element.css("left")
				})
			);

			this.element = this.element.parent().data(
				"ui-resizable", this.element.resizable( "instance" )
			);

			this.elementIsWrapper = true;

			this.element.css({
				marginLeft: this.originalElement.css("marginLeft"),
				marginTop: this.originalElement.css("marginTop"),
				marginRight: this.originalElement.css("marginRight"),
				marginBottom: this.originalElement.css("marginBottom")
			});
			this.originalElement.css({
				marginLeft: 0,
				marginTop: 0,
				marginRight: 0,
				marginBottom: 0
			});
			// support: Safari
			// Prevent Safari textarea resize
			this.originalResizeStyle = this.originalElement.css("resize");
			this.originalElement.css("resize", "none");

			this._proportionallyResizeElements.push( this.originalElement.css({
				position: "static",
				zoom: 1,
				display: "block"
			}) );

			// support: IE9
			// avoid IE jump (hard set the margin)
			this.originalElement.css({ margin: this.originalElement.css("margin") });

			this._proportionallyResize();
		}

		this.handles = o.handles ||
			( !$(".ui-resizable-handle", this.element).length ?
				"e,s,se" : {
					n: ".ui-resizable-n",
					e: ".ui-resizable-e",
					s: ".ui-resizable-s",
					w: ".ui-resizable-w",
					se: ".ui-resizable-se",
					sw: ".ui-resizable-sw",
					ne: ".ui-resizable-ne",
					nw: ".ui-resizable-nw"
				} );

		this._handles = $();
		if ( this.handles.constructor === String ) {

			if ( this.handles === "all") {
				this.handles = "n,e,s,w,se,sw,ne,nw";
			}

			n = this.handles.split(",");
			this.handles = {};

			for (i = 0; i < n.length; i++) {

				handle = $.trim(n[i]);
				hname = "ui-resizable-" + handle;
				axis = $("<div class='ui-resizable-handle " + hname + "'></div>");

				axis.css({ zIndex: o.zIndex });

				// TODO : What's going on here?
				if ("se" === handle) {
					axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se");
				}

				this.handles[handle] = ".ui-resizable-" + handle;
				this.element.append(axis);
			}

		}

		this._renderAxis = function(target) {

			var i, axis, padPos, padWrapper;

			target = target || this.element;

			for (i in this.handles) {

				if (this.handles[i].constructor === String) {
					this.handles[i] = this.element.children( this.handles[ i ] ).first().show();
				} else if ( this.handles[ i ].jquery || this.handles[ i ].nodeType ) {
					this.handles[ i ] = $( this.handles[ i ] );
					this._on( this.handles[ i ], { "mousedown": that._mouseDown });
				}

				if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)) {

					axis = $(this.handles[i], this.element);

					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();

					padPos = [ "padding",
						/ne|nw|n/.test(i) ? "Top" :
						/se|sw|s/.test(i) ? "Bottom" :
						/^e$/.test(i) ? "Right" : "Left" ].join("");

					target.css(padPos, padWrapper);

					this._proportionallyResize();
				}

				this._handles = this._handles.add( this.handles[ i ] );
			}
		};

		// TODO: make renderAxis a prototype function
		this._renderAxis(this.element);

		this._handles = this._handles.add( this.element.find( ".ui-resizable-handle" ) );
		this._handles.disableSelection();

		this._handles.mouseover(function() {
			if (!that.resizing) {
				if (this.className) {
					axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
				}
				that.axis = axis && axis[1] ? axis[1] : "se";
			}
		});

		if (o.autoHide) {
			this._handles.hide();
			$(this.element)
				.addClass("ui-resizable-autohide")
				.mouseenter(function() {
					if (o.disabled) {
						return;
					}
					$(this).removeClass("ui-resizable-autohide");
					that._handles.show();
				})
				.mouseleave(function() {
					if (o.disabled) {
						return;
					}
					if (!that.resizing) {
						$(this).addClass("ui-resizable-autohide");
						that._handles.hide();
					}
				});
		}

		this._mouseInit();
	},

	_destroy: function() {

		this._mouseDestroy();

		var wrapper,
			_destroy = function(exp) {
				$(exp)
					.removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
					.removeData("resizable")
					.removeData("ui-resizable")
					.unbind(".resizable")
					.find(".ui-resizable-handle")
						.remove();
			};

		// TODO: Unwrap at same DOM position
		if (this.elementIsWrapper) {
			_destroy(this.element);
			wrapper = this.element;
			this.originalElement.css({
				position: wrapper.css("position"),
				width: wrapper.outerWidth(),
				height: wrapper.outerHeight(),
				top: wrapper.css("top"),
				left: wrapper.css("left")
			}).insertAfter( wrapper );
			wrapper.remove();
		}

		this.originalElement.css("resize", this.originalResizeStyle);
		_destroy(this.originalElement);

		return this;
	},

	_mouseCapture: function(event) {
		var i, handle,
			capture = false;

		for (i in this.handles) {
			handle = $(this.handles[i])[0];
			if (handle === event.target || $.contains(handle, event.target)) {
				capture = true;
			}
		}

		return !this.options.disabled && capture;
	},

	_mouseStart: function(event) {

		var curleft, curtop, cursor,
			o = this.options,
			el = this.element;

		this.resizing = true;

		this._renderProxy();

		curleft = this._num(this.helper.css("left"));
		curtop = this._num(this.helper.css("top"));

		if (o.containment) {
			curleft += $(o.containment).scrollLeft() || 0;
			curtop += $(o.containment).scrollTop() || 0;
		}

		this.offset = this.helper.offset();
		this.position = { left: curleft, top: curtop };

		this.size = this._helper ? {
				width: this.helper.width(),
				height: this.helper.height()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.originalSize = this._helper ? {
				width: el.outerWidth(),
				height: el.outerHeight()
			} : {
				width: el.width(),
				height: el.height()
			};

		this.sizeDiff = {
			width: el.outerWidth() - el.width(),
			height: el.outerHeight() - el.height()
		};

		this.originalPosition = { left: curleft, top: curtop };
		this.originalMousePosition = { left: event.pageX, top: event.pageY };

		this.aspectRatio = (typeof o.aspectRatio === "number") ?
			o.aspectRatio :
			((this.originalSize.width / this.originalSize.height) || 1);

		cursor = $(".ui-resizable-" + this.axis).css("cursor");
		$("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor);

		el.addClass("ui-resizable-resizing");
		this._propagate("start", event);
		return true;
	},

	_mouseDrag: function(event) {

		var data, props,
			smp = this.originalMousePosition,
			a = this.axis,
			dx = (event.pageX - smp.left) || 0,
			dy = (event.pageY - smp.top) || 0,
			trigger = this._change[a];

		this._updatePrevProperties();

		if (!trigger) {
			return false;
		}

		data = trigger.apply(this, [ event, dx, dy ]);

		this._updateVirtualBoundaries(event.shiftKey);
		if (this._aspectRatio || event.shiftKey) {
			data = this._updateRatio(data, event);
		}

		data = this._respectSize(data, event);

		this._updateCache(data);

		this._propagate("resize", event);

		props = this._applyChanges();

		if ( !this._helper && this._proportionallyResizeElements.length ) {
			this._proportionallyResize();
		}

		if ( !$.isEmptyObject( props ) ) {
			this._updatePrevProperties();
			this._trigger( "resize", event, this.ui() );
			this._applyChanges();
		}

		return false;
	},

	_mouseStop: function(event) {

		this.resizing = false;
		var pr, ista, soffseth, soffsetw, s, left, top,
			o = this.options, that = this;

		if (this._helper) {

			pr = this._proportionallyResizeElements;
			ista = pr.length && (/textarea/i).test(pr[0].nodeName);
			soffseth = ista && this._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height;
			soffsetw = ista ? 0 : that.sizeDiff.width;

			s = {
				width: (that.helper.width()  - soffsetw),
				height: (that.helper.height() - soffseth)
			};
			left = (parseInt(that.element.css("left"), 10) +
				(that.position.left - that.originalPosition.left)) || null;
			top = (parseInt(that.element.css("top"), 10) +
				(that.position.top - that.originalPosition.top)) || null;

			if (!o.animate) {
				this.element.css($.extend(s, { top: top, left: left }));
			}

			that.helper.height(that.size.height);
			that.helper.width(that.size.width);

			if (this._helper && !o.animate) {
				this._proportionallyResize();
			}
		}

		$("body").css("cursor", "auto");

		this.element.removeClass("ui-resizable-resizing");

		this._propagate("stop", event);

		if (this._helper) {
			this.helper.remove();
		}

		return false;

	},

	_updatePrevProperties: function() {
		this.prevPosition = {
			top: this.position.top,
			left: this.position.left
		};
		this.prevSize = {
			width: this.size.width,
			height: this.size.height
		};
	},

	_applyChanges: function() {
		var props = {};

		if ( this.position.top !== this.prevPosition.top ) {
			props.top = this.position.top + "px";
		}
		if ( this.position.left !== this.prevPosition.left ) {
			props.left = this.position.left + "px";
		}
		if ( this.size.width !== this.prevSize.width ) {
			props.width = this.size.width + "px";
		}
		if ( this.size.height !== this.prevSize.height ) {
			props.height = this.size.height + "px";
		}

		this.helper.css( props );

		return props;
	},

	_updateVirtualBoundaries: function(forceAspectRatio) {
		var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b,
			o = this.options;

		b = {
			minWidth: this._isNumber(o.minWidth) ? o.minWidth : 0,
			maxWidth: this._isNumber(o.maxWidth) ? o.maxWidth : Infinity,
			minHeight: this._isNumber(o.minHeight) ? o.minHeight : 0,
			maxHeight: this._isNumber(o.maxHeight) ? o.maxHeight : Infinity
		};

		if (this._aspectRatio || forceAspectRatio) {
			pMinWidth = b.minHeight * this.aspectRatio;
			pMinHeight = b.minWidth / this.aspectRatio;
			pMaxWidth = b.maxHeight * this.aspectRatio;
			pMaxHeight = b.maxWidth / this.aspectRatio;

			if (pMinWidth > b.minWidth) {
				b.minWidth = pMinWidth;
			}
			if (pMinHeight > b.minHeight) {
				b.minHeight = pMinHeight;
			}
			if (pMaxWidth < b.maxWidth) {
				b.maxWidth = pMaxWidth;
			}
			if (pMaxHeight < b.maxHeight) {
				b.maxHeight = pMaxHeight;
			}
		}
		this._vBoundaries = b;
	},

	_updateCache: function(data) {
		this.offset = this.helper.offset();
		if (this._isNumber(data.left)) {
			this.position.left = data.left;
		}
		if (this._isNumber(data.top)) {
			this.position.top = data.top;
		}
		if (this._isNumber(data.height)) {
			this.size.height = data.height;
		}
		if (this._isNumber(data.width)) {
			this.size.width = data.width;
		}
	},

	_updateRatio: function( data ) {

		var cpos = this.position,
			csize = this.size,
			a = this.axis;

		if (this._isNumber(data.height)) {
			data.width = (data.height * this.aspectRatio);
		} else if (this._isNumber(data.width)) {
			data.height = (data.width / this.aspectRatio);
		}

		if (a === "sw") {
			data.left = cpos.left + (csize.width - data.width);
			data.top = null;
		}
		if (a === "nw") {
			data.top = cpos.top + (csize.height - data.height);
			data.left = cpos.left + (csize.width - data.width);
		}

		return data;
	},

	_respectSize: function( data ) {

		var o = this._vBoundaries,
			a = this.axis,
			ismaxw = this._isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width),
			ismaxh = this._isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
			isminw = this._isNumber(data.width) && o.minWidth && (o.minWidth > data.width),
			isminh = this._isNumber(data.height) && o.minHeight && (o.minHeight > data.height),
			dw = this.originalPosition.left + this.originalSize.width,
			dh = this.position.top + this.size.height,
			cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
		if (isminw) {
			data.width = o.minWidth;
		}
		if (isminh) {
			data.height = o.minHeight;
		}
		if (ismaxw) {
			data.width = o.maxWidth;
		}
		if (ismaxh) {
			data.height = o.maxHeight;
		}

		if (isminw && cw) {
			data.left = dw - o.minWidth;
		}
		if (ismaxw && cw) {
			data.left = dw - o.maxWidth;
		}
		if (isminh && ch) {
			data.top = dh - o.minHeight;
		}
		if (ismaxh && ch) {
			data.top = dh - o.maxHeight;
		}

		// Fixing jump error on top/left - bug #2330
		if (!data.width && !data.height && !data.left && data.top) {
			data.top = null;
		} else if (!data.width && !data.height && !data.top && data.left) {
			data.left = null;
		}

		return data;
	},

	_getPaddingPlusBorderDimensions: function( element ) {
		var i = 0,
			widths = [],
			borders = [
				element.css( "borderTopWidth" ),
				element.css( "borderRightWidth" ),
				element.css( "borderBottomWidth" ),
				element.css( "borderLeftWidth" )
			],
			paddings = [
				element.css( "paddingTop" ),
				element.css( "paddingRight" ),
				element.css( "paddingBottom" ),
				element.css( "paddingLeft" )
			];

		for ( ; i < 4; i++ ) {
			widths[ i ] = ( parseInt( borders[ i ], 10 ) || 0 );
			widths[ i ] += ( parseInt( paddings[ i ], 10 ) || 0 );
		}

		return {
			height: widths[ 0 ] + widths[ 2 ],
			width: widths[ 1 ] + widths[ 3 ]
		};
	},

	_proportionallyResize: function() {

		if (!this._proportionallyResizeElements.length) {
			return;
		}

		var prel,
			i = 0,
			element = this.helper || this.element;

		for ( ; i < this._proportionallyResizeElements.length; i++) {

			prel = this._proportionallyResizeElements[i];

			// TODO: Seems like a bug to cache this.outerDimensions
			// considering that we are in a loop.
			if (!this.outerDimensions) {
				this.outerDimensions = this._getPaddingPlusBorderDimensions( prel );
			}

			prel.css({
				height: (element.height() - this.outerDimensions.height) || 0,
				width: (element.width() - this.outerDimensions.width) || 0
			});

		}

	},

	_renderProxy: function() {

		var el = this.element, o = this.options;
		this.elementOffset = el.offset();

		if (this._helper) {

			this.helper = this.helper || $("<div style='overflow:hidden;'></div>");

			this.helper.addClass(this._helper).css({
				width: this.element.outerWidth() - 1,
				height: this.element.outerHeight() - 1,
				position: "absolute",
				left: this.elementOffset.left + "px",
				top: this.elementOffset.top + "px",
				zIndex: ++o.zIndex //TODO: Don't modify option
			});

			this.helper
				.appendTo("body")
				.disableSelection();

		} else {
			this.helper = this.element;
		}

	},

	_change: {
		e: function(event, dx) {
			return { width: this.originalSize.width + dx };
		},
		w: function(event, dx) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { left: sp.left + dx, width: cs.width - dx };
		},
		n: function(event, dx, dy) {
			var cs = this.originalSize, sp = this.originalPosition;
			return { top: sp.top + dy, height: cs.height - dy };
		},
		s: function(event, dx, dy) {
			return { height: this.originalSize.height + dy };
		},
		se: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments),
				this._change.e.apply(this, [ event, dx, dy ]));
		},
		sw: function(event, dx, dy) {
			return $.extend(this._change.s.apply(this, arguments),
				this._change.w.apply(this, [ event, dx, dy ]));
		},
		ne: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments),
				this._change.e.apply(this, [ event, dx, dy ]));
		},
		nw: function(event, dx, dy) {
			return $.extend(this._change.n.apply(this, arguments),
				this._change.w.apply(this, [ event, dx, dy ]));
		}
	},

	_propagate: function(n, event) {
		$.ui.plugin.call(this, n, [ event, this.ui() ]);
		(n !== "resize" && this._trigger(n, event, this.ui()));
	},

	plugins: {},

	ui: function() {
		return {
			originalElement: this.originalElement,
			element: this.element,
			helper: this.helper,
			position: this.position,
			size: this.size,
			originalSize: this.originalSize,
			originalPosition: this.originalPosition
		};
	}

});

/*
 * Resizable Extensions
 */

$.ui.plugin.add("resizable", "animate", {

	stop: function( event ) {
		var that = $(this).resizable( "instance" ),
			o = that.options,
			pr = that._proportionallyResizeElements,
			ista = pr.length && (/textarea/i).test(pr[0].nodeName),
			soffseth = ista && that._hasScroll(pr[0], "left") ? 0 : that.sizeDiff.height,
			soffsetw = ista ? 0 : that.sizeDiff.width,
			style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
			left = (parseInt(that.element.css("left"), 10) +
				(that.position.left - that.originalPosition.left)) || null,
			top = (parseInt(that.element.css("top"), 10) +
				(that.position.top - that.originalPosition.top)) || null;

		that.element.animate(
			$.extend(style, top && left ? { top: top, left: left } : {}), {
				duration: o.animateDuration,
				easing: o.animateEasing,
				step: function() {

					var data = {
						width: parseInt(that.element.css("width"), 10),
						height: parseInt(that.element.css("height"), 10),
						top: parseInt(that.element.css("top"), 10),
						left: parseInt(that.element.css("left"), 10)
					};

					if (pr && pr.length) {
						$(pr[0]).css({ width: data.width, height: data.height });
					}

					// propagating resize, and updating values for each animation step
					that._updateCache(data);
					that._propagate("resize", event);

				}
			}
		);
	}

});

$.ui.plugin.add( "resizable", "containment", {

	start: function() {
		var element, p, co, ch, cw, width, height,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			el = that.element,
			oc = o.containment,
			ce = ( oc instanceof $ ) ? oc.get( 0 ) : ( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc;

		if ( !ce ) {
			return;
		}

		that.containerElement = $( ce );

		if ( /document/.test( oc ) || oc === document ) {
			that.containerOffset = {
				left: 0,
				top: 0
			};
			that.containerPosition = {
				left: 0,
				top: 0
			};

			that.parentData = {
				element: $( document ),
				left: 0,
				top: 0,
				width: $( document ).width(),
				height: $( document ).height() || document.body.parentNode.scrollHeight
			};
		} else {
			element = $( ce );
			p = [];
			$([ "Top", "Right", "Left", "Bottom" ]).each(function( i, name ) {
				p[ i ] = that._num( element.css( "padding" + name ) );
			});

			that.containerOffset = element.offset();
			that.containerPosition = element.position();
			that.containerSize = {
				height: ( element.innerHeight() - p[ 3 ] ),
				width: ( element.innerWidth() - p[ 1 ] )
			};

			co = that.containerOffset;
			ch = that.containerSize.height;
			cw = that.containerSize.width;
			width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw );
			height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ;

			that.parentData = {
				element: ce,
				left: co.left,
				top: co.top,
				width: width,
				height: height
			};
		}
	},

	resize: function( event ) {
		var woset, hoset, isParent, isOffsetRelative,
			that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cp = that.position,
			pRatio = that._aspectRatio || event.shiftKey,
			cop = {
				top: 0,
				left: 0
			},
			ce = that.containerElement,
			continueResize = true;

		if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) {
			cop = co;
		}

		if ( cp.left < ( that._helper ? co.left : 0 ) ) {
			that.size.width = that.size.width +
				( that._helper ?
					( that.position.left - co.left ) :
					( that.position.left - cop.left ) );

			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
			that.position.left = o.helper ? co.left : 0;
		}

		if ( cp.top < ( that._helper ? co.top : 0 ) ) {
			that.size.height = that.size.height +
				( that._helper ?
					( that.position.top - co.top ) :
					that.position.top );

			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
			that.position.top = that._helper ? co.top : 0;
		}

		isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 );
		isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) );

		if ( isParent && isOffsetRelative ) {
			that.offset.left = that.parentData.left + that.position.left;
			that.offset.top = that.parentData.top + that.position.top;
		} else {
			that.offset.left = that.element.offset().left;
			that.offset.top = that.element.offset().top;
		}

		woset = Math.abs( that.sizeDiff.width +
			(that._helper ?
				that.offset.left - cop.left :
				(that.offset.left - co.left)) );

		hoset = Math.abs( that.sizeDiff.height +
			(that._helper ?
				that.offset.top - cop.top :
				(that.offset.top - co.top)) );

		if ( woset + that.size.width >= that.parentData.width ) {
			that.size.width = that.parentData.width - woset;
			if ( pRatio ) {
				that.size.height = that.size.width / that.aspectRatio;
				continueResize = false;
			}
		}

		if ( hoset + that.size.height >= that.parentData.height ) {
			that.size.height = that.parentData.height - hoset;
			if ( pRatio ) {
				that.size.width = that.size.height * that.aspectRatio;
				continueResize = false;
			}
		}

		if ( !continueResize ) {
			that.position.left = that.prevPosition.left;
			that.position.top = that.prevPosition.top;
			that.size.width = that.prevSize.width;
			that.size.height = that.prevSize.height;
		}
	},

	stop: function() {
		var that = $( this ).resizable( "instance" ),
			o = that.options,
			co = that.containerOffset,
			cop = that.containerPosition,
			ce = that.containerElement,
			helper = $( that.helper ),
			ho = helper.offset(),
			w = helper.outerWidth() - that.sizeDiff.width,
			h = helper.outerHeight() - that.sizeDiff.height;

		if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) {
			$( this ).css({
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			});
		}

		if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) {
			$( this ).css({
				left: ho.left - cop.left - co.left,
				width: w,
				height: h
			});
		}
	}
});

$.ui.plugin.add("resizable", "alsoResize", {

	start: function() {
		var that = $(this).resizable( "instance" ),
			o = that.options;

		$(o.alsoResize).each(function() {
			var el = $(this);
			el.data("ui-resizable-alsoresize", {
				width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
				left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10)
			});
		});
	},

	resize: function(event, ui) {
		var that = $(this).resizable( "instance" ),
			o = that.options,
			os = that.originalSize,
			op = that.originalPosition,
			delta = {
				height: (that.size.height - os.height) || 0,
				width: (that.size.width - os.width) || 0,
				top: (that.position.top - op.top) || 0,
				left: (that.position.left - op.left) || 0
			};

			$(o.alsoResize).each(function() {
				var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {},
					css = el.parents(ui.originalElement[0]).length ?
							[ "width", "height" ] :
							[ "width", "height", "top", "left" ];

				$.each(css, function(i, prop) {
					var sum = (start[prop] || 0) + (delta[prop] || 0);
					if (sum && sum >= 0) {
						style[prop] = sum || null;
					}
				});

				el.css(style);
			});
	},

	stop: function() {
		$(this).removeData("resizable-alsoresize");
	}
});

$.ui.plugin.add("resizable", "ghost", {

	start: function() {

		var that = $(this).resizable( "instance" ), o = that.options, cs = that.size;

		that.ghost = that.originalElement.clone();
		that.ghost
			.css({
				opacity: 0.25,
				display: "block",
				position: "relative",
				height: cs.height,
				width: cs.width,
				margin: 0,
				left: 0,
				top: 0
			})
			.addClass("ui-resizable-ghost")
			.addClass(typeof o.ghost === "string" ? o.ghost : "");

		that.ghost.appendTo(that.helper);

	},

	resize: function() {
		var that = $(this).resizable( "instance" );
		if (that.ghost) {
			that.ghost.css({
				position: "relative",
				height: that.size.height,
				width: that.size.width
			});
		}
	},

	stop: function() {
		var that = $(this).resizable( "instance" );
		if (that.ghost && that.helper) {
			that.helper.get(0).removeChild(that.ghost.get(0));
		}
	}

});

$.ui.plugin.add("resizable", "grid", {

	resize: function() {
		var outerDimensions,
			that = $(this).resizable( "instance" ),
			o = that.options,
			cs = that.size,
			os = that.originalSize,
			op = that.originalPosition,
			a = that.axis,
			grid = typeof o.grid === "number" ? [ o.grid, o.grid ] : o.grid,
			gridX = (grid[0] || 1),
			gridY = (grid[1] || 1),
			ox = Math.round((cs.width - os.width) / gridX) * gridX,
			oy = Math.round((cs.height - os.height) / gridY) * gridY,
			newWidth = os.width + ox,
			newHeight = os.height + oy,
			isMaxWidth = o.maxWidth && (o.maxWidth < newWidth),
			isMaxHeight = o.maxHeight && (o.maxHeight < newHeight),
			isMinWidth = o.minWidth && (o.minWidth > newWidth),
			isMinHeight = o.minHeight && (o.minHeight > newHeight);

		o.grid = grid;

		if (isMinWidth) {
			newWidth += gridX;
		}
		if (isMinHeight) {
			newHeight += gridY;
		}
		if (isMaxWidth) {
			newWidth -= gridX;
		}
		if (isMaxHeight) {
			newHeight -= gridY;
		}

		if (/^(se|s|e)$/.test(a)) {
			that.size.width = newWidth;
			that.size.height = newHeight;
		} else if (/^(ne)$/.test(a)) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.top = op.top - oy;
		} else if (/^(sw)$/.test(a)) {
			that.size.width = newWidth;
			that.size.height = newHeight;
			that.position.left = op.left - ox;
		} else {
			if ( newHeight - gridY <= 0 || newWidth - gridX <= 0) {
				outerDimensions = that._getPaddingPlusBorderDimensions( this );
			}

			if ( newHeight - gridY > 0 ) {
				that.size.height = newHeight;
				that.position.top = op.top - oy;
			} else {
				newHeight = gridY - outerDimensions.height;
				that.size.height = newHeight;
				that.position.top = op.top + os.height - newHeight;
			}
			if ( newWidth - gridX > 0 ) {
				that.size.width = newWidth;
				that.position.left = op.left - ox;
			} else {
				newWidth = gridX - outerDimensions.width;
				that.size.width = newWidth;
				that.position.left = op.left + os.width - newWidth;
			}
		}
	}

});

var resizable = $.ui.resizable;


/*!
 * jQuery UI Dialog 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/dialog/
 */


var dialog = $.widget( "ui.dialog", {
	version: "1.11.4",
	options: {
		appendTo: "body",
		autoOpen: true,
		buttons: [],
		closeOnEscape: true,
		closeText: "Close",
		dialogClass: "",
		draggable: true,
		hide: null,
		height: "auto",
		maxHeight: null,
		maxWidth: null,
		minHeight: 150,
		minWidth: 150,
		modal: false,
		position: {
			my: "center",
			at: "center",
			of: window,
			collision: "fit",
			// Ensure the titlebar is always visible
			using: function( pos ) {
				var topOffset = $( this ).css( pos ).offset().top;
				if ( topOffset < 0 ) {
					$( this ).css( "top", pos.top - topOffset );
				}
			}
		},
		resizable: true,
		show: null,
		title: null,
		width: 300,

		// callbacks
		beforeClose: null,
		close: null,
		drag: null,
		dragStart: null,
		dragStop: null,
		focus: null,
		open: null,
		resize: null,
		resizeStart: null,
		resizeStop: null
	},

	sizeRelatedOptions: {
		buttons: true,
		height: true,
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true,
		width: true
	},

	resizableRelatedOptions: {
		maxHeight: true,
		maxWidth: true,
		minHeight: true,
		minWidth: true
	},

	_create: function() {
		this.originalCss = {
			display: this.element[ 0 ].style.display,
			width: this.element[ 0 ].style.width,
			minHeight: this.element[ 0 ].style.minHeight,
			maxHeight: this.element[ 0 ].style.maxHeight,
			height: this.element[ 0 ].style.height
		};
		this.originalPosition = {
			parent: this.element.parent(),
			index: this.element.parent().children().index( this.element )
		};
		this.originalTitle = this.element.attr( "title" );
		this.options.title = this.options.title || this.originalTitle;

		this._createWrapper();

		this.element
			.show()
			.removeAttr( "title" )
			.addClass( "ui-dialog-content ui-widget-content" )
			.appendTo( this.uiDialog );

		this._createTitlebar();
		this._createButtonPane();

		if ( this.options.draggable && $.fn.draggable ) {
			this._makeDraggable();
		}
		if ( this.options.resizable && $.fn.resizable ) {
			this._makeResizable();
		}

		this._isOpen = false;

		this._trackFocus();
	},

	_init: function() {
		if ( this.options.autoOpen ) {
			this.open();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;
		if ( element && (element.jquery || element.nodeType) ) {
			return $( element );
		}
		return this.document.find( element || "body" ).eq( 0 );
	},

	_destroy: function() {
		var next,
			originalPosition = this.originalPosition;

		this._untrackInstance();
		this._destroyOverlay();

		this.element
			.removeUniqueId()
			.removeClass( "ui-dialog-content ui-widget-content" )
			.css( this.originalCss )
			// Without detaching first, the following becomes really slow
			.detach();

		this.uiDialog.stop( true, true ).remove();

		if ( this.originalTitle ) {
			this.element.attr( "title", this.originalTitle );
		}

		next = originalPosition.parent.children().eq( originalPosition.index );
		// Don't try to place the dialog next to itself (#8613)
		if ( next.length && next[ 0 ] !== this.element[ 0 ] ) {
			next.before( this.element );
		} else {
			originalPosition.parent.append( this.element );
		}
	},

	widget: function() {
		return this.uiDialog;
	},

	disable: $.noop,
	enable: $.noop,

	close: function( event ) {
		var activeElement,
			that = this;

		if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) {
			return;
		}

		this._isOpen = false;
		this._focusedElement = null;
		this._destroyOverlay();
		this._untrackInstance();

		if ( !this.opener.filter( ":focusable" ).focus().length ) {

			// support: IE9
			// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
			try {
				activeElement = this.document[ 0 ].activeElement;

				// Support: IE9, IE10
				// If the <body> is blurred, IE will switch windows, see #4520
				if ( activeElement && activeElement.nodeName.toLowerCase() !== "body" ) {

					// Hiding a focused element doesn't trigger blur in WebKit
					// so in case we have nothing to focus on, explicitly blur the active element
					// https://bugs.webkit.org/show_bug.cgi?id=47182
					$( activeElement ).blur();
				}
			} catch ( error ) {}
		}

		this._hide( this.uiDialog, this.options.hide, function() {
			that._trigger( "close", event );
		});
	},

	isOpen: function() {
		return this._isOpen;
	},

	moveToTop: function() {
		this._moveToTop();
	},

	_moveToTop: function( event, silent ) {
		var moved = false,
			zIndices = this.uiDialog.siblings( ".ui-front:visible" ).map(function() {
				return +$( this ).css( "z-index" );
			}).get(),
			zIndexMax = Math.max.apply( null, zIndices );

		if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) {
			this.uiDialog.css( "z-index", zIndexMax + 1 );
			moved = true;
		}

		if ( moved && !silent ) {
			this._trigger( "focus", event );
		}
		return moved;
	},

	open: function() {
		var that = this;
		if ( this._isOpen ) {
			if ( this._moveToTop() ) {
				this._focusTabbable();
			}
			return;
		}

		this._isOpen = true;
		this.opener = $( this.document[ 0 ].activeElement );

		this._size();
		this._position();
		this._createOverlay();
		this._moveToTop( null, true );

		// Ensure the overlay is moved to the top with the dialog, but only when
		// opening. The overlay shouldn't move after the dialog is open so that
		// modeless dialogs opened after the modal dialog stack properly.
		if ( this.overlay ) {
			this.overlay.css( "z-index", this.uiDialog.css( "z-index" ) - 1 );
		}

		this._show( this.uiDialog, this.options.show, function() {
			that._focusTabbable();
			that._trigger( "focus" );
		});

		// Track the dialog immediately upon openening in case a focus event
		// somehow occurs outside of the dialog before an element inside the
		// dialog is focused (#10152)
		this._makeFocusTarget();

		this._trigger( "open" );
	},

	_focusTabbable: function() {
		// Set focus to the first match:
		// 1. An element that was focused previously
		// 2. First element inside the dialog matching [autofocus]
		// 3. Tabbable element inside the content element
		// 4. Tabbable element inside the buttonpane
		// 5. The close button
		// 6. The dialog itself
		var hasFocus = this._focusedElement;
		if ( !hasFocus ) {
			hasFocus = this.element.find( "[autofocus]" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.element.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogButtonPane.find( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" );
		}
		if ( !hasFocus.length ) {
			hasFocus = this.uiDialog;
		}
		hasFocus.eq( 0 ).focus();
	},

	_keepFocus: function( event ) {
		function checkFocus() {
			var activeElement = this.document[0].activeElement,
				isActive = this.uiDialog[0] === activeElement ||
					$.contains( this.uiDialog[0], activeElement );
			if ( !isActive ) {
				this._focusTabbable();
			}
		}
		event.preventDefault();
		checkFocus.call( this );
		// support: IE
		// IE <= 8 doesn't prevent moving focus even with event.preventDefault()
		// so we check again later
		this._delay( checkFocus );
	},

	_createWrapper: function() {
		this.uiDialog = $("<div>")
			.addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " +
				this.options.dialogClass )
			.hide()
			.attr({
				// Setting tabIndex makes the div focusable
				tabIndex: -1,
				role: "dialog"
			})
			.appendTo( this._appendTo() );

		this._on( this.uiDialog, {
			keydown: function( event ) {
				if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
						event.keyCode === $.ui.keyCode.ESCAPE ) {
					event.preventDefault();
					this.close( event );
					return;
				}

				// prevent tabbing out of dialogs
				if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) {
					return;
				}
				var tabbables = this.uiDialog.find( ":tabbable" ),
					first = tabbables.filter( ":first" ),
					last = tabbables.filter( ":last" );

				if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) {
					this._delay(function() {
						first.focus();
					});
					event.preventDefault();
				} else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) {
					this._delay(function() {
						last.focus();
					});
					event.preventDefault();
				}
			},
			mousedown: function( event ) {
				if ( this._moveToTop( event ) ) {
					this._focusTabbable();
				}
			}
		});

		// We assume that any existing aria-describedby attribute means
		// that the dialog content is marked up properly
		// otherwise we brute force the content as the description
		if ( !this.element.find( "[aria-describedby]" ).length ) {
			this.uiDialog.attr({
				"aria-describedby": this.element.uniqueId().attr( "id" )
			});
		}
	},

	_createTitlebar: function() {
		var uiDialogTitle;

		this.uiDialogTitlebar = $( "<div>" )
			.addClass( "ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix" )
			.prependTo( this.uiDialog );
		this._on( this.uiDialogTitlebar, {
			mousedown: function( event ) {
				// Don't prevent click on close button (#8838)
				// Focusing a dialog that is partially scrolled out of view
				// causes the browser to scroll it into view, preventing the click event
				if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) {
					// Dialog isn't getting focus when dragging (#8063)
					this.uiDialog.focus();
				}
			}
		});

		// support: IE
		// Use type="button" to prevent enter keypresses in textboxes from closing the
		// dialog in IE (#9312)
		this.uiDialogTitlebarClose = $( "<button type='button'></button>" )
			.button({
				label: this.options.closeText,
				icons: {
					primary: "ui-icon-closethick"
				},
				text: false
			})
			.addClass( "ui-dialog-titlebar-close" )
			.appendTo( this.uiDialogTitlebar );
		this._on( this.uiDialogTitlebarClose, {
			click: function( event ) {
				event.preventDefault();
				this.close( event );
			}
		});

		uiDialogTitle = $( "<span>" )
			.uniqueId()
			.addClass( "ui-dialog-title" )
			.prependTo( this.uiDialogTitlebar );
		this._title( uiDialogTitle );

		this.uiDialog.attr({
			"aria-labelledby": uiDialogTitle.attr( "id" )
		});
	},

	_title: function( title ) {
		if ( !this.options.title ) {
			title.html( "&#160;" );
		}
		title.text( this.options.title );
	},

	_createButtonPane: function() {
		this.uiDialogButtonPane = $( "<div>" )
			.addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" );

		this.uiButtonSet = $( "<div>" )
			.addClass( "ui-dialog-buttonset" )
			.appendTo( this.uiDialogButtonPane );

		this._createButtons();
	},

	_createButtons: function() {
		var that = this,
			buttons = this.options.buttons;

		// if we already have a button pane, remove it
		this.uiDialogButtonPane.remove();
		this.uiButtonSet.empty();

		if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) {
			this.uiDialog.removeClass( "ui-dialog-buttons" );
			return;
		}

		$.each( buttons, function( name, props ) {
			var click, buttonOptions;
			props = $.isFunction( props ) ?
				{ click: props, text: name } :
				props;
			// Default to a non-submitting button
			props = $.extend( { type: "button" }, props );
			// Change the context for the click callback to be the main element
			click = props.click;
			props.click = function() {
				click.apply( that.element[ 0 ], arguments );
			};
			buttonOptions = {
				icons: props.icons,
				text: props.showText
			};
			delete props.icons;
			delete props.showText;
			$( "<button></button>", props )
				.button( buttonOptions )
				.appendTo( that.uiButtonSet );
		});
		this.uiDialog.addClass( "ui-dialog-buttons" );
		this.uiDialogButtonPane.appendTo( this.uiDialog );
	},

	_makeDraggable: function() {
		var that = this,
			options = this.options;

		function filteredUi( ui ) {
			return {
				position: ui.position,
				offset: ui.offset
			};
		}

		this.uiDialog.draggable({
			cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
			handle: ".ui-dialog-titlebar",
			containment: "document",
			start: function( event, ui ) {
				$( this ).addClass( "ui-dialog-dragging" );
				that._blockFrames();
				that._trigger( "dragStart", event, filteredUi( ui ) );
			},
			drag: function( event, ui ) {
				that._trigger( "drag", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var left = ui.offset.left - that.document.scrollLeft(),
					top = ui.offset.top - that.document.scrollTop();

				options.position = {
					my: "left top",
					at: "left" + (left >= 0 ? "+" : "") + left + " " +
						"top" + (top >= 0 ? "+" : "") + top,
					of: that.window
				};
				$( this ).removeClass( "ui-dialog-dragging" );
				that._unblockFrames();
				that._trigger( "dragStop", event, filteredUi( ui ) );
			}
		});
	},

	_makeResizable: function() {
		var that = this,
			options = this.options,
			handles = options.resizable,
			// .ui-resizable has position: relative defined in the stylesheet
			// but dialogs have to use absolute or fixed positioning
			position = this.uiDialog.css("position"),
			resizeHandles = typeof handles === "string" ?
				handles	:
				"n,e,s,w,se,sw,ne,nw";

		function filteredUi( ui ) {
			return {
				originalPosition: ui.originalPosition,
				originalSize: ui.originalSize,
				position: ui.position,
				size: ui.size
			};
		}

		this.uiDialog.resizable({
			cancel: ".ui-dialog-content",
			containment: "document",
			alsoResize: this.element,
			maxWidth: options.maxWidth,
			maxHeight: options.maxHeight,
			minWidth: options.minWidth,
			minHeight: this._minHeight(),
			handles: resizeHandles,
			start: function( event, ui ) {
				$( this ).addClass( "ui-dialog-resizing" );
				that._blockFrames();
				that._trigger( "resizeStart", event, filteredUi( ui ) );
			},
			resize: function( event, ui ) {
				that._trigger( "resize", event, filteredUi( ui ) );
			},
			stop: function( event, ui ) {
				var offset = that.uiDialog.offset(),
					left = offset.left - that.document.scrollLeft(),
					top = offset.top - that.document.scrollTop();

				options.height = that.uiDialog.height();
				options.width = that.uiDialog.width();
				options.position = {
					my: "left top",
					at: "left" + (left >= 0 ? "+" : "") + left + " " +
						"top" + (top >= 0 ? "+" : "") + top,
					of: that.window
				};
				$( this ).removeClass( "ui-dialog-resizing" );
				that._unblockFrames();
				that._trigger( "resizeStop", event, filteredUi( ui ) );
			}
		})
		.css( "position", position );
	},

	_trackFocus: function() {
		this._on( this.widget(), {
			focusin: function( event ) {
				this._makeFocusTarget();
				this._focusedElement = $( event.target );
			}
		});
	},

	_makeFocusTarget: function() {
		this._untrackInstance();
		this._trackingInstances().unshift( this );
	},

	_untrackInstance: function() {
		var instances = this._trackingInstances(),
			exists = $.inArray( this, instances );
		if ( exists !== -1 ) {
			instances.splice( exists, 1 );
		}
	},

	_trackingInstances: function() {
		var instances = this.document.data( "ui-dialog-instances" );
		if ( !instances ) {
			instances = [];
			this.document.data( "ui-dialog-instances", instances );
		}
		return instances;
	},

	_minHeight: function() {
		var options = this.options;

		return options.height === "auto" ?
			options.minHeight :
			Math.min( options.minHeight, options.height );
	},

	_position: function() {
		// Need to show the dialog to get the actual offset in the position plugin
		var isVisible = this.uiDialog.is( ":visible" );
		if ( !isVisible ) {
			this.uiDialog.show();
		}
		this.uiDialog.position( this.options.position );
		if ( !isVisible ) {
			this.uiDialog.hide();
		}
	},

	_setOptions: function( options ) {
		var that = this,
			resize = false,
			resizableOptions = {};

		$.each( options, function( key, value ) {
			that._setOption( key, value );

			if ( key in that.sizeRelatedOptions ) {
				resize = true;
			}
			if ( key in that.resizableRelatedOptions ) {
				resizableOptions[ key ] = value;
			}
		});

		if ( resize ) {
			this._size();
			this._position();
		}
		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", resizableOptions );
		}
	},

	_setOption: function( key, value ) {
		var isDraggable, isResizable,
			uiDialog = this.uiDialog;

		if ( key === "dialogClass" ) {
			uiDialog
				.removeClass( this.options.dialogClass )
				.addClass( value );
		}

		if ( key === "disabled" ) {
			return;
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.uiDialog.appendTo( this._appendTo() );
		}

		if ( key === "buttons" ) {
			this._createButtons();
		}

		if ( key === "closeText" ) {
			this.uiDialogTitlebarClose.button({
				// Ensure that we always pass a string
				label: "" + value
			});
		}

		if ( key === "draggable" ) {
			isDraggable = uiDialog.is( ":data(ui-draggable)" );
			if ( isDraggable && !value ) {
				uiDialog.draggable( "destroy" );
			}

			if ( !isDraggable && value ) {
				this._makeDraggable();
			}
		}

		if ( key === "position" ) {
			this._position();
		}

		if ( key === "resizable" ) {
			// currently resizable, becoming non-resizable
			isResizable = uiDialog.is( ":data(ui-resizable)" );
			if ( isResizable && !value ) {
				uiDialog.resizable( "destroy" );
			}

			// currently resizable, changing handles
			if ( isResizable && typeof value === "string" ) {
				uiDialog.resizable( "option", "handles", value );
			}

			// currently non-resizable, becoming resizable
			if ( !isResizable && value !== false ) {
				this._makeResizable();
			}
		}

		if ( key === "title" ) {
			this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) );
		}
	},

	_size: function() {
		// If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
		// divs will both have width and height set, so we need to reset them
		var nonContentHeight, minContentHeight, maxContentHeight,
			options = this.options;

		// Reset content sizing
		this.element.show().css({
			width: "auto",
			minHeight: 0,
			maxHeight: "none",
			height: 0
		});

		if ( options.minWidth > options.width ) {
			options.width = options.minWidth;
		}

		// reset wrapper sizing
		// determine the height of all the non-content elements
		nonContentHeight = this.uiDialog.css({
				height: "auto",
				width: options.width
			})
			.outerHeight();
		minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
		maxContentHeight = typeof options.maxHeight === "number" ?
			Math.max( 0, options.maxHeight - nonContentHeight ) :
			"none";

		if ( options.height === "auto" ) {
			this.element.css({
				minHeight: minContentHeight,
				maxHeight: maxContentHeight,
				height: "auto"
			});
		} else {
			this.element.height( Math.max( 0, options.height - nonContentHeight ) );
		}

		if ( this.uiDialog.is( ":data(ui-resizable)" ) ) {
			this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
		}
	},

	_blockFrames: function() {
		this.iframeBlocks = this.document.find( "iframe" ).map(function() {
			var iframe = $( this );

			return $( "<div>" )
				.css({
					position: "absolute",
					width: iframe.outerWidth(),
					height: iframe.outerHeight()
				})
				.appendTo( iframe.parent() )
				.offset( iframe.offset() )[0];
		});
	},

	_unblockFrames: function() {
		if ( this.iframeBlocks ) {
			this.iframeBlocks.remove();
			delete this.iframeBlocks;
		}
	},

	_allowInteraction: function( event ) {
		if ( $( event.target ).closest( ".ui-dialog" ).length ) {
			return true;
		}

		// TODO: Remove hack when datepicker implements
		// the .ui-front logic (#8989)
		return !!$( event.target ).closest( ".ui-datepicker" ).length;
	},

	_createOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		// We use a delay in case the overlay is created from an
		// event that we're going to be cancelling (#2804)
		var isOpening = true;
		this._delay(function() {
			isOpening = false;
		});

		if ( !this.document.data( "ui-dialog-overlays" ) ) {

			// Prevent use of anchors and inputs
			// Using _on() for an event handler shared across many instances is
			// safe because the dialogs stack and must be closed in reverse order
			this._on( this.document, {
				focusin: function( event ) {
					if ( isOpening ) {
						return;
					}

					if ( !this._allowInteraction( event ) ) {
						event.preventDefault();
						this._trackingInstances()[ 0 ]._focusTabbable();
					}
				}
			});
		}

		this.overlay = $( "<div>" )
			.addClass( "ui-widget-overlay ui-front" )
			.appendTo( this._appendTo() );
		this._on( this.overlay, {
			mousedown: "_keepFocus"
		});
		this.document.data( "ui-dialog-overlays",
			(this.document.data( "ui-dialog-overlays" ) || 0) + 1 );
	},

	_destroyOverlay: function() {
		if ( !this.options.modal ) {
			return;
		}

		if ( this.overlay ) {
			var overlays = this.document.data( "ui-dialog-overlays" ) - 1;

			if ( !overlays ) {
				this.document
					.unbind( "focusin" )
					.removeData( "ui-dialog-overlays" );
			} else {
				this.document.data( "ui-dialog-overlays", overlays );
			}

			this.overlay.remove();
			this.overlay = null;
		}
	}
});


/*!
 * jQuery UI Droppable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/droppable/
 */


$.widget( "ui.droppable", {
	version: "1.11.4",
	widgetEventPrefix: "drop",
	options: {
		accept: "*",
		activeClass: false,
		addClasses: true,
		greedy: false,
		hoverClass: false,
		scope: "default",
		tolerance: "intersect",

		// callbacks
		activate: null,
		deactivate: null,
		drop: null,
		out: null,
		over: null
	},
	_create: function() {

		var proportions,
			o = this.options,
			accept = o.accept;

		this.isover = false;
		this.isout = true;

		this.accept = $.isFunction( accept ) ? accept : function( d ) {
			return d.is( accept );
		};

		this.proportions = function( /* valueToWrite */ ) {
			if ( arguments.length ) {
				// Store the droppable's proportions
				proportions = arguments[ 0 ];
			} else {
				// Retrieve or derive the droppable's proportions
				return proportions ?
					proportions :
					proportions = {
						width: this.element[ 0 ].offsetWidth,
						height: this.element[ 0 ].offsetHeight
					};
			}
		};

		this._addToManager( o.scope );

		o.addClasses && this.element.addClass( "ui-droppable" );

	},

	_addToManager: function( scope ) {
		// Add the reference and positions to the manager
		$.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || [];
		$.ui.ddmanager.droppables[ scope ].push( this );
	},

	_splice: function( drop ) {
		var i = 0;
		for ( ; i < drop.length; i++ ) {
			if ( drop[ i ] === this ) {
				drop.splice( i, 1 );
			}
		}
	},

	_destroy: function() {
		var drop = $.ui.ddmanager.droppables[ this.options.scope ];

		this._splice( drop );

		this.element.removeClass( "ui-droppable ui-droppable-disabled" );
	},

	_setOption: function( key, value ) {

		if ( key === "accept" ) {
			this.accept = $.isFunction( value ) ? value : function( d ) {
				return d.is( value );
			};
		} else if ( key === "scope" ) {
			var drop = $.ui.ddmanager.droppables[ this.options.scope ];

			this._splice( drop );
			this._addToManager( value );
		}

		this._super( key, value );
	},

	_activate: function( event ) {
		var draggable = $.ui.ddmanager.current;
		if ( this.options.activeClass ) {
			this.element.addClass( this.options.activeClass );
		}
		if ( draggable ){
			this._trigger( "activate", event, this.ui( draggable ) );
		}
	},

	_deactivate: function( event ) {
		var draggable = $.ui.ddmanager.current;
		if ( this.options.activeClass ) {
			this.element.removeClass( this.options.activeClass );
		}
		if ( draggable ){
			this._trigger( "deactivate", event, this.ui( draggable ) );
		}
	},

	_over: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.hoverClass ) {
				this.element.addClass( this.options.hoverClass );
			}
			this._trigger( "over", event, this.ui( draggable ) );
		}

	},

	_out: function( event ) {

		var draggable = $.ui.ddmanager.current;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.hoverClass ) {
				this.element.removeClass( this.options.hoverClass );
			}
			this._trigger( "out", event, this.ui( draggable ) );
		}

	},

	_drop: function( event, custom ) {

		var draggable = custom || $.ui.ddmanager.current,
			childrenIntersection = false;

		// Bail if draggable and droppable are same element
		if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) {
			return false;
		}

		this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() {
			var inst = $( this ).droppable( "instance" );
			if (
				inst.options.greedy &&
				!inst.options.disabled &&
				inst.options.scope === draggable.options.scope &&
				inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) &&
				$.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance, event )
			) { childrenIntersection = true; return false; }
		});
		if ( childrenIntersection ) {
			return false;
		}

		if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
			if ( this.options.activeClass ) {
				this.element.removeClass( this.options.activeClass );
			}
			if ( this.options.hoverClass ) {
				this.element.removeClass( this.options.hoverClass );
			}
			this._trigger( "drop", event, this.ui( draggable ) );
			return this.element;
		}

		return false;

	},

	ui: function( c ) {
		return {
			draggable: ( c.currentItem || c.element ),
			helper: c.helper,
			position: c.position,
			offset: c.positionAbs
		};
	}

});

$.ui.intersect = (function() {
	function isOverAxis( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	}

	return function( draggable, droppable, toleranceMode, event ) {

		if ( !droppable.offset ) {
			return false;
		}

		var x1 = ( draggable.positionAbs || draggable.position.absolute ).left + draggable.margins.left,
			y1 = ( draggable.positionAbs || draggable.position.absolute ).top + draggable.margins.top,
			x2 = x1 + draggable.helperProportions.width,
			y2 = y1 + draggable.helperProportions.height,
			l = droppable.offset.left,
			t = droppable.offset.top,
			r = l + droppable.proportions().width,
			b = t + droppable.proportions().height;

		switch ( toleranceMode ) {
		case "fit":
			return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b );
		case "intersect":
			return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half
				x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half
				t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half
				y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half
		case "pointer":
			return isOverAxis( event.pageY, t, droppable.proportions().height ) && isOverAxis( event.pageX, l, droppable.proportions().width );
		case "touch":
			return (
				( y1 >= t && y1 <= b ) || // Top edge touching
				( y2 >= t && y2 <= b ) || // Bottom edge touching
				( y1 < t && y2 > b ) // Surrounded vertically
			) && (
				( x1 >= l && x1 <= r ) || // Left edge touching
				( x2 >= l && x2 <= r ) || // Right edge touching
				( x1 < l && x2 > r ) // Surrounded horizontally
			);
		default:
			return false;
		}
	};
})();

/*
	This manager tracks offsets of draggables and droppables
*/
$.ui.ddmanager = {
	current: null,
	droppables: { "default": [] },
	prepareOffsets: function( t, event ) {

		var i, j,
			m = $.ui.ddmanager.droppables[ t.options.scope ] || [],
			type = event ? event.type : null, // workaround for #2317
			list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack();

		droppablesLoop: for ( i = 0; i < m.length; i++ ) {

			// No disabled and non-accepted
			if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) {
				continue;
			}

			// Filter out elements in the current dragged item
			for ( j = 0; j < list.length; j++ ) {
				if ( list[ j ] === m[ i ].element[ 0 ] ) {
					m[ i ].proportions().height = 0;
					continue droppablesLoop;
				}
			}

			m[ i ].visible = m[ i ].element.css( "display" ) !== "none";
			if ( !m[ i ].visible ) {
				continue;
			}

			// Activate the droppable if used directly from draggables
			if ( type === "mousedown" ) {
				m[ i ]._activate.call( m[ i ], event );
			}

			m[ i ].offset = m[ i ].element.offset();
			m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight });

		}

	},
	drop: function( draggable, event ) {

		var dropped = false;
		// Create a copy of the droppables in case the list changes during the drop (#9116)
		$.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() {

			if ( !this.options ) {
				return;
			}
			if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance, event ) ) {
				dropped = this._drop.call( this, event ) || dropped;
			}

			if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) {
				this.isout = true;
				this.isover = false;
				this._deactivate.call( this, event );
			}

		});
		return dropped;

	},
	dragStart: function( draggable, event ) {
		// Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
		draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
			if ( !draggable.options.refreshPositions ) {
				$.ui.ddmanager.prepareOffsets( draggable, event );
			}
		});
	},
	drag: function( draggable, event ) {

		// If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
		if ( draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}

		// Run through all droppables and check their positions based on specific tolerance options
		$.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() {

			if ( this.options.disabled || this.greedyChild || !this.visible ) {
				return;
			}

			var parentInstance, scope, parent,
				intersects = $.ui.intersect( draggable, this, this.options.tolerance, event ),
				c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null );
			if ( !c ) {
				return;
			}

			if ( this.options.greedy ) {
				// find droppable parents with same scope
				scope = this.options.scope;
				parent = this.element.parents( ":data(ui-droppable)" ).filter(function() {
					return $( this ).droppable( "instance" ).options.scope === scope;
				});

				if ( parent.length ) {
					parentInstance = $( parent[ 0 ] ).droppable( "instance" );
					parentInstance.greedyChild = ( c === "isover" );
				}
			}

			// we just moved into a greedy child
			if ( parentInstance && c === "isover" ) {
				parentInstance.isover = false;
				parentInstance.isout = true;
				parentInstance._out.call( parentInstance, event );
			}

			this[ c ] = true;
			this[c === "isout" ? "isover" : "isout"] = false;
			this[c === "isover" ? "_over" : "_out"].call( this, event );

			// we just moved out of a greedy child
			if ( parentInstance && c === "isout" ) {
				parentInstance.isout = false;
				parentInstance.isover = true;
				parentInstance._over.call( parentInstance, event );
			}
		});

	},
	dragStop: function( draggable, event ) {
		draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
		// Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
		if ( !draggable.options.refreshPositions ) {
			$.ui.ddmanager.prepareOffsets( draggable, event );
		}
	}
};

var droppable = $.ui.droppable;


/*!
 * jQuery UI Effects 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/category/effects-core/
 */


var dataSpace = "ui-effects-",

	// Create a local jQuery because jQuery Color relies on it and the
	// global may not exist with AMD and a custom build (#10199)
	jQuery = $;

$.effects = {
	effect: {}
};

/*!
 * jQuery Color Animations v2.1.2
 * https://github.com/jquery/jquery-color
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * Date: Wed Jan 16 08:47:09 2013 -0600
 */
(function( jQuery, undefined ) {

	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

	// plusequals test for += 100 -= 100
	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
	// a set of RE's that can match strings and generate color tuples.
	stringParsers = [ {
			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ],
					execResult[ 3 ],
					execResult[ 4 ]
				];
			}
		}, {
			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ] * 2.55,
					execResult[ 2 ] * 2.55,
					execResult[ 3 ] * 2.55,
					execResult[ 4 ]
				];
			}
		}, {
			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ], 16 )
				];
			}
		}, {
			// this regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
				];
			}
		}, {
			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			space: "hsla",
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ] / 100,
					execResult[ 3 ] / 100,
					execResult[ 4 ]
				];
			}
		} ],

	// jQuery.Color( )
	color = jQuery.Color = function( color, green, blue, alpha ) {
		return new jQuery.Color.fn.parse( color, green, blue, alpha );
	},
	spaces = {
		rgba: {
			props: {
				red: {
					idx: 0,
					type: "byte"
				},
				green: {
					idx: 1,
					type: "byte"
				},
				blue: {
					idx: 2,
					type: "byte"
				}
			}
		},

		hsla: {
			props: {
				hue: {
					idx: 0,
					type: "degrees"
				},
				saturation: {
					idx: 1,
					type: "percent"
				},
				lightness: {
					idx: 2,
					type: "percent"
				}
			}
		}
	},
	propTypes = {
		"byte": {
			floor: true,
			max: 255
		},
		"percent": {
			max: 1
		},
		"degrees": {
			mod: 360,
			floor: true
		}
	},
	support = color.support = {},

	// element for support tests
	supportElem = jQuery( "<p>" )[ 0 ],

	// colors = jQuery.Color.names
	colors,

	// local aliases of functions called often
	each = jQuery.each;

// determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;

// define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
	space.cache = "_" + spaceName;
	space.props.alpha = {
		idx: 3,
		type: "percent",
		def: 1
	};
});

function clamp( value, prop, allowEmpty ) {
	var type = propTypes[ prop.type ] || {};

	if ( value == null ) {
		return (allowEmpty || !prop.def) ? null : prop.def;
	}

	// ~~ is an short way of doing floor for positive numbers
	value = type.floor ? ~~value : parseFloat( value );

	// IE will pass in empty strings as value for alpha,
	// which will hit this case
	if ( isNaN( value ) ) {
		return prop.def;
	}

	if ( type.mod ) {
		// we add mod before modding to make sure that negatives values
		// get converted properly: -10 -> 350
		return (value + type.mod) % type.mod;
	}

	// for now all property types without mod have min and max
	return 0 > value ? 0 : type.max < value ? type.max : value;
}

function stringParse( string ) {
	var inst = color(),
		rgba = inst._rgba = [];

	string = string.toLowerCase();

	each( stringParsers, function( i, parser ) {
		var parsed,
			match = parser.re.exec( string ),
			values = match && parser.parse( match ),
			spaceName = parser.space || "rgba";

		if ( values ) {
			parsed = inst[ spaceName ]( values );

			// if this was an rgba parse the assignment might happen twice
			// oh well....
			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
			rgba = inst._rgba = parsed._rgba;

			// exit each( stringParsers ) here because we matched
			return false;
		}
	});

	// Found a stringParser that handled it
	if ( rgba.length ) {

		// if this came from a parsed string, force "transparent" when alpha is 0
		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
		if ( rgba.join() === "0,0,0,0" ) {
			jQuery.extend( rgba, colors.transparent );
		}
		return inst;
	}

	// named colors
	return colors[ string ];
}

color.fn = jQuery.extend( color.prototype, {
	parse: function( red, green, blue, alpha ) {
		if ( red === undefined ) {
			this._rgba = [ null, null, null, null ];
			return this;
		}
		if ( red.jquery || red.nodeType ) {
			red = jQuery( red ).css( green );
			green = undefined;
		}

		var inst = this,
			type = jQuery.type( red ),
			rgba = this._rgba = [];

		// more than 1 argument specified - assume ( red, green, blue, alpha )
		if ( green !== undefined ) {
			red = [ red, green, blue, alpha ];
			type = "array";
		}

		if ( type === "string" ) {
			return this.parse( stringParse( red ) || colors._default );
		}

		if ( type === "array" ) {
			each( spaces.rgba.props, function( key, prop ) {
				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
			});
			return this;
		}

		if ( type === "object" ) {
			if ( red instanceof color ) {
				each( spaces, function( spaceName, space ) {
					if ( red[ space.cache ] ) {
						inst[ space.cache ] = red[ space.cache ].slice();
					}
				});
			} else {
				each( spaces, function( spaceName, space ) {
					var cache = space.cache;
					each( space.props, function( key, prop ) {

						// if the cache doesn't exist, and we know how to convert
						if ( !inst[ cache ] && space.to ) {

							// if the value was null, we don't need to copy it
							// if the key was alpha, we don't need to copy it either
							if ( key === "alpha" || red[ key ] == null ) {
								return;
							}
							inst[ cache ] = space.to( inst._rgba );
						}

						// this is the only case where we allow nulls for ALL properties.
						// call clamp with alwaysAllowEmpty
						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
					});

					// everything defined but alpha?
					if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
						// use the default of 1
						inst[ cache ][ 3 ] = 1;
						if ( space.from ) {
							inst._rgba = space.from( inst[ cache ] );
						}
					}
				});
			}
			return this;
		}
	},
	is: function( compare ) {
		var is = color( compare ),
			same = true,
			inst = this;

		each( spaces, function( _, space ) {
			var localCache,
				isCache = is[ space.cache ];
			if (isCache) {
				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
				each( space.props, function( _, prop ) {
					if ( isCache[ prop.idx ] != null ) {
						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
						return same;
					}
				});
			}
			return same;
		});
		return same;
	},
	_space: function() {
		var used = [],
			inst = this;
		each( spaces, function( spaceName, space ) {
			if ( inst[ space.cache ] ) {
				used.push( spaceName );
			}
		});
		return used.pop();
	},
	transition: function( other, distance ) {
		var end = color( other ),
			spaceName = end._space(),
			space = spaces[ spaceName ],
			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
			start = startColor[ space.cache ] || space.to( startColor._rgba ),
			result = start.slice();

		end = end[ space.cache ];
		each( space.props, function( key, prop ) {
			var index = prop.idx,
				startValue = start[ index ],
				endValue = end[ index ],
				type = propTypes[ prop.type ] || {};

			// if null, don't override start value
			if ( endValue === null ) {
				return;
			}
			// if null - use end
			if ( startValue === null ) {
				result[ index ] = endValue;
			} else {
				if ( type.mod ) {
					if ( endValue - startValue > type.mod / 2 ) {
						startValue += type.mod;
					} else if ( startValue - endValue > type.mod / 2 ) {
						startValue -= type.mod;
					}
				}
				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
			}
		});
		return this[ spaceName ]( result );
	},
	blend: function( opaque ) {
		// if we are already opaque - return ourself
		if ( this._rgba[ 3 ] === 1 ) {
			return this;
		}

		var rgb = this._rgba.slice(),
			a = rgb.pop(),
			blend = color( opaque )._rgba;

		return color( jQuery.map( rgb, function( v, i ) {
			return ( 1 - a ) * blend[ i ] + a * v;
		}));
	},
	toRgbaString: function() {
		var prefix = "rgba(",
			rgba = jQuery.map( this._rgba, function( v, i ) {
				return v == null ? ( i > 2 ? 1 : 0 ) : v;
			});

		if ( rgba[ 3 ] === 1 ) {
			rgba.pop();
			prefix = "rgb(";
		}

		return prefix + rgba.join() + ")";
	},
	toHslaString: function() {
		var prefix = "hsla(",
			hsla = jQuery.map( this.hsla(), function( v, i ) {
				if ( v == null ) {
					v = i > 2 ? 1 : 0;
				}

				// catch 1 and 2
				if ( i && i < 3 ) {
					v = Math.round( v * 100 ) + "%";
				}
				return v;
			});

		if ( hsla[ 3 ] === 1 ) {
			hsla.pop();
			prefix = "hsl(";
		}
		return prefix + hsla.join() + ")";
	},
	toHexString: function( includeAlpha ) {
		var rgba = this._rgba.slice(),
			alpha = rgba.pop();

		if ( includeAlpha ) {
			rgba.push( ~~( alpha * 255 ) );
		}

		return "#" + jQuery.map( rgba, function( v ) {

			// default to 0 when nulls exist
			v = ( v || 0 ).toString( 16 );
			return v.length === 1 ? "0" + v : v;
		}).join("");
	},
	toString: function() {
		return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
	}
});
color.fn.parse.prototype = color.fn;

// hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021

function hue2rgb( p, q, h ) {
	h = ( h + 1 ) % 1;
	if ( h * 6 < 1 ) {
		return p + ( q - p ) * h * 6;
	}
	if ( h * 2 < 1) {
		return q;
	}
	if ( h * 3 < 2 ) {
		return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
	}
	return p;
}

spaces.hsla.to = function( rgba ) {
	if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
		return [ null, null, null, rgba[ 3 ] ];
	}
	var r = rgba[ 0 ] / 255,
		g = rgba[ 1 ] / 255,
		b = rgba[ 2 ] / 255,
		a = rgba[ 3 ],
		max = Math.max( r, g, b ),
		min = Math.min( r, g, b ),
		diff = max - min,
		add = max + min,
		l = add * 0.5,
		h, s;

	if ( min === max ) {
		h = 0;
	} else if ( r === max ) {
		h = ( 60 * ( g - b ) / diff ) + 360;
	} else if ( g === max ) {
		h = ( 60 * ( b - r ) / diff ) + 120;
	} else {
		h = ( 60 * ( r - g ) / diff ) + 240;
	}

	// chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
	// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
	if ( diff === 0 ) {
		s = 0;
	} else if ( l <= 0.5 ) {
		s = diff / add;
	} else {
		s = diff / ( 2 - add );
	}
	return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
};

spaces.hsla.from = function( hsla ) {
	if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
		return [ null, null, null, hsla[ 3 ] ];
	}
	var h = hsla[ 0 ] / 360,
		s = hsla[ 1 ],
		l = hsla[ 2 ],
		a = hsla[ 3 ],
		q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
		p = 2 * l - q;

	return [
		Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
		Math.round( hue2rgb( p, q, h ) * 255 ),
		Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
		a
	];
};

each( spaces, function( spaceName, space ) {
	var props = space.props,
		cache = space.cache,
		to = space.to,
		from = space.from;

	// makes rgba() and hsla()
	color.fn[ spaceName ] = function( value ) {

		// generate a cache for this space if it doesn't exist
		if ( to && !this[ cache ] ) {
			this[ cache ] = to( this._rgba );
		}
		if ( value === undefined ) {
			return this[ cache ].slice();
		}

		var ret,
			type = jQuery.type( value ),
			arr = ( type === "array" || type === "object" ) ? value : arguments,
			local = this[ cache ].slice();

		each( props, function( key, prop ) {
			var val = arr[ type === "object" ? key : prop.idx ];
			if ( val == null ) {
				val = local[ prop.idx ];
			}
			local[ prop.idx ] = clamp( val, prop );
		});

		if ( from ) {
			ret = color( from( local ) );
			ret[ cache ] = local;
			return ret;
		} else {
			return color( local );
		}
	};

	// makes red() green() blue() alpha() hue() saturation() lightness()
	each( props, function( key, prop ) {
		// alpha is included in more than one space
		if ( color.fn[ key ] ) {
			return;
		}
		color.fn[ key ] = function( value ) {
			var vtype = jQuery.type( value ),
				fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
				local = this[ fn ](),
				cur = local[ prop.idx ],
				match;

			if ( vtype === "undefined" ) {
				return cur;
			}

			if ( vtype === "function" ) {
				value = value.call( this, cur );
				vtype = jQuery.type( value );
			}
			if ( value == null && prop.empty ) {
				return this;
			}
			if ( vtype === "string" ) {
				match = rplusequals.exec( value );
				if ( match ) {
					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
				}
			}
			local[ prop.idx ] = value;
			return this[ fn ]( local );
		};
	});
});

// add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
	var hooks = hook.split( " " );
	each( hooks, function( i, hook ) {
		jQuery.cssHooks[ hook ] = {
			set: function( elem, value ) {
				var parsed, curElem,
					backgroundColor = "";

				if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) {
					value = color( parsed || value );
					if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
						curElem = hook === "backgroundColor" ? elem.parentNode : elem;
						while (
							(backgroundColor === "" || backgroundColor === "transparent") &&
							curElem && curElem.style
						) {
							try {
								backgroundColor = jQuery.css( curElem, "backgroundColor" );
								curElem = curElem.parentNode;
							} catch ( e ) {
							}
						}

						value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
							backgroundColor :
							"_default" );
					}

					value = value.toRgbaString();
				}
				try {
					elem.style[ hook ] = value;
				} catch ( e ) {
					// wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
				}
			}
		};
		jQuery.fx.step[ hook ] = function( fx ) {
			if ( !fx.colorInit ) {
				fx.start = color( fx.elem, hook );
				fx.end = color( fx.end );
				fx.colorInit = true;
			}
			jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
		};
	});

};

color.hook( stepHooks );

jQuery.cssHooks.borderColor = {
	expand: function( value ) {
		var expanded = {};

		each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
			expanded[ "border" + part + "Color" ] = value;
		});
		return expanded;
	}
};

// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {
	// 4.1. Basic color keywords
	aqua: "#00ffff",
	black: "#000000",
	blue: "#0000ff",
	fuchsia: "#ff00ff",
	gray: "#808080",
	green: "#008000",
	lime: "#00ff00",
	maroon: "#800000",
	navy: "#000080",
	olive: "#808000",
	purple: "#800080",
	red: "#ff0000",
	silver: "#c0c0c0",
	teal: "#008080",
	white: "#ffffff",
	yellow: "#ffff00",

	// 4.2.3. "transparent" color keyword
	transparent: [ null, null, null, 0 ],

	_default: "#ffffff"
};

})( jQuery );

/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
(function() {

var classAnimationActions = [ "add", "remove", "toggle" ],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
	$.fx.step[ prop ] = function( fx ) {
		if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
			jQuery.style( fx.elem, prop, fx.end );
			fx.setAttr = true;
		}
	};
});

function getElementStyles( elem ) {
	var key, len,
		style = elem.ownerDocument.defaultView ?
			elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
			elem.currentStyle,
		styles = {};

	if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
		len = style.length;
		while ( len-- ) {
			key = style[ len ];
			if ( typeof style[ key ] === "string" ) {
				styles[ $.camelCase( key ) ] = style[ key ];
			}
		}
	// support: Opera, IE <9
	} else {
		for ( key in style ) {
			if ( typeof style[ key ] === "string" ) {
				styles[ key ] = style[ key ];
			}
		}
	}

	return styles;
}

function styleDifference( oldStyle, newStyle ) {
	var diff = {},
		name, value;

	for ( name in newStyle ) {
		value = newStyle[ name ];
		if ( oldStyle[ name ] !== value ) {
			if ( !shorthandStyles[ name ] ) {
				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
					diff[ name ] = value;
				}
			}
		}
	}

	return diff;
}

// support: jQuery <1.8
if ( !$.fn.addBack ) {
	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

$.effects.animateClass = function( value, duration, easing, callback ) {
	var o = $.speed( duration, easing, callback );

	return this.queue( function() {
		var animated = $( this ),
			baseClass = animated.attr( "class" ) || "",
			applyClassChange,
			allAnimations = o.children ? animated.find( "*" ).addBack() : animated;

		// map the animated objects to store the original styles.
		allAnimations = allAnimations.map(function() {
			var el = $( this );
			return {
				el: el,
				start: getElementStyles( this )
			};
		});

		// apply class change
		applyClassChange = function() {
			$.each( classAnimationActions, function(i, action) {
				if ( value[ action ] ) {
					animated[ action + "Class" ]( value[ action ] );
				}
			});
		};
		applyClassChange();

		// map all animated objects again - calculate new styles and diff
		allAnimations = allAnimations.map(function() {
			this.end = getElementStyles( this.el[ 0 ] );
			this.diff = styleDifference( this.start, this.end );
			return this;
		});

		// apply original class
		animated.attr( "class", baseClass );

		// map all animated objects again - this time collecting a promise
		allAnimations = allAnimations.map(function() {
			var styleInfo = this,
				dfd = $.Deferred(),
				opts = $.extend({}, o, {
					queue: false,
					complete: function() {
						dfd.resolve( styleInfo );
					}
				});

			this.el.animate( this.diff, opts );
			return dfd.promise();
		});

		// once all animations have completed:
		$.when.apply( $, allAnimations.get() ).done(function() {

			// set the final class
			applyClassChange();

			// for each animated element,
			// clear all css properties that were animated
			$.each( arguments, function() {
				var el = this.el;
				$.each( this.diff, function(key) {
					el.css( key, "" );
				});
			});

			// this is guarnteed to be there if you use jQuery.speed()
			// it also handles dequeuing the next anim...
			o.complete.call( animated[ 0 ] );
		});
	});
};

$.fn.extend({
	addClass: (function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return speed ?
				$.effects.animateClass.call( this,
					{ add: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	})( $.fn.addClass ),

	removeClass: (function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return arguments.length > 1 ?
				$.effects.animateClass.call( this,
					{ remove: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	})( $.fn.removeClass ),

	toggleClass: (function( orig ) {
		return function( classNames, force, speed, easing, callback ) {
			if ( typeof force === "boolean" || force === undefined ) {
				if ( !speed ) {
					// without speed parameter
					return orig.apply( this, arguments );
				} else {
					return $.effects.animateClass.call( this,
						(force ? { add: classNames } : { remove: classNames }),
						speed, easing, callback );
				}
			} else {
				// without force parameter
				return $.effects.animateClass.call( this,
					{ toggle: classNames }, force, speed, easing );
			}
		};
	})( $.fn.toggleClass ),

	switchClass: function( remove, add, speed, easing, callback) {
		return $.effects.animateClass.call( this, {
			add: add,
			remove: remove
		}, speed, easing, callback );
	}
});

})();

/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

(function() {

$.extend( $.effects, {
	version: "1.11.4",

	// Saves a set of properties in a data storage
	save: function( element, set ) {
		for ( var i = 0; i < set.length; i++ ) {
			if ( set[ i ] !== null ) {
				element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
			}
		}
	},

	// Restores a set of previously saved properties from a data storage
	restore: function( element, set ) {
		var val, i;
		for ( i = 0; i < set.length; i++ ) {
			if ( set[ i ] !== null ) {
				val = element.data( dataSpace + set[ i ] );
				// support: jQuery 1.6.2
				// http://bugs.jquery.com/ticket/9917
				// jQuery 1.6.2 incorrectly returns undefined for any falsy value.
				// We can't differentiate between "" and 0 here, so we just assume
				// empty string since it's likely to be a more common value...
				if ( val === undefined ) {
					val = "";
				}
				element.css( set[ i ], val );
			}
		}
	},

	setMode: function( el, mode ) {
		if (mode === "toggle") {
			mode = el.is( ":hidden" ) ? "show" : "hide";
		}
		return mode;
	},

	// Translates a [top,left] array into a baseline value
	// this should be a little more flexible in the future to handle a string & hash
	getBaseline: function( origin, original ) {
		var y, x;
		switch ( origin[ 0 ] ) {
			case "top": y = 0; break;
			case "middle": y = 0.5; break;
			case "bottom": y = 1; break;
			default: y = origin[ 0 ] / original.height;
		}
		switch ( origin[ 1 ] ) {
			case "left": x = 0; break;
			case "center": x = 0.5; break;
			case "right": x = 1; break;
			default: x = origin[ 1 ] / original.width;
		}
		return {
			x: x,
			y: y
		};
	},

	// Wraps the element around a wrapper that copies position properties
	createWrapper: function( element ) {

		// if the element is already wrapped, return it
		if ( element.parent().is( ".ui-effects-wrapper" )) {
			return element.parent();
		}

		// wrap the element
		var props = {
				width: element.outerWidth(true),
				height: element.outerHeight(true),
				"float": element.css( "float" )
			},
			wrapper = $( "<div></div>" )
				.addClass( "ui-effects-wrapper" )
				.css({
					fontSize: "100%",
					background: "transparent",
					border: "none",
					margin: 0,
					padding: 0
				}),
			// Store the size in case width/height are defined in % - Fixes #5245
			size = {
				width: element.width(),
				height: element.height()
			},
			active = document.activeElement;

		// support: Firefox
		// Firefox incorrectly exposes anonymous content
		// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
		try {
			active.id;
		} catch ( e ) {
			active = document.body;
		}

		element.wrap( wrapper );

		// Fixes #7595 - Elements lose focus when wrapped.
		if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
			$( active ).focus();
		}

		wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element

		// transfer positioning properties to the wrapper
		if ( element.css( "position" ) === "static" ) {
			wrapper.css({ position: "relative" });
			element.css({ position: "relative" });
		} else {
			$.extend( props, {
				position: element.css( "position" ),
				zIndex: element.css( "z-index" )
			});
			$.each([ "top", "left", "bottom", "right" ], function(i, pos) {
				props[ pos ] = element.css( pos );
				if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
					props[ pos ] = "auto";
				}
			});
			element.css({
				position: "relative",
				top: 0,
				left: 0,
				right: "auto",
				bottom: "auto"
			});
		}
		element.css(size);

		return wrapper.css( props ).show();
	},

	removeWrapper: function( element ) {
		var active = document.activeElement;

		if ( element.parent().is( ".ui-effects-wrapper" ) ) {
			element.parent().replaceWith( element );

			// Fixes #7595 - Elements lose focus when wrapped.
			if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
				$( active ).focus();
			}
		}

		return element;
	},

	setTransition: function( element, list, factor, value ) {
		value = value || {};
		$.each( list, function( i, x ) {
			var unit = element.cssUnit( x );
			if ( unit[ 0 ] > 0 ) {
				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
			}
		});
		return value;
	}
});

// return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {

	// allow passing all options as the first parameter
	if ( $.isPlainObject( effect ) ) {
		options = effect;
		effect = effect.effect;
	}

	// convert to an object
	effect = { effect: effect };

	// catch (effect, null, ...)
	if ( options == null ) {
		options = {};
	}

	// catch (effect, callback)
	if ( $.isFunction( options ) ) {
		callback = options;
		speed = null;
		options = {};
	}

	// catch (effect, speed, ?)
	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
		callback = speed;
		speed = options;
		options = {};
	}

	// catch (effect, options, callback)
	if ( $.isFunction( speed ) ) {
		callback = speed;
		speed = null;
	}

	// add options to effect
	if ( options ) {
		$.extend( effect, options );
	}

	speed = speed || options.duration;
	effect.duration = $.fx.off ? 0 :
		typeof speed === "number" ? speed :
		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
		$.fx.speeds._default;

	effect.complete = callback || options.complete;

	return effect;
}

function standardAnimationOption( option ) {
	// Valid standard speeds (nothing, number, named speed)
	if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
		return true;
	}

	// Invalid strings - treat as "normal" speed
	if ( typeof option === "string" && !$.effects.effect[ option ] ) {
		return true;
	}

	// Complete callback
	if ( $.isFunction( option ) ) {
		return true;
	}

	// Options hash (but not naming an effect)
	if ( typeof option === "object" && !option.effect ) {
		return true;
	}

	// Didn't match any standard API
	return false;
}

$.fn.extend({
	effect: function( /* effect, options, speed, callback */ ) {
		var args = _normalizeArguments.apply( this, arguments ),
			mode = args.mode,
			queue = args.queue,
			effectMethod = $.effects.effect[ args.effect ];

		if ( $.fx.off || !effectMethod ) {
			// delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args.duration, args.complete );
			} else {
				return this.each( function() {
					if ( args.complete ) {
						args.complete.call( this );
					}
				});
			}
		}

		function run( next ) {
			var elem = $( this ),
				complete = args.complete,
				mode = args.mode;

			function done() {
				if ( $.isFunction( complete ) ) {
					complete.call( elem[0] );
				}
				if ( $.isFunction( next ) ) {
					next();
				}
			}

			// If the element already has the correct final state, delegate to
			// the core methods so the internal tracking of "olddisplay" works.
			if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
				elem[ mode ]();
				done();
			} else {
				effectMethod.call( elem[0], args, done );
			}
		}

		return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
	},

	show: (function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "show";
				return this.effect.call( this, args );
			}
		};
	})( $.fn.show ),

	hide: (function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "hide";
				return this.effect.call( this, args );
			}
		};
	})( $.fn.hide ),

	toggle: (function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "toggle";
				return this.effect.call( this, args );
			}
		};
	})( $.fn.toggle ),

	// helper functions
	cssUnit: function(key) {
		var style = this.css( key ),
			val = [];

		$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
			if ( style.indexOf( unit ) > 0 ) {
				val = [ parseFloat( style ), unit ];
			}
		});
		return val;
	}
});

})();

/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

(function() {

// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)

var baseEasings = {};

$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
	baseEasings[ name ] = function( p ) {
		return Math.pow( p, i + 2 );
	};
});

$.extend( baseEasings, {
	Sine: function( p ) {
		return 1 - Math.cos( p * Math.PI / 2 );
	},
	Circ: function( p ) {
		return 1 - Math.sqrt( 1 - p * p );
	},
	Elastic: function( p ) {
		return p === 0 || p === 1 ? p :
			-Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
	},
	Back: function( p ) {
		return p * p * ( 3 * p - 2 );
	},
	Bounce: function( p ) {
		var pow2,
			bounce = 4;

		while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
		return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
	}
});

$.each( baseEasings, function( name, easeIn ) {
	$.easing[ "easeIn" + name ] = easeIn;
	$.easing[ "easeOut" + name ] = function( p ) {
		return 1 - easeIn( 1 - p );
	};
	$.easing[ "easeInOut" + name ] = function( p ) {
		return p < 0.5 ?
			easeIn( p * 2 ) / 2 :
			1 - easeIn( p * -2 + 2 ) / 2;
	};
});

})();

var effect = $.effects;


/*!
 * jQuery UI Effects Blind 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/blind-effect/
 */


var effectBlind = $.effects.effect.blind = function( o, done ) {
	// Create element
	var el = $( this ),
		rvertical = /up|down|vertical/,
		rpositivemotion = /up|left|vertical|horizontal/,
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		direction = o.direction || "up",
		vertical = rvertical.test( direction ),
		ref = vertical ? "height" : "width",
		ref2 = vertical ? "top" : "left",
		motion = rpositivemotion.test( direction ),
		animation = {},
		show = mode === "show",
		wrapper, distance, margin;

	// if already wrapped, the wrapper's properties are my property. #6245
	if ( el.parent().is( ".ui-effects-wrapper" ) ) {
		$.effects.save( el.parent(), props );
	} else {
		$.effects.save( el, props );
	}
	el.show();
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});

	distance = wrapper[ ref ]();
	margin = parseFloat( wrapper.css( ref2 ) ) || 0;

	animation[ ref ] = show ? distance : 0;
	if ( !motion ) {
		el
			.css( vertical ? "bottom" : "right", 0 )
			.css( vertical ? "top" : "left", "auto" )
			.css({ position: "absolute" });

		animation[ ref2 ] = show ? margin : distance + margin;
	}

	// start at 0 if we are showing
	if ( show ) {
		wrapper.css( ref, 0 );
		if ( !motion ) {
			wrapper.css( ref2, margin + distance );
		}
	}

	// Animate
	wrapper.animate( animation, {
		duration: o.duration,
		easing: o.easing,
		queue: false,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});
};


/*!
 * jQuery UI Effects Bounce 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/bounce-effect/
 */


var effectBounce = $.effects.effect.bounce = function( o, done ) {
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],

		// defaults:
		mode = $.effects.setMode( el, o.mode || "effect" ),
		hide = mode === "hide",
		show = mode === "show",
		direction = o.direction || "up",
		distance = o.distance,
		times = o.times || 5,

		// number of internal animations
		anims = times * 2 + ( show || hide ? 1 : 0 ),
		speed = o.duration / anims,
		easing = o.easing,

		// utility:
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ),
		i,
		upAnim,
		downAnim,

		// we will need to re-assemble the queue to stack our animations in place
		queue = el.queue(),
		queuelen = queue.length;

	// Avoid touching opacity to prevent clearType and PNG issues in IE
	if ( show || hide ) {
		props.push( "opacity" );
	}

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el ); // Create Wrapper

	// default distance for the BIGGEST bounce is the outer Distance / 3
	if ( !distance ) {
		distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
	}

	if ( show ) {
		downAnim = { opacity: 1 };
		downAnim[ ref ] = 0;

		// if we are showing, force opacity 0 and set the initial position
		// then do the "first" animation
		el.css( "opacity", 0 )
			.css( ref, motion ? -distance * 2 : distance * 2 )
			.animate( downAnim, speed, easing );
	}

	// start at the smallest distance if we are hiding
	if ( hide ) {
		distance = distance / Math.pow( 2, times - 1 );
	}

	downAnim = {};
	downAnim[ ref ] = 0;
	// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
	for ( i = 0; i < times; i++ ) {
		upAnim = {};
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		el.animate( upAnim, speed, easing )
			.animate( downAnim, speed, easing );

		distance = hide ? distance * 2 : distance / 2;
	}

	// Last Bounce when Hiding
	if ( hide ) {
		upAnim = { opacity: 0 };
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		el.animate( upAnim, speed, easing );
	}

	el.queue(function() {
		if ( hide ) {
			el.hide();
		}
		$.effects.restore( el, props );
		$.effects.removeWrapper( el );
		done();
	});

	// inject all the animations we just queued to be first in line (after "inprogress")
	if ( queuelen > 1) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	el.dequeue();

};


/*!
 * jQuery UI Effects Clip 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/clip-effect/
 */


var effectClip = $.effects.effect.clip = function( o, done ) {
	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		direction = o.direction || "vertical",
		vert = direction === "vertical",
		size = vert ? "height" : "width",
		position = vert ? "top" : "left",
		animation = {},
		wrapper, animate, distance;

	// Save & Show
	$.effects.save( el, props );
	el.show();

	// Create Wrapper
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});
	animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
	distance = animate[ size ]();

	// Shift
	if ( show ) {
		animate.css( size, 0 );
		animate.css( position, distance / 2 );
	}

	// Create Animation Object:
	animation[ size ] = show ? distance : 0;
	animation[ position ] = show ? 0 : distance / 2;

	// Animate
	animate.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( !show ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});

};


/*!
 * jQuery UI Effects Drop 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/drop-effect/
 */


var effectDrop = $.effects.effect.drop = function( o, done ) {

	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		direction = o.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
		animation = {
			opacity: show ? 1 : 0
		},
		distance;

	// Adjust
	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );

	distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ) / 2;

	if ( show ) {
		el
			.css( "opacity", 0 )
			.css( ref, motion === "pos" ? -distance : distance );
	}

	// Animation
	animation[ ref ] = ( show ?
		( motion === "pos" ? "+=" : "-=" ) :
		( motion === "pos" ? "-=" : "+=" ) ) +
		distance;

	// Animate
	el.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});
};


/*!
 * jQuery UI Effects Explode 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/explode-effect/
 */


var effectExplode = $.effects.effect.explode = function( o, done ) {

	var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
		cells = rows,
		el = $( this ),
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",

		// show and then visibility:hidden the element before calculating offset
		offset = el.show().css( "visibility", "hidden" ).offset(),

		// width and height of a piece
		width = Math.ceil( el.outerWidth() / cells ),
		height = Math.ceil( el.outerHeight() / rows ),
		pieces = [],

		// loop
		i, j, left, top, mx, my;

	// children animate complete:
	function childComplete() {
		pieces.push( this );
		if ( pieces.length === rows * cells ) {
			animComplete();
		}
	}

	// clone the element for each row and cell.
	for ( i = 0; i < rows ; i++ ) { // ===>
		top = offset.top + i * height;
		my = i - ( rows - 1 ) / 2 ;

		for ( j = 0; j < cells ; j++ ) { // |||
			left = offset.left + j * width;
			mx = j - ( cells - 1 ) / 2 ;

			// Create a clone of the now hidden main element that will be absolute positioned
			// within a wrapper div off the -left and -top equal to size of our pieces
			el
				.clone()
				.appendTo( "body" )
				.wrap( "<div></div>" )
				.css({
					position: "absolute",
					visibility: "visible",
					left: -j * width,
					top: -i * height
				})

			// select the wrapper - make it overflow: hidden and absolute positioned based on
			// where the original was located +left and +top equal to the size of pieces
				.parent()
				.addClass( "ui-effects-explode" )
				.css({
					position: "absolute",
					overflow: "hidden",
					width: width,
					height: height,
					left: left + ( show ? mx * width : 0 ),
					top: top + ( show ? my * height : 0 ),
					opacity: show ? 0 : 1
				}).animate({
					left: left + ( show ? 0 : mx * width ),
					top: top + ( show ? 0 : my * height ),
					opacity: show ? 1 : 0
				}, o.duration || 500, o.easing, childComplete );
		}
	}

	function animComplete() {
		el.css({
			visibility: "visible"
		});
		$( pieces ).remove();
		if ( !show ) {
			el.hide();
		}
		done();
	}
};


/*!
 * jQuery UI Effects Fade 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/fade-effect/
 */


var effectFade = $.effects.effect.fade = function( o, done ) {
	var el = $( this ),
		mode = $.effects.setMode( el, o.mode || "toggle" );

	el.animate({
		opacity: mode
	}, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: done
	});
};


/*!
 * jQuery UI Effects Fold 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/fold-effect/
 */


var effectFold = $.effects.effect.fold = function( o, done ) {

	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "hide" ),
		show = mode === "show",
		hide = mode === "hide",
		size = o.size || 15,
		percent = /([0-9]+)%/.exec( size ),
		horizFirst = !!o.horizFirst,
		widthFirst = show !== horizFirst,
		ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
		duration = o.duration / 2,
		wrapper, distance,
		animation1 = {},
		animation2 = {};

	$.effects.save( el, props );
	el.show();

	// Create Wrapper
	wrapper = $.effects.createWrapper( el ).css({
		overflow: "hidden"
	});
	distance = widthFirst ?
		[ wrapper.width(), wrapper.height() ] :
		[ wrapper.height(), wrapper.width() ];

	if ( percent ) {
		size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
	}
	if ( show ) {
		wrapper.css( horizFirst ? {
			height: 0,
			width: size
		} : {
			height: size,
			width: 0
		});
	}

	// Animation
	animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
	animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;

	// Animate
	wrapper
		.animate( animation1, duration, o.easing )
		.animate( animation2, duration, o.easing, function() {
			if ( hide ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		});

};


/*!
 * jQuery UI Effects Highlight 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/highlight-effect/
 */


var effectHighlight = $.effects.effect.highlight = function( o, done ) {
	var elem = $( this ),
		props = [ "backgroundImage", "backgroundColor", "opacity" ],
		mode = $.effects.setMode( elem, o.mode || "show" ),
		animation = {
			backgroundColor: elem.css( "backgroundColor" )
		};

	if (mode === "hide") {
		animation.opacity = 0;
	}

	$.effects.save( elem, props );

	elem
		.show()
		.css({
			backgroundImage: "none",
			backgroundColor: o.color || "#ffff99"
		})
		.animate( animation, {
			queue: false,
			duration: o.duration,
			easing: o.easing,
			complete: function() {
				if ( mode === "hide" ) {
					elem.hide();
				}
				$.effects.restore( elem, props );
				done();
			}
		});
};


/*!
 * jQuery UI Effects Size 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/size-effect/
 */


var effectSize = $.effects.effect.size = function( o, done ) {

	// Create element
	var original, baseline, factor,
		el = $( this ),
		props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],

		// Always restore
		props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],

		// Copy for children
		props2 = [ "width", "height", "overflow" ],
		cProps = [ "fontSize" ],
		vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
		hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],

		// Set options
		mode = $.effects.setMode( el, o.mode || "effect" ),
		restore = o.restore || mode !== "effect",
		scale = o.scale || "both",
		origin = o.origin || [ "middle", "center" ],
		position = el.css( "position" ),
		props = restore ? props0 : props1,
		zero = {
			height: 0,
			width: 0,
			outerHeight: 0,
			outerWidth: 0
		};

	if ( mode === "show" ) {
		el.show();
	}
	original = {
		height: el.height(),
		width: el.width(),
		outerHeight: el.outerHeight(),
		outerWidth: el.outerWidth()
	};

	if ( o.mode === "toggle" && mode === "show" ) {
		el.from = o.to || zero;
		el.to = o.from || original;
	} else {
		el.from = o.from || ( mode === "show" ? zero : original );
		el.to = o.to || ( mode === "hide" ? zero : original );
	}

	// Set scaling factor
	factor = {
		from: {
			y: el.from.height / original.height,
			x: el.from.width / original.width
		},
		to: {
			y: el.to.height / original.height,
			x: el.to.width / original.width
		}
	};

	// Scale the css box
	if ( scale === "box" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			props = props.concat( vProps );
			el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
			el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
		}

		// Horizontal props scaling
		if ( factor.from.x !== factor.to.x ) {
			props = props.concat( hProps );
			el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
			el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
		}
	}

	// Scale the content
	if ( scale === "content" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			props = props.concat( cProps ).concat( props2 );
			el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
			el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
		}
	}

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );
	el.css( "overflow", "hidden" ).css( el.from );

	// Adjust
	if (origin) { // Calculate baseline shifts
		baseline = $.effects.getBaseline( origin, original );
		el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
		el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
		el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
		el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
	}
	el.css( el.from ); // set top & left

	// Animate
	if ( scale === "content" || scale === "both" ) { // Scale the children

		// Add margins/font-size
		vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
		hProps = hProps.concat([ "marginLeft", "marginRight" ]);
		props2 = props0.concat(vProps).concat(hProps);

		el.find( "*[width]" ).each( function() {
			var child = $( this ),
				c_original = {
					height: child.height(),
					width: child.width(),
					outerHeight: child.outerHeight(),
					outerWidth: child.outerWidth()
				};
			if (restore) {
				$.effects.save(child, props2);
			}

			child.from = {
				height: c_original.height * factor.from.y,
				width: c_original.width * factor.from.x,
				outerHeight: c_original.outerHeight * factor.from.y,
				outerWidth: c_original.outerWidth * factor.from.x
			};
			child.to = {
				height: c_original.height * factor.to.y,
				width: c_original.width * factor.to.x,
				outerHeight: c_original.height * factor.to.y,
				outerWidth: c_original.width * factor.to.x
			};

			// Vertical props scaling
			if ( factor.from.y !== factor.to.y ) {
				child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
				child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
			}

			// Horizontal props scaling
			if ( factor.from.x !== factor.to.x ) {
				child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
				child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
			}

			// Animate children
			child.css( child.from );
			child.animate( child.to, o.duration, o.easing, function() {

				// Restore children
				if ( restore ) {
					$.effects.restore( child, props2 );
				}
			});
		});
	}

	// Animate
	el.animate( el.to, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( el.to.opacity === 0 ) {
				el.css( "opacity", el.from.opacity );
			}
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			if ( !restore ) {

				// we need to calculate our new positioning based on the scaling
				if ( position === "static" ) {
					el.css({
						position: "relative",
						top: el.to.top,
						left: el.to.left
					});
				} else {
					$.each([ "top", "left" ], function( idx, pos ) {
						el.css( pos, function( _, str ) {
							var val = parseInt( str, 10 ),
								toRef = idx ? el.to.left : el.to.top;

							// if original was "auto", recalculate the new value from wrapper
							if ( str === "auto" ) {
								return toRef + "px";
							}

							return val + toRef + "px";
						});
					});
				}
			}

			$.effects.removeWrapper( el );
			done();
		}
	});

};


/*!
 * jQuery UI Effects Scale 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/scale-effect/
 */


var effectScale = $.effects.effect.scale = function( o, done ) {

	// Create element
	var el = $( this ),
		options = $.extend( true, {}, o ),
		mode = $.effects.setMode( el, o.mode || "effect" ),
		percent = parseInt( o.percent, 10 ) ||
			( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
		direction = o.direction || "both",
		origin = o.origin,
		original = {
			height: el.height(),
			width: el.width(),
			outerHeight: el.outerHeight(),
			outerWidth: el.outerWidth()
		},
		factor = {
			y: direction !== "horizontal" ? (percent / 100) : 1,
			x: direction !== "vertical" ? (percent / 100) : 1
		};

	// We are going to pass this effect to the size effect:
	options.effect = "size";
	options.queue = false;
	options.complete = done;

	// Set default origin and restore for show/hide
	if ( mode !== "effect" ) {
		options.origin = origin || [ "middle", "center" ];
		options.restore = true;
	}

	options.from = o.from || ( mode === "show" ? {
		height: 0,
		width: 0,
		outerHeight: 0,
		outerWidth: 0
	} : original );
	options.to = {
		height: original.height * factor.y,
		width: original.width * factor.x,
		outerHeight: original.outerHeight * factor.y,
		outerWidth: original.outerWidth * factor.x
	};

	// Fade option to support puff
	if ( options.fade ) {
		if ( mode === "show" ) {
			options.from.opacity = 0;
			options.to.opacity = 1;
		}
		if ( mode === "hide" ) {
			options.from.opacity = 1;
			options.to.opacity = 0;
		}
	}

	// Animate
	el.effect( options );

};


/*!
 * jQuery UI Effects Puff 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/puff-effect/
 */


var effectPuff = $.effects.effect.puff = function( o, done ) {
	var elem = $( this ),
		mode = $.effects.setMode( elem, o.mode || "hide" ),
		hide = mode === "hide",
		percent = parseInt( o.percent, 10 ) || 150,
		factor = percent / 100,
		original = {
			height: elem.height(),
			width: elem.width(),
			outerHeight: elem.outerHeight(),
			outerWidth: elem.outerWidth()
		};

	$.extend( o, {
		effect: "scale",
		queue: false,
		fade: true,
		mode: mode,
		complete: done,
		percent: hide ? percent : 100,
		from: hide ?
			original :
			{
				height: original.height * factor,
				width: original.width * factor,
				outerHeight: original.outerHeight * factor,
				outerWidth: original.outerWidth * factor
			}
	});

	elem.effect( o );
};


/*!
 * jQuery UI Effects Pulsate 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/pulsate-effect/
 */


var effectPulsate = $.effects.effect.pulsate = function( o, done ) {
	var elem = $( this ),
		mode = $.effects.setMode( elem, o.mode || "show" ),
		show = mode === "show",
		hide = mode === "hide",
		showhide = ( show || mode === "hide" ),

		// showing or hiding leaves of the "last" animation
		anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
		duration = o.duration / anims,
		animateTo = 0,
		queue = elem.queue(),
		queuelen = queue.length,
		i;

	if ( show || !elem.is(":visible")) {
		elem.css( "opacity", 0 ).show();
		animateTo = 1;
	}

	// anims - 1 opacity "toggles"
	for ( i = 1; i < anims; i++ ) {
		elem.animate({
			opacity: animateTo
		}, duration, o.easing );
		animateTo = 1 - animateTo;
	}

	elem.animate({
		opacity: animateTo
	}, duration, o.easing);

	elem.queue(function() {
		if ( hide ) {
			elem.hide();
		}
		done();
	});

	// We just queued up "anims" animations, we need to put them next in the queue
	if ( queuelen > 1 ) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	elem.dequeue();
};


/*!
 * jQuery UI Effects Shake 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/shake-effect/
 */


var effectShake = $.effects.effect.shake = function( o, done ) {

	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
		mode = $.effects.setMode( el, o.mode || "effect" ),
		direction = o.direction || "left",
		distance = o.distance || 20,
		times = o.times || 3,
		anims = times * 2 + 1,
		speed = Math.round( o.duration / anims ),
		ref = (direction === "up" || direction === "down") ? "top" : "left",
		positiveMotion = (direction === "up" || direction === "left"),
		animation = {},
		animation1 = {},
		animation2 = {},
		i,

		// we will need to re-assemble the queue to stack our animations in place
		queue = el.queue(),
		queuelen = queue.length;

	$.effects.save( el, props );
	el.show();
	$.effects.createWrapper( el );

	// Animation
	animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
	animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
	animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;

	// Animate
	el.animate( animation, speed, o.easing );

	// Shakes
	for ( i = 1; i < times; i++ ) {
		el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
	}
	el
		.animate( animation1, speed, o.easing )
		.animate( animation, speed / 2, o.easing )
		.queue(function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		});

	// inject all the animations we just queued to be first in line (after "inprogress")
	if ( queuelen > 1) {
		queue.splice.apply( queue,
			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
	}
	el.dequeue();

};


/*!
 * jQuery UI Effects Slide 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/slide-effect/
 */


var effectSlide = $.effects.effect.slide = function( o, done ) {

	// Create element
	var el = $( this ),
		props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
		mode = $.effects.setMode( el, o.mode || "show" ),
		show = mode === "show",
		direction = o.direction || "left",
		ref = (direction === "up" || direction === "down") ? "top" : "left",
		positiveMotion = (direction === "up" || direction === "left"),
		distance,
		animation = {};

	// Adjust
	$.effects.save( el, props );
	el.show();
	distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );

	$.effects.createWrapper( el ).css({
		overflow: "hidden"
	});

	if ( show ) {
		el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
	}

	// Animation
	animation[ ref ] = ( show ?
		( positiveMotion ? "+=" : "-=") :
		( positiveMotion ? "-=" : "+=")) +
		distance;

	// Animate
	el.animate( animation, {
		queue: false,
		duration: o.duration,
		easing: o.easing,
		complete: function() {
			if ( mode === "hide" ) {
				el.hide();
			}
			$.effects.restore( el, props );
			$.effects.removeWrapper( el );
			done();
		}
	});
};


/*!
 * jQuery UI Effects Transfer 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/transfer-effect/
 */


var effectTransfer = $.effects.effect.transfer = function( o, done ) {
	var elem = $( this ),
		target = $( o.to ),
		targetFixed = target.css( "position" ) === "fixed",
		body = $("body"),
		fixTop = targetFixed ? body.scrollTop() : 0,
		fixLeft = targetFixed ? body.scrollLeft() : 0,
		endPosition = target.offset(),
		animation = {
			top: endPosition.top - fixTop,
			left: endPosition.left - fixLeft,
			height: target.innerHeight(),
			width: target.innerWidth()
		},
		startPosition = elem.offset(),
		transfer = $( "<div class='ui-effects-transfer'></div>" )
			.appendTo( document.body )
			.addClass( o.className )
			.css({
				top: startPosition.top - fixTop,
				left: startPosition.left - fixLeft,
				height: elem.innerHeight(),
				width: elem.innerWidth(),
				position: targetFixed ? "fixed" : "absolute"
			})
			.animate( animation, o.duration, o.easing, function() {
				transfer.remove();
				done();
			});
};


/*!
 * jQuery UI Progressbar 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/progressbar/
 */


var progressbar = $.widget( "ui.progressbar", {
	version: "1.11.4",
	options: {
		max: 100,
		value: 0,

		change: null,
		complete: null
	},

	min: 0,

	_create: function() {
		// Constrain initial value
		this.oldValue = this.options.value = this._constrainedValue();

		this.element
			.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
			.attr({
				// Only set static values, aria-valuenow and aria-valuemax are
				// set inside _refreshValue()
				role: "progressbar",
				"aria-valuemin": this.min
			});

		this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
			.appendTo( this.element );

		this._refreshValue();
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );

		this.valueDiv.remove();
	},

	value: function( newValue ) {
		if ( newValue === undefined ) {
			return this.options.value;
		}

		this.options.value = this._constrainedValue( newValue );
		this._refreshValue();
	},

	_constrainedValue: function( newValue ) {
		if ( newValue === undefined ) {
			newValue = this.options.value;
		}

		this.indeterminate = newValue === false;

		// sanitize value
		if ( typeof newValue !== "number" ) {
			newValue = 0;
		}

		return this.indeterminate ? false :
			Math.min( this.options.max, Math.max( this.min, newValue ) );
	},

	_setOptions: function( options ) {
		// Ensure "value" option is set after other values (like max)
		var value = options.value;
		delete options.value;

		this._super( options );

		this.options.value = this._constrainedValue( value );
		this._refreshValue();
	},

	_setOption: function( key, value ) {
		if ( key === "max" ) {
			// Don't allow a max less than min
			value = Math.max( this.min, value );
		}
		if ( key === "disabled" ) {
			this.element
				.toggleClass( "ui-state-disabled", !!value )
				.attr( "aria-disabled", value );
		}
		this._super( key, value );
	},

	_percentage: function() {
		return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min );
	},

	_refreshValue: function() {
		var value = this.options.value,
			percentage = this._percentage();

		this.valueDiv
			.toggle( this.indeterminate || value > this.min )
			.toggleClass( "ui-corner-right", value === this.options.max )
			.width( percentage.toFixed(0) + "%" );

		this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate );

		if ( this.indeterminate ) {
			this.element.removeAttr( "aria-valuenow" );
			if ( !this.overlayDiv ) {
				this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv );
			}
		} else {
			this.element.attr({
				"aria-valuemax": this.options.max,
				"aria-valuenow": value
			});
			if ( this.overlayDiv ) {
				this.overlayDiv.remove();
				this.overlayDiv = null;
			}
		}

		if ( this.oldValue !== value ) {
			this.oldValue = value;
			this._trigger( "change" );
		}
		if ( value === this.options.max ) {
			this._trigger( "complete" );
		}
	}
});


/*!
 * jQuery UI Selectable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/selectable/
 */


var selectable = $.widget("ui.selectable", $.ui.mouse, {
	version: "1.11.4",
	options: {
		appendTo: "body",
		autoRefresh: true,
		distance: 0,
		filter: "*",
		tolerance: "touch",

		// callbacks
		selected: null,
		selecting: null,
		start: null,
		stop: null,
		unselected: null,
		unselecting: null
	},
	_create: function() {
		var selectees,
			that = this;

		this.element.addClass("ui-selectable");

		this.dragged = false;

		// cache selectee children based on filter
		this.refresh = function() {
			selectees = $(that.options.filter, that.element[0]);
			selectees.addClass("ui-selectee");
			selectees.each(function() {
				var $this = $(this),
					pos = $this.offset();
				$.data(this, "selectable-item", {
					element: this,
					$element: $this,
					left: pos.left,
					top: pos.top,
					right: pos.left + $this.outerWidth(),
					bottom: pos.top + $this.outerHeight(),
					startselected: false,
					selected: $this.hasClass("ui-selected"),
					selecting: $this.hasClass("ui-selecting"),
					unselecting: $this.hasClass("ui-unselecting")
				});
			});
		};
		this.refresh();

		this.selectees = selectees.addClass("ui-selectee");

		this._mouseInit();

		this.helper = $("<div class='ui-selectable-helper'></div>");
	},

	_destroy: function() {
		this.selectees
			.removeClass("ui-selectee")
			.removeData("selectable-item");
		this.element
			.removeClass("ui-selectable ui-selectable-disabled");
		this._mouseDestroy();
	},

	_mouseStart: function(event) {
		var that = this,
			options = this.options;

		this.opos = [ event.pageX, event.pageY ];

		if (this.options.disabled) {
			return;
		}

		this.selectees = $(options.filter, this.element[0]);

		this._trigger("start", event);

		$(options.appendTo).append(this.helper);
		// position helper (lasso)
		this.helper.css({
			"left": event.pageX,
			"top": event.pageY,
			"width": 0,
			"height": 0
		});

		if (options.autoRefresh) {
			this.refresh();
		}

		this.selectees.filter(".ui-selected").each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.startselected = true;
			if (!event.metaKey && !event.ctrlKey) {
				selectee.$element.removeClass("ui-selected");
				selectee.selected = false;
				selectee.$element.addClass("ui-unselecting");
				selectee.unselecting = true;
				// selectable UNSELECTING callback
				that._trigger("unselecting", event, {
					unselecting: selectee.element
				});
			}
		});

		$(event.target).parents().addBack().each(function() {
			var doSelect,
				selectee = $.data(this, "selectable-item");
			if (selectee) {
				doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected");
				selectee.$element
					.removeClass(doSelect ? "ui-unselecting" : "ui-selected")
					.addClass(doSelect ? "ui-selecting" : "ui-unselecting");
				selectee.unselecting = !doSelect;
				selectee.selecting = doSelect;
				selectee.selected = doSelect;
				// selectable (UN)SELECTING callback
				if (doSelect) {
					that._trigger("selecting", event, {
						selecting: selectee.element
					});
				} else {
					that._trigger("unselecting", event, {
						unselecting: selectee.element
					});
				}
				return false;
			}
		});

	},

	_mouseDrag: function(event) {

		this.dragged = true;

		if (this.options.disabled) {
			return;
		}

		var tmp,
			that = this,
			options = this.options,
			x1 = this.opos[0],
			y1 = this.opos[1],
			x2 = event.pageX,
			y2 = event.pageY;

		if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; }
		if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; }
		this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 });

		this.selectees.each(function() {
			var selectee = $.data(this, "selectable-item"),
				hit = false;

			//prevent helper from being selected if appendTo: selectable
			if (!selectee || selectee.element === that.element[0]) {
				return;
			}

			if (options.tolerance === "touch") {
				hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
			} else if (options.tolerance === "fit") {
				hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
			}

			if (hit) {
				// SELECT
				if (selectee.selected) {
					selectee.$element.removeClass("ui-selected");
					selectee.selected = false;
				}
				if (selectee.unselecting) {
					selectee.$element.removeClass("ui-unselecting");
					selectee.unselecting = false;
				}
				if (!selectee.selecting) {
					selectee.$element.addClass("ui-selecting");
					selectee.selecting = true;
					// selectable SELECTING callback
					that._trigger("selecting", event, {
						selecting: selectee.element
					});
				}
			} else {
				// UNSELECT
				if (selectee.selecting) {
					if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
						selectee.$element.removeClass("ui-selecting");
						selectee.selecting = false;
						selectee.$element.addClass("ui-selected");
						selectee.selected = true;
					} else {
						selectee.$element.removeClass("ui-selecting");
						selectee.selecting = false;
						if (selectee.startselected) {
							selectee.$element.addClass("ui-unselecting");
							selectee.unselecting = true;
						}
						// selectable UNSELECTING callback
						that._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
				if (selectee.selected) {
					if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
						selectee.$element.removeClass("ui-selected");
						selectee.selected = false;

						selectee.$element.addClass("ui-unselecting");
						selectee.unselecting = true;
						// selectable UNSELECTING callback
						that._trigger("unselecting", event, {
							unselecting: selectee.element
						});
					}
				}
			}
		});

		return false;
	},

	_mouseStop: function(event) {
		var that = this;

		this.dragged = false;

		$(".ui-unselecting", this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass("ui-unselecting");
			selectee.unselecting = false;
			selectee.startselected = false;
			that._trigger("unselected", event, {
				unselected: selectee.element
			});
		});
		$(".ui-selecting", this.element[0]).each(function() {
			var selectee = $.data(this, "selectable-item");
			selectee.$element.removeClass("ui-selecting").addClass("ui-selected");
			selectee.selecting = false;
			selectee.selected = true;
			selectee.startselected = true;
			that._trigger("selected", event, {
				selected: selectee.element
			});
		});
		this._trigger("stop", event);

		this.helper.remove();

		return false;
	}

});


/*!
 * jQuery UI Selectmenu 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/selectmenu
 */


var selectmenu = $.widget( "ui.selectmenu", {
	version: "1.11.4",
	defaultElement: "<select>",
	options: {
		appendTo: null,
		disabled: null,
		icons: {
			button: "ui-icon-triangle-1-s"
		},
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		width: null,

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		select: null
	},

	_create: function() {
		var selectmenuId = this.element.uniqueId().attr( "id" );
		this.ids = {
			element: selectmenuId,
			button: selectmenuId + "-button",
			menu: selectmenuId + "-menu"
		};

		this._drawButton();
		this._drawMenu();

		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_drawButton: function() {
		var that = this;

		// Associate existing label with the new button
		this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button );
		this._on( this.label, {
			click: function( event ) {
				this.button.focus();
				event.preventDefault();
			}
		});

		// Hide original select element
		this.element.hide();

		// Create button
		this.button = $( "<span>", {
			"class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all",
			tabindex: this.options.disabled ? -1 : 0,
			id: this.ids.button,
			role: "combobox",
			"aria-expanded": "false",
			"aria-autocomplete": "list",
			"aria-owns": this.ids.menu,
			"aria-haspopup": "true"
		})
			.insertAfter( this.element );

		$( "<span>", {
			"class": "ui-icon " + this.options.icons.button
		})
			.prependTo( this.button );

		this.buttonText = $( "<span>", {
			"class": "ui-selectmenu-text"
		})
			.appendTo( this.button );

		this._setText( this.buttonText, this.element.find( "option:selected" ).text() );
		this._resizeButton();

		this._on( this.button, this._buttonEvents );
		this.button.one( "focusin", function() {

			// Delay rendering the menu items until the button receives focus.
			// The menu may have already been rendered via a programmatic open.
			if ( !that.menuItems ) {
				that._refreshMenu();
			}
		});
		this._hoverable( this.button );
		this._focusable( this.button );
	},

	_drawMenu: function() {
		var that = this;

		// Create menu
		this.menu = $( "<ul>", {
			"aria-hidden": "true",
			"aria-labelledby": this.ids.button,
			id: this.ids.menu
		});

		// Wrap menu
		this.menuWrap = $( "<div>", {
			"class": "ui-selectmenu-menu ui-front"
		})
			.append( this.menu )
			.appendTo( this._appendTo() );

		// Initialize menu widget
		this.menuInstance = this.menu
			.menu({
				role: "listbox",
				select: function( event, ui ) {
					event.preventDefault();

					// support: IE8
					// If the item was selected via a click, the text selection
					// will be destroyed in IE
					that._setSelection();

					that._select( ui.item.data( "ui-selectmenu-item" ), event );
				},
				focus: function( event, ui ) {
					var item = ui.item.data( "ui-selectmenu-item" );

					// Prevent inital focus from firing and check if its a newly focused item
					if ( that.focusIndex != null && item.index !== that.focusIndex ) {
						that._trigger( "focus", event, { item: item } );
						if ( !that.isOpen ) {
							that._select( item, event );
						}
					}
					that.focusIndex = item.index;

					that.button.attr( "aria-activedescendant",
						that.menuItems.eq( item.index ).attr( "id" ) );
				}
			})
			.menu( "instance" );

		// Adjust menu styles to dropdown
		this.menu
			.addClass( "ui-corner-bottom" )
			.removeClass( "ui-corner-all" );

		// Don't close the menu on mouseleave
		this.menuInstance._off( this.menu, "mouseleave" );

		// Cancel the menu's collapseAll on document click
		this.menuInstance._closeOnDocumentClick = function() {
			return false;
		};

		// Selects often contain empty items, but never contain dividers
		this.menuInstance._isDivider = function() {
			return false;
		};
	},

	refresh: function() {
		this._refreshMenu();
		this._setText( this.buttonText, this._getSelectedItem().text() );
		if ( !this.options.width ) {
			this._resizeButton();
		}
	},

	_refreshMenu: function() {
		this.menu.empty();

		var item,
			options = this.element.find( "option" );

		if ( !options.length ) {
			return;
		}

		this._parseOptions( options );
		this._renderMenu( this.menu, this.items );

		this.menuInstance.refresh();
		this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" );

		item = this._getSelectedItem();

		// Update the menu to have the correct item focused
		this.menuInstance.focus( null, item );
		this._setAria( item.data( "ui-selectmenu-item" ) );

		// Set disabled state
		this._setOption( "disabled", this.element.prop( "disabled" ) );
	},

	open: function( event ) {
		if ( this.options.disabled ) {
			return;
		}

		// If this is the first time the menu is being opened, render the items
		if ( !this.menuItems ) {
			this._refreshMenu();
		} else {

			// Menu clears focus on close, reset focus to selected item
			this.menu.find( ".ui-state-focus" ).removeClass( "ui-state-focus" );
			this.menuInstance.focus( null, this._getSelectedItem() );
		}

		this.isOpen = true;
		this._toggleAttr();
		this._resizeMenu();
		this._position();

		this._on( this.document, this._documentClick );

		this._trigger( "open", event );
	},

	_position: function() {
		this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) );
	},

	close: function( event ) {
		if ( !this.isOpen ) {
			return;
		}

		this.isOpen = false;
		this._toggleAttr();

		this.range = null;
		this._off( this.document );

		this._trigger( "close", event );
	},

	widget: function() {
		return this.button;
	},

	menuWidget: function() {
		return this.menu;
	},

	_renderMenu: function( ul, items ) {
		var that = this,
			currentOptgroup = "";

		$.each( items, function( index, item ) {
			if ( item.optgroup !== currentOptgroup ) {
				$( "<li>", {
					"class": "ui-selectmenu-optgroup ui-menu-divider" +
						( item.element.parent( "optgroup" ).prop( "disabled" ) ?
							" ui-state-disabled" :
							"" ),
					text: item.optgroup
				})
					.appendTo( ul );

				currentOptgroup = item.optgroup;
			}

			that._renderItemData( ul, item );
		});
	},

	_renderItemData: function( ul, item ) {
		return this._renderItem( ul, item ).data( "ui-selectmenu-item", item );
	},

	_renderItem: function( ul, item ) {
		var li = $( "<li>" );

		if ( item.disabled ) {
			li.addClass( "ui-state-disabled" );
		}
		this._setText( li, item.label );

		return li.appendTo( ul );
	},

	_setText: function( element, value ) {
		if ( value ) {
			element.text( value );
		} else {
			element.html( "&#160;" );
		}
	},

	_move: function( direction, event ) {
		var item, next,
			filter = ".ui-menu-item";

		if ( this.isOpen ) {
			item = this.menuItems.eq( this.focusIndex );
		} else {
			item = this.menuItems.eq( this.element[ 0 ].selectedIndex );
			filter += ":not(.ui-state-disabled)";
		}

		if ( direction === "first" || direction === "last" ) {
			next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 );
		} else {
			next = item[ direction + "All" ]( filter ).eq( 0 );
		}

		if ( next.length ) {
			this.menuInstance.focus( event, next );
		}
	},

	_getSelectedItem: function() {
		return this.menuItems.eq( this.element[ 0 ].selectedIndex );
	},

	_toggle: function( event ) {
		this[ this.isOpen ? "close" : "open" ]( event );
	},

	_setSelection: function() {
		var selection;

		if ( !this.range ) {
			return;
		}

		if ( window.getSelection ) {
			selection = window.getSelection();
			selection.removeAllRanges();
			selection.addRange( this.range );

		// support: IE8
		} else {
			this.range.select();
		}

		// support: IE
		// Setting the text selection kills the button focus in IE, but
		// restoring the focus doesn't kill the selection.
		this.button.focus();
	},

	_documentClick: {
		mousedown: function( event ) {
			if ( !this.isOpen ) {
				return;
			}

			if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" + this.ids.button ).length ) {
				this.close( event );
			}
		}
	},

	_buttonEvents: {

		// Prevent text selection from being reset when interacting with the selectmenu (#10144)
		mousedown: function() {
			var selection;

			if ( window.getSelection ) {
				selection = window.getSelection();
				if ( selection.rangeCount ) {
					this.range = selection.getRangeAt( 0 );
				}

			// support: IE8
			} else {
				this.range = document.selection.createRange();
			}
		},

		click: function( event ) {
			this._setSelection();
			this._toggle( event );
		},

		keydown: function( event ) {
			var preventDefault = true;
			switch ( event.keyCode ) {
				case $.ui.keyCode.TAB:
				case $.ui.keyCode.ESCAPE:
					this.close( event );
					preventDefault = false;
					break;
				case $.ui.keyCode.ENTER:
					if ( this.isOpen ) {
						this._selectFocusedItem( event );
					}
					break;
				case $.ui.keyCode.UP:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "prev", event );
					}
					break;
				case $.ui.keyCode.DOWN:
					if ( event.altKey ) {
						this._toggle( event );
					} else {
						this._move( "next", event );
					}
					break;
				case $.ui.keyCode.SPACE:
					if ( this.isOpen ) {
						this._selectFocusedItem( event );
					} else {
						this._toggle( event );
					}
					break;
				case $.ui.keyCode.LEFT:
					this._move( "prev", event );
					break;
				case $.ui.keyCode.RIGHT:
					this._move( "next", event );
					break;
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.PAGE_UP:
					this._move( "first", event );
					break;
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_DOWN:
					this._move( "last", event );
					break;
				default:
					this.menu.trigger( event );
					preventDefault = false;
			}

			if ( preventDefault ) {
				event.preventDefault();
			}
		}
	},

	_selectFocusedItem: function( event ) {
		var item = this.menuItems.eq( this.focusIndex );
		if ( !item.hasClass( "ui-state-disabled" ) ) {
			this._select( item.data( "ui-selectmenu-item" ), event );
		}
	},

	_select: function( item, event ) {
		var oldIndex = this.element[ 0 ].selectedIndex;

		// Change native select element
		this.element[ 0 ].selectedIndex = item.index;
		this._setText( this.buttonText, item.label );
		this._setAria( item );
		this._trigger( "select", event, { item: item } );

		if ( item.index !== oldIndex ) {
			this._trigger( "change", event, { item: item } );
		}

		this.close( event );
	},

	_setAria: function( item ) {
		var id = this.menuItems.eq( item.index ).attr( "id" );

		this.button.attr({
			"aria-labelledby": id,
			"aria-activedescendant": id
		});
		this.menu.attr( "aria-activedescendant", id );
	},

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			this.button.find( "span.ui-icon" )
				.removeClass( this.options.icons.button )
				.addClass( value.button );
		}

		this._super( key, value );

		if ( key === "appendTo" ) {
			this.menuWrap.appendTo( this._appendTo() );
		}

		if ( key === "disabled" ) {
			this.menuInstance.option( "disabled", value );
			this.button
				.toggleClass( "ui-state-disabled", value )
				.attr( "aria-disabled", value );

			this.element.prop( "disabled", value );
			if ( value ) {
				this.button.attr( "tabindex", -1 );
				this.close();
			} else {
				this.button.attr( "tabindex", 0 );
			}
		}

		if ( key === "width" ) {
			this._resizeButton();
		}
	},

	_appendTo: function() {
		var element = this.options.appendTo;

		if ( element ) {
			element = element.jquery || element.nodeType ?
				$( element ) :
				this.document.find( element ).eq( 0 );
		}

		if ( !element || !element[ 0 ] ) {
			element = this.element.closest( ".ui-front" );
		}

		if ( !element.length ) {
			element = this.document[ 0 ].body;
		}

		return element;
	},

	_toggleAttr: function() {
		this.button
			.toggleClass( "ui-corner-top", this.isOpen )
			.toggleClass( "ui-corner-all", !this.isOpen )
			.attr( "aria-expanded", this.isOpen );
		this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen );
		this.menu.attr( "aria-hidden", !this.isOpen );
	},

	_resizeButton: function() {
		var width = this.options.width;

		if ( !width ) {
			width = this.element.show().outerWidth();
			this.element.hide();
		}

		this.button.outerWidth( width );
	},

	_resizeMenu: function() {
		this.menu.outerWidth( Math.max(
			this.button.outerWidth(),

			// support: IE10
			// IE10 wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping
			this.menu.width( "" ).outerWidth() + 1
		) );
	},

	_getCreateOptions: function() {
		return { disabled: this.element.prop( "disabled" ) };
	},

	_parseOptions: function( options ) {
		var data = [];
		options.each(function( index, item ) {
			var option = $( item ),
				optgroup = option.parent( "optgroup" );
			data.push({
				element: option,
				index: index,
				value: option.val(),
				label: option.text(),
				optgroup: optgroup.attr( "label" ) || "",
				disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" )
			});
		});
		this.items = data;
	},

	_destroy: function() {
		this.menuWrap.remove();
		this.button.remove();
		this.element.show();
		this.element.removeUniqueId();
		this.label.attr( "for", this.ids.element );
	}
});


/*!
 * jQuery UI Slider 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/slider/
 */


var slider = $.widget( "ui.slider", $.ui.mouse, {
	version: "1.11.4",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this.element
			.addClass( "ui-slider" +
				" ui-slider-" + this.orientation +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all");

		this._refresh();
		this._setOption( "disabled", this.options.disabled );

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
			handle = "<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this.handle = this.handles.eq( 0 );

		this.handles.each(function( i ) {
			$( this ).data( "ui-slider-handle-index", i );
		});
	},

	_createRange: function() {
		var options = this.options,
			classes = "";

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[0], options.values[0] ];
				} else if ( $.isArray( options.values ) ) {
					options.values = options.values.slice(0);
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div></div>" )
					.appendTo( this.element );

				classes = "ui-slider-range" +
				// note: this isn't the most fittingly semantic framework class for this element,
				// but worked best visually with a variety of themes
				" ui-widget-header ui-corner-all";
			} else {
				this.range.removeClass( "ui-slider-range-min ui-slider-range-max" )
					// Handle range switching from true to min/max
					.css({
						"left": "",
						"bottom": ""
					});
			}

			this.range.addClass( classes +
				( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) );
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this.element
			.removeClass( "ui-slider" +
				" ui-slider-horizontal" +
				" ui-slider-vertical" +
				" ui-widget" +
				" ui-widget-content" +
				" ui-corner-all" );

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each(function( i ) {
			var thisDistance = Math.abs( normValue - that.values(i) );
			if (( distance > thisDistance ) ||
				( distance === thisDistance &&
					(i === that._lastChangedValue || that.values(i) === o.min ))) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		});

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		closestHandle
			.addClass( "ui-state-active" )
			.focus();

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
				( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
				( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this.handles.removeClass( "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_start: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}
		return this._trigger( "start", event, uiHash );
	},

	_slide: function( event, index, newVal ) {
		var otherVal,
			newValues,
			allowed;

		if ( this.options.values && this.options.values.length ) {
			otherVal = this.values( index ? 0 : 1 );

			if ( ( this.options.values.length === 2 && this.options.range === true ) &&
					( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
				) {
				newVal = otherVal;
			}

			if ( newVal !== this.values( index ) ) {
				newValues = this.values();
				newValues[ index ] = newVal;
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal,
					values: newValues
				} );
				otherVal = this.values( index ? 0 : 1 );
				if ( allowed !== false ) {
					this.values( index, newVal );
				}
			}
		} else {
			if ( newVal !== this.value() ) {
				// A slide can be canceled by returning false from the slide callback
				allowed = this._trigger( "slide", event, {
					handle: this.handles[ index ],
					value: newVal
				} );
				if ( allowed !== false ) {
					this.value( newVal );
				}
			}
		}
	},

	_stop: function( event, index ) {
		var uiHash = {
			handle: this.handles[ index ],
			value: this.value()
		};
		if ( this.options.values && this.options.values.length ) {
			uiHash.value = this.values( index );
			uiHash.values = this.values();
		}

		this._trigger( "stop", event, uiHash );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {
			var uiHash = {
				handle: this.handles[ index ],
				value: this.value()
			};
			if ( this.options.values && this.options.values.length ) {
				uiHash.value = this.values( index );
				uiHash.values = this.values();
			}

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;

			this._trigger( "change", event, uiHash );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this.options.values && this.options.values.length ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		if ( key === "disabled" ) {
			this.element.toggleClass( "ui-state-disabled", !!value );
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this.element
					.removeClass( "ui-slider-horizontal ui-slider-vertical" )
					.addClass( "ui-slider-" + this.orientation );
				this._refreshValue();

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();
				for ( i = 0; i < valsLength; i += 1 ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this.options.values && this.options.values.length ) {
			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = (val - this._valueMin()) % step,
			alignValue = val - valModStep;

		if ( Math.abs(valModStep) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed(5) );
	},

	_calculateNewMax: function() {
		var max = this.options.max,
			min = this._valueMin(),
			step = this.options.step,
			aboveMin = Math.floor( ( +( max - min ).toFixed( this._precision() ) ) / step ) * step;
		max = aboveMin + min;
		this.max = parseFloat( max.toFixed( this._precision() ) );
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this.options.values && this.options.values.length ) {
			this.handles.each(function( i ) {
				valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
						}
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						$( event.target ).addClass( "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this.options.values && this.options.values.length ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( (this._valueMax() - this._valueMin()) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				$( event.target ).removeClass( "ui-state-active" );
			}
		}
	}
});


/*!
 * jQuery UI Sortable 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/sortable/
 */


var sortable = $.widget("ui.sortable", $.ui.mouse, {
	version: "1.11.4",
	widgetEventPrefix: "sort",
	ready: false,
	options: {
		appendTo: "parent",
		axis: false,
		connectWith: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		dropOnEmpty: true,
		forcePlaceholderSize: false,
		forceHelperSize: false,
		grid: false,
		handle: false,
		helper: "original",
		items: "> *",
		opacity: false,
		placeholder: false,
		revert: false,
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		scope: "default",
		tolerance: "intersect",
		zIndex: 1000,

		// callbacks
		activate: null,
		beforeStop: null,
		change: null,
		deactivate: null,
		out: null,
		over: null,
		receive: null,
		remove: null,
		sort: null,
		start: null,
		stop: null,
		update: null
	},

	_isOverAxis: function( x, reference, size ) {
		return ( x >= reference ) && ( x < ( reference + size ) );
	},

	_isFloating: function( item ) {
		return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
	},

	_create: function() {
		this.containerCache = {};
		this.element.addClass("ui-sortable");

		//Get the items
		this.refresh();

		//Let's determine the parent's offset
		this.offset = this.element.offset();

		//Initialize mouse events for interaction
		this._mouseInit();

		this._setHandleClassName();

		//We're ready to go
		this.ready = true;

	},

	_setOption: function( key, value ) {
		this._super( key, value );

		if ( key === "handle" ) {
			this._setHandleClassName();
		}
	},

	_setHandleClassName: function() {
		this.element.find( ".ui-sortable-handle" ).removeClass( "ui-sortable-handle" );
		$.each( this.items, function() {
			( this.instance.options.handle ?
				this.item.find( this.instance.options.handle ) : this.item )
				.addClass( "ui-sortable-handle" );
		});
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-sortable ui-sortable-disabled" )
			.find( ".ui-sortable-handle" )
				.removeClass( "ui-sortable-handle" );
		this._mouseDestroy();

		for ( var i = this.items.length - 1; i >= 0; i-- ) {
			this.items[i].item.removeData(this.widgetName + "-item");
		}

		return this;
	},

	_mouseCapture: function(event, overrideHandle) {
		var currentItem = null,
			validHandle = false,
			that = this;

		if (this.reverting) {
			return false;
		}

		if(this.options.disabled || this.options.type === "static") {
			return false;
		}

		//We have to refresh the items data once first
		this._refreshItems(event);

		//Find out if the clicked node (or one of its parents) is a actual item in this.items
		$(event.target).parents().each(function() {
			if($.data(this, that.widgetName + "-item") === that) {
				currentItem = $(this);
				return false;
			}
		});
		if($.data(event.target, that.widgetName + "-item") === that) {
			currentItem = $(event.target);
		}

		if(!currentItem) {
			return false;
		}
		if(this.options.handle && !overrideHandle) {
			$(this.options.handle, currentItem).find("*").addBack().each(function() {
				if(this === event.target) {
					validHandle = true;
				}
			});
			if(!validHandle) {
				return false;
			}
		}

		this.currentItem = currentItem;
		this._removeCurrentsFromItems();
		return true;

	},

	_mouseStart: function(event, overrideHandle, noActivation) {

		var i, body,
			o = this.options;

		this.currentContainer = this;

		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
		this.refreshPositions();

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Get the next scrolling parent
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.currentItem.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		// Only after we got the offset, we can change the helper's position to absolute
		// TODO: Still need to figure out a way to make relative sorting possible
		this.helper.css("position", "absolute");
		this.cssPosition = this.helper.css("position");

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if "cursorAt" is supplied
		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));

		//Cache the former DOM position
		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };

		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
		if(this.helper[0] !== this.currentItem[0]) {
			this.currentItem.hide();
		}

		//Create the placeholder
		this._createPlaceholder();

		//Set a containment if given in the options
		if(o.containment) {
			this._setContainment();
		}

		if( o.cursor && o.cursor !== "auto" ) { // cursor option
			body = this.document.find( "body" );

			// support: IE
			this.storedCursor = body.css( "cursor" );
			body.css( "cursor", o.cursor );

			this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
		}

		if(o.opacity) { // opacity option
			if (this.helper.css("opacity")) {
				this._storedOpacity = this.helper.css("opacity");
			}
			this.helper.css("opacity", o.opacity);
		}

		if(o.zIndex) { // zIndex option
			if (this.helper.css("zIndex")) {
				this._storedZIndex = this.helper.css("zIndex");
			}
			this.helper.css("zIndex", o.zIndex);
		}

		//Prepare scrolling
		if(this.scrollParent[0] !== this.document[0] && this.scrollParent[0].tagName !== "HTML") {
			this.overflowOffset = this.scrollParent.offset();
		}

		//Call callbacks
		this._trigger("start", event, this._uiHash());

		//Recache the helper size
		if(!this._preserveHelperProportions) {
			this._cacheHelperProportions();
		}


		//Post "activate" events to possible containers
		if( !noActivation ) {
			for ( i = this.containers.length - 1; i >= 0; i-- ) {
				this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
			}
		}

		//Prepare possible droppables
		if($.ui.ddmanager) {
			$.ui.ddmanager.current = this;
		}

		if ($.ui.ddmanager && !o.dropBehaviour) {
			$.ui.ddmanager.prepareOffsets(this, event);
		}

		this.dragging = true;

		this.helper.addClass("ui-sortable-helper");
		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;

	},

	_mouseDrag: function(event) {
		var i, item, itemElement, intersection,
			o = this.options,
			scrolled = false;

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		if (!this.lastPositionAbs) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Do scrolling
		if(this.options.scroll) {
			if(this.scrollParent[0] !== this.document[0] && this.scrollParent[0].tagName !== "HTML") {

				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
				} else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
				}

				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
				} else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
				}

			} else {

				if(event.pageY - this.document.scrollTop() < o.scrollSensitivity) {
					scrolled = this.document.scrollTop(this.document.scrollTop() - o.scrollSpeed);
				} else if(this.window.height() - (event.pageY - this.document.scrollTop()) < o.scrollSensitivity) {
					scrolled = this.document.scrollTop(this.document.scrollTop() + o.scrollSpeed);
				}

				if(event.pageX - this.document.scrollLeft() < o.scrollSensitivity) {
					scrolled = this.document.scrollLeft(this.document.scrollLeft() - o.scrollSpeed);
				} else if(this.window.width() - (event.pageX - this.document.scrollLeft()) < o.scrollSensitivity) {
					scrolled = this.document.scrollLeft(this.document.scrollLeft() + o.scrollSpeed);
				}

			}

			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
				$.ui.ddmanager.prepareOffsets(this, event);
			}
		}

		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo("absolute");

		//Set the helper position
		if(!this.options.axis || this.options.axis !== "y") {
			this.helper[0].style.left = this.position.left+"px";
		}
		if(!this.options.axis || this.options.axis !== "x") {
			this.helper[0].style.top = this.position.top+"px";
		}

		//Rearrange
		for (i = this.items.length - 1; i >= 0; i--) {

			//Cache variables and intersection, continue if no intersection
			item = this.items[i];
			itemElement = item.item[0];
			intersection = this._intersectsWithPointer(item);
			if (!intersection) {
				continue;
			}

			// Only put the placeholder inside the current Container, skip all
			// items from other containers. This works because when moving
			// an item from one container to another the
			// currentContainer is switched before the placeholder is moved.
			//
			// Without this, moving items in "sub-sortables" can cause
			// the placeholder to jitter between the outer and inner container.
			if (item.instance !== this.currentContainer) {
				continue;
			}

			// cannot intersect with itself
			// no useless actions that have been done before
			// no action if the item moved is the parent of the item checked
			if (itemElement !== this.currentItem[0] &&
				this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
				!$.contains(this.placeholder[0], itemElement) &&
				(this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
			) {

				this.direction = intersection === 1 ? "down" : "up";

				if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
					this._rearrange(event, item);
				} else {
					break;
				}

				this._trigger("change", event, this._uiHash());
				break;
			}
		}

		//Post events to containers
		this._contactContainers(event);

		//Interconnect with droppables
		if($.ui.ddmanager) {
			$.ui.ddmanager.drag(this, event);
		}

		//Call callbacks
		this._trigger("sort", event, this._uiHash());

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

	_mouseStop: function(event, noPropagation) {

		if(!event) {
			return;
		}

		//If we are using droppables, inform the manager about the drop
		if ($.ui.ddmanager && !this.options.dropBehaviour) {
			$.ui.ddmanager.drop(this, event);
		}

		if(this.options.revert) {
			var that = this,
				cur = this.placeholder.offset(),
				axis = this.options.axis,
				animation = {};

			if ( !axis || axis === "x" ) {
				animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === this.document[0].body ? 0 : this.offsetParent[0].scrollLeft);
			}
			if ( !axis || axis === "y" ) {
				animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === this.document[0].body ? 0 : this.offsetParent[0].scrollTop);
			}
			this.reverting = true;
			$(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
				that._clear(event);
			});
		} else {
			this._clear(event, noPropagation);
		}

		return false;

	},

	cancel: function() {

		if(this.dragging) {

			this._mouseUp({ target: null });

			if(this.options.helper === "original") {
				this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
			} else {
				this.currentItem.show();
			}

			//Post deactivating events to containers
			for (var i = this.containers.length - 1; i >= 0; i--){
				this.containers[i]._trigger("deactivate", null, this._uiHash(this));
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", null, this._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		if (this.placeholder) {
			//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
			if(this.placeholder[0].parentNode) {
				this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
			}
			if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
				this.helper.remove();
			}

			$.extend(this, {
				helper: null,
				dragging: false,
				reverting: false,
				_noFinalSort: null
			});

			if(this.domPosition.prev) {
				$(this.domPosition.prev).after(this.currentItem);
			} else {
				$(this.domPosition.parent).prepend(this.currentItem);
			}
		}

		return this;

	},

	serialize: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected),
			str = [];
		o = o || {};

		$(items).each(function() {
			var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
			if (res) {
				str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
			}
		});

		if(!str.length && o.key) {
			str.push(o.key + "=");
		}

		return str.join("&");

	},

	toArray: function(o) {

		var items = this._getItemsAsjQuery(o && o.connected),
			ret = [];

		o = o || {};

		items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
		return ret;

	},

	/* Be careful with the following core functions */
	_intersectsWith: function(item) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height,
			l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height,
			dyClick = this.offset.click.top,
			dxClick = this.offset.click.left,
			isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
			isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
			isOverElement = isOverElementHeight && isOverElementWidth;

		if ( this.options.tolerance === "pointer" ||
			this.options.forcePointerForContainers ||
			(this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
		) {
			return isOverElement;
		} else {

			return (l < x1 + (this.helperProportions.width / 2) && // Right Half
				x2 - (this.helperProportions.width / 2) < r && // Left Half
				t < y1 + (this.helperProportions.height / 2) && // Bottom Half
				y2 - (this.helperProportions.height / 2) < b ); // Top Half

		}
	},

	_intersectsWithPointer: function(item) {

		var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
			isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
			isOverElement = isOverElementHeight && isOverElementWidth,
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (!isOverElement) {
			return false;
		}

		return this.floating ?
			( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
			: ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );

	},

	_intersectsWithSides: function(item) {

		var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
			isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
			verticalDirection = this._getDragVerticalDirection(),
			horizontalDirection = this._getDragHorizontalDirection();

		if (this.floating && horizontalDirection) {
			return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
		} else {
			return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
		}

	},

	_getDragVerticalDirection: function() {
		var delta = this.positionAbs.top - this.lastPositionAbs.top;
		return delta !== 0 && (delta > 0 ? "down" : "up");
	},

	_getDragHorizontalDirection: function() {
		var delta = this.positionAbs.left - this.lastPositionAbs.left;
		return delta !== 0 && (delta > 0 ? "right" : "left");
	},

	refresh: function(event) {
		this._refreshItems(event);
		this._setHandleClassName();
		this.refreshPositions();
		return this;
	},

	_connectWith: function() {
		var options = this.options;
		return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
	},

	_getItemsAsjQuery: function(connected) {

		var i, j, cur, inst,
			items = [],
			queries = [],
			connectWith = this._connectWith();

		if(connectWith && connected) {
			for (i = connectWith.length - 1; i >= 0; i--){
				cur = $(connectWith[i], this.document[0]);
				for ( j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
					}
				}
			}
		}

		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);

		function addItems() {
			items.push( this );
		}
		for (i = queries.length - 1; i >= 0; i--){
			queries[i][0].each( addItems );
		}

		return $(items);

	},

	_removeCurrentsFromItems: function() {

		var list = this.currentItem.find(":data(" + this.widgetName + "-item)");

		this.items = $.grep(this.items, function (item) {
			for (var j=0; j < list.length; j++) {
				if(list[j] === item.item[0]) {
					return false;
				}
			}
			return true;
		});

	},

	_refreshItems: function(event) {

		this.items = [];
		this.containers = [this];

		var i, j, cur, inst, targetData, _queries, item, queriesLength,
			items = this.items,
			queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
			connectWith = this._connectWith();

		if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
			for (i = connectWith.length - 1; i >= 0; i--){
				cur = $(connectWith[i], this.document[0]);
				for (j = cur.length - 1; j >= 0; j--){
					inst = $.data(cur[j], this.widgetFullName);
					if(inst && inst !== this && !inst.options.disabled) {
						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
						this.containers.push(inst);
					}
				}
			}
		}

		for (i = queries.length - 1; i >= 0; i--) {
			targetData = queries[i][1];
			_queries = queries[i][0];

			for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				item = $(_queries[j]);

				item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
					width: 0, height: 0,
					left: 0, top: 0
				});
			}
		}

	},

	refreshPositions: function(fast) {

		// Determine whether items are being displayed horizontally
		this.floating = this.items.length ?
			this.options.axis === "x" || this._isFloating( this.items[ 0 ].item ) :
			false;

		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
		if(this.offsetParent && this.helper) {
			this.offset.parent = this._getParentOffset();
		}

		var i, item, t, p;

		for (i = this.items.length - 1; i >= 0; i--){
			item = this.items[i];

			//We ignore calculating positions of all connected containers when we're not over them
			if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
				continue;
			}

			t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;

			if (!fast) {
				item.width = t.outerWidth();
				item.height = t.outerHeight();
			}

			p = t.offset();
			item.left = p.left;
			item.top = p.top;
		}

		if(this.options.custom && this.options.custom.refreshContainers) {
			this.options.custom.refreshContainers.call(this);
		} else {
			for (i = this.containers.length - 1; i >= 0; i--){
				p = this.containers[i].element.offset();
				this.containers[i].containerCache.left = p.left;
				this.containers[i].containerCache.top = p.top;
				this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
			}
		}

		return this;
	},

	_createPlaceholder: function(that) {
		that = that || this;
		var className,
			o = that.options;

		if(!o.placeholder || o.placeholder.constructor === String) {
			className = o.placeholder;
			o.placeholder = {
				element: function() {

					var nodeName = that.currentItem[0].nodeName.toLowerCase(),
						element = $( "<" + nodeName + ">", that.document[0] )
							.addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
							.removeClass("ui-sortable-helper");

					if ( nodeName === "tbody" ) {
						that._createTrPlaceholder(
							that.currentItem.find( "tr" ).eq( 0 ),
							$( "<tr>", that.document[ 0 ] ).appendTo( element )
						);
					} else if ( nodeName === "tr" ) {
						that._createTrPlaceholder( that.currentItem, element );
					} else if ( nodeName === "img" ) {
						element.attr( "src", that.currentItem.attr( "src" ) );
					}

					if ( !className ) {
						element.css( "visibility", "hidden" );
					}

					return element;
				},
				update: function(container, p) {

					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
					if(className && !o.forcePlaceholderSize) {
						return;
					}

					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
					if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
					if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
				}
			};
		}

		//Create the placeholder
		that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));

		//Append it after the actual current item
		that.currentItem.after(that.placeholder);

		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
		o.placeholder.update(that, that.placeholder);

	},

	_createTrPlaceholder: function( sourceTr, targetTr ) {
		var that = this;

		sourceTr.children().each(function() {
			$( "<td>&#160;</td>", that.document[ 0 ] )
				.attr( "colspan", $( this ).attr( "colspan" ) || 1 )
				.appendTo( targetTr );
		});
	},

	_contactContainers: function(event) {
		var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis,
			innermostContainer = null,
			innermostIndex = null;

		// get innermost container that intersects with item
		for (i = this.containers.length - 1; i >= 0; i--) {

			// never consider a container that's located within the item itself
			if($.contains(this.currentItem[0], this.containers[i].element[0])) {
				continue;
			}

			if(this._intersectsWith(this.containers[i].containerCache)) {

				// if we've already found a container and it's more "inner" than this, then continue
				if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
					continue;
				}

				innermostContainer = this.containers[i];
				innermostIndex = i;

			} else {
				// container doesn't intersect. trigger "out" event if necessary
				if(this.containers[i].containerCache.over) {
					this.containers[i]._trigger("out", event, this._uiHash(this));
					this.containers[i].containerCache.over = 0;
				}
			}

		}

		// if no intersecting containers found, return
		if(!innermostContainer) {
			return;
		}

		// move the item into the container if it's not there already
		if(this.containers.length === 1) {
			if (!this.containers[innermostIndex].containerCache.over) {
				this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
				this.containers[innermostIndex].containerCache.over = 1;
			}
		} else {

			//When entering a new container, we will find the item with the least distance and append our item near it
			dist = 10000;
			itemWithLeastDistance = null;
			floating = innermostContainer.floating || this._isFloating(this.currentItem);
			posProperty = floating ? "left" : "top";
			sizeProperty = floating ? "width" : "height";
			axis = floating ? "clientX" : "clientY";

			for (j = this.items.length - 1; j >= 0; j--) {
				if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
					continue;
				}
				if(this.items[j].item[0] === this.currentItem[0]) {
					continue;
				}

				cur = this.items[j].item.offset()[posProperty];
				nearBottom = false;
				if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
					nearBottom = true;
				}

				if ( Math.abs( event[ axis ] - cur ) < dist ) {
					dist = Math.abs( event[ axis ] - cur );
					itemWithLeastDistance = this.items[ j ];
					this.direction = nearBottom ? "up": "down";
				}
			}

			//Check if dropOnEmpty is enabled
			if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
				return;
			}

			if(this.currentContainer === this.containers[innermostIndex]) {
				if ( !this.currentContainer.containerCache.over ) {
					this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
					this.currentContainer.containerCache.over = 1;
				}
				return;
			}

			itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
			this._trigger("change", event, this._uiHash());
			this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
			this.currentContainer = this.containers[innermostIndex];

			//Update the placeholder
			this.options.placeholder.update(this.currentContainer, this.placeholder);

			this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
			this.containers[innermostIndex].containerCache.over = 1;
		}


	},

	_createHelper: function(event) {

		var o = this.options,
			helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);

		//Add the helper to the DOM if that didn't happen already
		if(!helper.parents("body").length) {
			$(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
		}

		if(helper[0] === this.currentItem[0]) {
			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
		}

		if(!helper[0].style.width || o.forceHelperSize) {
			helper.width(this.currentItem.width());
		}
		if(!helper[0].style.height || o.forceHelperSize) {
			helper.height(this.currentItem.height());
		}

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if (typeof obj === "string") {
			obj = obj.split(" ");
		}
		if ($.isArray(obj)) {
			obj = {left: +obj[0], top: +obj[1] || 0};
		}
		if ("left" in obj) {
			this.offset.click.left = obj.left + this.margins.left;
		}
		if ("right" in obj) {
			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		}
		if ("top" in obj) {
			this.offset.click.top = obj.top + this.margins.top;
		}
		if ("bottom" in obj) {
			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
		}
	},

	_getParentOffset: function() {


		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition === "absolute" && this.scrollParent[0] !== this.document[0] && $.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		// This needs to be actually done for all browsers, since pageX/pageY includes this information
		// with an ugly IE fix
		if( this.offsetParent[0] === this.document[0].body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
			po = { top: 0, left: 0 };
		}

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition === "relative") {
			var p = this.currentItem.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var ce, co, over,
			o = this.options;
		if(o.containment === "parent") {
			o.containment = this.helper[0].parentNode;
		}
		if(o.containment === "document" || o.containment === "window") {
			this.containment = [
				0 - this.offset.relative.left - this.offset.parent.left,
				0 - this.offset.relative.top - this.offset.parent.top,
				o.containment === "document" ? this.document.width() : this.window.width() - this.helperProportions.width - this.margins.left,
				(o.containment === "document" ? this.document.width() : this.window.height() || this.document[0].body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
			];
		}

		if(!(/^(document|window|parent)$/).test(o.containment)) {
			ce = $(o.containment)[0];
			co = $(o.containment).offset();
			over = ($(ce).css("overflow") !== "hidden");

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) {
			pos = this.position;
		}
		var mod = d === "absolute" ? 1 : -1,
			scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== this.document[0] && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
			scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top	+																// The absolute mouse position
				this.offset.relative.top * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top * mod -											// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left +																// The absolute mouse position
				this.offset.relative.left * mod +										// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left * mod	-										// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var top, left,
			o = this.options,
			pageX = event.pageX,
			pageY = event.pageY,
			scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== this.document[0] && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition === "relative" && !(this.scrollParent[0] !== this.document[0] && this.scrollParent[0] !== this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) {
					pageX = this.containment[0] + this.offset.click.left;
				}
				if(event.pageY - this.offset.click.top < this.containment[1]) {
					pageY = this.containment[1] + this.offset.click.top;
				}
				if(event.pageX - this.offset.click.left > this.containment[2]) {
					pageX = this.containment[2] + this.offset.click.left;
				}
				if(event.pageY - this.offset.click.top > this.containment[3]) {
					pageY = this.containment[3] + this.offset.click.top;
				}
			}

			if(o.grid) {
				top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY -																// The absolute mouse position
				this.offset.click.top -													// Click offset (relative to the element)
				this.offset.relative.top	-											// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.top +												// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX -																// The absolute mouse position
				this.offset.click.left -												// Click offset (relative to the element)
				this.offset.relative.left	-											// Only for relative positioned nodes: Relative offset from element to offset parent
				this.offset.parent.left +												// The offsetParent's offset without borders (offset + border)
				( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_rearrange: function(event, i, a, hardRefresh) {

		a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));

		//Various things done here to improve the performance:
		// 1. we create a setTimeout, that calls refreshPositions
		// 2. on the instance, we have a counter variable, that get's higher after every append
		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
		// 4. this lets only the last addition to the timeout stack through
		this.counter = this.counter ? ++this.counter : 1;
		var counter = this.counter;

		this._delay(function() {
			if(counter === this.counter) {
				this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
			}
		});

	},

	_clear: function(event, noPropagation) {

		this.reverting = false;
		// We delay all events that have to be triggered to after the point where the placeholder has been removed and
		// everything else normalized again
		var i,
			delayedTriggers = [];

		// We first have to update the dom position of the actual currentItem
		// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
		if(!this._noFinalSort && this.currentItem.parent().length) {
			this.placeholder.before(this.currentItem);
		}
		this._noFinalSort = null;

		if(this.helper[0] === this.currentItem[0]) {
			for(i in this._storedCSS) {
				if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
					this._storedCSS[i] = "";
				}
			}
			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
		} else {
			this.currentItem.show();
		}

		if(this.fromOutside && !noPropagation) {
			delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
		}
		if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
			delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
		}

		// Check if the items Container has Changed and trigger appropriate
		// events.
		if (this !== this.currentContainer) {
			if(!noPropagation) {
				delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
				delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.currentContainer));
				delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.currentContainer));
			}
		}


		//Post events to containers
		function delayEvent( type, instance, container ) {
			return function( event ) {
				container._trigger( type, event, instance._uiHash( instance ) );
			};
		}
		for (i = this.containers.length - 1; i >= 0; i--){
			if (!noPropagation) {
				delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
			}
			if(this.containers[i].containerCache.over) {
				delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
				this.containers[i].containerCache.over = 0;
			}
		}

		//Do what was originally in plugins
		if ( this.storedCursor ) {
			this.document.find( "body" ).css( "cursor", this.storedCursor );
			this.storedStylesheet.remove();
		}
		if(this._storedOpacity) {
			this.helper.css("opacity", this._storedOpacity);
		}
		if(this._storedZIndex) {
			this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
		}

		this.dragging = false;

		if(!noPropagation) {
			this._trigger("beforeStop", event, this._uiHash());
		}

		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);

		if ( !this.cancelHelperRemoval ) {
			if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
				this.helper.remove();
			}
			this.helper = null;
		}

		if(!noPropagation) {
			for (i=0; i < delayedTriggers.length; i++) {
				delayedTriggers[i].call(this, event);
			} //Trigger all delayed events
			this._trigger("stop", event, this._uiHash());
		}

		this.fromOutside = false;
		return !this.cancelHelperRemoval;

	},

	_trigger: function() {
		if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
			this.cancel();
		}
	},

	_uiHash: function(_inst) {
		var inst = _inst || this;
		return {
			helper: inst.helper,
			placeholder: inst.placeholder || $([]),
			position: inst.position,
			originalPosition: inst.originalPosition,
			offset: inst.positionAbs,
			item: inst.currentItem,
			sender: _inst ? _inst.element : null
		};
	}

});


/*!
 * jQuery UI Spinner 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/spinner/
 */


function spinner_modifier( fn ) {
	return function() {
		var previous = this.element.val();
		fn.apply( this, arguments );
		this._refresh();
		if ( previous !== this.element.val() ) {
			this._trigger( "change" );
		}
	};
}

var spinner = $.widget( "ui.spinner", {
	version: "1.11.4",
	defaultElement: "<input>",
	widgetEventPrefix: "spin",
	options: {
		culture: null,
		icons: {
			down: "ui-icon-triangle-1-s",
			up: "ui-icon-triangle-1-n"
		},
		incremental: true,
		max: null,
		min: null,
		numberFormat: null,
		page: 10,
		step: 1,

		change: null,
		spin: null,
		start: null,
		stop: null
	},

	_create: function() {
		// handle string values that need to be parsed
		this._setOption( "max", this.options.max );
		this._setOption( "min", this.options.min );
		this._setOption( "step", this.options.step );

		// Only format if there is a value, prevents the field from being marked
		// as invalid in Firefox, see #9573.
		if ( this.value() !== "" ) {
			// Format the value, but don't constrain.
			this._value( this.element.val(), true );
		}

		this._draw();
		this._on( this._events );
		this._refresh();

		// turning off autocomplete prevents the browser from remembering the
		// value when navigating through history, so we re-enable autocomplete
		// if the page is unloaded before the widget is destroyed. #7790
		this._on( this.window, {
			beforeunload: function() {
				this.element.removeAttr( "autocomplete" );
			}
		});
	},

	_getCreateOptions: function() {
		var options = {},
			element = this.element;

		$.each( [ "min", "max", "step" ], function( i, option ) {
			var value = element.attr( option );
			if ( value !== undefined && value.length ) {
				options[ option ] = value;
			}
		});

		return options;
	},

	_events: {
		keydown: function( event ) {
			if ( this._start( event ) && this._keydown( event ) ) {
				event.preventDefault();
			}
		},
		keyup: "_stop",
		focus: function() {
			this.previous = this.element.val();
		},
		blur: function( event ) {
			if ( this.cancelBlur ) {
				delete this.cancelBlur;
				return;
			}

			this._stop();
			this._refresh();
			if ( this.previous !== this.element.val() ) {
				this._trigger( "change", event );
			}
		},
		mousewheel: function( event, delta ) {
			if ( !delta ) {
				return;
			}
			if ( !this.spinning && !this._start( event ) ) {
				return false;
			}

			this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
			clearTimeout( this.mousewheelTimer );
			this.mousewheelTimer = this._delay(function() {
				if ( this.spinning ) {
					this._stop( event );
				}
			}, 100 );
			event.preventDefault();
		},
		"mousedown .ui-spinner-button": function( event ) {
			var previous;

			// We never want the buttons to have focus; whenever the user is
			// interacting with the spinner, the focus should be on the input.
			// If the input is focused then this.previous is properly set from
			// when the input first received focus. If the input is not focused
			// then we need to set this.previous based on the value before spinning.
			previous = this.element[0] === this.document[0].activeElement ?
				this.previous : this.element.val();
			function checkFocus() {
				var isActive = this.element[0] === this.document[0].activeElement;
				if ( !isActive ) {
					this.element.focus();
					this.previous = previous;
					// support: IE
					// IE sets focus asynchronously, so we need to check if focus
					// moved off of the input because the user clicked on the button.
					this._delay(function() {
						this.previous = previous;
					});
				}
			}

			// ensure focus is on (or stays on) the text field
			event.preventDefault();
			checkFocus.call( this );

			// support: IE
			// IE doesn't prevent moving focus even with event.preventDefault()
			// so we set a flag to know when we should ignore the blur event
			// and check (again) if focus moved off of the input.
			this.cancelBlur = true;
			this._delay(function() {
				delete this.cancelBlur;
				checkFocus.call( this );
			});

			if ( this._start( event ) === false ) {
				return;
			}

			this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
		},
		"mouseup .ui-spinner-button": "_stop",
		"mouseenter .ui-spinner-button": function( event ) {
			// button will add ui-state-active if mouse was down while mouseleave and kept down
			if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
				return;
			}

			if ( this._start( event ) === false ) {
				return false;
			}
			this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
		},
		// TODO: do we really want to consider this a stop?
		// shouldn't we just stop the repeater and wait until mouseup before
		// we trigger the stop event?
		"mouseleave .ui-spinner-button": "_stop"
	},

	_draw: function() {
		var uiSpinner = this.uiSpinner = this.element
			.addClass( "ui-spinner-input" )
			.attr( "autocomplete", "off" )
			.wrap( this._uiSpinnerHtml() )
			.parent()
				// add buttons
				.append( this._buttonHtml() );

		this.element.attr( "role", "spinbutton" );

		// button bindings
		this.buttons = uiSpinner.find( ".ui-spinner-button" )
			.attr( "tabIndex", -1 )
			.button()
			.removeClass( "ui-corner-all" );

		// IE 6 doesn't understand height: 50% for the buttons
		// unless the wrapper has an explicit height
		if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
				uiSpinner.height() > 0 ) {
			uiSpinner.height( uiSpinner.height() );
		}

		// disable spinner if element was already disabled
		if ( this.options.disabled ) {
			this.disable();
		}
	},

	_keydown: function( event ) {
		var options = this.options,
			keyCode = $.ui.keyCode;

		switch ( event.keyCode ) {
		case keyCode.UP:
			this._repeat( null, 1, event );
			return true;
		case keyCode.DOWN:
			this._repeat( null, -1, event );
			return true;
		case keyCode.PAGE_UP:
			this._repeat( null, options.page, event );
			return true;
		case keyCode.PAGE_DOWN:
			this._repeat( null, -options.page, event );
			return true;
		}

		return false;
	},

	_uiSpinnerHtml: function() {
		return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
	},

	_buttonHtml: function() {
		return "" +
			"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
				"<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" +
			"</a>" +
			"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
				"<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" +
			"</a>";
	},

	_start: function( event ) {
		if ( !this.spinning && this._trigger( "start", event ) === false ) {
			return false;
		}

		if ( !this.counter ) {
			this.counter = 1;
		}
		this.spinning = true;
		return true;
	},

	_repeat: function( i, steps, event ) {
		i = i || 500;

		clearTimeout( this.timer );
		this.timer = this._delay(function() {
			this._repeat( 40, steps, event );
		}, i );

		this._spin( steps * this.options.step, event );
	},

	_spin: function( step, event ) {
		var value = this.value() || 0;

		if ( !this.counter ) {
			this.counter = 1;
		}

		value = this._adjustValue( value + step * this._increment( this.counter ) );

		if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
			this._value( value );
			this.counter++;
		}
	},

	_increment: function( i ) {
		var incremental = this.options.incremental;

		if ( incremental ) {
			return $.isFunction( incremental ) ?
				incremental( i ) :
				Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 );
		}

		return 1;
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_adjustValue: function( value ) {
		var base, aboveMin,
			options = this.options;

		// make sure we're at a valid step
		// - find out where we are relative to the base (min or 0)
		base = options.min !== null ? options.min : 0;
		aboveMin = value - base;
		// - round to the nearest step
		aboveMin = Math.round(aboveMin / options.step) * options.step;
		// - rounding is based on 0, so adjust back to our base
		value = base + aboveMin;

		// fix precision from bad JS floating point math
		value = parseFloat( value.toFixed( this._precision() ) );

		// clamp the value
		if ( options.max !== null && value > options.max) {
			return options.max;
		}
		if ( options.min !== null && value < options.min ) {
			return options.min;
		}

		return value;
	},

	_stop: function( event ) {
		if ( !this.spinning ) {
			return;
		}

		clearTimeout( this.timer );
		clearTimeout( this.mousewheelTimer );
		this.counter = 0;
		this.spinning = false;
		this._trigger( "stop", event );
	},

	_setOption: function( key, value ) {
		if ( key === "culture" || key === "numberFormat" ) {
			var prevValue = this._parse( this.element.val() );
			this.options[ key ] = value;
			this.element.val( this._format( prevValue ) );
			return;
		}

		if ( key === "max" || key === "min" || key === "step" ) {
			if ( typeof value === "string" ) {
				value = this._parse( value );
			}
		}
		if ( key === "icons" ) {
			this.buttons.first().find( ".ui-icon" )
				.removeClass( this.options.icons.up )
				.addClass( value.up );
			this.buttons.last().find( ".ui-icon" )
				.removeClass( this.options.icons.down )
				.addClass( value.down );
		}

		this._super( key, value );

		if ( key === "disabled" ) {
			this.widget().toggleClass( "ui-state-disabled", !!value );
			this.element.prop( "disabled", !!value );
			this.buttons.button( value ? "disable" : "enable" );
		}
	},

	_setOptions: spinner_modifier(function( options ) {
		this._super( options );
	}),

	_parse: function( val ) {
		if ( typeof val === "string" && val !== "" ) {
			val = window.Globalize && this.options.numberFormat ?
				Globalize.parseFloat( val, 10, this.options.culture ) : +val;
		}
		return val === "" || isNaN( val ) ? null : val;
	},

	_format: function( value ) {
		if ( value === "" ) {
			return "";
		}
		return window.Globalize && this.options.numberFormat ?
			Globalize.format( value, this.options.numberFormat, this.options.culture ) :
			value;
	},

	_refresh: function() {
		this.element.attr({
			"aria-valuemin": this.options.min,
			"aria-valuemax": this.options.max,
			// TODO: what should we do with values that can't be parsed?
			"aria-valuenow": this._parse( this.element.val() )
		});
	},

	isValid: function() {
		var value = this.value();

		// null is invalid
		if ( value === null ) {
			return false;
		}

		// if value gets adjusted, it's invalid
		return value === this._adjustValue( value );
	},

	// update the value without triggering change
	_value: function( value, allowAny ) {
		var parsed;
		if ( value !== "" ) {
			parsed = this._parse( value );
			if ( parsed !== null ) {
				if ( !allowAny ) {
					parsed = this._adjustValue( parsed );
				}
				value = this._format( parsed );
			}
		}
		this.element.val( value );
		this._refresh();
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-spinner-input" )
			.prop( "disabled", false )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-valuemin" )
			.removeAttr( "aria-valuemax" )
			.removeAttr( "aria-valuenow" );
		this.uiSpinner.replaceWith( this.element );
	},

	stepUp: spinner_modifier(function( steps ) {
		this._stepUp( steps );
	}),
	_stepUp: function( steps ) {
		if ( this._start() ) {
			this._spin( (steps || 1) * this.options.step );
			this._stop();
		}
	},

	stepDown: spinner_modifier(function( steps ) {
		this._stepDown( steps );
	}),
	_stepDown: function( steps ) {
		if ( this._start() ) {
			this._spin( (steps || 1) * -this.options.step );
			this._stop();
		}
	},

	pageUp: spinner_modifier(function( pages ) {
		this._stepUp( (pages || 1) * this.options.page );
	}),

	pageDown: spinner_modifier(function( pages ) {
		this._stepDown( (pages || 1) * this.options.page );
	}),

	value: function( newVal ) {
		if ( !arguments.length ) {
			return this._parse( this.element.val() );
		}
		spinner_modifier( this._value ).call( this, newVal );
	},

	widget: function() {
		return this.uiSpinner;
	}
});


/*!
 * jQuery UI Tabs 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/tabs/
 */


var tabs = $.widget( "ui.tabs", {
	version: "1.11.4",
	delay: 300,
	options: {
		active: null,
		collapsible: false,
		event: "click",
		heightStyle: "content",
		hide: null,
		show: null,

		// callbacks
		activate: null,
		beforeActivate: null,
		beforeLoad: null,
		load: null
	},

	_isLocal: (function() {
		var rhash = /#.*$/;

		return function( anchor ) {
			var anchorUrl, locationUrl;

			// support: IE7
			// IE7 doesn't normalize the href property when set via script (#9317)
			anchor = anchor.cloneNode( false );

			anchorUrl = anchor.href.replace( rhash, "" );
			locationUrl = location.href.replace( rhash, "" );

			// decoding may throw an error if the URL isn't UTF-8 (#9518)
			try {
				anchorUrl = decodeURIComponent( anchorUrl );
			} catch ( error ) {}
			try {
				locationUrl = decodeURIComponent( locationUrl );
			} catch ( error ) {}

			return anchor.hash.length > 1 && anchorUrl === locationUrl;
		};
	})(),

	_create: function() {
		var that = this,
			options = this.options;

		this.running = false;

		this.element
			.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
			.toggleClass( "ui-tabs-collapsible", options.collapsible );

		this._processTabs();
		options.active = this._initialActive();

		// Take disabling tabs via class attribute from HTML
		// into account and update option properly.
		if ( $.isArray( options.disabled ) ) {
			options.disabled = $.unique( options.disabled.concat(
				$.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
					return that.tabs.index( li );
				})
			) ).sort();
		}

		// check for length avoids error when initializing empty list
		if ( this.options.active !== false && this.anchors.length ) {
			this.active = this._findActive( options.active );
		} else {
			this.active = $();
		}

		this._refresh();

		if ( this.active.length ) {
			this.load( options.active );
		}
	},

	_initialActive: function() {
		var active = this.options.active,
			collapsible = this.options.collapsible,
			locationHash = location.hash.substring( 1 );

		if ( active === null ) {
			// check the fragment identifier in the URL
			if ( locationHash ) {
				this.tabs.each(function( i, tab ) {
					if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
						active = i;
						return false;
					}
				});
			}

			// check for a tab marked active via a class
			if ( active === null ) {
				active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
			}

			// no active tab, set to false
			if ( active === null || active === -1 ) {
				active = this.tabs.length ? 0 : false;
			}
		}

		// handle numbers: negative, out of range
		if ( active !== false ) {
			active = this.tabs.index( this.tabs.eq( active ) );
			if ( active === -1 ) {
				active = collapsible ? false : 0;
			}
		}

		// don't allow collapsible: false and active: false
		if ( !collapsible && active === false && this.anchors.length ) {
			active = 0;
		}

		return active;
	},

	_getCreateEventData: function() {
		return {
			tab: this.active,
			panel: !this.active.length ? $() : this._getPanelForTab( this.active )
		};
	},

	_tabKeydown: function( event ) {
		var focusedTab = $( this.document[0].activeElement ).closest( "li" ),
			selectedIndex = this.tabs.index( focusedTab ),
			goingForward = true;

		if ( this._handlePageNav( event ) ) {
			return;
		}

		switch ( event.keyCode ) {
			case $.ui.keyCode.RIGHT:
			case $.ui.keyCode.DOWN:
				selectedIndex++;
				break;
			case $.ui.keyCode.UP:
			case $.ui.keyCode.LEFT:
				goingForward = false;
				selectedIndex--;
				break;
			case $.ui.keyCode.END:
				selectedIndex = this.anchors.length - 1;
				break;
			case $.ui.keyCode.HOME:
				selectedIndex = 0;
				break;
			case $.ui.keyCode.SPACE:
				// Activate only, no collapsing
				event.preventDefault();
				clearTimeout( this.activating );
				this._activate( selectedIndex );
				return;
			case $.ui.keyCode.ENTER:
				// Toggle (cancel delayed activation, allow collapsing)
				event.preventDefault();
				clearTimeout( this.activating );
				// Determine if we should collapse or activate
				this._activate( selectedIndex === this.options.active ? false : selectedIndex );
				return;
			default:
				return;
		}

		// Focus the appropriate tab, based on which key was pressed
		event.preventDefault();
		clearTimeout( this.activating );
		selectedIndex = this._focusNextTab( selectedIndex, goingForward );

		// Navigating with control/command key will prevent automatic activation
		if ( !event.ctrlKey && !event.metaKey ) {

			// Update aria-selected immediately so that AT think the tab is already selected.
			// Otherwise AT may confuse the user by stating that they need to activate the tab,
			// but the tab will already be activated by the time the announcement finishes.
			focusedTab.attr( "aria-selected", "false" );
			this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );

			this.activating = this._delay(function() {
				this.option( "active", selectedIndex );
			}, this.delay );
		}
	},

	_panelKeydown: function( event ) {
		if ( this._handlePageNav( event ) ) {
			return;
		}

		// Ctrl+up moves focus to the current tab
		if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
			event.preventDefault();
			this.active.focus();
		}
	},

	// Alt+page up/down moves focus to the previous/next tab (and activates)
	_handlePageNav: function( event ) {
		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
			this._activate( this._focusNextTab( this.options.active - 1, false ) );
			return true;
		}
		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
			this._activate( this._focusNextTab( this.options.active + 1, true ) );
			return true;
		}
	},

	_findNextTab: function( index, goingForward ) {
		var lastTabIndex = this.tabs.length - 1;

		function constrain() {
			if ( index > lastTabIndex ) {
				index = 0;
			}
			if ( index < 0 ) {
				index = lastTabIndex;
			}
			return index;
		}

		while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
			index = goingForward ? index + 1 : index - 1;
		}

		return index;
	},

	_focusNextTab: function( index, goingForward ) {
		index = this._findNextTab( index, goingForward );
		this.tabs.eq( index ).focus();
		return index;
	},

	_setOption: function( key, value ) {
		if ( key === "active" ) {
			// _activate() will handle invalid values and update this.options
			this._activate( value );
			return;
		}

		if ( key === "disabled" ) {
			// don't use the widget factory's disabled handling
			this._setupDisabled( value );
			return;
		}

		this._super( key, value);

		if ( key === "collapsible" ) {
			this.element.toggleClass( "ui-tabs-collapsible", value );
			// Setting collapsible: false while collapsed; open first panel
			if ( !value && this.options.active === false ) {
				this._activate( 0 );
			}
		}

		if ( key === "event" ) {
			this._setupEvents( value );
		}

		if ( key === "heightStyle" ) {
			this._setupHeightStyle( value );
		}
	},

	_sanitizeSelector: function( hash ) {
		return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
	},

	refresh: function() {
		var options = this.options,
			lis = this.tablist.children( ":has(a[href])" );

		// get disabled tabs from class attribute from HTML
		// this will get converted to a boolean if needed in _refresh()
		options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
			return lis.index( tab );
		});

		this._processTabs();

		// was collapsed or no tabs
		if ( options.active === false || !this.anchors.length ) {
			options.active = false;
			this.active = $();
		// was active, but active tab is gone
		} else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {
			// all remaining tabs are disabled
			if ( this.tabs.length === options.disabled.length ) {
				options.active = false;
				this.active = $();
			// activate previous tab
			} else {
				this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
			}
		// was active, active tab still exists
		} else {
			// make sure active index is correct
			options.active = this.tabs.index( this.active );
		}

		this._refresh();
	},

	_refresh: function() {
		this._setupDisabled( this.options.disabled );
		this._setupEvents( this.options.event );
		this._setupHeightStyle( this.options.heightStyle );

		this.tabs.not( this.active ).attr({
			"aria-selected": "false",
			"aria-expanded": "false",
			tabIndex: -1
		});
		this.panels.not( this._getPanelForTab( this.active ) )
			.hide()
			.attr({
				"aria-hidden": "true"
			});

		// Make sure one tab is in the tab order
		if ( !this.active.length ) {
			this.tabs.eq( 0 ).attr( "tabIndex", 0 );
		} else {
			this.active
				.addClass( "ui-tabs-active ui-state-active" )
				.attr({
					"aria-selected": "true",
					"aria-expanded": "true",
					tabIndex: 0
				});
			this._getPanelForTab( this.active )
				.show()
				.attr({
					"aria-hidden": "false"
				});
		}
	},

	_processTabs: function() {
		var that = this,
			prevTabs = this.tabs,
			prevAnchors = this.anchors,
			prevPanels = this.panels;

		this.tablist = this._getList()
			.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
			.attr( "role", "tablist" )

			// Prevent users from focusing disabled tabs via click
			.delegate( "> li", "mousedown" + this.eventNamespace, function( event ) {
				if ( $( this ).is( ".ui-state-disabled" ) ) {
					event.preventDefault();
				}
			})

			// support: IE <9
			// Preventing the default action in mousedown doesn't prevent IE
			// from focusing the element, so if the anchor gets focused, blur.
			// We don't have to worry about focusing the previously focused
			// element since clicking on a non-focusable element should focus
			// the body anyway.
			.delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
				if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
					this.blur();
				}
			});

		this.tabs = this.tablist.find( "> li:has(a[href])" )
			.addClass( "ui-state-default ui-corner-top" )
			.attr({
				role: "tab",
				tabIndex: -1
			});

		this.anchors = this.tabs.map(function() {
				return $( "a", this )[ 0 ];
			})
			.addClass( "ui-tabs-anchor" )
			.attr({
				role: "presentation",
				tabIndex: -1
			});

		this.panels = $();

		this.anchors.each(function( i, anchor ) {
			var selector, panel, panelId,
				anchorId = $( anchor ).uniqueId().attr( "id" ),
				tab = $( anchor ).closest( "li" ),
				originalAriaControls = tab.attr( "aria-controls" );

			// inline tab
			if ( that._isLocal( anchor ) ) {
				selector = anchor.hash;
				panelId = selector.substring( 1 );
				panel = that.element.find( that._sanitizeSelector( selector ) );
			// remote tab
			} else {
				// If the tab doesn't already have aria-controls,
				// generate an id by using a throw-away element
				panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id;
				selector = "#" + panelId;
				panel = that.element.find( selector );
				if ( !panel.length ) {
					panel = that._createPanel( panelId );
					panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
				}
				panel.attr( "aria-live", "polite" );
			}

			if ( panel.length) {
				that.panels = that.panels.add( panel );
			}
			if ( originalAriaControls ) {
				tab.data( "ui-tabs-aria-controls", originalAriaControls );
			}
			tab.attr({
				"aria-controls": panelId,
				"aria-labelledby": anchorId
			});
			panel.attr( "aria-labelledby", anchorId );
		});

		this.panels
			.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
			.attr( "role", "tabpanel" );

		// Avoid memory leaks (#10056)
		if ( prevTabs ) {
			this._off( prevTabs.not( this.tabs ) );
			this._off( prevAnchors.not( this.anchors ) );
			this._off( prevPanels.not( this.panels ) );
		}
	},

	// allow overriding how to find the list for rare usage scenarios (#7715)
	_getList: function() {
		return this.tablist || this.element.find( "ol,ul" ).eq( 0 );
	},

	_createPanel: function( id ) {
		return $( "<div>" )
			.attr( "id", id )
			.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
			.data( "ui-tabs-destroy", true );
	},

	_setupDisabled: function( disabled ) {
		if ( $.isArray( disabled ) ) {
			if ( !disabled.length ) {
				disabled = false;
			} else if ( disabled.length === this.anchors.length ) {
				disabled = true;
			}
		}

		// disable tabs
		for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
			if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
				$( li )
					.addClass( "ui-state-disabled" )
					.attr( "aria-disabled", "true" );
			} else {
				$( li )
					.removeClass( "ui-state-disabled" )
					.removeAttr( "aria-disabled" );
			}
		}

		this.options.disabled = disabled;
	},

	_setupEvents: function( event ) {
		var events = {};
		if ( event ) {
			$.each( event.split(" "), function( index, eventName ) {
				events[ eventName ] = "_eventHandler";
			});
		}

		this._off( this.anchors.add( this.tabs ).add( this.panels ) );
		// Always prevent the default action, even when disabled
		this._on( true, this.anchors, {
			click: function( event ) {
				event.preventDefault();
			}
		});
		this._on( this.anchors, events );
		this._on( this.tabs, { keydown: "_tabKeydown" } );
		this._on( this.panels, { keydown: "_panelKeydown" } );

		this._focusable( this.tabs );
		this._hoverable( this.tabs );
	},

	_setupHeightStyle: function( heightStyle ) {
		var maxHeight,
			parent = this.element.parent();

		if ( heightStyle === "fill" ) {
			maxHeight = parent.height();
			maxHeight -= this.element.outerHeight() - this.element.height();

			this.element.siblings( ":visible" ).each(function() {
				var elem = $( this ),
					position = elem.css( "position" );

				if ( position === "absolute" || position === "fixed" ) {
					return;
				}
				maxHeight -= elem.outerHeight( true );
			});

			this.element.children().not( this.panels ).each(function() {
				maxHeight -= $( this ).outerHeight( true );
			});

			this.panels.each(function() {
				$( this ).height( Math.max( 0, maxHeight -
					$( this ).innerHeight() + $( this ).height() ) );
			})
			.css( "overflow", "auto" );
		} else if ( heightStyle === "auto" ) {
			maxHeight = 0;
			this.panels.each(function() {
				maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
			}).height( maxHeight );
		}
	},

	_eventHandler: function( event ) {
		var options = this.options,
			active = this.active,
			anchor = $( event.currentTarget ),
			tab = anchor.closest( "li" ),
			clickedIsActive = tab[ 0 ] === active[ 0 ],
			collapsing = clickedIsActive && options.collapsible,
			toShow = collapsing ? $() : this._getPanelForTab( tab ),
			toHide = !active.length ? $() : this._getPanelForTab( active ),
			eventData = {
				oldTab: active,
				oldPanel: toHide,
				newTab: collapsing ? $() : tab,
				newPanel: toShow
			};

		event.preventDefault();

		if ( tab.hasClass( "ui-state-disabled" ) ||
				// tab is already loading
				tab.hasClass( "ui-tabs-loading" ) ||
				// can't switch durning an animation
				this.running ||
				// click on active header, but not collapsible
				( clickedIsActive && !options.collapsible ) ||
				// allow canceling activation
				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
			return;
		}

		options.active = collapsing ? false : this.tabs.index( tab );

		this.active = clickedIsActive ? $() : tab;
		if ( this.xhr ) {
			this.xhr.abort();
		}

		if ( !toHide.length && !toShow.length ) {
			$.error( "jQuery UI Tabs: Mismatching fragment identifier." );
		}

		if ( toShow.length ) {
			this.load( this.tabs.index( tab ), event );
		}
		this._toggle( event, eventData );
	},

	// handles show/hide for selecting tabs
	_toggle: function( event, eventData ) {
		var that = this,
			toShow = eventData.newPanel,
			toHide = eventData.oldPanel;

		this.running = true;

		function complete() {
			that.running = false;
			that._trigger( "activate", event, eventData );
		}

		function show() {
			eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );

			if ( toShow.length && that.options.show ) {
				that._show( toShow, that.options.show, complete );
			} else {
				toShow.show();
				complete();
			}
		}

		// start out by hiding, then showing, then completing
		if ( toHide.length && this.options.hide ) {
			this._hide( toHide, this.options.hide, function() {
				eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
				show();
			});
		} else {
			eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
			toHide.hide();
			show();
		}

		toHide.attr( "aria-hidden", "true" );
		eventData.oldTab.attr({
			"aria-selected": "false",
			"aria-expanded": "false"
		});
		// If we're switching tabs, remove the old tab from the tab order.
		// If we're opening from collapsed state, remove the previous tab from the tab order.
		// If we're collapsing, then keep the collapsing tab in the tab order.
		if ( toShow.length && toHide.length ) {
			eventData.oldTab.attr( "tabIndex", -1 );
		} else if ( toShow.length ) {
			this.tabs.filter(function() {
				return $( this ).attr( "tabIndex" ) === 0;
			})
			.attr( "tabIndex", -1 );
		}

		toShow.attr( "aria-hidden", "false" );
		eventData.newTab.attr({
			"aria-selected": "true",
			"aria-expanded": "true",
			tabIndex: 0
		});
	},

	_activate: function( index ) {
		var anchor,
			active = this._findActive( index );

		// trying to activate the already active panel
		if ( active[ 0 ] === this.active[ 0 ] ) {
			return;
		}

		// trying to collapse, simulate a click on the current active header
		if ( !active.length ) {
			active = this.active;
		}

		anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
		this._eventHandler({
			target: anchor,
			currentTarget: anchor,
			preventDefault: $.noop
		});
	},

	_findActive: function( index ) {
		return index === false ? $() : this.tabs.eq( index );
	},

	_getIndex: function( index ) {
		// meta-function to give users option to provide a href string instead of a numerical index.
		if ( typeof index === "string" ) {
			index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) );
		}

		return index;
	},

	_destroy: function() {
		if ( this.xhr ) {
			this.xhr.abort();
		}

		this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );

		this.tablist
			.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
			.removeAttr( "role" );

		this.anchors
			.removeClass( "ui-tabs-anchor" )
			.removeAttr( "role" )
			.removeAttr( "tabIndex" )
			.removeUniqueId();

		this.tablist.unbind( this.eventNamespace );

		this.tabs.add( this.panels ).each(function() {
			if ( $.data( this, "ui-tabs-destroy" ) ) {
				$( this ).remove();
			} else {
				$( this )
					.removeClass( "ui-state-default ui-state-active ui-state-disabled " +
						"ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
					.removeAttr( "tabIndex" )
					.removeAttr( "aria-live" )
					.removeAttr( "aria-busy" )
					.removeAttr( "aria-selected" )
					.removeAttr( "aria-labelledby" )
					.removeAttr( "aria-hidden" )
					.removeAttr( "aria-expanded" )
					.removeAttr( "role" );
			}
		});

		this.tabs.each(function() {
			var li = $( this ),
				prev = li.data( "ui-tabs-aria-controls" );
			if ( prev ) {
				li
					.attr( "aria-controls", prev )
					.removeData( "ui-tabs-aria-controls" );
			} else {
				li.removeAttr( "aria-controls" );
			}
		});

		this.panels.show();

		if ( this.options.heightStyle !== "content" ) {
			this.panels.css( "height", "" );
		}
	},

	enable: function( index ) {
		var disabled = this.options.disabled;
		if ( disabled === false ) {
			return;
		}

		if ( index === undefined ) {
			disabled = false;
		} else {
			index = this._getIndex( index );
			if ( $.isArray( disabled ) ) {
				disabled = $.map( disabled, function( num ) {
					return num !== index ? num : null;
				});
			} else {
				disabled = $.map( this.tabs, function( li, num ) {
					return num !== index ? num : null;
				});
			}
		}
		this._setupDisabled( disabled );
	},

	disable: function( index ) {
		var disabled = this.options.disabled;
		if ( disabled === true ) {
			return;
		}

		if ( index === undefined ) {
			disabled = true;
		} else {
			index = this._getIndex( index );
			if ( $.inArray( index, disabled ) !== -1 ) {
				return;
			}
			if ( $.isArray( disabled ) ) {
				disabled = $.merge( [ index ], disabled ).sort();
			} else {
				disabled = [ index ];
			}
		}
		this._setupDisabled( disabled );
	},

	load: function( index, event ) {
		index = this._getIndex( index );
		var that = this,
			tab = this.tabs.eq( index ),
			anchor = tab.find( ".ui-tabs-anchor" ),
			panel = this._getPanelForTab( tab ),
			eventData = {
				tab: tab,
				panel: panel
			},
			complete = function( jqXHR, status ) {
				if ( status === "abort" ) {
					that.panels.stop( false, true );
				}

				tab.removeClass( "ui-tabs-loading" );
				panel.removeAttr( "aria-busy" );

				if ( jqXHR === that.xhr ) {
					delete that.xhr;
				}
			};

		// not remote
		if ( this._isLocal( anchor[ 0 ] ) ) {
			return;
		}

		this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );

		// support: jQuery <1.8
		// jQuery <1.8 returns false if the request is canceled in beforeSend,
		// but as of 1.8, $.ajax() always returns a jqXHR object.
		if ( this.xhr && this.xhr.statusText !== "canceled" ) {
			tab.addClass( "ui-tabs-loading" );
			panel.attr( "aria-busy", "true" );

			this.xhr
				.done(function( response, status, jqXHR ) {
					// support: jQuery <1.8
					// http://bugs.jquery.com/ticket/11778
					setTimeout(function() {
						panel.html( response );
						that._trigger( "load", event, eventData );

						complete( jqXHR, status );
					}, 1 );
				})
				.fail(function( jqXHR, status ) {
					// support: jQuery <1.8
					// http://bugs.jquery.com/ticket/11778
					setTimeout(function() {
						complete( jqXHR, status );
					}, 1 );
				});
		}
	},

	_ajaxSettings: function( anchor, event, eventData ) {
		var that = this;
		return {
			url: anchor.attr( "href" ),
			beforeSend: function( jqXHR, settings ) {
				return that._trigger( "beforeLoad", event,
					$.extend( { jqXHR: jqXHR, ajaxSettings: settings }, eventData ) );
			}
		};
	},

	_getPanelForTab: function( tab ) {
		var id = $( tab ).attr( "aria-controls" );
		return this.element.find( this._sanitizeSelector( "#" + id ) );
	}
});


/*!
 * jQuery UI Tooltip 1.11.4
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * http://api.jqueryui.com/tooltip/
 */


var tooltip = $.widget( "ui.tooltip", {
	version: "1.11.4",
	options: {
		content: function() {
			// support: IE<9, Opera in jQuery <1.7
			// .text() can't accept undefined, so coerce to a string
			var title = $( this ).attr( "title" ) || "";
			// Escape title, since we're going from an attribute to raw HTML
			return $( "<a>" ).text( title ).html();
		},
		hide: true,
		// Disabled elements have inconsistent behavior across browsers (#8661)
		items: "[title]:not([disabled])",
		position: {
			my: "left top+15",
			at: "left bottom",
			collision: "flipfit flip"
		},
		show: true,
		tooltipClass: null,
		track: false,

		// callbacks
		close: null,
		open: null
	},

	_addDescribedBy: function( elem, id ) {
		var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
		describedby.push( id );
		elem
			.data( "ui-tooltip-id", id )
			.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
	},

	_removeDescribedBy: function( elem ) {
		var id = elem.data( "ui-tooltip-id" ),
			describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
			index = $.inArray( id, describedby );

		if ( index !== -1 ) {
			describedby.splice( index, 1 );
		}

		elem.removeData( "ui-tooltip-id" );
		describedby = $.trim( describedby.join( " " ) );
		if ( describedby ) {
			elem.attr( "aria-describedby", describedby );
		} else {
			elem.removeAttr( "aria-describedby" );
		}
	},

	_create: function() {
		this._on({
			mouseover: "open",
			focusin: "open"
		});

		// IDs of generated tooltips, needed for destroy
		this.tooltips = {};

		// IDs of parent tooltips where we removed the title attribute
		this.parents = {};

		if ( this.options.disabled ) {
			this._disable();
		}

		// Append the aria-live region so tooltips announce correctly
		this.liveRegion = $( "<div>" )
			.attr({
				role: "log",
				"aria-live": "assertive",
				"aria-relevant": "additions"
			})
			.addClass( "ui-helper-hidden-accessible" )
			.appendTo( this.document[ 0 ].body );
	},

	_setOption: function( key, value ) {
		var that = this;

		if ( key === "disabled" ) {
			this[ value ? "_disable" : "_enable" ]();
			this.options[ key ] = value;
			// disable element style changes
			return;
		}

		this._super( key, value );

		if ( key === "content" ) {
			$.each( this.tooltips, function( id, tooltipData ) {
				that._updateContent( tooltipData.element );
			});
		}
	},

	_disable: function() {
		var that = this;

		// close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {
			var event = $.Event( "blur" );
			event.target = event.currentTarget = tooltipData.element[ 0 ];
			that.close( event, true );
		});

		// remove title attributes to prevent native tooltips
		this.element.find( this.options.items ).addBack().each(function() {
			var element = $( this );
			if ( element.is( "[title]" ) ) {
				element
					.data( "ui-tooltip-title", element.attr( "title" ) )
					.removeAttr( "title" );
			}
		});
	},

	_enable: function() {
		// restore title attributes
		this.element.find( this.options.items ).addBack().each(function() {
			var element = $( this );
			if ( element.data( "ui-tooltip-title" ) ) {
				element.attr( "title", element.data( "ui-tooltip-title" ) );
			}
		});
	},

	open: function( event ) {
		var that = this,
			target = $( event ? event.target : this.element )
				// we need closest here due to mouseover bubbling,
				// but always pointing at the same event target
				.closest( this.options.items );

		// No element to show a tooltip for or the tooltip is already open
		if ( !target.length || target.data( "ui-tooltip-id" ) ) {
			return;
		}

		if ( target.attr( "title" ) ) {
			target.data( "ui-tooltip-title", target.attr( "title" ) );
		}

		target.data( "ui-tooltip-open", true );

		// kill parent tooltips, custom or native, for hover
		if ( event && event.type === "mouseover" ) {
			target.parents().each(function() {
				var parent = $( this ),
					blurEvent;
				if ( parent.data( "ui-tooltip-open" ) ) {
					blurEvent = $.Event( "blur" );
					blurEvent.target = blurEvent.currentTarget = this;
					that.close( blurEvent, true );
				}
				if ( parent.attr( "title" ) ) {
					parent.uniqueId();
					that.parents[ this.id ] = {
						element: this,
						title: parent.attr( "title" )
					};
					parent.attr( "title", "" );
				}
			});
		}

		this._registerCloseHandlers( event, target );
		this._updateContent( target, event );
	},

	_updateContent: function( target, event ) {
		var content,
			contentOption = this.options.content,
			that = this,
			eventType = event ? event.type : null;

		if ( typeof contentOption === "string" ) {
			return this._open( event, target, contentOption );
		}

		content = contentOption.call( target[0], function( response ) {

			// IE may instantly serve a cached response for ajax requests
			// delay this call to _open so the other call to _open runs first
			that._delay(function() {

				// Ignore async response if tooltip was closed already
				if ( !target.data( "ui-tooltip-open" ) ) {
					return;
				}

				// jQuery creates a special event for focusin when it doesn't
				// exist natively. To improve performance, the native event
				// object is reused and the type is changed. Therefore, we can't
				// rely on the type being correct after the event finished
				// bubbling, so we set it back to the previous value. (#8740)
				if ( event ) {
					event.type = eventType;
				}
				this._open( event, target, response );
			});
		});
		if ( content ) {
			this._open( event, target, content );
		}
	},

	_open: function( event, target, content ) {
		var tooltipData, tooltip, delayedShow, a11yContent,
			positionOption = $.extend( {}, this.options.position );

		if ( !content ) {
			return;
		}

		// Content can be updated multiple times. If the tooltip already
		// exists, then just update the content and bail.
		tooltipData = this._find( target );
		if ( tooltipData ) {
			tooltipData.tooltip.find( ".ui-tooltip-content" ).html( content );
			return;
		}

		// if we have a title, clear it to prevent the native tooltip
		// we have to check first to avoid defining a title if none exists
		// (we don't want to cause an element to start matching [title])
		//
		// We use removeAttr only for key events, to allow IE to export the correct
		// accessible attributes. For mouse events, set to empty string to avoid
		// native tooltip showing up (happens only when removing inside mouseover).
		if ( target.is( "[title]" ) ) {
			if ( event && event.type === "mouseover" ) {
				target.attr( "title", "" );
			} else {
				target.removeAttr( "title" );
			}
		}

		tooltipData = this._tooltip( target );
		tooltip = tooltipData.tooltip;
		this._addDescribedBy( target, tooltip.attr( "id" ) );
		tooltip.find( ".ui-tooltip-content" ).html( content );

		// Support: Voiceover on OS X, JAWS on IE <= 9
		// JAWS announces deletions even when aria-relevant="additions"
		// Voiceover will sometimes re-read the entire log region's contents from the beginning
		this.liveRegion.children().hide();
		if ( content.clone ) {
			a11yContent = content.clone();
			a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" );
		} else {
			a11yContent = content;
		}
		$( "<div>" ).html( a11yContent ).appendTo( this.liveRegion );

		function position( event ) {
			positionOption.of = event;
			if ( tooltip.is( ":hidden" ) ) {
				return;
			}
			tooltip.position( positionOption );
		}
		if ( this.options.track && event && /^mouse/.test( event.type ) ) {
			this._on( this.document, {
				mousemove: position
			});
			// trigger once to override element-relative positioning
			position( event );
		} else {
			tooltip.position( $.extend({
				of: target
			}, this.options.position ) );
		}

		tooltip.hide();

		this._show( tooltip, this.options.show );
		// Handle tracking tooltips that are shown with a delay (#8644). As soon
		// as the tooltip is visible, position the tooltip using the most recent
		// event.
		if ( this.options.show && this.options.show.delay ) {
			delayedShow = this.delayedShow = setInterval(function() {
				if ( tooltip.is( ":visible" ) ) {
					position( positionOption.of );
					clearInterval( delayedShow );
				}
			}, $.fx.interval );
		}

		this._trigger( "open", event, { tooltip: tooltip } );
	},

	_registerCloseHandlers: function( event, target ) {
		var events = {
			keyup: function( event ) {
				if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
					var fakeEvent = $.Event(event);
					fakeEvent.currentTarget = target[0];
					this.close( fakeEvent, true );
				}
			}
		};

		// Only bind remove handler for delegated targets. Non-delegated
		// tooltips will handle this in destroy.
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			events.remove = function() {
				this._removeTooltip( this._find( target ).tooltip );
			};
		}

		if ( !event || event.type === "mouseover" ) {
			events.mouseleave = "close";
		}
		if ( !event || event.type === "focusin" ) {
			events.focusout = "close";
		}
		this._on( true, target, events );
	},

	close: function( event ) {
		var tooltip,
			that = this,
			target = $( event ? event.currentTarget : this.element ),
			tooltipData = this._find( target );

		// The tooltip may already be closed
		if ( !tooltipData ) {

			// We set ui-tooltip-open immediately upon open (in open()), but only set the
			// additional data once there's actually content to show (in _open()). So even if the
			// tooltip doesn't have full data, we always remove ui-tooltip-open in case we're in
			// the period between open() and _open().
			target.removeData( "ui-tooltip-open" );
			return;
		}

		tooltip = tooltipData.tooltip;

		// disabling closes the tooltip, so we need to track when we're closing
		// to avoid an infinite loop in case the tooltip becomes disabled on close
		if ( tooltipData.closing ) {
			return;
		}

		// Clear the interval for delayed tracking tooltips
		clearInterval( this.delayedShow );

		// only set title if we had one before (see comment in _open())
		// If the title attribute has changed since open(), don't restore
		if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) {
			target.attr( "title", target.data( "ui-tooltip-title" ) );
		}

		this._removeDescribedBy( target );

		tooltipData.hiding = true;
		tooltip.stop( true );
		this._hide( tooltip, this.options.hide, function() {
			that._removeTooltip( $( this ) );
		});

		target.removeData( "ui-tooltip-open" );
		this._off( target, "mouseleave focusout keyup" );

		// Remove 'remove' binding only on delegated targets
		if ( target[ 0 ] !== this.element[ 0 ] ) {
			this._off( target, "remove" );
		}
		this._off( this.document, "mousemove" );

		if ( event && event.type === "mouseleave" ) {
			$.each( this.parents, function( id, parent ) {
				$( parent.element ).attr( "title", parent.title );
				delete that.parents[ id ];
			});
		}

		tooltipData.closing = true;
		this._trigger( "close", event, { tooltip: tooltip } );
		if ( !tooltipData.hiding ) {
			tooltipData.closing = false;
		}
	},

	_tooltip: function( element ) {
		var tooltip = $( "<div>" )
				.attr( "role", "tooltip" )
				.addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
					( this.options.tooltipClass || "" ) ),
			id = tooltip.uniqueId().attr( "id" );

		$( "<div>" )
			.addClass( "ui-tooltip-content" )
			.appendTo( tooltip );

		tooltip.appendTo( this.document[0].body );

		return this.tooltips[ id ] = {
			element: element,
			tooltip: tooltip
		};
	},

	_find: function( target ) {
		var id = target.data( "ui-tooltip-id" );
		return id ? this.tooltips[ id ] : null;
	},

	_removeTooltip: function( tooltip ) {
		tooltip.remove();
		delete this.tooltips[ tooltip.attr( "id" ) ];
	},

	_destroy: function() {
		var that = this;

		// close open tooltips
		$.each( this.tooltips, function( id, tooltipData ) {
			// Delegate to close method to handle common cleanup
			var event = $.Event( "blur" ),
				element = tooltipData.element;
			event.target = event.currentTarget = element[ 0 ];
			that.close( event, true );

			// Remove immediately; destroying an open tooltip doesn't use the
			// hide animation
			$( "#" + id ).remove();

			// Restore the title
			if ( element.data( "ui-tooltip-title" ) ) {
				// If the title attribute has changed since open(), don't restore
				if ( !element.attr( "title" ) ) {
					element.attr( "title", element.data( "ui-tooltip-title" ) );
				}
				element.removeData( "ui-tooltip-title" );
			}
		});
		this.liveRegion.remove();
	}
});



}));
/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
         
        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
var variableGlobale_listeDesIdParametresCouleur = '';
var variableGlobale_listeDesIdParametresSupprimes = '';
var variableGlobale_listeDesIdFiltreWebshopSupprimes = new Array();
var variableGlobale_listeDesIdCritereProduitWebshopSupprimes = new Array();
var variableGlobale_listeDesIdFiltreAppShopSupprimes = new Array();
var variableGlobale_listeDesIdCritereProduitAppShopSupprimes = new Array();
var variableGlobale_listeDesIdModeExpeditionWebshopSupprimes = new Array();
var listeDesValeursLibresSupprimees = new Array();

var NUMERO_SOCIETE_LGI;
// Variables globales pour controler saisies
var verifierEmail = /^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,}$/;

//etat numéro page en session
var pageSelectionnees = null;

// Reg expression
regMajuscule = /[A-Z]/;
regMinuscule = /[a-z]/;
regChiffre = /[0-9]/;

function verifierEmailAvecOuSansBalisage(email) {
    if (email.indexOf('<') != -1) {
        reg = new RegExp('^[a-zA-Z0-9-_]+<[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,}>$', 'i');
    } else {
        reg = new RegExp('^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,}$', 'i');
    }
    return reg;
}
var recherchesParIntervalles = "";
var verifierDecimal = /^[0-9]+([.,][0-9]+)?$/;
var verifierEntier = /^[0-9]+$/;
// Variables globales pour tester navigateur
var utilisateurAgent = navigator.userAgent.toLowerCase();
var est_konq = (utilisateurAgent.indexOf('konqueror') != -1);
var est_konq = (utilisateurAgent.indexOf('konqueror') != -1);
var est_safari = ((utilisateurAgent.indexOf('safari') != -1)
	&& (utilisateurAgent.indexOf('mac') != -1)) ? true : false;
var est_khtml = (est_safari || est_konq);
var est_gecko = ((!est_khtml) && (navigator.product) &&
	(navigator.product.toLowerCase() == "gecko")) ? true : false;
var est_fb = ((utilisateurAgent.indexOf('mozilla/5') != -1) && (utilisateurAgent.indexOf('spoofer') == -1) &&
	(utilisateurAgent.indexOf('compatible') == -1) && (utilisateurAgent.indexOf('opera') == -1) &&
	(utilisateurAgent.indexOf('webtv') == -1) && (utilisateurAgent.indexOf('hotjava') == -1) &&
	(est_gecko) && (navigator.vendor == "Firebird"));
var est_fireFox = ((utilisateurAgent.indexOf('mozilla/5') != -1) && (utilisateurAgent.indexOf('spoofer') == -1) &&
	(utilisateurAgent.indexOf('compatible') == -1) && (utilisateurAgent.indexOf('opera') == -1) &&
	(utilisateurAgent.indexOf('webtv') == -1) && (utilisateurAgent.indexOf('hotjava') == -1) &&
	(est_gecko) && ((navigator.vendor == "Firefox") || (utilisateurAgent.indexOf('firefox') != -1)));
var est_internetEplorer = ((utilisateurAgent.indexOf('trident') != -1) && (utilisateurAgent.indexOf('.net') != -1));
var classeExplorer = "";
var nbTdentifiantsSelectionnes;
var nbTdentifiantsGroupeSelectionnes;
//CKEDITOR.basePath = '/ressource/js/librairie/ckeditor/';

//gestion des appels serveur recherche 
var ecritureTimer = null;
var ecritureTimerHortibox = null;
var finEcritureInterval = 1000;  //time en ms,
var finEcritureIntervalHortibox = 1000;  //time en ms,
//gestion edition sur dt multiple
var colonneCachee;
var bloquerAppelAjax = false;
var activerAllerVersLeHaut = "";

function fermerPopup(id) {
    fenetreSpecifique = "";
    //pour les popups avec dxDatagrid il faut renseigner le id
    if (typeof id !== 'undefined') {
        fenetreSpecifique = '#' + id;
    }
    // Si page appelante  de la méthode est logsBase, donc récupérer l'ancienne hauteur de div conteneur
    if ($('#popUpObjet').is(':visible')) {
        $('#pageContenu').height(objetGlobal_hauteurPageContenu);
    }
    if (!$('#formulaireDemandeDeCompte #societeEtCompte').is(':visible')) { // La fenêtre de 2ième étape de demande de compte ne peut pas se fermer
        if ($(fenetreSpecifique + '.contenuPopup:visible').hasClass("listeLargeursColonnes") == false) {
            $('#layoutPopup').fadeOut(400);
            $(fenetreSpecifique + '.contenuPopup').fadeOut(400);
        } else {
            $(fenetreSpecifique + '.contenuPopup:visible').last().fadeOut(400);
            if ($(fenetreSpecifique + '.contenuPopup:visible').length < 2) {
                $('#layoutPopup').fadeOut(400);
            }
            // en cas de mode visualisation 2 fenetres erreur datatable listeDesLargeursColonnes test fait en cas de chargement listeDesLargeursColonnes
            if ($('#listeDesLargeursColonnes').length > 0) {
                $('#listeDesLargeursColonnes').remove();
            }

        }
    }
    if (fenetreSpecifique != "") {
        var gridDX = $(fenetreSpecifique).find(".dx-datagrid");
        if (gridDX.length > 0) {
            if ($(this) != null) {
                var gridPopup = $(gridDX[0]).parent().dxDataGrid("instance");
                if (gridPopup != null) {
                    gridPopup.hideColumnChooser();
                }

            }
        }
    }
}

// WAZ 20/06/2024 Complément S181573
//Cette fonction pour stoper les évènements en dehors de popup
function propagationPopup() {
    event.stopPropagation();
    $('#iframeOverlay').hide();       //WAZ : Masquer l'empêchement de clic en dehors de l'alerte 
    $("#iframeOverlayPopup").hide();  //WAZ : Masquer l'empêchement de clic en dehors de l'alerte
}

function fermerPopupEtRafraichirGrid(idGrid,id) {
    fenetreSpecifique = "";
    if (typeof id !== 'undefined') {
        fenetreSpecifique = '#' + id;
    }
    // Si page appelante  de la méthode est logsBase, donc récupérer l'ancienne hauteur de div conteneur
    if ($('#popUpObjet').is(':visible')) {
        $('#pageContenu').height(objetGlobal_hauteurPageContenu);
    }
    if (!$('#formulaireDemandeDeCompte #societeEtCompte').is(':visible')) { // La fenêtre de 2ième étape de demande de compte ne peut pas se fermer
        if ($(fenetreSpecifique + '.contenuPopup:visible').hasClass("listeLargeursColonnes") == false) {
            $('#layoutPopup').fadeOut(400);
            $(fenetreSpecifique + '.contenuPopup').fadeOut(400);
        } else {
            $(fenetreSpecifique + '.contenuPopup:visible').last().fadeOut(400);
            if ($(fenetreSpecifique + '.contenuPopup:visible').length < 2) {
                $('#layoutPopup').fadeOut(400);
            }
            // en cas de mode visualisation 2 fenetres erreur datatable listeDesLargeursColonnes test fait en cas de chargement listeDesLargeursColonnes
            if ($('#listeDesLargeursColonnes').length > 0) {
                $('#listeDesLargeursColonnes').remove();
            }

        }
    }
    if (idGrid == "tableauListeDesProduitsDX") {
        $('body').css("overflow-y", "scroll");

        modifierModeDAffichageWebShop('Liste', true);
    } else {
        $('body').css("overflow-y", "scroll");
        retourCatalogue(); visualiserPanier('FOURNISSEUR');
    }
   


}


function afficherPopup(idElementHTML, modal, avecAppelAjax, largeursColonnes, idTableauParent, idModule, parametres, sousDossier) {
    afficherChargement();
    $('body').css("overflow-y", "hidden");
    if (avecAppelAjax !== undefined && avecAppelAjax != '') {
        $.ajax({
            url: "/layout/listeDesLargeursColonnes",
            data: {
                'largeursColonnes': largeursColonnes.join("|"),
                'idTableauParent': idTableauParent
            },
            success: function (data) {
               
                $('#' + idElementHTML).find('#divDetails').html(data);
            }
        });
    }
    afficherLayoutPopup();
    if (avecAppelAjax !== undefined && avecAppelAjax == '') {
        $('#' + idElementHTML).data("dtParent", idTableauParent);
        if (idModule !== undefined && idModule != '') {
            $('#' + idElementHTML).data("dtModule", idModule);
            $('#' + idElementHTML).data("dtParametres", parametres);
            $('#' + idElementHTML).data("dtSousDossier", sousDossier + "/");

        }
    }
    $('#' + idElementHTML).show(400);
    if (modal) {
        $('#layoutPopup').attr('onclick', '');
    } else {
        $('#layoutPopup').attr('onclick', 'fermerPopup();');
    }
    masquerChargement();
}
function exporterLesDonneesDataTable() {
    var idTableauExport = $('#popupExportDT').data('dtParent');
    formatExport = $('input[name=Export-radio-value]:checked').val();
    langueExport = $('input[name=Langue-radio-value]:checked').val();
    if ($('#' + idTableauExport).DataTable().settings()[0].ajax == null) {
        var idModule = $('#popupExportDT').data('dtModule');
        var parametreExport = $('#popupExportDT').data('dtParametres');
        var sousDossier = $('#popupExportDT').data('dtSousDossier');
        if (sousDossier != "/") {
            sousDossier = sousDossier + idModule;
        } else {
            sousDossier = idModule;
        }
        settingsDuTableau = $('#' + idTableauExport).DataTable().settings()[0];
        // Recherche globale dans le tableau
        rechercheTexte = settingsDuTableau.oPreviousSearch.sSearch;
        // Filtre sur chaque colonne
        filtreSurColonne = "";
        colonnesARechercher = settingsDuTableau.aoPreSearchCols;
        for (i = 0; i < colonnesARechercher.length; i++) { // Filtre par colonne
            filtreSurColonne += '&&filtre_' + i + '=' + encodeURIComponent(colonnesARechercher[i].sSearch);
        }
        // Tri
        colonneATrier = -1;
        indiceOriginalDeColonne = -1;
        sensDeTri = '';
        if (settingsDuTableau.aaSorting.toString() != '') {
            colonneATrier = settingsDuTableau.aaSorting.toString().split(',')[0].trim();
            indiceOriginalDeColonne = settingsDuTableau.aoColumns[colonneATrier]._ColReorder_iOrigCol;
            sensDeTri = settingsDuTableau.aaSorting.toString().split(',')[1].trim();
        }

        iframe = document.createElement('iframe');
        iframe.style.height = '0px';
        iframe.style.width = '0px';
        if (formatExport == "csv") {
            iframe.src = '/' + idModule.charAt(0).toLowerCase() + idModule.slice(1) + '/exporterListe' + idModule + 'EnCSV?champARechercher=' + encodeURIComponent(rechercheTexte) +
                        filtreSurColonne +
                        '&&colonneATrier=' + indiceOriginalDeColonne +
                        '&&sensDeTri=' + sensDeTri + '&&numeroLangueExport=' + langueExport + parametreExport;

            document.body.appendChild(iframe);
        } else if (formatExport == "xls" || formatExport == "pdf") {
            iframe.src = '/layout/exporterUneListeEnPDFOuXLS?champARechercher=' + encodeURIComponent(rechercheTexte) +
                            filtreSurColonne +
                            '&&colonneATrier=' + indiceOriginalDeColonne +
                            '&&sensDeTri=' + sensDeTri +
                            '&&template=~/views/' + sousDossier.toLowerCase() + '/listeAExporter.cshtml' +
                            '&&extensionFichier=' + formatExport.toUpperCase() + '&&numeroLangueExport=' + langueExport + parametreExport;

            document.body.appendChild(iframe);
        }

    } else {
        $('#' + idTableauExport + '_wrapper').find('.DTTT_button_' + formatExport).trigger('click');
    }

    fermerPopup();
}

function afficherLayoutPopup() {
    $('#layoutPopup').fadeTo(200, 0.5, function () { });
}


function initialiserColorPicker() {
    $('.colorPicker').spectrum({
        preferredFormat: 'hex6',
        cancelText: ANNULER,
        chooseText: VALIDER,
        clickoutFiresChange: true,
        showInput: true, /*,
        showButtons: false, */
        change: function (color) {
            if (typeof (variableGlobale_listeDesIdParametresCouleur) != 'undefined'
                && variableGlobale_listeDesIdParametresCouleur.indexOf(this.id.split('-')[2] + SEPARATEUR_SAISI) != 0 // Pas le premier element dans la liste
                && variableGlobale_listeDesIdParametresCouleur.indexOf(SEPARATEUR_SAISI + this.id.split('-')[2] + SEPARATEUR_SAISI) == -1 // Pas au milieu de la liste
            ) {
                $('#' + this.id).val(color.toHexString());
                //alert($('#' + this.id).val());
                variableGlobale_listeDesIdParametresCouleur += this.id.split('-')[2] + SEPARATEUR_SAISI;
            }
        }
    });
    if (typeof (variableGlobale_listeDesIdParametresCouleur) == 'undefined') {
        $('.colorPicker').val('#000000');
    }
}
function validerDateLivraison(affichageControleDate) {
    if (typeof (affichageControleDate) === 'undefined') {
        affichageControleDate = true;
    }
    var resultat = true;    
    if (typeof saisieEnModeSemaine == 'undefined' || saisieEnModeSemaine != "True") {
        var date = $('#dateLivraison').datepicker("getDate");
        var dateJourMinimale = new Date();
        dateJourMinimale.setDate(dateJourMinimale.getDate() - 1 + offsetDateLivraison);
        dateJourMinimale.setHours(23);
        dateJourMinimale.setMinutes(59);
        dateJourMinimale.setSeconds(59);
        if ($('#dateLivraison').val() != '') {

            if (date < dateJourMinimale) {
                dateJourMinimale.setDate(dateJourMinimale.getDate() + 1);
                if (affichageControleDate) {
                    alerte(MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON_SUPEREUR_OU_EGALE_AU + " " + $.datepicker.formatDate('dd/mm/yy', dateJourMinimale), 'erreur');
                }

                resultat = false;
            }
        } else {
            dateJourMinimale.setDate(dateJourMinimale.getDate() + 1);
            if (affichageControleDate) {
                alerte(MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON_SUPEREUR_OU_EGALE_AU + " " + $.datepicker.formatDate('dd/mm/yy', dateJourMinimale), 'erreur');
            }

            resultat = false;
        }
    } else {
        if ($('#semaineDateLivraison').val() == null && $('#semaineDateLivraison').val() == "") {
            alerte(MERCI_DE_SAISIR_UNE_SEMAINE_DE_LIVRAISON);
            resultat = false;
        }
    }
    return resultat;
}
// Initialiser les calendriers du plugin Datepicker
function initialiserCalendrier(webShop) {


    $('.datepicker').each(function () {
        // traitement des jours de livraison bloqués
        if (typeof webShop !== 'undefined' && webShop.toLowerCase() == 'webshop') {
            var jourBloqueArray = jourBloques.split(',');
            for (var i = 0; i < jourBloqueArray.length; i++) {
                jourBloqueArray[i] = parseInt(jourBloqueArray[i], 10);
            }
            if (preinitialiserDateLivraison == "True") {
                datePrenisialiseFormatte = new Date(dateDeLivraisonPreinitialisee.split(" ")[0].split("/")[2], dateDeLivraisonPreinitialisee.split(" ")[0].split("/")[1] - 1, dateDeLivraisonPreinitialisee.split(" ")[0].split("/")[0]);
                datePrenisialise = calculerDateValidePourLivraison(datePrenisialiseFormatte);
                moisDatePrenisialise = (datePrenisialise.getMonth() + 1).toString();
                jourDatePrenisialise = datePrenisialise.getDate().toString();
                if (moisDatePrenisialise.length < 2) moisDatePrenisialise = "0" + moisDatePrenisialise;
                if (jourDatePrenisialise.length < 2) jourDatePrenisialise = "0" + jourDatePrenisialise;
                dateDeLivraisonPreinitialisee = jourDatePrenisialise + '/' + moisDatePrenisialise + '/' + datePrenisialise.getFullYear();
            }
        }

        $(this).datepicker({
            showOn: 'button',
            buttonImage: '/ressource/image/layout/layout/ic_calendrier_gris.png',
            buttonImageOnly: true,
            showButtonPanel: true,
            onSelect: function (dateText, inst) {
                if ((typeof webShop !== 'undefined' && webShop == 'webshop') || $("#pageMobile").length > 0) {
                    var dateValide = true;
                    var dateMinimum = new Date();
                    dateMinimum.setDate(dateMinimum.getDate() - 1 + offsetDateLivraison);
                    var dateDeJour = new Date();
                    dateDeJour.setDate(dateDeJour.getDate() + offsetDateLivraison);
                    if ($('#dateLivraison').val() != '' && $('#dateLivraison').datepicker("getDate") < dateMinimum) {
                        dateValide = false;
                        if (offsetDateLivraison == 0) {
                            messageErreur = MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON_SUPEREUR_A_DATE_D_AUJOURDHUI;
                        } else {
                            // dateMinimum.setDate(dateMinimum.getDate() + 1);
                            dateDeJour = calculerDateValidePourLivraison(dateDeJour);
                            messageErreur = MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON_SUPEREUR_OU_EGALE_AU + " " + $.datepicker.formatDate('dd/mm/yy', dateDeJour);

                        }
                        //$('#dateLivraison').val(dateLivraisonEncours);
                        $('#dateLivraison').datepicker("setDate", dateLivraisonEncours);
                    }
                    if (dateValide) {

                        if (typeof webShop !== 'undefined' && webShop.toLowerCase() == 'webshop') {
                            if (cataloguesConditionneeParDateLivraison == "cataloguesConditionneeParDateLivraison" || $('#dateLivraison').data("prev") == "") {
                                rechargerCataloguesWebshop();
                            }
                            $('#dateLivraison').data("prev", $('#dateLivraison').val());
                            //cas pour Desktop seulement (à modifier après)
                            //if ($("#pageMobile").length <= 0) {

                                viderCalculsEnSessionEtMettreAJourDateDeLivraison(dateText, 'calendrier');
                            //}
                            if ($('#ui-datepicker-div').hasClass('dateModale')) {
                                desactiverModeModal();
                            }
                        }
                    } else {
                        alerte(messageErreur, 'erreur');
                    }

                    if ($("#pageMobile").length > 0) {
                        $('#layoutChargementDate').hide();

                    }
                } 
//                else if ($(this).hasClass('datepickerPeremptionHortibox')) {
//                    enregistrerDatePeremptionNew(this, $(this).hasClass('repertoire') ? 'dossier' : 'fichier');
//                }
            },
            beforeShowDay: function (day) {
                if (typeof webShop !== 'undefined' && webShop.toLowerCase() == 'webshop') {
                    moisCalendrier = (day.getMonth() + 1).toString();
                    jourCalendrier = day.getDate().toString();
                    if (moisCalendrier.length < 2) moisCalendrier = "0" + moisCalendrier;
                    if (jourCalendrier.length < 2) jourCalendrier = "0" + jourCalendrier;
                    jourf = jourCalendrier + "-" + moisCalendrier;
                    jourb = day.getDay();
                    // traiement des jours fériés
                    if ($.inArray(jourf, joursFeries.split(',')) >= 0) {
                        if (autoriserJoursFeries == "True") {
                            return [true, "ferrieAutoriseClass", JOUR_FERIE];
                        } else {
                            return [false, "ferrieClass", JOUR_FERIE];
                        }
                    }
                    // traiement des jours bloqué pour la livraison
                    else if ($.inArray(jourb, jourBloqueArray) >= 0) {
                        return [false, "bloqueClass"];
                    } else {
                        return [true, ""];
                    }
                } else {
                    return [true, ""]
                }

            }

        });
        $.datepicker._gotoToday = function (id) {
            dateDeJour = new Date();
            if (typeof webShop !== 'undefined' && webShop.toLowerCase() == 'webshop') {
                dateDeJour.setDate(dateDeJour.getDate() + offsetDateLivraison);
                dateDeJour = calculerDateValidePourLivraison(dateDeJour);
                $(id).datepicker('setDate', dateDeJour).datepicker('hide').blur();
                if (cataloguesConditionneeParDateLivraison == "cataloguesConditionneeParDateLivraison" || $('#dateLivraison').data("prev") == "") {
                    rechargerCataloguesWebshop();
                }
                $('#dateLivraison').data("prev", $('#dateLivraison').val());
                if ($("#pageMobile").length > 0) {
                    $('#layoutChargementDate').hide();
                }
                //cas pour Desktop seulement (à modifier après)
                //if ($("#pageMobile").length <= 0) {
                    viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'calendrier');
                //}
                if ($('#ui-datepicker-div').hasClass('dateModale')) {
                    desactiverModeModal();
                }
            } else if ($(this).hasClass('datepickerPeremptionHortibox')) {
                $(id).datepicker('setDate', dateDeJour).datepicker('hide').blur();
                enregistrerDatePeremptionNew(this, $(this).hasClass('repertoire') ? 'dossier' : 'fichier');
            } else {
                $(id).datepicker('setDate', dateDeJour).datepicker('hide').blur();
            }

        };
    });
    var changerMois = false;
    if (typeof webShop !== 'undefined' && webShop.toLowerCase() == 'webshop' && typeof templatePersonnalise !== 'undefined' && templatePersonnalise != "") {
        changerMois = true;
    }
    // Options regionales de datePicker: Format de la date & noms de mois
    if (langueUtilisateur == ID_SITE_EN_FRANCAIS || langueUtilisateur == null || langueUtilisateur == "") {
        $.datepicker.regional['fr'] = {
            prevText: '&#x3c;Préc',
            nextText: 'Suiv&#x3e;',
            currentText: 'Aujourd\'hui',
            closeText: 'fermer',
            monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
            monthNamesShort: ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aoû', 'Sep', 'Oct', 'Nov', 'Déc'],
            dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
            dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
            dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
            dateFormat: 'dd/mm/yy',
            weekText: 'Sm',
            weekHeader: 'Sm',
            yearRange: $(".datepickerPeremptionHortibox").length > 0 ? "-20:+20" : "-2:+1",
            changeYear: true,
            changeMonth: changerMois,
            hideIfNoPrevNext: changerMois,
            showWeek: true,
            firstDay: 1
        };
        $.datepicker.setDefaults($.datepicker.regional['fr']);
    } else {
        $.datepicker.setDefaults($.datepicker.regional['en']);
    }
} 

function calculerDateValidePourLivraison(dateDeJour) {
    var jourBloqueArray = jourBloques.split(',');
    for (var i = 0; i < jourBloqueArray.length; i++) {
        jourBloqueArray[i] = parseInt(jourBloqueArray[i], 10);
    }
    for (var i = 0; i <= 60; i++) {
        dateDeJourCalculer = new Date(dateDeJour);
        dateDeJourCalculer = new Date(dateDeJourCalculer.setDate(dateDeJourCalculer.getDate() + i));
        moisDateCalculer = (dateDeJourCalculer.getMonth() + 1).toString();
        jourDateCalculer = dateDeJourCalculer.getDate().toString();
        if (moisDateCalculer.length < 2) moisDateCalculer = "0" + moisDateCalculer;
        if (jourDateCalculer.length < 2) jourDateCalculer = "0" + jourDateCalculer;
        dateCalculerFerie = jourDateCalculer + "-" + moisDateCalculer;
        dateCalculerBloque = dateDeJourCalculer.getDay();

        if ($.inArray(dateCalculerFerie, joursFeries.split(',')) < 0 && $.inArray(dateCalculerBloque, jourBloqueArray) < 0) {
            break;
        }
    }
    return dateDeJourCalculer;
}

function priseEnChargeExport(idTableau, module, parametres, sousDossier) {

    if ($('#' + idTableau).DataTable().settings()[0].ajax == null) {
        sauvegarderEtat(idTableau);
    }
    afficherPopup('popupExportDT', false, '', '', idTableau, module, parametres, sousDossier);
}
function calculerHauteurTableau() {
    if ($('#conteneurPage').length > 0) {
        positionHaut_conteneurPage = $('#conteneurPage').offset().top;
        positionBas_tfoot = $('.contenuPage table tfoot').offset().top + $('.contenuPage table:not(.dx-datagrid-table) tfoot').height(); //.offset().bottom ne marche pas
        distanceEntreTFootEtConteneurPage = positionBas_tfoot - positionHaut_conteneurPage;

        if (screen.height > 950 && screen.height < 1060) {
            distanceEntreTFootEtConteneurPage = distanceEntreTFootEtConteneurPage + 20;
        }

        $('.contenuPage table:not(.dx-datagrid-table) tbody').height(($('#conteneurPage').height() - distanceEntreTFootEtConteneurPage - 25) <= 0 ? 300 : ($('#conteneurPage').height() - distanceEntreTFootEtConteneurPage - 25));
    }
}

function afficherOuMasquerParametrageTableau(idTableau, iconeParametre) {
    if ($(iconeParametre).attr('title') == AFFICHER_LE_PARAMETRAGE_DU_TABLEAU) {
        if ($('#divDesFiltresParIntervalles').length > 0) {
            $('#divDesFiltresParIntervalles').show();
        }
        if ($('#' + idTableau).find('.tailleMax').length > 0) {
            tbody = $('#' + idTableau).find('.tailleMax');
            tbody.removeClass('tailleMax');
            tbody.addClass('tailleMaxOuvert');
        } else {
            if ($('#' + idTableau).find('.tailleMaxConseilAssocie').length > 0) {
                tbody = $('#' + idTableau).find('.tailleMaxConseilAssocie');
                tbody.removeClass('tailleMaxConseilAssocie');
            }
        }
        $('#' + idTableau + '_wrapper .dataTables_length, #' + idTableau + '_wrapper .column-filter-widgets,  #' + idTableau + '_wrapper .ColVis').show(500);
        $('#' + idTableau + '_wrapper').animate({ top: 0 }, 500, function () { });
        if (DROIT_EXPORT_TABLEAUX == DROIT_EXPORT_TABLEAUX_AUTORISE) {
            $('#' + idTableau + '_wrapper .DTTT_container').css('visibility', 'visible');
        }
        $(iconeParametre).attr('title', MASQUER_LE_PARAMETRAGE_DU_TABLEAU).attr('src', '/ressource/image/commun/parametrageActive.png');
    } else {
        if ($('#divDesFiltresParIntervalles').length > 0) {
            $('#divDesFiltresParIntervalles').hide();
        }
        $('#' + idTableau + '_wrapper .dataTables_length, #' + idTableau + '_wrapper .column-filter-widgets,  #' + idTableau + '_wrapper .ColVis').hide(500);
        if (idTableau.indexOf("moduleConseilAssocieDescriptif_tableauDesDescriptifs") >= 0 || idTableau.indexOf("moduleConseilAssocieDescriptif_tableauListeDesConseils") >= 0) {

            $('#' + idTableau + ' tbody').addClass('tailleMaxConseilAssocie');
        } else {
            $('#' + idTableau + ' tbody').addClass('tailleMax');
            $('#' + idTableau + ' tbody').removeClass('tailleMaxOuvert');
        }
        $('#' + idTableau + '_wrapper').animate({ top: -80 }, 500, function () { });

        if (DROIT_EXPORT_TABLEAUX == DROIT_EXPORT_TABLEAUX_AUTORISE) {
            $('#' + idTableau + '_wrapper .DTTT_container').css('visibility', 'hidden');
        }
        $(iconeParametre).attr('title', AFFICHER_LE_PARAMETRAGE_DU_TABLEAU).attr('src', ($(iconeParametre).hasClass("avecAlert") ? '/ressource/image/commun/parametrageAlerte.png' : '/ressource/image/commun/parametrage.png'));
    }

    if (!$('#' + idTableau).hasClass('nonScrollable')) {
        setTimeout(function () { calculerHauteurTableau(); }, 550);
    }
    //reinitialiserComboBoxDeFiltre(idTableau);
}
// pour bien gérer les filtres quand permutations de colonnes
// Fonction non optimale, perte de performance énorme, bien visible sur administrerUnCompte
function reinitialiserComboBoxDeFiltre(idTableau) {
    oTable = $('#' + idTableau).dataTable();
    $('#' + idTableau + '_wrapper .column-filter-widget').each(function (i) {
        $('select', this).each(function (indiceCombobox) {
            oTable.fnFilter($(this).val(), indiceCombobox);
        });
    });
    $('#' + idTableau + '_wrapper .column-filter-widget select').each(function (indcieColonne) {
        if (oTable.fnSettings().aoColumns[indcieColonne].bVisible
            && oTable.fnSettings().aoColumns[indcieColonne].sName != 'colonneDateAvecHeure'
            && oTable.fnSettings().aoColumns[indcieColonne].sName != 'colonneConsultation'
            && oTable.fnSettings().aoColumns[indcieColonne].sName != 'colonneSuppression'
            && oTable.fnSettings().aoColumns[indcieColonne].sName != 'colonneDateSansHeure'
        ) {
            $(this).find('option:selected').html($('#' + idTableau + ' thead th:eq(' + indcieColonne + ')').text());
        }
    });
}

function materialiserChampsDeRecherche(idTableau, webShop) {
    // Permet de placer "Rechercher..." 
    // Pour que l'input bénéficie de ceci il faut simplement lui attribuer la classe CSS champDeRecherche et appeler la fonction
    classeExplorer = "";

    if (idTableau.indexOf("moduleConseilAssocieDescriptif_tableauDesDescriptifs") < 0 && idTableau.indexOf("moduleConseilAssocieDescriptif_tableauListeDesConseils") < 0 && idTableau.indexOf("tableauChoixAdressLivraison") < 0) {
        if (typeof webShop === 'undefined') {
            $('#' + idTableau).on("remove", function () {
                sauvegarderEtat(idTableau);
            });
        }
        $('#' + idTableau + ' tbody').addClass('tailleMax');
    } else {
        $('#' + idTableau + ' tbody').addClass('tailleMaxConseilAssocie');

    }
    $('#' + idTableau + '_wrapper').find('.dataTables_filter input').attr('id', 'recherche_' + idTableau);
    //.replace("RechercheLGI", "").replace("ModifierGroupe", "").replace("preselectionvlv", "").replace("preselectionmesDescriptifs", "")
    //pagination
    //idTableauPagination = idTableau.replace("RechercheLGI", "").replace("ModifierGroupe", "").replace("preselectionvlv", "").replace("preselectionmesDescriptifs", "");


    //paginate_button
    tableauindice = retournerIndiceTableau(idTableau);
    if (tableauindice < 0) {
        pageSelectionnees.push(idTableau + "_0");
    }

    idInputEnCours = 'recherche_' + idTableau;
    if (est_fireFox) {
        $('#' + idTableau + '_filter').addClass('positionFireFoxRech');
        $('#' + idInputEnCours).addClass('positionFireFoxInput');

    } else {
        if (est_internetEplorer) {
            $('#' + idTableau + '_filter').addClass('positionExplorerRech');
            $('#' + idInputEnCours).addClass('positionFireFoxInput');
            classeExplorer = " ViderSaisieExplorer";
        }
    }
    $('#' + idTableau + '_wrapper').find('.champDeRecherche, .dataTables_filter input').removeAttr("type");
    $('#' + idTableau + '_wrapper').find('.champDeRecherche, .dataTables_filter input').each(function () {
        if ($(this).val() == '') {
            $(this).val(RECHERCHER + ' ...');
            $(this).addClass('styleValeurParDefaut');
        } else {
            if (typeof webShop !== 'undefined' && webShop == true && (idTableau == "tableauListeDesProduits" || idTableau == "tableauListePanier")) {
            } else {
                $(this).after('<img class="viderSaisie ' + classeExplorer + '" src="/ressource/image/commun/ic_supprimer_noir.png" onclick="$(this).prev().val(\'\'); $(this).remove(); viderRecherche(\'' + idTableau + '\');" alt="" />');
            }

        }
        $(this).focus(function () {
            if ($(this).val().trim() == RECHERCHER + ' ...') {
                $(this).val('');
                $(this).removeClass('styleValeurParDefaut');
            }
        });
        if (typeof webShop === 'undefined' || (idTableau != "tableauListeDesProduits" && idTableau != "tableauListePanier")) {
            $(this).keyup(function () {
                if ($(this).val() != '' && !$(this).next().is('img')) {
                    $(this).after('<img class="viderSaisie ' + classeExplorer + '" src="/ressource/image/commun/ic_supprimer_noir.png" onclick="$(this).prev().val(\'\'); $(this).remove(); viderRecherche(\'' + idTableau + '\');" alt="" />');
                } else if ($(this).val() == '' && $(this).next().is('img')) {
                    $(this).next().remove();
                }
                // sauvegarderRechercheTableau(idInputEnCours);

            });
        }

        $(this).blur(function () {
            if ($(this).val() == '') {
                $(this).val(RECHERCHER + ' ...');
                $(this).addClass('styleValeurParDefaut');
            }
        });
    });

    $('#' + idTableau + ' tfoot th').each(function () {
        if ($(this).hasClass('recherchable')) {
            $(this).html('<label class="colonneRechercheLabel" ><input type="text" class="rechercheParColonne" onkeyup="filtrerkeyup(this,\'' + idTableau + '\')" onchange="filtrerchange(this,\'' + idTableau + '\')" /> </label>');
        } else {
            $(this).html('<label class="colonneRechercheLabelVide" ><input type="text"  class="rechercheParColonneVide"  readonly /> </label>');
        }

    });
    if ($('#' + idTableau).find(".iconeParametrageLargeursColonnes").length > 0) {
        $('#' + idTableau).find(".iconeParametrageLargeursColonnes").appendTo($('#' + idTableau + '_wrapper').find(".ColVis"));
    }
    if ($('#' + idTableau).find(".iconeExportParLangues").length > 0) {
        $('#' + idTableau).find(".iconeExportParLangues").appendTo($('#' + idTableau + '_wrapper').find(".ColVis"));
        if ($('#' + idTableau + '_wrapper').find(".DTTT_container").length > 0) {
            $('#' + idTableau + '_wrapper').find(".DTTT_container").hide();
        }
    }


}

function filtrerkeyup(inputColonneRecherche, idTableau) {
    var otable = $('#' + idTableau).DataTable();

    if (ecritureTimer != null) {
        clearTimeout(ecritureTimer);
    }
    ecritureTimer = setTimeout(function () {
        finEcriture(inputColonneRecherche, otable);
    }, finEcritureInterval);

    if ($(inputColonneRecherche).val() != '' && !$(inputColonneRecherche).next().is('img')) {
        $(inputColonneRecherche).after('<img class="viderSaisieColonne" src="/ressource/image/commun/' + BOUTON_SUPPRIMER_FILTRE + '" onclick="$(this).prev().val(\'\'); $(this).prev().change(); " alt="" />');
    } else if ($(inputColonneRecherche).val() == '' && $(inputColonneRecherche).next().is('img')) {
        $(inputColonneRecherche).next().remove();
    }

}



function filtrerchange(inputColonneRecherche, idTableau) {
    var otable = $('#' + idTableau).DataTable();
    if ($(inputColonneRecherche).val() != '' && !$(inputColonneRecherche).next().is('img')) {
        $(inputColonneRecherche).after('<img class="viderSaisieColonne" src="/ressource/image/commun/' + BOUTON_SUPPRIMER_FILTRE + '" onclick="$(this).prev().val(\'\'); $(this).prev().change(); " alt="" />');
    } else if ($(inputColonneRecherche).val() == '' && $(inputColonneRecherche).next().is('img')) {
        $(inputColonneRecherche).next().remove();
        finEcriture(inputColonneRecherche, otable);
    }
}

function finEcriture(objColonne, otable) {
    if (etatTest) {

        var presearch = otable.settings()[0].aoPreSearchCols[$(objColonne).parent().parent().data("origCol")].sSearch;
        if (presearch.indexOf('[') >= 0 && presearch.indexOf(']') >= 0) {
            presearch = presearch.replace(presearch.substring(presearch.indexOf('['), presearch.indexOf(']') + 1), "");
        }

        var search = (objColonne.value != "" ? presearch + "[" + enleverAccents(objColonne.value) + "]" : presearch + "");

        otable
                .column($(objColonne).parent().parent().data("origCol"))
                .search(search)
                .draw();
    }
}

function viderRecherche(idTableau) {
    //sauvegarderRechercheTableau('recherche_' + idTableau);
    datatable = $('#' + idTableau).DataTable();
    datatable.settings()[0].oPreviousSearch.sSearch = '';
    if (etatTest) {
        datatable.draw();
    }

}



//function filtrerkeyupHortibox(inputRecherche,chemin) {


//    if (ecritureTimerHortibox != null) {
//        clearTimeout(ecritureTimerHortibox);
//    }
//    ecritureTimerHortibox = setTimeout(function () {
//        
//        finEcritureHortibox(inputRecherche, chemin);
//    }, finEcritureIntervalHortibox);

//    if ($(inputRecherche).val() != '' && !$(inputRecherche).next().is('img')) {
//        $(inputRecherche).after('<img class="viderSaisieHortibox" src="/ressource/image/webshop/annuler.png" onclick="$(this).prev().prev().val(\'\'); naviguerVers(\'' + repertoireRecementExploreeNew + '\',\'' + "liste" + '\')" alt="" />');
//    } else if ($(inputRecherche).val() == '' && $(inputRecherche).next().is('img')) {
//        $(inputRecherche).next().remove();
//    }

//}

function ConvertirEnJson(textATransformer) {
    var elementsHtmlText = $('<textarea id="prenomEtNomPasDeContrat1" />').html(textATransformer);
    var elementsHtml = $('<textarea id="prenomEtNomPasDeContrat" />').html(textATransformer).text();
    var span = document.createElement('span');
    span.innerHTML = elementsHtml;
    var elementToJson = "";

    if (span.hasChildNodes) {
        for (i = 0; i < span.childNodes.length; i++) {

            elementToJson = elementToJson + span.childNodes[i].textContent;
        }
    }
    return elementToJson != "" ? JSON.parse(elementToJson) : [];
}

function filtrerchangeHortibox(inputBouton, chemin) {
    if ($(".inputRechercheDansLEnteteNavigateurFichier").val() != '' && !$(".inputRechercheDansLEnteteNavigateurFichier").next().is('img')) {
        $(".inputRechercheDansLEnteteNavigateurFichier").after('<img class="viderSaisieHortibox" src="/ressource/image/webshop/annuler.png" onclick="$(this).prev().prev().val(\'\');  naviguerVers(\'' + repertoireRecementExploreeNew + '\',\'' + "liste" + '\') " alt="" />');
    } else if ($(".inputRechercheDansLEnteteNavigateurFichier").val() == '' && $(".inputRechercheDansLEnteteNavigateurFichier").next().is('img')) {
        $(".inputRechercheDansLEnteteNavigateurFichier").next().remove();
    }
    finEcritureHortibox($(".inputRechercheDansLEnteteNavigateurFichier"), repertoireRecementCliquee);
}

function finEcritureHortibox(inputRecherche, chemin) {
    //rechercherDossier();
    naviguerVers(repertoireRecementCliquee, formatAffichage, '', '', $(inputRecherche).val());
}

function viderRechercheHortibox() {
    //reinitialiserRechercheNew(chemin);

}



// Compteur caracteres
function onClickInputTextEtTextarea(id) {
    nombreCaracteresMaximum = (($('#' + id).attr('maxLength') !== undefined) ? ($('#' + id).attr('maxLength')) : '');
    nombreCaracteresSaisis = (($('#' + id).hasClass('styleValeurParDefaut')) ? 0 : $('#' + id).val().length);

    if (COMPTEUR_CARACTERES == COMPTEUR_CARACTERES_ACTIVE && $('#compteur_' + id).length == 0) {

        if ($($('#' + id).parent())[0].nodeName.toLowerCase() == 'td') { // Input dans une cellule TD d'un tableau html, lors d'une modification directe sur le tableau
            $('#' + id).parent().append('<div style="position: relative;"><div id="compteur_' + id + '" class="compteurCaracteres">' + nombreCaracteresSaisis + ' / ' + nombreCaracteresMaximum + ' ' + CARACTERES + '</div></div>');
            $('#compteur_' + id).css('left', 0);
            $('#compteur_' + id).css('bottom', -12);
        } else { // Div
                        //  WAZ 20/06/2024 complément DS 181573 
                        // Sélectionner la div à observer pour appliquer le class compteurCaracteres_filtre seulement dans le div de filtre avancé                         
                        var targetNodeconteneurFiltre = document.getElementById('conteneurFiltre');

                        // Vérifier si l'élément existe avant de commencer l'observation
                        if (targetNodeconteneurFiltre) {
                            var config = { attributes: true, childList: true, subtree: true };

                            var callback = function (mutationsList) {
                                for (var mutation of mutationsList) {
                                    if (mutation.type === 'attributes' || mutation.type === 'childList') {
                                        if ($(targetNodeconteneurFiltre).is(':visible')) {
                                            $('#compteur_' + id).removeClass('compteurCaracteres').addClass('compteurCaracteres_filtre');
                                        } 
                                    }
                                }
                            };

                            var observer = new MutationObserver(callback);
                            observer.observe(targetNodeconteneurFiltre, config);
                        }
                        // WAZ : 18/10/2024 complément DS 185544
                        // Sélectionner la div à observer : beePluginpour appliquer le class compteurCaracteres_modeleEmail seulement dans le div de beePlugin
                         var targetNodeconteneurmodeleEmail = document.getElementById('beePlugin');

                        // Vérifier si l'élément existe avant de commencer l'observation
                        if (targetNodeconteneurmodeleEmail) {
                            var config = { attributes: true, childList: true, subtree: true };

                            var callback = function (mutationsList) {
                                for (var mutation of mutationsList) {
                                    if (mutation.type === 'attributes' || mutation.type === 'childList') {
                                        if ($(targetNodeconteneurmodeleEmail).is(':visible')) {
                                            $('#compteur_' + id).removeClass('compteurCaracteres').addClass('compteurCaracteres_modeleEmail');
                                        }
                                    }
                                }
                            };

                            var observer = new MutationObserver(callback);
                            observer.observe(targetNodeconteneurmodeleEmail, config);
                        }
                        
            if ($('#' + id).parent().parent().hasClass('dataTables_filter') === false) {

                if ($('#' + id).parent().hasClass('ligneLabelEtInput')) {
                    $('#' + id).parent().append('<div style="position: relative;"><div id="compteur_' + id + '" class="compteurCaracteres">' + nombreCaracteresSaisis + ' / ' + nombreCaracteresMaximum + ' ' + CARACTERES + '</div></div>');

                } else {
                    $('#' + id).parent().parent().append('<div style="position: relative;"><div id="compteur_' + id + '" class="compteurCaracteres">' + nombreCaracteresSaisis + ' / ' + nombreCaracteresMaximum + ' ' + CARACTERES + '</div></div>');

                }

                bottom = parseFloat(-$('#' + id).height()) + 2;
                $('#compteur_' + id).css('bottom', bottom);
                $('#compteur_' + id).css('left', Math.abs($('#' + id).position().left));
            }

        }
    } else if (COMPTEUR_CARACTERES == COMPTEUR_CARACTERES_ACTIVE && $('#compteur_' + id).parent().is(':hidden')) {
        $('#compteur_' + id).parent().show();
        $('#compteur_' + id).html(nombreCaracteresSaisis + ' / ' + nombreCaracteresMaximum + ' ' + CARACTERES);
    }

    materialiserLimiteAtteinteDansComptageDeCaractere('compteur_' + id, nombreCaracteresSaisis, nombreCaracteresMaximum);
}

function cablerComptageDeCaractereSurInputEtTextArea() {
    // Evenements sur input text ou textarea pour le comptage de caractère
    $(document).on('click', 'input[type="text"]:not([readonly], .rechercheHortibox,.cke_dialog_ui_input_text, .rechercheParColonne, .sansCompteur):not(#identifiantLogin):not(#nouveauDossier):not(.dx-texteditor-input), textarea:not([readonly])', function (event) {
        onClickInputTextEtTextarea(this.id);
    });

    $(document).on('keydown', 'input[type="text"]:not([readonly]):not(.rechercheHortibox):not(#identifiantLogin):not(#nouveauDossier):not(.dx-texteditor-input), textarea:not([readonly])', function (event) {
    // WAZ 20/06/2024 Complément S181573
    // Déclaration des variables nombreCaracteresSaisis et nombreCaracteresMaximum au niveau supérieur
    // pour garantir qu'elles soient accessibles à la fois dans l'événement 'keydown' et dans la fonction 'input'.

    var nombreCaracteresSaisis;
    var nombreCaracteresMaximum;
        $('input[type="text"]:not([readonly]):not(#identifiantLogin), textarea:not([readonly])').bind('input', function () {
            nombreCaracteresSaisis = $(this).val().length;
            nombreCaracteresMaximum = (($('#' + this.id).attr('maxLength') !== undefined) ? ($('#' + this.id).attr('maxLength')) : '');
            $('#compteur_' + this.id).html(nombreCaracteresSaisis + ' / ' + nombreCaracteresMaximum + ' ' + CARACTERES);
        });
        materialiserLimiteAtteinteDansComptageDeCaractere(this.id, nombreCaracteresSaisis, nombreCaracteresMaximum);
    });
    $(document).on('blur', 'input[type="text"]:not([readonly]):not(#identifiantLogin):not(.rechercheHortibox):not(#nouveauDossier):not(.dx-texteditor-input), textarea:not([readonly])', function (event) {
        onblurInputTextEtTextarea(this.id);
    });
}

function activerOuDesactiverCompteurCaracteres(id) {
    $.ajax({
        url: '/layout/activerOuDesactiverCompteurCaracteres',
        data: {
            'etatCompteur': $('#activerDesactiverCompteurCaracteres').is(':checked')
        },
        success: function (etatCompteur) {
            COMPTEUR_CARACTERES = etatCompteur;
        }
    });
}

function materialiserLimiteAtteinteDansComptageDeCaractere(id, nombreCaracteresSaisis, nombreCaracteresMaximum) {

    if ($('#compteur_' + id).length) {

        // Obliger de "réinitialiser" pour le cas ou l'utilisateur clique trop vite : avant que le setTimeout ne se termine. Dans ce cas la matérialisation reste constamment.
        $('#compteur_' + id).css('color', '#404040').css('font-weight', 'normal');
        $('#compteur_' + id).html($('#compteur_' + id).html().replace(' !', ''));
        $('#' + id).removeClass('bordureRouge');

        if (nombreCaracteresSaisis == nombreCaracteresMaximum) {
            $('#compteur_' + id).css('color', '#d22201').css('font-weight', 'bold');
            $('#compteur_' + id).html($('#compteur_' + id).html() + ' !');
            $('#' + id).addClass('bordureRouge');
            setTimeout(function () {
                $('#compteur_' + id).css('color', '#404040').css('font-weight', 'normal');
                $('#compteur_' + id).html($('#compteur_' + id).html().replace(' !', ''));
                $('#' + id).removeClass('bordureRouge');
            }, 2000);
        }

    }

}


function onblurInputTextEtTextarea(id) {
    if ($('#compteur_' + id).length != 0) {
        $('#compteur_' + id).parent().hide();
    }
}



// une fonction qui remplie les select des filtres d'un datatable 
function remplirLesFiltres(cheminControleur, idTableauHtml, mode, etat, tableauDesLargeuresEtIndices) {
    numeroFiltre = "";
    if (idTableauHtml == "moduleConsulterGroupe_tableauClients") {
        numeroFiltre = numeroGroupe;
    }
    $.ajax({
        url: cheminControleur,
        data: {
            'mode': mode,
            'numeroFiltre': numeroFiltre
        },
        async: false,
        success: function (donnesFiltres) {
            donnees = JSON.parse(donnesFiltres);

            var tableauDesListesDeroulantesFiltres = document.getElementById(idTableauHtml + "_wrapper").getElementsByClassName("column-filter-widgets")[0].querySelectorAll("select");


            var tailleTableauDesListes = tableauDesListesDeroulantesFiltres.length
            for (var i = 0; i < tailleTableauDesListes; i++) {
                tableauDesListesDeroulantesFiltres[i].innerHTML = tableauDesListesDeroulantesFiltres[i].innerHTML + donnees[i].join('');
                //$(tableauDesListesDeroulantesFiltres[i]).append(donnees[i]);
                if (donnees[i].length > 0) {
                    // activer the menu
                    tableauDesListesDeroulantesFiltres[i].disabled = false;
                } else {
                    // desactiver le menu, 
                    tableauDesListesDeroulantesFiltres[i].disabled = true;
                }
            }

            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters($('#' + idTableauHtml).DataTable(), true, idTableauHtml, etat); }, 0);

        }
    });
}

function formatChrono(valeur, type) {
    nbZeros = 0;
    if (type == "cent") {
        if (valeur.toString().length < 3) {
            nbZeros = 3 - valeur.toString().length;
        }
    } else {
        if (valeur.toString().length < 2) {
            nbZeros = 2 - valeur.toString().length;
        }
    }

    for (i = 0; i < nbZeros; i++) {
        valeur = "0" + valeur;
    }

    return valeur;
}


function retournerIndiceTableau(idTableauHtml) {
    recherche_term = idTableauHtml + '_'; // search term
    //    rechercheObjet = new RegExp(recherche_term, "i");
    retour = -1;

    idxPagination = 0;
    trouv = false;
    while (idxPagination < pageSelectionnees.length && trouv == false) {
        if (pageSelectionnees[idxPagination].indexOf(recherche_term) == 0) {
            retour = idxPagination;
            trouv = true;
        } else {
            idxPagination++;
        }
    }


    return retour;

}
function retournerdebutPage(tableau) {
    pageSelect = 0
    if (tableau != null && tableau >= 0) {
        tableauIntermediaire = pageSelectionnees[tableau].split("_")
        pageSelect = tableauIntermediaire[tableauIntermediaire.length - 1];
    }

    return pageSelect;

}
function forcerCablagePagination(idTableauHtml) {
    $('.dataTables_paginate a').on("click", function () {
        dataTableEnCours = ($('#' + idTableauHtml).DataTable()).settings()[0];
        tableauindice = retournerIndiceTableau(idTableauHtml);
        // idTableauHtml = (((typeof consultationBDDVegetale !== 'undefined' && consultationBDDVegetale == 'True') || (typeof administrateurVLV !== 'undefined' && administrateurVLV == 'True')) ? idTableauHtml + 'RechercheLGI' : ((typeof recherchePreselection !== 'undefined' && recherchePreselection != "") ? idTableauHtml + recherchePreselection : idTableauHtml));
        pageSelectionnees[tableauindice] = idTableauHtml + "_" + dataTableEnCours._iDisplayStart;

    });
    dataTableEnCours = ($('#' + idTableauHtml).DataTable()).settings()[0];

    tableauindice = retournerIndiceTableau(idTableauHtml);

    //idTableauHtml = (((typeof consultationBDDVegetale !== 'undefined' && consultationBDDVegetale == 'True') || (typeof administrateurVLV !== 'undefined' && administrateurVLV == 'True')) ? idTableauHtml + 'RechercheLGI' : ((typeof recherchePreselection !== 'undefined' && recherchePreselection != "") ? idTableauHtml + recherchePreselection : idTableauHtml));
    pageSelectionnees[tableauindice] = idTableauHtml + "_" + dataTableEnCours._iDisplayStart;

    $("#" + idTableauHtml + ' ,tbody').animate({
        scrollTop: 0
    }, 700);
}

//initialiser le panneau du colvis
function initialiserCoVis(idTableauHtml) {
    if ($('.ColVis_collection').length > 0) {
        $('.ColVis_collection').remove();
    }
    if ($('.ColVis_collectionBackground').length > 0) {
        $('.ColVis_collectionBackground').remove();
    }
    $('#' + idTableauHtml + '_wrapper .ColVis_MasterButton').trigger('click');
    $('.ColVis_catcher').trigger('click');
    $('.ColVis_collection').last().css('zIndex', -1000).css('top', 1000).attr('id', 'ColVis_collection_' + idTableauHtml);
    setTimeout(function () {
        $('.ColVis_MasterButton').on("click", function () {
            $('.ColVis_collection').css('zIndex', 10000);

        });
        $.fn.DataTable.ColVis.fnRebuild();
    }, 200);

}

// remplacer les caractères accentués par des charactères sans accents
var tableauDesCaracteresSpeciaux = [
    { 'base': 'A', 'lettres': '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F' },
    { 'base': 'AA', 'lettres': '\uA732' },
    { 'base': 'AE', 'lettres': '\u00C6\u01FC\u01E2' },
    { 'base': 'AO', 'lettres': '\uA734' },
    { 'base': 'AU', 'lettres': '\uA736' },
    { 'base': 'AV', 'lettres': '\uA738\uA73A' },
    { 'base': 'AY', 'lettres': '\uA73C' },
    { 'base': 'B', 'lettres': '\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181' },
    { 'base': 'C', 'lettres': '\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E' },
    { 'base': 'D', 'lettres': '\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779' },
    { 'base': 'DZ', 'lettres': '\u01F1\u01C4' },
    { 'base': 'Dz', 'lettres': '\u01F2\u01C5' },
    { 'base': 'E', 'lettres': '\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E' },
    { 'base': 'F', 'lettres': '\u0046\u24BB\uFF26\u1E1E\u0191\uA77B' },
    { 'base': 'G', 'lettres': '\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E' },
    { 'base': 'H', 'lettres': '\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D' },
    { 'base': 'I', 'lettres': '\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197' },
    { 'base': 'J', 'lettres': '\u004A\u24BF\uFF2A\u0134\u0248' },
    { 'base': 'K', 'lettres': '\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2' },
    { 'base': 'L', 'lettres': '\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780' },
    { 'base': 'LJ', 'lettres': '\u01C7' },
    { 'base': 'Lj', 'lettres': '\u01C8' },
    { 'base': 'M', 'lettres': '\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C' },
    { 'base': 'N', 'lettres': '\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4' },
    { 'base': 'NJ', 'lettres': '\u01CA' },
    { 'base': 'Nj', 'lettres': '\u01CB' },
    { 'base': 'O', 'lettres': '\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C' },
    { 'base': 'OI', 'lettres': '\u01A2' },
    { 'base': 'OO', 'lettres': '\uA74E' },
    { 'base': 'OU', 'lettres': '\u0222' },
    { 'base': 'OE', 'lettres': '\u008C\u0152' },
    { 'base': 'oe', 'lettres': '\u009C\u0153' },
    { 'base': 'P', 'lettres': '\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754' },
    { 'base': 'Q', 'lettres': '\u0051\u24C6\uFF31\uA756\uA758\u024A' },
    { 'base': 'R', 'lettres': '\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782' },
    { 'base': 'S', 'lettres': '\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784' },
    { 'base': 'T', 'lettres': '\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786' },
    { 'base': 'TZ', 'lettres': '\uA728' },
    { 'base': 'U', 'lettres': '\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244' },
    { 'base': 'V', 'lettres': '\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245' },
    { 'base': 'VY', 'lettres': '\uA760' },
    { 'base': 'W', 'lettres': '\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72' },
    { 'base': 'X', 'lettres': '\u0058\u24CD\uFF38\u1E8A\u1E8C' },
    { 'base': 'Y', 'lettres': '\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE' },
    { 'base': 'Z', 'lettres': '\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762' },
    { 'base': 'a', 'lettres': '\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250' },
    { 'base': 'aa', 'lettres': '\uA733' },
    { 'base': 'ae', 'lettres': '\u00E6\u01FD\u01E3' },
    { 'base': 'ao', 'lettres': '\uA735' },
    { 'base': 'au', 'lettres': '\uA737' },
    { 'base': 'av', 'lettres': '\uA739\uA73B' },
    { 'base': 'ay', 'lettres': '\uA73D' },
    { 'base': 'b', 'lettres': '\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253' },
    { 'base': 'c', 'lettres': '\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184' },
    { 'base': 'd', 'lettres': '\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A' },
    { 'base': 'dz', 'lettres': '\u01F3\u01C6' },
    { 'base': 'e', 'lettres': '\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD' },
    { 'base': 'f', 'lettres': '\u0066\u24D5\uFF46\u1E1F\u0192\uA77C' },
    { 'base': 'g', 'lettres': '\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F' },
    { 'base': 'h', 'lettres': '\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265' },
    { 'base': 'hv', 'lettres': '\u0195' },
    { 'base': 'i', 'lettres': '\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131' },
    { 'base': 'j', 'lettres': '\u006A\u24D9\uFF4A\u0135\u01F0\u0249' },
    { 'base': 'k', 'lettres': '\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3' },
    { 'base': 'l', 'lettres': '\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747' },
    { 'base': 'lj', 'lettres': '\u01C9' },
    { 'base': 'm', 'lettres': '\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F' },
    { 'base': 'n', 'lettres': '\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5' },
    { 'base': 'nj', 'lettres': '\u01CC' },
    { 'base': 'o', 'lettres': '\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275' },
    { 'base': 'oi', 'lettres': '\u01A3' },
    { 'base': 'ou', 'lettres': '\u0223' },
    { 'base': 'oo', 'lettres': '\uA74F' },
    { 'base': 'p', 'lettres': '\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755' },
    { 'base': 'q', 'lettres': '\u0071\u24E0\uFF51\u024B\uA757\uA759' },
    { 'base': 'r', 'lettres': '\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783' },
    { 'base': 's', 'lettres': '\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B' },
    { 'base': 't', 'lettres': '\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787' },
    { 'base': 'tz', 'lettres': '\uA729' },
    { 'base': 'u', 'lettres': '\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289' },
    { 'base': 'v', 'lettres': '\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C' },
    { 'base': 'vy', 'lettres': '\uA761' },
    { 'base': 'w', 'lettres': '\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73' },
    { 'base': 'x', 'lettres': '\u0078\u24E7\uFF58\u1E8B\u1E8D' },
    { 'base': 'y', 'lettres': '\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF' },
    { 'base': 'z', 'lettres': '\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763' }
];

var caracteresSpeciauxMap = {};
for (var i = 0; i < tableauDesCaracteresSpeciaux.length; i++) {
    var lettres = tableauDesCaracteresSpeciaux[i].lettres.split("");
    for (var j = 0; j < lettres.length; j++) {
        caracteresSpeciauxMap[lettres[j]] = tableauDesCaracteresSpeciaux[i].base;
    }
}


function enleverAccents(chaine) {
    return chaine.replace(/[^\u0000-\u007E]/g, function (a) {
        return caracteresSpeciauxMap[a] || a;
    });
}


function convertirCouleurHexaARgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

var delai = (function () {
    temps = 0;
    return function (callback, ms) {
        clearTimeout(temps);
        temps = setTimeout(callback, ms);
    };
})();


var dernieresVisualisationsDansLesTableaux = new Array();
var dernieresVisualisationsDansLesTableauxJSON;
$(document).on("click", 'table tbody tr', function () {
    $('tr').removeClass('derniereLigneMaterialisee');
    $(this).addClass('derniereLigneMaterialisee');
    //closest() retoune le parent directe de dom
    idTableauCourant = $(this).closest('table').attr('id');
    $row = $(this).closest('table');
    indexID = $row.find("th").filter(function () {
        return $(this).text() == 'ID';
    }).index();
    idEntite = $(this).find('td:eq(' + indexID + ')').html();

    obj = new Object();
    obj.idTab = idTableauCourant;
    obj.idEntiter = idEntite;


    index = -1;
    for (j = 0; j < dernieresVisualisationsDansLesTableaux.length; j++) {
        if (dernieresVisualisationsDansLesTableaux[j].idTab === idTableauCourant) {
            index = j;
            break;
        }
    }
    if (index > -1) {
        dernieresVisualisationsDansLesTableaux.splice(index, 1);
    }

    dernieresVisualisationsDansLesTableaux.push(obj);

    dernieresVisualisationsDansLesTableauxJSON = JSON.stringify(dernieresVisualisationsDansLesTableaux);

});

String.prototype.replaceAll = function (str1, str2, ignore) {
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof (str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
}
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
}

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function (searchString, position) {
        var subjectString = this.toString();
        if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
            position = subjectString.length;
        }
        position -= searchString.length;
        var lastIndex = subjectString.indexOf(searchString, position);
        return lastIndex !== -1 && lastIndex === position;
    };
}

//ancien Layout 

function rechercheTableauxEtMiseAJourEtat() {

    if ($('.sauvegardeEtat').length > 0) {
        //cas où il existe plusieurs dt ayant la même source alors on applique la sauvegarde sur le dernier dt uniquement
        idTableau = $(".conteneurBlocConditions").last().find('.dataTable').attr('id');
        sauvegarderEtat(idTableau);
    } else {
        $(document).find(".dataTable").each(function () {
            idTableau = $(this).attr('id');
            if ($('#' + idTableau).DataTable()) {
                sauvegarderEtat(idTableau);
            }
        });
    }
}



//"sauvegardeCallback, blocIsertion" cas descriptifsConseils avec insertion tableau + mise à jour état
function sauvegarderEtat(idTableau, sauvegardeCallback, blocIsertion) {

    sansFiltres = false;
    lesColonnes = [];
    if (typeof estVisibleCheckboxAssocie !== 'undefined' && estVisibleCheckboxAssocie == false) {
        if (idTableau.indexOf("moduleConseilAssocieDescriptif_tableauDesDescriptifs") >= 0 || idTableau.indexOf("moduleConseilAssocieDescriptif_tableauListeDesConseils") >= 0) {
            sansFiltres = true;
            $('#' + idTableau).DataTable().search('').columns().search('');
        }
    }

    if (idTableau == 'moduleDescriptif_tableauListeDesBDDVegetalesEnPreselection'
        || idTableau == 'moduleDescriptif_tableauListeDesBDDVegetalesEnRattachement'
        || idTableau == 'moduleDescriptif_tableauListeDesBDDVegetales'
        || idTableau == 'moduleDescriptif_tableauListeDesDescriptifsEnRattachement'
        || idTableau == 'moduleDescriptif_tableauListeDesDescriptifsEnPreselection'
        || idTableau == 'moduleDescriptif_tableauListeDesDescriptifs') {

        if (typeof tableauDesLargeuresEtIndicesDescriptif !== 'undefined' && tableauDesLargeuresEtIndicesDescriptif != '') {
            lesColonnes = tableauDesLargeuresEtIndicesDescriptif.split("|");
            tableauDesLargeuresEtIndicesDescriptif = "";
        }
    } else if (idTableau == 'moduleValeur_tableauListeDeValeurs'
        || idTableau == 'moduleValeur_tableauListeDeValeursVlv'
        || idTableau == 'moduleValeur_tableauListeDeValeursReferentes') {
        if (typeof tableauDesLargeuresEtIndicesValeurs !== 'undefined' && tableauDesLargeuresEtIndicesValeurs != '') {
            lesColonnes = tableauDesLargeuresEtIndicesValeurs.split("|");
            tableauDesLargeuresEtIndicesValeurs = "";
        }
    } else if (idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesVlv'
        || idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategories'
        || idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesReferentes') {
        if (typeof tableauDesLargeuresEtIndicesCriteresCategories !== 'undefined' && tableauDesLargeuresEtIndicesCriteresCategories != '') {
            lesColonnes = tableauDesLargeuresEtIndicesCriteresCategories.split("|");
            tableauDesLargeuresEtIndicesCriteresCategories = "";
        }
    } else if (idTableau == 'tableauListeDesCategoriesDescriptifs') {
        if (typeof tableauDesLargeuresEtIndicesCategorieDescriptifs !== 'undefined' && tableauDesLargeuresEtIndicesCategorieDescriptifs != '') {
            lesColonnes = tableauDesLargeuresEtIndicesCategorieDescriptifs.split("|");
            tableauDesLargeuresEtIndicesCategorieDescriptifs = "";
        }
    } else if (idTableau == 'moduleMediaCategorie_tableauListeDesCategoriesMedias'
        || idTableau == 'moduleMediaCategorie_tableauListeDesCategoriesMediasVlv') {
        if (typeof tableauDesLargeuresEtIndicesCategorieMedias !== 'undefined' && tableauDesLargeuresEtIndicesCategorieMedias != '') {
            lesColonnes = tableauDesLargeuresEtIndicesCategorieMedias.split("|");
            tableauDesLargeuresEtIndicesCategorieMedias = "";
        }
    } else if (idTableau == 'tableauListeDesTypesDeConseils') {
        if (typeof tableauDesLargeuresEtIndicesConseilsTypes !== 'undefined' && tableauDesLargeuresEtIndicesConseilsTypes != '') {
            lesColonnes = tableauDesLargeuresEtIndicesConseilsTypes.split("|");
            tableauDesLargeuresEtIndicesConseilsTypes = "";
        }
    } else if (idTableau == 'tableauListeDesTypesInfoComplementaireConseil') {
        if (typeof tableauDesLargeuresEtIndicesConseilInfoComplementaireTypes !== 'undefined' && tableauDesLargeuresEtIndicesConseilInfoComplementaireTypes != '') {
            lesColonnes = tableauDesLargeuresEtIndicesConseilInfoComplementaireTypes.split("|");
            tableauDesLargeuresEtIndicesConseilInfoComplementaireTypes = "";
        }
    } else if (idTableau == 'tableauListeDesInfosComplementaireConseil') {
        if (typeof tableauDesLargeuresEtIndicesInfosComplementaireConseils !== 'undefined' && tableauDesLargeuresEtIndicesInfosComplementaireConseils != '') {
            lesColonnes = tableauDesLargeuresEtIndicesInfosComplementaireConseils.split("|");
            tableauDesLargeuresEtIndicesInfosComplementaireConseils = "";
        }
    } else if (idTableau == 'moduleCritere_tableauListeDeCriteres'
        || idTableau == 'moduleCritere_tableauListeDeCriteresVlv'
        || idTableau == 'moduleCritere_tableauListeDeCriteresReferentes'
        || idTableau == 'moduleCritere_tableauListeDeCriteresWebshop'
        || idTableau == 'moduleCritere_tableauListeDeCriteresWebshopVlv'
        || idTableau == 'moduleCritere_tableauListeDeCriteresProduitWebshop'
        || idTableau == 'moduleCritere_tableauListeDeCriteresProduitWebshopVlv'
        || idTableau == 'moduleCritere_tableauListeDeCriteresHortibook'
        || idTableau == 'moduleCritere_tableauListeDeCriteresAppShop'
        || idTableau == 'moduleCritere_tableauListeDeCriteresAppShopVlv'
        || idTableau == 'moduleCritere_tableauListeDeCriteresProduitAppShop'
        || idTableau == 'moduleCritere_tableauListeDeCriteresProduitAppShopVlv'
    ) {
        if (typeof tableauDesLargeuresEtIndicesCritere !== 'undefined' && tableauDesLargeuresEtIndicesCritere != '') {
            lesColonnes = tableauDesLargeuresEtIndicesCritere.split("|");
            tableauDesLargeuresEtIndicesCritere = "";
        }
    } else if (idTableau == 'lieux') {
        if (typeof tableauDesLargeuresEtIndicesLieux !== 'undefined' && tableauDesLargeuresEtIndicesLieux != '') {
            lesColonnes = tableauDesLargeuresEtIndicesLieux.split("|");
            tableauDesLargeuresEtIndicesLieux = "";
        }
    } else if (idTableau == 'moduleMedia_tableauListeDeMedias'
        || idTableau == 'moduleConseil_tableauListeDesMedias'
        || idTableau == 'moduleDescriptif_tableauListeDeMedias'
        || idTableau == 'moduleMedia_tableauListeDeMediasVlv'
        || idTableau == 'moduleMedia_tableauListeDeMediasReferente') {
        if (typeof tableauDesLargeuresEtIndicesMedia !== 'undefined' && tableauDesLargeuresEtIndicesMedia != '') {
            lesColonnes = tableauDesLargeuresEtIndicesMedia.split("|");
            tableauDesLargeuresEtIndicesMedia = "";
        }
    } else if (idTableau == 'moduleLangue_tableauListeDesLangues') {
        if (typeof tableauDesLargeuresEtIndicesTraduction !== 'undefined' && tableauDesLargeuresEtIndicesTraduction != '') {
            lesColonnes = tableauDesLargeuresEtIndicesTraduction.split("|");
            tableauDesLargeuresEtIndicesTraduction = "";
        }
    } else if (idTableau == 'moduleLangue_tableauListeDesEntitees') {
        if (typeof tableauDesLargeuresEtIndicesTraduction !== 'undefined' && tableauDesLargeuresEtIndicesEntiteesTraduction != '') {
            lesColonnes = tableauDesLargeuresEtIndicesEntiteesTraduction.split("|");
            tableauDesLargeuresEtIndicesEntiteesTraduction = "";
        }
    } else if (idTableau == 'moduleLangue_tableauEditerTraduction') {
        if (typeof tableauDesLargeuresEtIndicesTraduction !== 'undefined' && tableauDesLargeuresEtIndicesEditerTraduction != '') {
            lesColonnes = tableauDesLargeuresEtIndicesEditerTraduction.split("|");
            tableauDesLargeuresEtIndicesEditerTraduction = "";
        }
    } else if (idTableau == 'tableauListeDesConseils'
        || idTableau == 'moduleConseilAssocieDescriptif_tableauListeDesConseils') {
        if (typeof tableauDesLargeuresEtIndicesConseil !== 'undefined' && tableauDesLargeuresEtIndicesConseil != '') {
            lesColonnes = tableauDesLargeuresEtIndicesConseil.split("|");
            tableauDesLargeuresEtIndicesConseil = "";
        }
    } else if (idTableau == 'tableauListeDesCatalogues') {
        if (typeof tableauDesLargeuresEtIndicesCatalogues !== 'undefined' && tableauDesLargeuresEtIndicesCatalogues != '') {
            lesColonnes = tableauDesLargeuresEtIndicesCatalogues.split("|");
            tableauDesLargeuresEtIndicesCatalogues = "";
        }
    } else if (idTableau == 'tableauLignesDeCatalogue') {
        if (typeof tableauDesLargeuresEtIndicesLignesCatalogue !== 'undefined' && tableauDesLargeuresEtIndicesLignesCatalogue != '') {
            lesColonnes = tableauDesLargeuresEtIndicesLignesCatalogue.split("|");
            tableauDesLargeuresEtIndicesLignesCatalogue = "";
        }
    } else if (idTableau == 'tableauListeDesComptesBancaires') {
        if (typeof tableauDesLargeuresEtIndicesComptesBancaires !== 'undefined' && tableauDesLargeuresEtIndicesComptesBancaires != '') {
            lesColonnes = tableauDesLargeuresEtIndicesComptesBancaires.split("|");
            tableauDesLargeuresEtIndicesComptesBancaires = "";
        }
    } else if (idTableau == 'tableauListeDesDemandesServices'
        || idTableau == 'tableauActualise_tableauListeDesDemandesServices') {
        if (typeof tableauDesLargeuresEtIndicesDemandesServices !== 'undefined' && tableauDesLargeuresEtIndicesDemandesServices != '') {
            lesColonnes = tableauDesLargeuresEtIndicesDemandesServices.split("|");
            tableauDesLargeuresEtIndicesDemandesServices = "";
        }
    } else if (idTableau == 'natureDemandeService') {
        if (typeof tableauDesLargeuresEtIndicesNatureDemandeService !== 'undefined' && tableauDesLargeuresEtIndicesNatureDemandeService != '') {
            lesColonnes = tableauDesLargeuresEtIndicesNatureDemandeService.split("|");
            tableauDesLargeuresEtIndicesNatureDemandeService = "";
        }
    } else if (idTableau == 'tableauListeDesProduitsDemandeService') {
        if (typeof tableauDesLargeuresEtIndicesProduitDemandeService !== 'undefined' && tableauDesLargeuresEtIndicesProduitDemandeService != '') {
            lesColonnes = tableauDesLargeuresEtIndicesProduitDemandeService.split("|");
            tableauDesLargeuresEtIndicesProduitDemandeService = "";
        }
    } else if (idTableau == 'tableauListeDesCategoriesDemandeService') {
        if (typeof tableauDesLargeuresEtIndicesCategorieDemandeService !== 'undefined' && tableauDesLargeuresEtIndicesCategorieDemandeService != '') {
            lesColonnes = tableauDesLargeuresEtIndicesCategorieDemandeService.split("|");
            tableauDesLargeuresEtIndicesCategorieDemandeService = "";
        }
    } else if (idTableau == 'tableauListeDesSousCategoriesDemandeService') {
        if (typeof tableauDesLargeuresEtIndicesSousCategorieDemandeService !== 'undefined' && tableauDesLargeuresEtIndicesSousCategorieDemandeService != '') {
            lesColonnes = tableauDesLargeuresEtIndicesSousCategorieDemandeService.split("|");
            tableauDesLargeuresEtIndicesSousCategorieDemandeService = "";
        }
    } else if (idTableau == 'tableauListeDesAdressesDeLivraison') {
        if (typeof tableauDesLargeuresEtIndicesAdresseLivraison !== 'undefined' && tableauDesLargeuresEtIndicesAdresseLivraison != '') {
            lesColonnes = tableauDesLargeuresEtIndicesAdresseLivraison.split("|");
            tableauDesLargeuresEtIndicesAdresseLivraison = "";
        }
    } else if (idTableau == 'tableauListeTypeUniteVente'
        || idTableau == 'tableauListePresentations'
        || idTableau == "tableauListeMillesimes") {
        if (typeof tableauDesLargeuresEtIndicesDictionnaire !== 'undefined' && tableauDesLargeuresEtIndicesDictionnaire != '') {
            lesColonnes = tableauDesLargeuresEtIndicesDictionnaire.split("|");
            tableauDesLargeuresEtIndicesDictionnaire = "";
        }
    } else if (idTableau == 'tableauEletter') {
        if (typeof tableauDesLargeuresEtIndicesEletter !== 'undefined' && tableauDesLargeuresEtIndicesEletter != '') {
            lesColonnes = tableauDesLargeuresEtIndicesEletter.split("|");
            tableauDesLargeuresEtIndicesEletter = "";
        }
    } else if (idTableau == 'tableauListeDEmailsConseilsEnvoyes') {
        if (typeof tableauDesLargeuresEtIndicesEmailsConseilsEnvoyes !== 'undefined' && tableauDesLargeuresEtIndicesEmailsConseilsEnvoyes != '') {
            lesColonnes = tableauDesLargeuresEtIndicesEmailsConseilsEnvoyes.split("|");
            tableauDesLargeuresEtIndicesEmailsConseilsEnvoyes = "";
        }
    } else if (idTableau == 'tableauGroupes'
        || idTableau == 'tableauGroupes_detailSociete') {
        if (typeof tableauDesLargeuresEtIndicesGroupe !== 'undefined' && tableauDesLargeuresEtIndicesGroupe != '') {
            lesColonnes = tableauDesLargeuresEtIndicesGroupe.split("|");
            tableauDesLargeuresEtIndicesGroupe = "";
        }

    } else if (idTableau == 'tableauListeDesArticles') {
        if (typeof tableauDesLargeuresEtIndicesArticles !== 'undefined' && tableauDesLargeuresEtIndicesArticles != '') {
            lesColonnes = tableauDesLargeuresEtIndicesArticles.split("|");
            tableauDesLargeuresEtIndicesArticles = "";
        }
    } else if (idTableau == 'tableauServices') {
        if (typeof tableauDesLargeuresEtIndicesServices !== 'undefined' && tableauDesLargeuresEtIndicesServices != '') {
            lesColonnes = tableauDesLargeuresEtIndicesServices.split("|");
            tableauDesLargeuresEtIndicesServices = "";
        }
    } else if (idTableau == 'tableauMesServices') {
        if (typeof tableauDesLargeuresEtIndicesMesServices !== 'undefined' && tableauDesLargeuresEtIndicesMesServices != '') {
            lesColonnes = tableauDesLargeuresEtIndicesMesServices.split("|");
            tableauDesLargeuresEtIndicesMesServices = "";
        }
    } else if (idTableau == 'tableauListeDesOperationsEnvoyees') {
        if (typeof tableauDesLargeuresEtIndicesOperations !== 'undefined' && tableauDesLargeuresEtIndicesOperations != '') {
            lesColonnes = tableauDesLargeuresEtIndicesOperations.split("|");
            tableauDesLargeuresEtIndicesOperations = "";
        }
    } else if (idTableau == 'tableauListeTaille'
        || idTableau == 'tableauListeUniteVente') {
        if (typeof tableauDesLargeuresEtIndicesTypeUniteVente !== 'undefined' && tableauDesLargeuresEtIndicesTypeUniteVente != '') {
            lesColonnes = tableauDesLargeuresEtIndicesTypeUniteVente.split("|");
            tableauDesLargeuresEtIndicesTypeUniteVente = "";
        }
    } else if (idTableau == 'moduleClients_tableauClients'
        || idTableau == 'moduleDemandeService_tableauClients'
        || idTableau == 'moduleAjoutGroupe_tableauClients'
        || idTableau == 'moduleAjoutGroupe_tableauClientsModifierGroupe'
        || idTableau == 'moduleConsulterGroupe_tableauClients') {
        if (typeof tableauDesLargeuresEtIndicesMesClients !== 'undefined' && tableauDesLargeuresEtIndicesMesClients != '') {
            lesColonnes = tableauDesLargeuresEtIndicesMesClients.split("|");
            tableauDesLargeuresEtIndicesMesClients = "";
        }
    } else if (idTableau == 'moduleComptesSecondaires_tableauListeDesComptes'
        || idTableau == 'moduleDemandeService_tableauListeDesComptes') {
        if (typeof tableauDesLargeuresEtIndicesComptes !== 'undefined' && tableauDesLargeuresEtIndicesComptes != '') {
            lesColonnes = tableauDesLargeuresEtIndicesComptes.split("|");
            tableauDesLargeuresEtIndicesComptes = "";
        }
    } else if (idTableau == 'tableauListeDeAuthentifications') {
        if (typeof tableauDesLargeuresEtIndicesAuthentifications !== 'undefined' && tableauDesLargeuresEtIndicesAuthentifications != '') {
            lesColonnes = tableauDesLargeuresEtIndicesAuthentifications.split("|");
            tableauDesLargeuresEtIndicesAuthentifications = "";
        }
    } else if (idTableau == 'tableauListeDEmaislEnvoyes') {
        if (typeof tableauDesLargeuresEtIndicesEmailsEnvoyes !== 'undefined' && tableauDesLargeuresEtIndicesEmailsEnvoyes != '') {
            lesColonnes = tableauDesLargeuresEtIndicesEmailsEnvoyes.split("|");
            tableauDesLargeuresEtIndicesEmailsEnvoyes = "";
        }
    } else if (idTableau == 'moduleHistoriqueConsultation_tableauListeDetailsHistoriqueConsultation') {
        if (typeof tableauDesLargeuresEtIndicesHistoriqueConsultation !== 'undefined' && tableauDesLargeuresEtIndicesHistoriqueConsultation != '') {
            lesColonnes = tableauDesLargeuresEtIndicesHistoriqueConsultation.split("|");
            tableauDesLargeuresEtIndicesHistoriqueConsultation = "";
        }
    } else if (idTableau == 'tableauListeDHistoriqueDImport') {
        if (typeof tableauDesLargeuresEtIndicesHistoriqueImport !== 'undefined' && tableauDesLargeuresEtIndicesHistoriqueImport != '') {
            lesColonnes = tableauDesLargeuresEtIndicesHistoriqueImport.split("|");
            tableauDesLargeuresEtIndicesHistoriqueImport = "";
        }
    } else if (idTableau == 'tableauDeLogsBase') {
        if (typeof tableauDesLargeuresEtIndicesLogsDeLaBase !== 'undefined' && tableauDesLargeuresEtIndicesLogsDeLaBase != '') {
            lesColonnes = tableauDesLargeuresEtIndicesLogsDeLaBase.split("|");
            tableauDesLargeuresEtIndicesLogsDeLaBase = "";
        }
    } else if (idTableau == 'tableauListeParametresApplication') {
        if (typeof tableauDesLargeuresEtIndicesParametresDeLApplication !== 'undefined' && tableauDesLargeuresEtIndicesParametresDeLApplication != '') {
            lesColonnes = tableauDesLargeuresEtIndicesParametresDeLApplication.split("|");
            tableauDesLargeuresEtIndicesParametresDeLApplication = "";
        }
    } else if (idTableau == 'tableauListeDesProduits') {
        if (typeof tableauDesLargeuresEtIndicesProduits !== 'undefined' && tableauDesLargeuresEtIndicesProduits != '') {
            lesColonnes = tableauDesLargeuresEtIndicesProduits.split("|");

            tableauDesLargeuresEtIndicesProduits = "";
        }
    } else if (idTableau == 'tableauListePanier' || idTableau == 'tableauListeRecapPanier') {
        if (typeof tableauDesLargeuresEtIndicesPanier !== 'undefined' && tableauDesLargeuresEtIndicesPanier != '') {
            lesColonnes = tableauDesLargeuresEtIndicesPanier.split("|");

            tableauDesLargeuresEtIndicesPanier = "";
        }
    } else if (idTableau == 'tableauListeClientsWebshop') {
        if (typeof tableauDesLargeuresEtIndicesClientWebshop !== 'undefined' && tableauDesLargeuresEtIndicesClientWebshop != '') {
            lesColonnes = tableauDesLargeuresEtIndicesClientWebshop.split("|");
            //tableauDesLargeuresEtIndicesClientWebshop = "";
        }
    } else if (idTableau == 'tableauListeDesComptesAAdministrer'
        || idTableau == 'tableauComptesConnectes') {
        if (typeof tableauDesLargeuresEtIndicesCompteAAdministrer !== 'undefined' && tableauDesLargeuresEtIndicesCompteAAdministrer != '') {
            lesColonnes = tableauDesLargeuresEtIndicesCompteAAdministrer.split("|");
            tableauDesLargeuresEtIndicesCompteAAdministrer = "";
        }

    } else if (idTableau == 'tableauListeDesVersionsCode') {
        if (typeof tableauDesLargeuresEtIndicesVersionsCode !== 'undefined' && tableauDesLargeuresEtIndicesVersionsCode != '') {
            lesColonnes = tableauDesLargeuresEtIndicesVersionsCode.split("|");
            tableauDesLargeuresEtIndicesVersionsCode = "";
        }
    }
    else if (idTableau == 'tableauListeDesConsommateurs') {
        if (typeof tableauDesLargeuresEtIndicesConsommateurs !== 'undefined' && tableauDesLargeuresEtIndicesConsommateurs != '') {
            lesColonnes = tableauDesLargeuresEtIndicesConsommateurs.split("|");
            tableauDesLargeuresEtIndicesConsommateurs = "";
        }
    } else if (idTableau == 'tableauListeModesExpeditions') {
        if (typeof tableauDesLargeuresEtIndicesModesExpeditions !== 'undefined' && tableauDesLargeuresEtIndicesModesExpeditions != '') {
            lesColonnes = tableauDesLargeuresEtIndicesModesExpeditions.split("|");
            tableauDesLargeuresEtIndicesModesExpeditions = "";
        }
    } else if (idTableau == 'tableauListeBoutiques') {
        if (typeof tableauDesLargeuresEtIndicesBoutiques !== 'undefined' && tableauDesLargeuresEtIndicesBoutiques != '') {
            lesColonnes = tableauDesLargeuresEtIndicesBoutiques.split("|");
            tableauDesLargeuresEtIndicesBoutiques = "";
        }
    } else if (idTableau == 'tableauListeDesPaiements') {
        if (typeof tableauDesLargeuresEtIndicesPaiements !== 'undefined' && tableauDesLargeuresEtIndicesPaiements != '') {
            lesColonnes = tableauDesLargeuresEtIndicesPaiements.split("|");
            tableauDesLargeuresEtIndicesPaiements = "";
        }
    } else if (idTableau == 'tableauListeCumulsEmballages') {
        if (typeof tableauDesLargeuresEtIndicesCumulsEmballages !== 'undefined' && tableauDesLargeuresEtIndicesCumulsEmballages != '') {
            lesColonnes = tableauDesLargeuresEtIndicesCumulsEmballages.split("|");
            tableauDesLargeuresEtIndicesCumulsEmballages = "";
        }
    } else if (idTableau == 'tableauListeDesOperationsWebshop') {
        if (typeof tableauDesLargeuresEtIndicesOperationsWebshop !== 'undefined' && tableauDesLargeuresEtIndicesOperationsWebshop != '') {
            lesColonnes = tableauDesLargeuresEtIndicesOperationsWebshop.split("|");
            //tableauDesLargeuresEtIndicesOperationsWebshop = "";
        }
    } else if (idTableau == 'tableauListeDesAdressesDeLivraisonWebshop') {
        if (typeof tableauDesLargeuresEtIndicesAdresseLivraison !== 'undefined' && tableauDesLargeuresEtIndicesAdresseLivraison != '') {
            lesColonnes = tableauDesLargeuresEtIndicesAdresseLivraison.split("|");
            tableauDesLargeuresEtIndicesAdresseLivraison = "";
        }
    } else if (idTableau == 'tableauListeDesDureesDemandesServices') {
        if (typeof tableauDesLargeuresEtIndicesDureeDemandesServices !== 'undefined' && tableauDesLargeuresEtIndicesDureeDemandesServices != '') {
            lesColonnes = tableauDesLargeuresEtIndicesDureeDemandesServices.split("|");
            tableauDesLargeuresEtIndicesDureeDemandesServices = "";
        }
    } else if (idTableau == 'tableauListeDesModelesEmails') {
        if (typeof tableauDesLargeuresEtIndicesDesModelesEmails !== 'undefined' && tableauDesLargeuresEtIndicesDesModelesEmails != '') {
            lesColonnes = tableauDesLargeuresEtIndicesDesModelesEmails.split("|");
            tableauDesLargeuresEtIndicesDesModelesEmails = "";
        }
    } else if (idTableau == "test") {

    }
    if (idTableau != "test") {
        settingsDeSauvegarde = $('#' + idTableau).DataTable().settings();

        iconeParametre = $('#' + settingsDeSauvegarde[0].sInstance).find(".iconeParametrage");
        iconeModeVisualisation = $('#' + settingsDeSauvegarde[0].sInstance).find(".iconeModeVisualisation");
        //console.debug(settingsDeSauvegarde[0]); /*Voir l'objet dans console FF*/
        columns = settingsDeSauvegarde[0].aoColumns;
        //var i, iLen, origCol, rechercheColonne, recherche;

        oState = {
            "iCreate": new Date(2015, 1, 1).getTime(),
            "iStart": settingsDeSauvegarde[0]._iDisplayStart,
            //"iEnd": settingsDeSauvegarde[0]._iDisplayEnd,
            "iLength": settingsDeSauvegarde[0]._iDisplayLength,
            "aaSorting": (settingsDeSauvegarde[0].sDom.indexOf('R') >= 0 ? [] : $.extend(true, [], settingsDeSauvegarde[0].aaSorting)),
            //$.extend(true, [], settingsDeSauvegarde[0].aaSorting),
            "oSearch": $.extend(true, {}, settingsDeSauvegarde[0].oPreviousSearch),
            "aoSearchCols": $.extend(true, [], settingsDeSauvegarde[0].aoPreSearchCols),
            "abVisCols": [],
            "ColReorder": [],
            "ColWidth": [],
            "paramVis": (iconeParametre.attr('title') == AFFICHER_LE_PARAMETRAGE_DU_TABLEAU ? 0 : 1),
            "modeVisualisation": (typeof modeVisualisationMode2 !== 'undefined' && modeVisualisationMode2 != null ? parseInt(modeVisualisationMode2) : 1)
        };
        for (i = 0, iLen = settingsDeSauvegarde[0].aoColumns.length; i < iLen; i++) {
            // abVisCols
            oState.abVisCols.push(settingsDeSauvegarde[0].aoColumns[i].bVisible);

            //Supprimer filtre libre si masquage colonne
            if (settingsDeSauvegarde[0].sDom.indexOf('R') >= 0) {

                origCol = settingsDeSauvegarde[0].aoColumns[i]._ColReorder_iOrigCol;
                recherche = settingsDeSauvegarde[0].aoPreSearchCols[origCol].sSearch;
                rechercheColonne = (recherche.indexOf('[') >= 0 && recherche.indexOf(']') >= 0 ? recherche.substring(recherche.indexOf('['), recherche.indexOf(']') + 1) : "");
                recherche = (rechercheColonne != "" ? recherche.replace(rechercheColonne, "") : recherche);

                oState.aoSearchCols[origCol].sSearch = (settingsDeSauvegarde[0].aoColumns[i].bVisible ? settingsDeSauvegarde[0].aoPreSearchCols[origCol].sSearch : recherche);

                // ColReorder
                oState.ColReorder.push(origCol);
                if (lesColonnes.length > 0) {
                    colonneEnCours = lesColonnes[origCol].split(";");
                    oState.ColWidth.push(colonneEnCours[1].ltrim().rtrim());
                }
            } else {

                //Supprimer filtre libre si masquage colonne
                recherche = settingsDeSauvegarde[0].aoPreSearchCols[i].sSearch;
                rechercheColonne = (recherche.indexOf('[') >= 0 && recherche.indexOf(']') >= 0 ? recherche.substring(recherche.indexOf('['), recherche.indexOf(']') + 1) : "");
                recherche = (rechercheColonne != "" ? recherche.replace(rechercheColonne, "") : recherche);

                oState.aoSearchCols[i].sSearch = (settingsDeSauvegarde[0].aoColumns[i].bVisible ? settingsDeSauvegarde[0].aoPreSearchCols[i].sSearch : recherche);
                if (lesColonnes.length > 0) {
                    colonneEnCours = lesColonnes[i].split(";");
                    oState.ColWidth.push(colonneEnCours[1].ltrim().rtrim());
                }
            }

        }
        for (i = 0, iLen = oState.aoSearchCols.length; i < iLen; i++) {
            oState.aoSearchCols[i].pSearch = [];
            expression = "_" + i + ";";
            reg = new RegExp(expression, 'g');
            trouverLigne = false;
            m = 0;
            if (recherchesParIntervalles != "" && reg.test(recherchesParIntervalles)) {
                lignesRecherche = recherchesParIntervalles.split('_');
                nbLignes = lignesRecherche.length;
                expression = "^" + i + ";";
                reg = new RegExp(expression, 'g');
                while (!trouverLigne && m < nbLignes) {
                    if (reg.test(lignesRecherche[m])) {
                        itervalles = lignesRecherche[m].split(';');
                        oState.aoSearchCols[i].pSearch.push(itervalles[1]);
                        oState.aoSearchCols[i].pSearch.push(itervalles[2]);
                        trouverLigne = true;
                    }
                    m++;

                }
            }
        }
        if (idTableau.indexOf("moduleConseilAssocieDescriptif") >= 0) {
            oState.ColWidth = [];
        }
        if (settingsDeSauvegarde[0].sDom.indexOf('R') >= 0) {
            $.each(settingsDeSauvegarde[0].aaSorting, function (i, col) {
                oState.aaSorting.push(col[i] >= columns.length ? [i, col[1]] : col);
            });
        }

        // pour la recherche globale coté liste des produit webshop 
        if (idTableau == 'tableauListeDesProduits') {
            oState.oSearch.sSearch = '';
            if (typeof zoneDeRecherche !== 'undefined') {
                zoneDeRecherche = "";
                $('#rechercheLignes').val(zoneDeRecherche);
                $('.annulerRechercheWebshop').hide();
            }
        }
        etatEnJSON = JSON.stringify(oState);
        if (comparerLesVariablesConfigurationTableaux(idTableau, etatEnJSON) == true
        || idTableau == 'tableauListeDesProduits'
        || idTableau == 'tableauListePanier'
        || idTableau == 'tableauListeClientsWebshop'
        || idTableau == 'tableauListeDesOperationsWebshop'
        || idTableau == 'tableauListeDesAdressesDeLivraisonWebshop') {
            sauvegarderEtatTableau(idTableau, etatEnJSON, sauvegardeCallback, blocIsertion);
        }


    }

}

function reInitialiserEtat(idTableau, indiceCheckBox) {
    if (idTableau == 'tableauListeDesProduits'
        || idTableau == 'tableauListePanier'
    ) {
        $("#layoutAlerteReinitialiserRenommageColonne").height($("#contenuPage").height());
        $('#layoutAlerteReinitialiserRenommageColonne').fadeIn(200);
        $('#alerteReinitialiserRenommageColonne').fadeIn(200);
        $('#bouttonAnnulerRenommageColonne').show();
        $('#bouttonValiderRenommageColonne').show();
        $('#bouttonValiderRenommageColonne').attr('onclick', 'poursuivreReInitialiserEtat("' + idTableau + '",' + indiceCheckBox + ');');

    } else {
        poursuivreReInitialiserEtat(idTableau, indiceCheckBox);
    }
}

function poursuivreReInitialiserEtat(idTableau, indiceCheckBox) {
    if ((idTableau == 'tableauListeDesProduits'
        || idTableau == 'tableauListePanier') && $("#reinitialiserRenommageColonne").length > 0 && $("#reinitialiserRenommageColonne").is(':checked')) {
        fermerAlerteReinitialiserRenommageColonne();
        $.ajax({
            url: '/societeEtCompte/supprimerLesRenommagesColonnesDUnTableau',
            data: {
                'idTableau': idTableau
            },
            success: function (retour) {

                if ($('#' + idTableau).find('tbody').find('tr:nth-child(1)').find('td').hasClass("dataTables_empty")) {
                    alerte(LE_TABLEAU_DOIT_AVOIR_AU_MOINS_UNE_LIGNE_REMPLIE);
                } else {
                    sauvegarderEtatTableau(idTableau, null);
                    if (typeof indiceCheckBox !== 'undefined') {
                        $.fn.dataTableExt.oApi.fnReinitiateDataTable(idTableau, indiceCheckBox);
                    } else {
                        $.fn.dataTableExt.oApi.fnReinitiateDataTable(idTableau);
                    }
                }
                if (idTableau == 'tableauListePanier') {
                    visualiserPanier('FOURNISSEUR');
                } else if (idTableau == 'tableauListeDesProduits') {
                    modifierModeDAffichageWebShop('Liste');
                }
            }
        });

    } else {
        if ($("#reinitialiserRenommageColonne").length > 0) {
            fermerAlerteReinitialiserRenommageColonne();
        }
        if ($('#' + idTableau).find('tbody').find('tr:nth-child(1)').find('td').hasClass("dataTables_empty")) {
            alerte(LE_TABLEAU_DOIT_AVOIR_AU_MOINS_UNE_LIGNE_REMPLIE);
        } else {
            sauvegarderEtatTableau(idTableau, null);
            if (typeof indiceCheckBox !== 'undefined') {
                $.fn.dataTableExt.oApi.fnReinitiateDataTable(idTableau, indiceCheckBox);
            } else {
                $.fn.dataTableExt.oApi.fnReinitiateDataTable(idTableau);
            }
        }
    }


}
function sauvegarderEtatTableau(id, etat, sauvegardeCallback, blocIsertion) {//moduleConseilAssocieDescriptif_tableauListeDesConseils_enConsultation
    $.ajax({
        url: '/societeEtCompte/sauvegarderEtatTableau',
        data: {
            'id': (id.indexOf("moduleConseilAssocieDescriptif_tableauDesDescriptifs") >= 0 && typeof estVisibleCheckboxAssocie !== 'undefined' && estVisibleCheckboxAssocie == false ? "moduleConseilAssocieDescriptif_tableauDesDescriptifs_enConsultation" :
                (id.indexOf("moduleConseilAssocieDescriptif_tableauDesDescriptifs") >= 0 ? "moduleConseilAssocieDescriptif_tableauDesDescriptifs" :
                (id.indexOf("moduleConseilAssocieDescriptif_tableauListeDesConseils") >= 0 && typeof estVisibleCheckboxAssocie !== 'undefined' && estVisibleCheckboxAssocie == false ? "moduleConseilAssocieDescriptif_tableauListeDesConseils_enConsultation" :
                (id.indexOf("moduleConseilAssocieDescriptif_tableauListeDesConseils") >= 0 ? "moduleConseilAssocieDescriptif_tableauListeDesConseils" :
                id)))),
            'etat': (etat == null ? JSON.stringify('') : etat)
        },
        success: function (configurationTableauxDeLUtilisateur) {
            if (configurationTableauxDeLUtilisateur != "") {
                //                if (id == 'tableauListeClientsWebshop') {
                //                    configurationTableauxAutresComptes = configurationTableauxDeLUtilisateur;
                //                } else {
                configurationTableaux = configurationTableauxDeLUtilisateur;
                //                }
                initialiserLesVariablesConfigurationTableaux();

                if (etat != null) {
                    if (id == 'tableauListeDesProduits' || id == 'tableauListePanier') {
                        if (nommagesColonnes != "") {
                            $.ajax({
                                url: '/webshop/renommageDesColonnes?numeroSociete=' + numeroSociete,
                                data: {
                                    'stringRenommage': nommagesColonnes,
                                    'idTableau': id
                                },
                                async: false,
                                success: function (retourServeur) {

                                    masquerChargement();
                                    alerte(ETAT_TABLEAU_SAUVEGARDE, 'confirmation');
                                }
                            });

                        } else {
                            masquerChargement();
                            alerte(ETAT_TABLEAU_SAUVEGARDE, 'confirmation');
                        }
                        if (id == 'tableauListeDesProduits') {
                            modifierModeDAffichageWebShop('Liste');
                        } else if (id == 'tableauListePanier') {
                            visualiserPanier('FOURNISSEUR');
                        }
                    } else if (id == 'listeDesLargeursColonnes' || id == 'tableauListeDesOperationsWebshop' || id == 'tableauListeClientsWebshop' || id == 'tableauListeDesAdressesDeLivraisonWebshop') {
                        masquerChargement();
                        if (id == 'tableauListeClientsWebshop' || id == 'tableauListeDesOperationsWebshop' || id == 'tableauListeDesAdressesDeLivraisonWebshop') {
                            alerte(ETAT_TABLEAU_SAUVEGARDE, 'confirmation');
                        }
                    }
                    //cas descriptifsConseils avec insertion tableau + mise à jour état
                    if (typeof sauvegardeCallback !== 'undefined' && sauvegardeCallback != null) {
                        sauvegardeCallback(blocIsertion);
                    }
                } else {
                    alerte(ETAT_TABLEAU_A_ETE_REINITIALISE, 'confirmation');
                    if (id == 'tableauListeDesProduits' || id == 'tableauListeClientsWebshop' || id == 'tableauListeDesOperationsWebshop' || id == 'tableauListePanier' || id == 'tableauListeDesAdressesDeLivraisonWebshop') {
                        masquerChargement();
                    }
                }

            } else {
                alerte(ERREUR_ETAT_TABLEAU_SAUVEGARDE, 'erreur');
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {

            if ((jqXHR.status !== 0 && est_fireFox) || est_fireFox == false) {
                alerte(ERREUR_ETAT_TABLEAU_SAUVEGARDE, 'erreur');
            }
        }
    });

}


function appliquerLesLargeurs(idTableau, largeursCololonnes, nommagesColonnes) {
    lesColonnesReordonnees = [];
    lesColonnes = largeursCololonnes.split("|");
    if (typeof nommagesColonnes !== 'undefined') {
        lesColonnesRenommees = nommagesColonnes.split("|");
    } else {
        lesColonnesRenommees = [];
    }
    contenuColonne = [];
    if (idTableau == 'moduleDescriptif_tableauListeDesBDDVegetalesEnPreselection'
    || idTableau == 'moduleDescriptif_tableauListeDesBDDVegetalesEnRattachement'
    || idTableau == 'moduleDescriptif_tableauListeDesBDDVegetales'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifsEnRattachement'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifsEnPreselection'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifs') {
        titresColonnes = titresColonnesDescriptifs;
    } else if (idTableau == 'moduleValeur_tableauListeDeValeurs'
    || idTableau == 'moduleValeur_tableauListeDeValeursVlv'
    || idTableau == 'moduleValeur_tableauListeDeValeursReferentes') {
        titresColonnes = titresColonnesValeurs;
    } else if (idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesVlv'
    || idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategories'
    || idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesReferentes') {
        titresColonnes = titresColonnesCriteresCategories;
    } else if (idTableau == 'tableauListeDesCategoriesDescriptifs') {
        titresColonnes = titresColonnesCategorieDescriptifs;
    } else if (idTableau == 'moduleMediaCategorie_tableauListeDesCategoriesMedias'
    || idTableau == 'moduleMediaCategorie_tableauListeDesCategoriesMediasVlv') {
        titresColonnes = titresColonnesCategorieMedias;
    } else if (idTableau == 'tableauListeDesTypesDeConseils') {
        titresColonnes = titresColonnesConseilsTypes;
    } else if (idTableau == 'tableauListeDesTypesInfoComplementaireConseil') {
        titresColonnes = titresColonnesConseilInfoComplementaireTypes;
    } else if (idTableau == 'tableauListeDesInfosComplementaireConseil') {
        titresColonnes = titresColonnesConseilInfoComplementaires;
    } else if (idTableau == 'copyrights') {
        titresColonnes = titresColonnesCopyrights;
    } else if (idTableau == 'moduleCritere_tableauListeDeCriteres'
    || idTableau == 'moduleCritere_tableauListeDeCriteresVlv'
    || idTableau == 'moduleCritere_tableauListeDeCriteresReferentes'
    || idTableau == 'moduleCritere_tableauListeDeCriteresWebshop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresWebshopVlv'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitWebshop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitWebshopVlv'

    || idTableau == 'moduleCritere_tableauListeDeCriteresAppShop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresAppShopVlv'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitAppShop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitAppShopVlv'

    || idTableau == 'moduleCritere_tableauListeDeCriteresHortibook') {
        titresColonnes = titresColonnesCritere;
    } else if (idTableau == 'lieux') {
        titresColonnes = titresColonnesLieux;
    } else if (idTableau == 'moduleMedia_tableauListeDeMedias'
    || idTableau == 'moduleConseil_tableauListeDesMedias'
    || idTableau == 'moduleDescriptif_tableauListeDeMedias'
    || idTableau == 'moduleMedia_tableauListeDeMediasVlv'
    || idTableau == 'moduleMedia_tableauListeDeMediasReferente') {
        titresColonnes = titresColonnesMedia;
    } else if (idTableau == 'moduleLangue_tableauListeDesEntitees') {
        titresColonnes = titresColonnesEntiteesTraduction;
    } else if (idTableau == 'moduleLangue_tableauListeDesLangues') {
        titresColonnes = titresColonnesTraduction;
    } else if (idTableau == 'moduleLangue_tableauEditerTraduction') {
        titresColonnes = titresColonnesEditerTraduction;
    } else if (idTableau == 'tableauListeDesConseils'
    || idTableau == 'moduleConseilAssocieDescriptif_tableauListeDesConseils') {
        titresColonnes = titresColonnesConseil;
    } else if (idTableau == 'tableauListeDesCatalogues') {
        titresColonnes = titresColonnesCatalogues;
    } else if (idTableau == 'tableauLignesDeCatalogue') {
        titresColonnes = titresColonnesLignesCatalogue;
    } else if (idTableau == 'tableauListeDesComptesBancaires') {
        titresColonnes = titresColonnesComptesBancaires;
    } else if (idTableau == 'tableauListeDesDemandesServices'
    || idTableau == 'tableauActualise_tableauListeDesDemandesServices') {
        titresColonnes = titresColonnesDemandesServices;
    } else if (idTableau == 'natureDemandeService') {
        titresColonnes = titresColonnesNatureDemandeService;
    } else if (idTableau == 'tableauListeDesProduitsDemandeService') {
        titresColonnes = titresColonnesProduitDemandeService;
    } else if (idTableau == 'tableauListeDesCategoriesDemandeService') {
        titresColonnes = titresColonnesCategorieDemandeService;
    } else if (idTableau == 'tableauListeDesSousCategoriesDemandeService') {
        titresColonnes = titresColonnesSousCategorieDemandeService;
    } else if (idTableau == 'tableauListeDesAdressesDeLivraison') {
        titresColonnes = titresColonnesAdresseLivraison;
    } else if (idTableau == 'tableauListeTypeUniteVente'
    || idTableau == 'tableauListePresentations'
    || idTableau == "tableauListeMillesimes") {
        titresColonnes = titresColonnesDictionnaire;
    } else if (idTableau == 'tableauEletter') {
        titresColonnes = titresColonnesEletter;
    } else if (idTableau == 'tableauListeDEmailsConseilsEnvoyes') {
        titresColonnes = titresColonnesEmailsConseilsEnvoyes;
    } else if (idTableau == 'tableauGroupes'
    || idTableau == 'tableauGroupes_detailSociete') {
        titresColonnes = titresColonnesGroupe;
    } else if (idTableau == 'tableauListeDesArticles') {
        titresColonnes = titresColonnesArticles;
    } else if (idTableau == 'tableauServices') {
        titresColonnes = titresColonnesServices;
    } else if (idTableau == 'tableauMesServices') {
        titresColonnes = titresColonnesMesServices;
    } else if (idTableau == 'tableauListeDesOperationsEnvoyees') {
        titresColonnes = titresColonnesOperations;
    } else if (idTableau == 'tableauListeTaille'
    || idTableau == 'tableauListeUniteVente') {
        titresColonnes = titresColonnesTypeUniteVente;
    } else if (idTableau == 'moduleClients_tableauClients'
    || idTableau == 'moduleDemandeService_tableauClients'
    || idTableau == 'moduleAjoutGroupe_tableauClients'
    || idTableau == 'moduleAjoutGroupe_tableauClientsModifierGroupe'
    || idTableau == 'moduleConsulterGroupe_tableauClients') {
        titresColonnes = titresColonnesMesClients;
    } else if (idTableau == 'moduleComptesSecondaires_tableauListeDesComptes'
    || idTableau == 'moduleDemandeService_tableauListeDesComptes') {
        titresColonnes = titresColonnesComptes;
    } else if (idTableau == 'tableauListeDeAuthentifications') {
        titresColonnes = titresColonnesAuthentifications;
    } else if (idTableau == 'tableauListeDEmaislEnvoyes') {
        titresColonnes = titresColonnesEmailsEnvoyes;
    } else if (idTableau == 'moduleHistoriqueConsultation_tableauListeDetailsHistoriqueConsultation') {
        titresColonnes = titresColonnesHistoriqueConsultation;
    } else if (idTableau == 'tableauListeDHistoriqueDImport') {
        titresColonnes = titresColonnesHistoriqueImport;
    } else if (idTableau == 'tableauDeLogsBase') {
        titresColonnes = titresColonnesLogsDeLaBase;
    } else if (idTableau == 'tableauListeParametresApplication') {
        titresColonnes = titresColonnesParametresDeLApplication;
    } else if (idTableau == 'tableauListeDesProduits') {
        titresColonnes = titresColonnesProduits;
    } else if (idTableau == 'tableauListePanier' || idTableau == 'tableauListeRecapPanier') {
        titresColonnes = titresColonnesPanier;
    } else if (idTableau == 'tableauListeClientsWebshop') {
        titresColonnes = titresColonnesClientWebshop;
    } else if (idTableau == 'tableauListeDesComptesAAdministrer'
    || idTableau == 'tableauComptesConnectes') {
        titresColonnes = titresColonnesCompteAAdministrer;
    } else if (idTableau == 'tableauListeDesVersionsCode') {
        titresColonnes = titresColonnesVersionsCode;
    } else if (idTableau == 'tableauListeDesConsommateurs') {
        titresColonnes = titresColonnesConsommateurs;
    } else if (idTableau == 'tableauListeModesExpeditions') {
        titresColonnes = titresColonnesModesExpeditions;
    } else if (idTableau == 'tableauListeBoutiques') {
        titresColonnes = titresColonnesBoutiques;
    } else if (idTableau == 'tableauListeDesPaiements') {
        titresColonnes = titresColonnesPaiements;
    } else if (idTableau == 'tableauListeCumulsEmballages') {
        titresColonnes = titresColonnesCumulsEmballages;
    } else if (idTableau == 'tableauListeDesOperationsWebshop') {
        titresColonnes = titresColonnesOperationsWebshop;
    } else if (idTableau == 'tableauListeDesAdressesDeLivraisonWebshop') {
        titresColonnes = titresColonnesAdresseLivraison;
    } else if (idTableau == 'tableauListeDesDureesDemandesServices') {
        titresColonnes = titresColonnesDureeDemandesServices;
    } else if (idTableau == 'tableauListeDesModelesEmails') {
        titresColonnes = titresColonnesDesModelesEmails;
    }

    if (largeursCololonnes != '' && largeursCololonnes != 'reinitialisé') {
        settingsDeSauvegarde = $('#' + idTableau).DataTable().settings();

        for (i = 0, iLen = settingsDeSauvegarde[0].aoColumns.length; i < iLen; i++) {

            if (settingsDeSauvegarde[0].sDom.indexOf('R') >= 0) {
                if (lesColonnes.length > 0) {
                    origCol = settingsDeSauvegarde[0].aoColumns[i]._ColReorder_iOrigCol;
                    colonneEnCours = lesColonnes[origCol].split(";");
                    if (settingsDeSauvegarde[0].aoColumns[i].bVisible) {
                        lesColonnesReordonnees.push(colonneEnCours[1].ltrim().rtrim());
                    }
                }
            } else {
                if (lesColonnes.length > 0) {
                    colonneEnCours = lesColonnes[i].split(";");
                    if (settingsDeSauvegarde[0].aoColumns[i].bVisible) {
                        lesColonnesReordonnees.push(colonneEnCours[1].ltrim().rtrim());
                    }
                }
            }

        }

        //titresColonnes
        for (i = 0, iLen = titresColonnes.length; i < iLen; i++) {
            lesTitresColonnes = titresColonnes[i].split(";");
            colonneEnCours = lesColonnes[i].split(";");
            lesTitresColonnes[3] = colonneEnCours[1].ltrim().rtrim();
            titresColonnes[i] = lesTitresColonnes.join(";");
        }
        j = 1;
        for (i = 0, iLen = lesColonnesReordonnees.length; i < iLen; i++) {

            if (parseInt(lesColonnesReordonnees[i]) > 0) {
                if ($('#' + idTableau).find('thead').find('th:nth-child(' + (j) + ')').length > 0) {
                    idClass = $('#' + idTableau).find('thead').find('th:nth-child(' + (j) + ')').attr("class").match(/width[\w-]*\b/);
                    if (idClass == null || idClass.length == 0) {
                        $('#' + idTableau).find('tbody').find('tr').find('td:nth-child(' + (j) + ')').each(function () {
                            largeurClass = $(this).attr("class").match(/width[\w-]*\b/);
                            if (largeurClass != null && largeurClass.length > 0) {
                                idClass = largeurClass;

                            }

                        });
                    }
                    if (idClass != null && idClass.length > 0) {
                        $('#' + idTableau).find('thead').find('th:nth-child(' + (j) + ')').removeClass(idClass[0]);
                        $('#' + idTableau).find('tfoot').find('th:nth-child(' + (j) + ')').removeClass(idClass[0]);
                        if ($('#' + idTableau).find('tbody').find('tr').find('.dataTables_empty').length == 0) {

                            $('#' + idTableau).find('tbody').find('tr').find('td:nth-child(' + (j) + ')').removeClass(idClass[0]);
                        } else {
                            //alert("vide");
                        }
                    } else {
                        if ($('#' + idTableau).find('tbody').find('tr').length > 0 && $('#' + idTableau).find('tbody').find('tr').find('.dataTables_empty').length == 0) {
                            $('#' + idTableau).find('tbody').find('tr').find('td:nth-child(' + (j) + ')')[0].className = $('#' + idTableau).find('tbody').find('tr').find('td:nth-child(' + (j) + ')')[0].className.replace(/\bwidth.*?\b/g, '');
                        } else {
                            //alert("vide2");
                        }
                    }

                    $('#' + idTableau).find('thead').find('th:nth-child(' + (j) + ')').css({
                        "min-width": lesColonnesReordonnees[i] + "px",
                        "max-width": lesColonnesReordonnees[i] + "px",
                        "width": lesColonnesReordonnees[i] + "px"
                    });
                    /*,
                    "word-wrap": "break-word"*/

                    $('#' + idTableau).find('tfoot').find('th:nth-child(' + (j) + ')').css({
                        "min-width": lesColonnesReordonnees[i] + "px",
                        "max-width": lesColonnesReordonnees[i] + "px",
                        "width": lesColonnesReordonnees[i] + "px"
                    });

                    if ($('#' + idTableau).find('tbody').find('tr').find('.dataTables_empty').length == 0) {
                        $('#' + idTableau).find('tbody').find('tr').find('td:nth-child(' + (j) + ')').css({
                            "min-width": lesColonnesReordonnees[i] + "px",
                            "max-width": lesColonnesReordonnees[i] + "px",
                            "width": lesColonnesReordonnees[i] + "px",
                            "word-wrap": "break-word"
                        });

                    } else {
                        //alert("vide3");
                    }
                } else {
                }
                j++;
            }



        }


    }
    if (lesColonnesRenommees.length > 0) {
        for (i = 0, iLen = lesColonnesRenommees.length - 1; i < iLen; i++) {
            contenuColonne = lesColonnesRenommees[i].split(";");
            contenuColonne[1] = contenuColonne[1].replaceAll("_", "");
            $('#' + idTableau).find('thead').find("[data-orig-col-header='" + contenuColonne[1] + "']").html(contenuColonne[0]);
        }
    }


    //A retirer
    //   if (idTableau == "tableauListeDesProduits") {
    //        $('.grilleTarifaireModeColonne').parent().parent().parent().find('.prixStyle').addClass('grilleListe');
    //        //code ajouter pour aligner la colonne de prix cas de affichageGrilleTarifaireModeListe == Modele.ParametreValeurBS.COMPLETE_EN_COLONNE (j'ai éliminer le padding par défaut qui est de (18px à gauche et à droite ) et je l'ai ajouter dans le width
    //        
    //        var newWidth = $('.grilleListe').width() + 16;
    //        $('.grilleListe').css('width', newWidth + 'px');
    //        $('.grilleListe').css('min-width', newWidth + 'px');
    //        $('.grilleListe').css('max-width', newWidth + 'px');
    //     
    //    }

}



function sauvegarderEtatTableauFixe(idTableau) {
    settingsDeSauvegarde = $('#' + idTableau).DataTable().settings();
    //console.debug(oSettings); /*Voir l'objet dans console FF*/
    // var iconeParametre = $('#' + settingsDeSauvegarde[0].sInstance).find(".iconeParametrage");

    // var i, iLen//, bInfinite = oSettings.oScroll.bInfinite;
    oState = {
        "iCreate": new Date().getTime(),
        "iStart": settingsDeSauvegarde[0]._iDisplayStart, //(bInfinite ? 0 : oSettings._iDisplayStart),
        //"iEnd": settingsDeSauvegarde[0]._iDisplayEnd, //(bInfinite ? oSettings._iDisplayLength : oSettings._iDisplayEnd),
        "iLength": settingsDeSauvegarde[0]._iDisplayLength,
        "aaSorting": $.extend(true, [], settingsDeSauvegarde[0].aaSorting),
        "oSearch": $.extend(true, {}, settingsDeSauvegarde[0].oPreviousSearch),
        "aoSearchCols": $.extend(true, [], settingsDeSauvegarde[0].aoPreSearchCols),
        "abVisCols": [],
        "ColReorder": [],
        "ColWidth": [],
        "paramVis": (iconeParametre.attr('title') == AFFICHER_LE_PARAMETRAGE_DU_TABLEAU ? 0 : 1),
        "modeVisualisation": (typeof modeVisualisationMode2 !== 'undefined' && modeVisualisationMode2 != null ? parseInt(modeVisualisationMode2) : 1)
    };

    for (i = 0, iLen = settingsDeSauvegarde[0].aoColumns.length; i < iLen; i++) {
        // abVisCols
        oState.abVisCols.push(settingsDeSauvegarde[0].aoColumns[i].bVisible);

        //Supprimer filtre libre si masquage colonne
        recherche = settingsDeSauvegarde[0].aoPreSearchCols[i].sSearch;
        rechercheColonne = (recherche.indexOf('[') >= 0 && recherche.indexOf(']') >= 0 ? recherche.substring(recherche.indexOf('['), recherche.indexOf(']') + 1) : "");
        recherche = (rechercheColonne != "" ? recherche.replace(rechercheColonne, "") : recherche);

        oState.aoSearchCols[i].sSearch = (settingsDeSauvegarde[0].aoColumns[i].bVisible ? settingsDeSauvegarde[0].aoPreSearchCols[i].sSearch : recherche);
    }
    for (i = 0, iLen = oState.aoSearchCols.length; i < iLen; i++) {
        oState.aoSearchCols[i].pSearch = [];
        expression = "_" + i + ";";
        reg = new RegExp(expression, 'g');
        trouverLigne = false;
        m = 0;
        if (recherchesParIntervalles != "" && reg.test(recherchesParIntervalles)) {
            lignesRecherche = recherchesParIntervalles.split('_');
            nbLignes = lignesRecherche.length;
            expression = "^" + i + ";";
            reg = new RegExp(expression, 'g');
            while (!trouverLigne && m < nbLignes) {
                if (reg.test(lignesRecherche[m])) {
                    itervalles = lignesRecherche[m].split(';');
                    oState.aoSearchCols[i].pSearch.push(itervalles[1]);
                    oState.aoSearchCols[i].pSearch.push(itervalles[2]);
                    trouverLigne = true;
                }
                m++;

            }
        }
    }
    etatEnJSON = JSON.stringify(oState);

    //alert(etatEnJSON); /*Voir l'état*/
    sauvegarderEtatTableau(idTableau, etatEnJSON);


}

function comparerLesVariablesConfigurationTableaux(idTableau, etat) {
    trouve = false;
    differents = false;
    if (configurationTableaux != null && configurationTableaux != '') {
        //listeEtatsTableaux = configurationTableaux.replace(/&quot;/g, '"').split(SEPARATEUR_ETATS_TABLEAUX); PB avec les ', l'instruction suivante résoud :
        listeEtatsTableaux = $('<div>' + configurationTableaux + '</div>').text().split(SEPARATEUR_ETATS_TABLEAUX);
        cpt = 0;
        nombreEtatsTableaux = listeEtatsTableaux.length;
        while (cpt < nombreEtatsTableaux && trouve == false) {
            idPlusEtatTableau = listeEtatsTableaux[cpt].split(SEPARATEUR_ID_VALEUR)
            if (idPlusEtatTableau[0] == idTableau) {
                trouve = true;

                etatEnBase = idPlusEtatTableau[1];
                if (etatEnBase != null && JSON.stringify(etatEnBase) === JSON.stringify(etat)) {

                    differents = false;
                } else {
                    differents = true;

                }

            } else {
                differents = true;
            }
            cpt++;
        }
    } else {
        differents = true;
    }
    return differents;
}


// Gestion de modification directe sur tableau
var ancienneLigneCliquee = null;

function gestionDeCLiqueSurIcones(idHtmlTableau, renommage) {
    $(document).on('click', '#' + idHtmlTableau + ' img', function (event) {

        if (event.handled != true) {
            // Récupérer la ligne sur la quelle on a cliqué
            ligneCliquee = $(this).parents('tr')[0];

            if ($(this).attr('id') == 'modifier') {
                // Empêcher d'avoir plusieurs lignes édités en même temps
                annulerModificationAncienneLigne(idHtmlTableau);
                if (idHtmlTableau == 'lieux') {
                    modifierLigne_PageLieu();
                } else if (idHtmlTableau == 'copyrights') {
                    modifierLigne_PageCopyright();
                } else if (idHtmlTableau == 'tableauListeParametresApplication') {
                    modifierLigne_PageParametreApplication();
                } else if (idHtmlTableau == 'tableauListeTypeUniteVente' || idHtmlTableau == 'tableauListePresentations' || idHtmlTableau == 'tableauListeMillesimes') {
                    modifierLigne_PageDictionnaire();
                } else if (idHtmlTableau == 'tableauListeUniteVente' || idHtmlTableau == 'tableauListeTaille') {
                    modifierLigne_PageTailleUniteVente();
                } else if (idHtmlTableau == 'listeDesLargeursColonnes') {
                    if (typeof renommage !== 'undefined' && renommage == true) {
                        modifierLigne_PageLargeursColonnes("global");
                    } else {
                        modifierLigne_PageLargeursColonnes();
                    }
                } else if (idHtmlTableau == 'tableauListeBoutiques') {
                    modifierLigne_PageBoutique();
                } else if (idHtmlTableau == 'tableauListeDesDureesDemandesServices') {
                    modifierLigne_PageDureesDemandeService();
                }
            } else if ($(this).attr('id') == 'enregistrer') {
                if (idHtmlTableau == 'lieux') {
                    enregistrerModificationLigne_PageLieu();
                } else if (idHtmlTableau == 'copyrights') {
                    enregistrerModificationLigne_PageCopyright();
                } else if (idHtmlTableau == 'tableauListeParametresApplication') {
                    enregistrerModificationLigne_PageParametreApplication();
                } else if (idHtmlTableau == 'tableauListeTypeUniteVente' || idHtmlTableau == 'tableauListePresentations' || idHtmlTableau == 'tableauListeMillesimes') {
                    enregistrerModificationLigne_PageDictionnaire();
                } else if (idHtmlTableau == 'tableauListeUniteVente' || idHtmlTableau == 'tableauListeTaille') {
                    enregistrerModificationLigne_PageTailleUniteVente();
                } else if (idHtmlTableau == 'listeDesLargeursColonnes') {
                    if (typeof renommage !== 'undefined' && renommage == true) {
                        enregistrerModificationLigne_PageLargeursColonnes("global");
                    } else {
                        enregistrerModificationLigne_PageLargeursColonnes();
                    }
                } else if (idHtmlTableau == 'tableauListeDesDureesDemandesServices') {
                    enregistrerModificationLigne_PageDureesDemandeService();
                }
            } else if ($(this).attr('id') == 'annuler') {
                annulerModificationAncienneLigne(idHtmlTableau);
            }
            ancienneLigneCliquee = ligneCliquee;
            event.handled = true;
        }
    });
}

function gestionDeCliquesurElementTD(idHtmlTableau, renommage) {

    $(document).on('click', '#' + idHtmlTableau + ' .valeurAModifier', function (e) {
        // Si le td contient déjà un input, alors déjà en modification, pas de traitement
        if ($(this).html().indexOf('select') == -1 && $(this).html().indexOf('input') == -1 && $(this).html().indexOf('textarea') == -1) {
            annulerModificationAncienneLigne(idHtmlTableau);
            ligneCliquee = $(this).parents('tr')[0];
            celluleCliquee = $(this);
            ancienneLigneCliquee = ligneCliquee;
            if (idHtmlTableau == 'lieux') {
                modifierLigne_PageLieu();
            } else if (idHtmlTableau == 'copyrights') {
                modifierLigne_PageCopyright();
            } else if (idHtmlTableau == 'tableauListeParametresApplication') {
                modifierLigne_PageParametreApplication();
            } else if (idHtmlTableau == 'tableauListeTypeUniteVente' || idHtmlTableau == 'tableauListePresentations' || idHtmlTableau == 'tableauListeMillesimes') {
                modifierLigne_PageDictionnaire();
            } else if (idHtmlTableau == 'listeDesLargeursColonnes') {
                if (typeof renommage !== 'undefined' && renommage == true) {
                    modifierLigne_PageLargeursColonnes("global");
                } else {
                    modifierLigne_PageLargeursColonnes();
                }
            } else if (idHtmlTableau == 'tableauListeDesDureesDemandesServices') {
                modifierLigne_PageDureesDemandeService();
            }
        }
    });


}
function gestionDeCliquesurElementTDMultiple(idHtmlTableau) {

    $(document).on('click', '#' + idHtmlTableau + ' .valeurAModifierMultiple', function (e) {

        // Si le td contient déjà un input, alors déjà en modification, pas de traitement

        if ($(this).html().indexOf('select') == -1 && $(this).html().indexOf('input') == -1 && $(this).html().indexOf('textarea') == -1) {
            annulerModificationAncienneLigne(idHtmlTableau);
            ligneCliquee = $(this).parents('tr')[0];
            ancienneLigneCliquee = ligneCliquee;
            if (idHtmlTableau == 'tableauListeUniteVente' || idHtmlTableau == 'tableauListeTaille') {
                modifierLigne_PageTailleUniteVente(this);
            }

        }
    });


}

function annulerModificationAncienneLigne(idHtmlTableau, colonnes) {
    oTable = $('#' + idHtmlTableau).DataTable({ 'retrieve': true });
    colonnesCachees = false;
    // cas du 1er appel
    if (ancienneLigneCliquee != null) {
        donneesDeLaLigne = oTable.row(ancienneLigneCliquee).data();
        // nombreColonnes = $('>td', ancienneLigneCliquee).length;
        nombreColonnes = donneesDeLaLigne.length;
        if (nombreColonnes > $('>td', ancienneLigneCliquee).length) {
            colonnesCachees = true;
        }

        for (i = 0; i < nombreColonnes; i++) {
            // A FAIRE --> détailler les paramètres de la fonction
            if (colonnes != null && colonnesCachees) {
                if (jQuery.inArray(i, colonnes)) {
                    oTable.cell(ancienneLigneCliquee, i).data("");
                } else {
                    oTable.cell(ancienneLigneCliquee, i).data(donneesDeLaLigne[i]);
                }
            } else {
                oTable.cell(ancienneLigneCliquee, i).data(donneesDeLaLigne[i]);
            }

            //fnUpdate(donneesDeLaLigne[i], ancienneLigneCliquee, i, false);
        }
        oSetting = oTable.settings()[0];
        tableauindice = retournerIndiceTableau(idHtmlTableau);
        pageSelectionnee = retournerdebutPage(tableauindice);
        oTable.settings()[0].iInitDisplayStart = oTable.settings()[0]._iDisplayStart;
        oTable.draw();
    }
}

function evenementToucheEntreeOuEchap(toucheAppuyee, idHtmlTableau, mode) {

    // 13 = entrée, 27 = echap
    if (toucheAppuyee == CODE_TOUCHE_ENTREE) {
        if (idHtmlTableau == 'lieux') {
            enregistrerModificationLigne_PageLieu();
        } else if (idHtmlTableau == 'copyrights') {
            enregistrerModificationLigne_PageCopyright();
        } else if (idHtmlTableau == 'tableauListeParametresApplication') {
            enregistrerModificationLigne_PageParametreApplication();
        } else if (idHtmlTableau == 'tableauListeTypeUniteVente' || idHtmlTableau == 'tableauListePresentations' || idHtmlTableau == 'tableauListeMillesimes') {
            enregistrerModificationLigne_PageDictionnaire();
        } else if (idHtmlTableau == 'tableauListeUniteVente' || idHtmlTableau == 'tableauListeTaille') {
            enregistrerModificationLigne_PageTailleUniteVente();
        } else if (idHtmlTableau == 'tableauLargeurColonneListe') {
            if (typeof mode !== 'undefined') {
                enregistrerModificationLigne_PageLargeursColonnes(mode);
            } else {
                enregistrerModificationLigne_PageLargeursColonnes();
            }

        } else if (idHtmlTableau == 'tableauListeDesDureesDemandesServices') {
            enregistrerModificationLigne_PageDureesDemandeService();
        }
    } else if (toucheAppuyee == CODE_TOUCHE_ECHAP) {
        if (idHtmlTableau == 'tableauListeUniteVente' || idHtmlTableau == 'tableauListeTaille') {
            annulerModificationAncienneLigne(idHtmlTableau, colonneCachee);
        } else {
            annulerModificationAncienneLigne(idHtmlTableau);
        }


    }
}


Array.prototype.unique = function () {
    var a = this.concat();
    for (var i = 0; i < a.length; ++i) {
        for (var j = i + 1; j < a.length; ++j) {
            if (a[i] === a[j])
                a.splice(j--, 1);
        }
    }

    return a;
};

Array.prototype.move = function (old_index, new_index) {
    if (new_index >= this.length) {
        var k = new_index - this.length;
        while ((k--) + 1) {
            this.push(undefined);
        }
    }
    this.splice(new_index, 0, this.splice(old_index, 1)[0]);
    return this; // for testing purposes
};
// WAZ 20/06/2024 Complément S181573
// Validation du valeur de l'input
function validerValeurInput(number) {
    if (number == '') {
        return false;
    }
    return true;
}

function validerDateFormat(date) {
    //date = $('#' + champDate).val();
    if (date == '') {
        return false;
    }

    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex
    var dateTableau = date.match(rxDatePattern); // is format OK?

    if (dateTableau == null) {
        return false;
    }

    //Checks for dd/mm/yyyy format.
    dateJour = parseInt(dateTableau[1]);
    dateMois = parseInt(dateTableau[3]);
    dateAnnee = parseInt(dateTableau[5]);
    if (dateMois < 1 || dateMois > 12) {
        return false;
    } else if (dateJour < 1 || dateJour > 31) {
        return false;
    } else if ((dateMois == 4 || dateMois == 6 || dateMois == 9 || dateMois == 11) && dateJour == 31) {
        return false;
    } else if (dateMois == 2) {
        var estBissextile = (dateAnnee % 4 == 0 && (dateAnnee % 100 != 0 || dateAnnee % 400 == 0));
        if (dateJour > 29 || (dateJour == 29 && !estBissextile)) {
            return false;
        }
    }
    return true;
}


function validerDateTimeFormat(date) {
    var rxDateTimePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4}) (\d{2}):(\d{2})$/; //Declare Regex
    var dateTimeTableau = date.match(rxDateTimePattern); // is format OK?
    if (dateTimeTableau === null) {
        return false;
    }
    //Checks for dd/mm/yyyy format.
    dateTimeJour = parseInt(dateTimeTableau[1]);
    dateTimeMois = parseInt(dateTimeTableau[3]);
    dateTimeAnnee = parseInt(dateTimeTableau[5]);
    dateTimeHeure = parseInt(dateTimeTableau[6]);
    dateTimeMinute = parseInt(dateTimeTableau[7]);
    if (dateTimeMois < 1 || dateTimeMois > 12) {
        return false;
    } else if (dateTimeJour < 1 || dateTimeJour > 31) {
        return false;
    } else if ((dateTimeMois == 4 || dateTimeMois == 6 || dateTimeMois == 9 || dateTimeMois == 11) && dateTimeJour == 31) {
        return false;
    } else if (dateTimeMois == 2) {
        var estBissextile = (dateTimeAnnee % 4 == 0 && (dateTimeAnnee % 100 != 0 || dateTimeAnnee % 400 == 0));
        if (dateTimeJour > 29 || (dateTimeJour == 29 && !estBissextile)) {
            return false;
        }
    } else if (dateTimeHeure < 0 || dateTimeHeure > 59) {
        return false;
    } else if (dateTimeMinute < 0 || dateTimeHeure > 59) {
        return false;
    }
    return true;
}

function navigationInputParFlecheDansTableau(idTableau) {
    var activeX = 0, activeY = 0;
    var tdIndexes = Array(), trIndexes = Array();
    var y;
    var x;
    var indiceTD, indiceTR;
    $(document).on("click", '#' + idTableau + ' tbody tr td input', function () {
        $('#' + idTableau + ' tbody tr:not(".restrictionNavigation"):eq(0) td input').each(function (i, v) {
            tdIndexes[i] = $(this).parent().index();
        });
        $('#' + idTableau + ' tbody tr:not(".restrictionNavigation")').has('input').each(function (i, v) {
            trIndexes[i] = $(this).index();
        });
        activeX = tdIndexes.indexOf($(this).parent().index());
        activeY = trIndexes.indexOf($(this).parent().parent().index());
        indiceTD = tdIndexes[activeX];
        indiceTR = trIndexes[activeY];
        
    });

    
    $(document).on("keydown", '#' + idTableau + ' tbody tr td input', function (e) {
        activeX = tdIndexes.indexOf($(this).parent().index());
        indiceTD = tdIndexes[activeX];
        indiceTR = trIndexes[activeY];
        if (e.keyCode == 38) { // move up
            activeY = (activeY > 0) ? activeY - 1 : activeY;
            indiceTR = trIndexes[activeY];
            while ((typeof $('#' + idTableau + ' tbody tr:not(".restrictionNavigation")').eq(indiceTR).find('td:not(".nonNaviguable")').eq(indiceTD).find('input').val() === 'undefined') && activeY > 0) {
                activeY--;
                indiceTR = trIndexes[activeY];
            }
        }
        if (e.keyCode == 40) { // move down
            activeY = (activeY < trIndexes.length - 1) ? activeY + 1 : activeY;
            indiceTR = trIndexes[activeY];
            while ((typeof $('#' + idTableau + ' tbody tr:not(".restrictionNavigation")').eq(indiceTR).find('td:not(".nonNaviguable")').eq(indiceTD).find('input').val() === 'undefined') && activeY < trIndexes.length - 1) {
                activeY++;
                indiceTR = trIndexes[activeY];
            }
        }
        if (e.keyCode == 38 || e.keyCode == 40) {
            $('#' + idTableau + ' tbody tr:not(".restrictionNavigation")').eq(indiceTR).find('td:not(".nonNaviguable")').eq(indiceTD).find('input').focus();
            e.preventDefault();
        }
    });

}

function ficheArticleEnPDF(numeroArticle, cleQRCode, numeroDescriptif, numeroLangue) {
    afficherChargement();
    var windowUrl = '/article/ficheArticle?numeroArticle=' + numeroArticle + '&cleQRCode=' + cleQRCode + '&numeroDescriptif=' + numeroDescriptif + '&numeroLangue=' + numeroLangue;
    var windowReference = window.open(windowUrl, '_blank');
    windowReference.focus();

    setTimeout(function () { masquerChargement(); }, 1000);
}


function operationEnPDF(numeroOperation, typeOperation, mobile) {
    if (typeof (mobile) === "undefined") {
        mobile = false;
    }
    var fenetreDeTelechargement;
    if (numeroOperation > 0) {
        if (mobile) {
            fenetreDeTelechargement = window.open('/webshopMobile/operationEnPDF?numeroOperation=' + numeroOperation + (typeOperation ? '&typeOperation=' + typeOperation : ""), '_blank');
        } else {
            fenetreDeTelechargement = window.open('/webshop/operationEnPDF?numeroOperation=' + numeroOperation + (typeOperation ? '&typeOperation=' + typeOperation : "") + '&saisieEnModeSemaine=' + saisieEnModeSemaine +"&estRecapitulatifCommande=true", '_blank');
        }
    } else {
        alerte(VOTRE_PANIER_EST_VIDE);
    }
}

function operationEnPDFListe(numeroOperation, typeOperation, mobile) {
    if (typeof (mobile) === "undefined") {
        mobile = false;
    }
    var fenetreDeTelechargement;
    if (numeroOperation > 0) {
        if (mobile) {
            fenetreDeTelechargement = window.open('/webshopMobile/operationEnPDF?numeroOperation=' + numeroOperation + (typeOperation ? '&typeOperation=' + typeOperation : ""), '_blank');
        } else {
            fenetreDeTelechargement = window.open('/webshop/operationEnPDF?numeroOperation=' + numeroOperation + (typeOperation ? '&typeOperation=' + typeOperation : "") + '&saisieEnModeSemaine=' + saisieEnModeSemaine, '_blank');
        }
    } else {
        alerte(VOTRE_PANIER_EST_VIDE);
    }
}


function afficherSupprimerParametre(idIconeSuppression) {
    afficherLayoutPopup();
    $('#fenetreSupprimer').show(400);
    $('#boutonSupprimer').attr('onclick', "supprimerParametreValeur('" + idIconeSuppression + "');");
}

function supprimerParametreValeur(idIconeSuppression) {
    if (typeof (idIconeSuppression) === 'object') {
        iconeSuppression = $(idIconeSuppression);
    } else {
        iconeSuppression = $('#' + idIconeSuppression);
    }

    if ($(iconeSuppression).parent().find('input[id*="parametre-"]').length != 0 && $(iconeSuppression).parent().find('input[id*="parametre-"]').val() != '' && $(iconeSuppression).parent().find('input[id*="parametre-' + VALEUR_DE_TYPE_COULEUR + '-"]').length == 0) {
        $(iconeSuppression).parent().find('input[id*="parametre-"]').val('');
    }
    if ($(iconeSuppression).parent().find('input[id*="valeur-"]:checked').length != 0) {
        $(iconeSuppression).parent().find('input[id*="valeur-"]:checked').prop('checked', false);
    }
    if ($(iconeSuppression).parent().find('select[id*="parametre-"]').length != 0 && $(iconeSuppression).parent().find('select[id*="parametre-"]').val() != PREMIERE_VALEUR_COMBOBOX) {
        if ($(iconeSuppression).parent().find('select[id*="parametre-"] .aUnValeurParDefaut').length != 0 && $(iconeSuppression).parent().find('select[id*="parametre-"]').val() != $(iconeSuppression).parent().find('select[id*="parametre-"] .aUnValeurParDefaut').val()) {
            $(iconeSuppression).parent().find('select[id*="parametre-"]').val($(iconeSuppression).parent().find('select[id*="parametre-"] .aUnValeurParDefaut').val());
        } else {
            $(iconeSuppression).parent().find('select[id*="parametre-"]').val(PREMIERE_VALEUR_COMBOBOX);
        }
    }
    if ($(iconeSuppression).parent().find('input[id*="parametre-' + VALEUR_DE_TYPE_COULEUR + '-"]').length != 0) {
        $(iconeSuppression).parent().find('.couleurValeur').css('background', $(iconeSuppression).parent().find('.couleurValeurDefaut').text());
        variableGlobale_listeDesIdParametresCouleur = variableGlobale_listeDesIdParametresCouleur.replace($(iconeSuppression).attr('id') + SEPARATEUR_SAISI, '');
        $(iconeSuppression).parent().find('input[id*="parametre-"]').val($(iconeSuppression).parent().find('.couleurValeurDefaut').text());
    }
    if ($(iconeSuppression).parent().find('input[type="file"]').length != 0) {
        $(iconeSuppression).parent().find('.miniatureImage').css('visibility', 'hidden');
        numeroParametre = $(iconeSuppression).parent().find('input[type="file"]').attr('id');
        if (variableGlobale_listeDesIdParametresSupprimes != '') {
            variableGlobale_listeDesIdParametresSupprimes += SEPARATEUR_SAISI;
        }
        variableGlobale_listeDesIdParametresSupprimes += numeroParametre;
    }

    if ($(iconeSuppression).parent().find('.parametreMail').length != 0) {
        id = $(iconeSuppression).parent().find('.parametreMail').attr('id');
        // Mot clé obligatoire
        motCle = id.split('-')[3];
        listeDeMotCle = motCle.split('  ');
        nombreMotCle = listeDeMotCle.length;
        motsClesObligatoires = '';
        cpt = 0;
        while (cpt < nombreMotCle) {
            motsClesObligatoires += ((listeDeMotCle[cpt].indexOf('[#') != -1) ? listeDeMotCle[cpt] : '');
            cpt++;
        }
        // Réinitialisation CkEditor
        CKEDITOR.instances[id].setData(
            ((typeof (logoSociete) != 'undefined') ? '<img src="' + DOMAINE + logoSociete.substring(1, logoSociete.length - 1) + '" alt="" style="float: left;" />' : '')
            + '</br></br></br></br>'
            + motsClesObligatoires
        );
        // Objet mail
        $('#objet-' + id.split('-')[2]).val('');

        numeroParametre = id.split('-')[2];
        variableGlobale_listeDesIdParametresSupprimes += numeroParametre + SEPARATEUR_SAISI;

    }

    if ($(iconeSuppression).parent().find('.parametreMailSimple').length != 0) { // parametre html sans mot clé et sans objet
        id = $(iconeSuppression).parent().find('.parametreMailSimple').attr('id');

        // Réinitialisation CkEditor
        CKEDITOR.instances[id].setData(
           '</br></br></br></br>'
        );
        numeroParametre = id.split('-')[2];
        variableGlobale_listeDesIdParametresSupprimes += numeroParametre + SEPARATEUR_SAISI;

    }

    if ($(iconeSuppression).parent().find('.parametreTextarea').length != 0) { // traitemant textarea sans cablage ckeditor

        $(iconeSuppression).parent().find('.parametreTextarea').val('');
        numeroParametre = $(iconeSuppression).parent().find('.parametreTextarea').attr('id').split('-')[2];
        variableGlobale_listeDesIdParametresSupprimes += numeroParametre + SEPARATEUR_SAISI;
    }

    if ($(iconeSuppression).parent().find('.paramereSMS').length != 0) { // traitemant textarea sans cablage ckeditor
        
        if ($(iconeSuppression).parent().find('.paramereSMS').attr('data-motcle') !== 'undefined' && $(iconeSuppression).parent().find('.paramereSMS').attr('data-motcle') != "") {
            //traitement textearea paramereSMS avec data motcle
            $(iconeSuppression).parent().find('.paramereSMS').val($(iconeSuppression).parent().find('.paramereSMS').attr('data-motcle'));
        } else {
            $(iconeSuppression).parent().find('.paramereSMS').val('');
        }
        numeroParametre = $(iconeSuppression).parent().find('.paramereSMS').attr('id').split('-')[2];
        variableGlobale_listeDesIdParametresSupprimes += numeroParametre + SEPARATEUR_SAISI;
    }

    fermerSupprimer();
    $('#layoutPopup').fadeOut(400);
}

function activerModeModal() {
    if ($("#pageMobile").length > 0) {
        $('#layoutChargementDate').css('height', document.documentElement.scrollHeight);
        $('#layoutChargementDate').fadeTo(200, 0.5, function () { });
    } else {
        if (typeof templatePersonnalise !== 'undefined' && templatePersonnalise != "") {
            $('#layoutChargementDateModal').css('height', document.documentElement.scrollHeight).css('top', 45).css("z-index", 15);
        } else {
            $('#layoutChargementDateModal').css('height', document.documentElement.scrollHeight).css('top', 30).css("z-index", 5);
        }
        $('body').css("overflow-y", "hidden");
        $('#layoutChargementDateModal').fadeTo(200, 0.5, function () { });
        $('body').scrollTop(0);
    }

    $('#ui-datepicker-div').addClass('dateModale');

}
function desactiverModeModal() {
    if ($("#pageMobile").length > 0) {
        $('#layoutChargementDate').css('height', document.documentElement.scrollHeight);
        $('#layoutChargementDate').fadeOut(200);
    } else {
        $('#layoutChargementDateModal').css('height', document.documentElement.scrollHeight).css('top', 0).css("z-index", 10);
        $('#layoutChargementDateModal').fadeOut(200);
    }
    $('body').css("overflow-y", "scroll");
    $('#ui-datepicker-div').removeClass('dateModale');
}
function testerCompteBloquer(retourServeur) {
    if (retourServeur != "") {
        if (retourServeur.indexOf('compteDesactive') >= 0) {
            valeurs = retourServeur.split('|');
            if (valeurs.length > 1) {
                alerte(valeurs[1], 'erreur');
            } else {
                alerte(COMPTE_CORRESPONDANT_AU_LOGIN_DESACTIVE, 'erreur')
            }
        } else if (retourServeur.indexOf('societeDesactive') >= 0) {
            valeurs = retourServeur.split('|');
            if (valeurs.length > 1) {
                alerte(valeurs[1], 'erreur');
            } else {
                alerte(SOCIETE_RATTACHEE_AU_LOGIN_DESACTIVE, 'erreur')
            }
        } else {
            alerte(IMPOSSIBLE_DE_SE_CONNECTER_AVEC_CE_TYPE_DE_COMPTE + ' !', 'erreur')
        }
    }
}
var testMessage;
//**************************************************************************************************** Alerte générique pour tout contexte
function preparerAlerte(message, type) {
    $('#bouttonValider').unbind();
    $('#bouttonAnnuler').unbind();
    $('#bouttonRefuser').hide();
    $('#messageAlerte').attr('class', '');
    $('#messageAlerte').html(message);
    if (type === 'temporaire') {
        $('#bouttonAnnuler').hide();
        $('#bouttonValider').hide();
        $('.iconeFermeture').hide();
        $('.titreAlerte').hide();
        $('#bouttonRefuser').hide();
        afficherAlerteTemporaire(2000, 1000);
    } else {
        $('.titreAlerte').show();
        $('.iconeFermeture').show();
        $('#bouttonValider').show();
        $('#layoutAlerte').fadeTo(200, 0.5, function () { });
        $('#alerte').fadeIn(200);
        $('#bouttonAnnuler').hide();
        if (type === 'confirmation') {
            $('#alerte').attr('class', 'alerteConfirmation');
            $('#messageAlerte').attr('class', 'logoAlerteConfirmation');
        } else if (type === 'erreur') {
            $('#alerte').attr('class', 'alerteErreur');
            $('#messageAlerte').attr('class', 'logoAlerteErreur');
        } else if (type === 'info' || type == null) {
            $('#alerte').attr('class', 'alerteInfo');
            $('#messageAlerte').attr('class', 'logoAlerteInfo');
        } else if (type === 'confirmationUtilisateur') {
            $('#alerte').attr('class', 'alerteInfo');
            $('#messageAlerte').attr('class', 'logoAlerteInfo');
            $('#bouttonAnnuler').show();
        } else if (type === 'confirmationUtilisateurAvecOptionRefus') {
            $('#alerte').attr('class', 'alerteInfo');
            $('#messageAlerte').attr('class', 'logoAlerteInfo');
            $('#bouttonAnnuler').show();
            $('#bouttonRefuser').show();
        } else if (type === 'confirmationUtilisateurSynchrone') {
            $('#alerte').attr('class', 'alerteInfo');
            $('#messageAlerte').attr('class', 'logoAlerteInfo');
            $('#bouttonAnnuler').show();
        }
    }
}
function confirmer(message, type, yesFn, noFn) {
    testMessage = message;
    // Pour que le fond transparent couvre toute la hauteur de page
    //$('#layoutAlerte').css('height', document.documentElement.scrollHeight);
    // Déclarer en position fixed désormais, donc plus besoin de l'insutruction JS
    preparerAlerte(message, type);
    $('#bouttonValider').click(yesFn);
    $('#bouttonAnnuler').click(noFn);

}
function alerte(message, type, fonctionAppelleeSiConfirmation) {
    testMessage = message;
    // Pour que le fond transparent couvre toute la hauteur de page
    //$('#layoutAlerte').css('height', document.documentElement.scrollHeight);
    // Déclarer en position fixed désormais, donc plus besoin de l'insutruction JS
    
    preparerAlerte(message, type);
    
    if (fonctionAppelleeSiConfirmation != null) {

        $('#bouttonValider').attr('onclick', 'confirmerMessageDAlerte(' + fonctionAppelleeSiConfirmation + ');');
        if (fonctionAppelleeSiConfirmation == 'validerUploadFichier') {
            $('#bouttonAnnuler').attr('onclick', '$(".conteneurDeGlissement").removeClass("conteneurActifAuMomentDeGlissementFichier"); fermerAlerte();');
        } else if (fonctionAppelleeSiConfirmation == 'rechargerPage') {
            bloquerAppelAjax = true;
        }
    } else {
        $('#bouttonValider').attr('onclick', 'fermerAlerte();');
        $('#bouttonValider').focus();
    }
    
    
}
//spéciale pour Hortibox
function alerteSpeciale(message, type, fonctionAppelleeSiConfirmation, fonctionAppelleeSiRefus, objetAppelant) {
   
    testMessage = message;
    // Pour que le fond transparent couvre toute la hauteur de page
    //$('#layoutAlerte').css('height', document.documentElement.scrollHeight);
    // Déclarer en position fixed désormais, donc plus besoin de l'insutruction JS
    preparerAlerte(message, type);

    if (fonctionAppelleeSiConfirmation != null) {
        $('#bouttonValider').attr('value', 'Oui');
        $('#bouttonValider').attr('onclick', 'confirmerMessageDAlerte(' + fonctionAppelleeSiConfirmation + ');');
        if (fonctionAppelleeSiConfirmation == 'validerUploadFichier') {
            $('#bouttonAnnuler').attr('onclick', '$(".conteneurDeGlissement").removeClass("conteneurActifAuMomentDeGlissementFichier"); fermerAlerte();');
        } else if (fonctionAppelleeSiConfirmation == 'rechargerPage') {
            bloquerAppelAjax = true;
        }

        if (fonctionAppelleeSiRefus != null) {

            $('#bouttonRefuser').attr('onclick', 'confirmerMessageDAlerte(' + fonctionAppelleeSiRefus + ');');
        }
        if (objetAppelant != null) {
            
            $('#bouttonAnnuler').attr('onclick', 'AnnulerActionHortibox()');
            $('#bouttonValider').focus();
        }
    } else {
        $('#bouttonValider').attr('onclick', 'fermerAlerte();');
        $('#bouttonValider').focus();
    }
}
function confirmerMessageDAlerte(fonctionAppelleeSiConfirmation) {
    fonctionAppelleeSiConfirmation();
    if (!$('#messageAlerte').hasClass('logoAlerteErreur')) { // Les alertes d'erreur doit se fermer par l'utilisateur lui même
        fermerAlerte();
    }
}

//**************************************************************************************************** Alerte pour contexte désactivation compte ou société

function alerte(message, type, fonctionAppelleeSiConfirmation, parametre1, parametre2, parametre3, parametre4) {
    // Pour que le fond transparent couvre toute la hauteur de page
    //$('#layoutAlerte').css('height', document.documentElement.scrollHeight);
    // Déclarer en position fixed désormais, donc plus besoin de l'insutruction JS
    //alert(parametre4);
    preparerAlerte(message, type);
    if (fonctionAppelleeSiConfirmation != null) {
        $('#bouttonValider').attr('onclick', 'confirmerMessageDAlerte(' + fonctionAppelleeSiConfirmation + ',' + parametre1 + ',' + parametre2 + ',' + parametre3 + ',"' + parametre4 + '");');
        if (fonctionAppelleeSiConfirmation == 'validerUploadFichier') {
            $('#bouttonAnnuler').attr('onclick', '$(".conteneurDeGlissement").removeClass("conteneurActifAuMomentDeGlissementFichier"); fermerAlerte();');
        } else if (fonctionAppelleeSiConfirmation == 'rechargerPage') {
            bloquerAppelAjax = true;
        }
    } else {
        $('#bouttonValider').attr('onclick', 'fermerAlerte();');
        $('#bouttonValider').focus();
    }
}

function confirmerMessageDAlerte(fonctionAppelleeSiConfirmation, parametre1, parametre2, parametre3, parametre4) {
    if (parametre3 == 'null') {
        fonctionAppelleeSiConfirmation(parametre1, parametre2);
    } else if (parametre4 == 'null') {
        fonctionAppelleeSiConfirmation(parametre1, parametre2, parametre3);
    } else {
        fonctionAppelleeSiConfirmation(parametre1, parametre2, parametre3, parametre4);
    }

    if (!$('#messageAlerte').hasClass('logoAlerteErreur')) { // Les alertes d'erreur doit se fermer par l'utilisateur lui même
        fermerAlerte();
    }
}

function alerte(message, type, fonctionAppelleeSiConfirmation, parametre1, parametre2, parametre3, parametre4, parametre5) {
    // Pour que le fond transparent couvre toute la hauteur de page
    //$('#layoutAlerte').css('height', document.documentElement.scrollHeight);
    // Déclarer en position fixed désormais, donc plus besoin de l'insutruction JS

    preparerAlerte(message, type);
    if (fonctionAppelleeSiConfirmation != null) {
        if (parametre4 == 'null' || typeof parametre4 === "undefined") {
            $('#bouttonValider').attr('onclick', 'confirmerMessageDAlerte(' + fonctionAppelleeSiConfirmation + ',' + parametre1 + ',' + parametre2 + ',' + parametre3 + ',"' + parametre4 + '");');
        } else if (parametre5 == 'null' || typeof parametre5 === "undefined") {
            $('#bouttonValider').attr('onclick', 'confirmerMessageDAlerte(' + fonctionAppelleeSiConfirmation + ',' + parametre1 + ',' + parametre2 + ',' + parametre3 + ',"' + parametre4 + '");');
        } else {
            $('#bouttonValider').attr('onclick', 'confirmerMessageDAlerte(' + fonctionAppelleeSiConfirmation + ',' + parametre1 + ',' + parametre2 + ',' + parametre3 + ',' + parametre4 + ', "' + parametre5 + '");');
        }

        if (fonctionAppelleeSiConfirmation == 'validerUploadFichier') {
            $('#bouttonAnnuler').attr('onclick', '$(".conteneurDeGlissement").removeClass("conteneurActifAuMomentDeGlissementFichier"); fermerAlerte();');
        } else if (fonctionAppelleeSiConfirmation == 'rechargerPage') {
            bloquerAppelAjax = true;
        }
    } else {
        $('#bouttonValider').attr('onclick', 'fermerAlerte();');
        $('#bouttonValider').focus();
    }

}

function confirmerMessageDAlerte(fonctionAppelleeSiConfirmation, parametre1, parametre2, parametre3, parametre4, parametre5) {

    if (parametre4 === 'null' || typeof parametre4 === "undefined") {
        fonctionAppelleeSiConfirmation(parametre1, parametre2, parametre3);
    } else if (parametre5 === 'null' || typeof parametre5 === "undefined") {
        fonctionAppelleeSiConfirmation(parametre1, parametre2, parametre3, parametre4);
    } else {
        fonctionAppelleeSiConfirmation(parametre1, parametre2, parametre3, parametre4, parametre5);
    }

    if (!$('#messageAlerte').hasClass('logoAlerteErreur')) { // Les alertes d'erreur doit se fermer par l'utilisateur lui même
        fermerAlerte();
    }
}
//**************************************************************************************************** Méthodes communes pour tous les contextes d'alerte

function fermerAlerte() {
    $('#layoutAlerte').fadeOut(200);
    $('#alerte').fadeOut(200);
}

function afficherAlerte(message, type) {
    // Pour que le fond transparent couvre toute la hauteur de page
    $('#layoutAlerte').css('height', document.documentElement.scrollHeight);

    $('#layoutAlerte').fadeTo(200, 0.5, function () { });
    $('#alerte').fadeIn(200);
    $('#messageAlerte').html(message);
    $('#bouttonAnnuler').hide();
    $('#messageAlerte').attr('class', '');

    if (type == 'confirmation') {
        $('#messageAlerte').attr('class', 'logoAlerteConfirmation');
    } else if (type == 'erreur') {
        $('#messageAlerte').attr('class', 'logoAlerteErreur');
    } else if (type == 'info' || type == null) {
        $('#messageAlerte').attr('class', 'logoAlerteInfo');
    } else if (type == 'confirmationUtilisateur') {
        $('#messageAlerte').attr('class', 'logoAlerteInfo');
        $('#bouttonAnnuler').show();
    } else if (type == 'confirmationUtilisateurSynchrone') {
        $('#messageAlerte').attr('class', 'logoAlerteInfo');
        $('#bouttonAnnuler').show();
    }
}

function afficherAlerteTemporaire(tempApparition, tempMasquage) { //temp en ms
    $('#layoutAlerte').fadeTo(tempApparition, 0.5, function () { });
    $('#alerte').fadeIn(tempApparition);
    setTimeout("$('#layoutAlerte, #alerte').fadeOut(" + tempMasquage + ")", tempMasquage);
}
function afficherSupprimerEletter(idElementASupprimer, URLApellee) {
    afficherLayoutPopup();
    $('#fenetreSupprimer').show(400);
    $('#boutonSupprimer').attr('onclick', 'supprimerEletter("' + idElementASupprimer + '", "' + URLApellee + '");');
    $('#boutonAnnulerSuppression').attr('onclick', 'fermerPopupSuppression();'); // WAZ : complément DS 188436
    $('#imageFermerPopup').attr('onclick', 'fermerPopupSuppression();'); // WAZ : complément DS 188436
    // Désactiver l'iframe Eletter en affichant l'overlay
    $('#iframeOverlay').show();
}

// WAZ : complément DS 188436
function fermerPopupSuppression() {
    // Vérifie si l'élément est visible
    if ($('#fenetreSupprimer').is(':visible')) {
        // Cache l'élément si visible
        $('#fenetreSupprimer').hide(400); // Cache avec une animation de 400ms
        $('#layoutPopup').hide(400);
        // Réactiver l'iframe en masquant l'overlay
        $('#iframeOverlay').hide();
        $('#iframeOverlayPopup').hide(); //WAZ : Masquer l'empêchement de clic en dehors de l'alerte 
    }
}

function supprimerEletter(idElementASupprimer, URLApellee) {
    afficherChargement();
    $.ajax({
        url: URLApellee,
        data: {
            'idElementASupprimer': idElementASupprimer
        },
        success: function (resultat) {
            $('#page').html(resultat);
            masquerChargement();
            fermerPopup();
            $('#iframeOverlayPopup').hide(); //WAZ : Masquer l'empêchement de clic en dehors de l'alerte 
        }
    });
}
function afficherSupprimerTemplateBeePlugin(nomTemplate, URLApellee, source) {
    afficherLayoutPopup();
    $('#fenetreSupprimer').show(400);
    $('#boutonSupprimer').attr('onclick', 'supprimerTemplateBeePlugin("' + nomTemplate + '", "' + URLApellee + '", "' + source + '");');
    // WAZ : complément DS 188436
    $('#boutonAnnulerSuppression').attr('onclick', 'fermerPopupSuppression();'); 
    $('#imageFermerPopup').attr('onclick', 'fermerPopupSuppression();');
    // Désactiver l'iframe Template BeePlugin en affichant l'overlay
    $('#iframeOverlay').show();
    $('#iframeOverlayPopup').hide();
}

function supprimerTemplateBeePlugin(nomTemplate, URLApellee, source) {
    afficherChargement();
    $.ajax({
        url: URLApellee,
        data: {
            'nomTemplate': nomTemplate,
            'source': source
        },
        success: function (resultat) {
            if (source != 'parametre') {
                $('#page').html(resultat);
            }       
            masquerChargement();
            fermerPopup();
            $('#iframeOverlayPopup').hide(); //WAZ : Masquer l'empêchement de clic en dehors de l'alerte 
        }
    });
}
function afficherSupprimer(idElementASupprimer, URLApellee, parametreGenerique) {
    afficherLayoutPopup();
    $('#fenetreSupprimer').show(400);
    if (parametreGenerique != null) {
        $('#boutonSupprimer').attr('onclick', 'supprimer("' + idElementASupprimer + '", "' + URLApellee + '", null ' + ', ' + parametreGenerique + ');');
    } else {
        $('#boutonSupprimer').attr('onclick', 'supprimer("' + idElementASupprimer + '", "' + URLApellee + '");');
    }

}
function afficherSupprimerAvecParametreString(idElementASupprimer, URLApellee, parametreGenerique) {
    afficherLayoutPopup();
    $('#fenetreSupprimer').show(400);
    if (parametreGenerique != null) {
        $('#boutonSupprimer').attr('onclick', 'supprimer("' + idElementASupprimer + '", "' + URLApellee + '", null ' + ', "' + parametreGenerique + '");');
    } else {
        $('#boutonSupprimer').attr('onclick', 'supprimer("' + idElementASupprimer + '", "' + URLApellee + '");');
    }

}
function fermerSupprimer() {
    $('#layoutSupprimer').fadeOut(200);
    $('#fenetreSupprimer').fadeOut(200);
}
/// <reference path="alerte.js" />

var objectGlobal_idElementASupprimer;
var objectGlobal_URLApellee;

var elementHortiBoxSupprime = false;

function supprimer(idElementASupprimer, URLApellee, alerteDeConfirmationSupression, parametreGenerique) {

    objectGlobal_idElementASupprimer = idElementASupprimer;
    objectGlobal_URLApellee = URLApellee;
    afficherChargement();
    $.ajax({
        url: URLApellee,
        data: {
            'idElementASupprimer': idElementASupprimer,
            'alerteDeConfirmationSupression': ((typeof (alerteDeConfirmationSupression) != 'undefined') ? alerteDeConfirmationSupression : ''),
            'parametreGenerique': parametreGenerique,
            'typeSite': (typeof (typeSite) != 'undefined') ? typeSite : ''
        },
        success: function (resultat) {
            if (resultat.indexOf('suppressionEchouee') == -1
                && resultat.indexOf('demandeDeConfirmationSupressionEnfant') == -1
                && resultat.indexOf('demandeDeConfirmationSupressionRepertoireHortibox') == -1
            ) {
                // Suppression d 'un element Hortibox
                if (URLApellee.indexOf('supprimeFichierOuDossier') != -1) {
                    if ($('.flex-container').length < 0) {
                        if ($('a[rel="' + idElementASupprimer + '"]').parent().hasClass('ligneFichier')) { // Fichier
                            $('a[rel="' + idElementASupprimer + '"]').parent().parent().hide();
                        } else {// Dossier
                            idElementLi = $('a[rel="' + idElementASupprimer + '/"]').parent().attr('id');
                            $('a[rel="' + idElementASupprimer + '/"]').parent().hide();
                        }
                    } else {

                        var tree = $("#conteneurNavigateurFichier").jstree(true);

                        if (repertoireRecementCliquee.substr(0, repertoireRecementCliquee.lastIndexOf('/')).trim() == idElementASupprimer.trim()) {
                            repertoireRecementCliquee = repertoireRecementCliquee.replaceAll("//", "/").replaceAll("\\", "/");
                            cheminPourJsTree = repertoireRecementCliquee.substr(0, repertoireRecementCliquee.lastIndexOf('/'));
                            cheminPourJsTree = cheminPourJsTree.substr(0, cheminPourJsTree.lastIndexOf('/'));
                            var node = tree.get_node(cheminPourJsTree.replaceAll("//", "/").replaceAll("/", "\\"));
                            tree.refresh_node(node);
                            naviguerVers(cheminPourJsTree, formatAffichage);
                        } else {
                            cheminPourJsTree = repertoireRecementCliquee.replaceAll('//', '/');
                            if (repertoireRecementCliquee.replaceAll('//', '/').endsWith("/")) {
                                cheminPourJsTree = repertoireRecementCliquee.substring(0, repertoireRecementCliquee.length - 1);
                            }
                            var node = tree.get_node(cheminPourJsTree.replaceAll("//", "/").replaceAll("/", "\\"));
                            tree.refresh_node(node);
                            naviguerVers(repertoireRecementCliquee, formatAffichage);
                        }
                        //                        if (typeof node !== 'undefined') {
                        //                            
                        //                        } else {
                        //                            cheminPourJsTree = cheminPourJsTree.substr(0, cheminPourJsTree.lastIndexOf('/'));
                        //                            alert(cheminPourJsTree);
                        //                            node = tree.get_node(cheminPourJsTree.replaceAll("//", "/").replaceAll("\\", "/"));
                        //                            tree.refresh_node(node);
                        //                            naviguerVers(cheminPourJsTree, "liste");
                        //                        }

                    }
                } else if (resultat.indexOf('suppressionIconeDossier') != -1) {
                    idELementARafraichir = '';
                    nombreDeNiveaux = idElementASupprimer.split('/').length;
                    cpt = 0;
                    while (cpt < nombreDeNiveaux - 1) {
                        idELementARafraichir += idElementASupprimer.split('/')[cpt] + '/';
                        cpt++;
                    }

                    if (nombreDeNiveaux != 2) {
                        rafraichirHoritiboxEnCascade(idELementARafraichir);
                    } else {
                        // navigateur fichiers
                        $('#conteneurNavigateurFichier').fileTree({ script: '/Layout/navigateurFichiers?navigateurFichiers=oui&format=page', root: 'fichier/', multiFolder: false }, function (fichier) {
                            selectionnerUnFichier(fichier);
                        });
                    }
                } else if (URLApellee.indexOf('supprimerBoutonPersonnalise') != -1) {
                    if (numeroService == ID_SERVICE_COMMUN) {
                        rafraichirBarreDeNavigation();
                    }
                    $('#page').html(resultat);
                } else {
                    $('#page').html(resultat);
                }
                alerte(ELEMENT_A_BIEN_ETE_SUPPRIME, 'confirmation');
                if (URLApellee.indexOf('supprimeFichierOuDossier') != -1) {
                    rafraichirTailleFichiersSociete();
                }
            } else if (resultat.indexOf('suppressionEchouee') != -1) {
                resultat = resultat.split('separateurSuppression');
                libelleAttachement = ((resultat[3].indexOf('libelleMasculin') != -1) ? SONT_RATTACHES.toLowerCase() : SONT_RATTACHEES.toLowerCase());
                alerte(resultat[1] + ' ' + IMPOSSIBLE_A_SUPPRIMER_CAR_DES.toLowerCase() + ' ' + resultat[2].toLowerCase() + ' ' + libelleAttachement + '. </br>', 'erreur');
            } else if (resultat.indexOf('demandeDeConfirmationSupressionEnfant') != -1) {
                resultat = resultat.split('separateurSuppression');
                libelleAttachement = ((resultat[3].indexOf('libelleMasculin') != -1) ? SONT_RATTACHES.toLowerCase() : SONT_RATTACHEES.toLowerCase());
                alerte(resultat[1] + ' ' + IMPOSSIBLE_A_SUPPRIMER_CAR_DES.toLowerCase() + ' ' + resultat[2].toLowerCase() + ' ' + libelleAttachement + '. </br>' + VOULEZ_VOUS_LES_SUPPRIMER_D_ABORD + ' ?', 'confirmationUtilisateur', 'confirmerSupression');
            } else if (resultat.indexOf('demandeDeConfirmationSupressionRepertoireHortibox') != -1) {
                resultat = resultat.split('separateurSuppression');
                alerte(resultat[1] + '. </br>' + CONFIRMEZ_LA_SUPPRESSION + ' ?', 'confirmationUtilisateur', 'confirmerSupression');
            }
            masquerChargement();
            fermerPopup();
        }
    });
}

function confirmerSupression() {
    supprimer(objectGlobal_idElementASupprimer, objectGlobal_URLApellee, 'confirmationSupression');
}
var valeurTri = "";
var pageCouranteMozaique = 1;
var numeroPage = 1;
var reinitialiserPaginationListeProduit = false;
var catalogueCocherStringify = new Array();
var catalogueCocher = new Array();
var filtersStringify = new Array();
var filtresCocher = new Array();
var filtreCritereValeurCocherStringify = new Array();
var filtreCritereValeurCocher = new Array();
var filtresArticleCritereXXCocherStringify = new Array();
var filtresArticleCritereXXCocher = new Array();
var filtresTaillePresentationCocherStringify = new Array();
var filtresTaillePresentationCocher = new Array();
var listeNomFiltreCritereValeur = new Array();
var listeIdFiltreCritereValeur = new Array();
var listecodeFamillesSelectionnee = new Array();
var listeNomCritere = new Array();
var listeNomCatalog = new Array();
var listeNomFamille = new Array();
var listeNomSurFamille = new Array();
var listeNomCritereArticle = new Array();
var listeNomTaillePresentation = new Array();
var XHR = new Array();
var typeAnnulation = 0;
var nommagesColonnes;
var zoneDeRecherche = "";
var listeDesNumerosExterneCataloguesNonValides = new Array();
var aAssortiment = false;
var activerAllerVersLeHaut = "";
var testSurIE = false;
var positionScroll = 0;
var appelExterneFait = false;
var numeroArticleVisibleEnDetail = -1;
var numeroCatalogueCocheParAppelExterne = -1;
var connexionDeconnexion = false;
var myTableProduits;
var nbElements = 0;
var largeurTableau = 0;
var pageSize;
var initializedDX = false;
function initialiserAccueilWebShop(messageDeRetourPaiement, messageErreurAccesExterne) {
    allerVersLeHaut();
    activerLesChampsDePanier();
    testerCompteBloquer(messageErreurSuiteConnexionDirecte);
    $('#chargement').addClass("webshopChargement");
    if ($.cookie('infosCompte') == null) {
        demarrerOuRedemarrerCompteurTimeOut();
    }
    nommagesColonnes = "";
    catalogueCocher = [];
    catalogueCocherStringify = "[]";
    $(document).on("keydown", function (e) {
        if (e.which === 8 && !$(e.target).is("input, textarea")) {
            e.preventDefault();
        }
    });

    $('.imageClickable').click(function (e) {
        window.open($(this).data("lien"), '_blank')
    });


    $('#detailsPanier').draggable({
        handle: '#titreDetailsPanier', // Draggable seulement depuis le titre du popup
        containment: 'body' // Pour empêcher la sortie de l'élément hors de la page
    });
    $('#justificationsPrix').draggable({
        handle: '#titrejustificationPrix', // Draggable seulement depuis le titre du popup
        containment: 'body' // Pour empêcher la sortie de l'élément hors de la page
    });
    $('#cumulsEmballages').draggable({
    });
    $('#cumulsEmballages').resizable();
    initialiserCalendrier('webshop');
    $('.ui-datepicker-trigger').attr('src', '/ressource/image/webshop' + templatePersonnalise + '/calendrier.png');
    $('#login').focus(function () {
        value = $('#login').val();
        if (value.indexOf(LOGIN_OU_MOT_DE_PASSE_INCORRECT) >= 0) {
            $('#login').val("");
            $('#login').css('color', '#fff');
        }
        if (templatePersonnalise != "" && $('#login').hasClass('error')) {
            $('#loginErreur').hide();
            $('#motDePasse').removeClass('error');
            $('#login').removeClass('error');
        }
    });
    $('#loginBox').focus(function () {
        value = $('#loginBox').val();
        if (value.indexOf(LOGIN_OU_MOT_DE_PASSE_INCORRECT) >= 0) {
            $('#loginBox').val("");
        }
        if (templatePersonnalise != "" && $('#loginBox').hasClass('error')) {
            $('#loginBoxErreur').hide();
            $('#motDePasseBox').removeClass('error');
            $('#loginBox').removeClass('error');
        }
    });

    $('#detailsPanier').draggable({
        handle: '#titreDetailsPanier', // Draggable seulement depuis le titre du popup
        containment: 'body' // Pour empêcher la sortie de l'élément hors de la page
    });
    $('#justificationsPrix').draggable({
        handle: '#titrejustificationPrix', // Draggable seulement depuis le titre du popup
        containment: 'body' // Pour empêcher la sortie de l'élément hors de la page
    });
    $('#cumulsEmballages').draggable({
    });
    $('#cumulsEmballages').resizable();
    initialiserCalendrier('webshop');
    $('.ui-datepicker-trigger').attr('src', '/ressource/image/webshop' + templatePersonnalise + '/calendrier.png');
    $('#login').focus(function () {
        value = $('#login').val();
        if (value.indexOf(LOGIN_OU_MOT_DE_PASSE_INCORRECT) >= 0) {
            $('#login').val("");
            $('#login').css('color', '#fff');
        }
    });
    $('#loginBox').focus(function () {
        value = $('#loginBox').val();
        if (value.indexOf(LOGIN_OU_MOT_DE_PASSE_INCORRECT) >= 0) {
            $('#loginBox').val("");
        }
    });

    $('#filtreQuantite').slider({
        range: true,
        min: parseFloat(minQuantite),
        max: parseFloat(maxQuantite),
        values: [parseFloat(minQuantite), parseFloat(maxQuantite)],
        slide: function (event, ui) {
            $('.quantiteMin').text(ui.values[0]);
            $('.quantiteMax').text(ui.values[1]);
        }
    });
    $('.quantiteMin').text($('#filtreQuantite').slider("values", 0));
    $('.quantiteMax').text($('#filtreQuantite').slider("values", 1));

    if (COMMANDE_MONO_CATALOGUE == 'OUI') {
        if (echapperLeChangementDeCatalogue != 'OUI') {

            $((typeCatalogue == 'Type 5' ? '.contenuBlockMesCatalogues .checkbox:eq(0)' : '.choixCatalogue:eq(0)')).removeClass('choixCatalogueNonCocher');
            $((typeCatalogue == 'Type 5' ? '.contenuBlockMesCatalogues .checkbox:eq(0)' : '.choixCatalogue:eq(0)')).addClass('choixCatalogueCocher');
            if (typeCatalogue != 'Type 5') {
                $('.choixCatalogue:eq(0)').find('.cocherOuNon').removeClass('icon-ic-check-vide');
                $('.choixCatalogue:eq(0)').find('.cocherOuNon').addClass('icon-ic-check');
            } else {
                $('.contenuBlockMesCatalogues .checkbox:eq(0)').prop('checked', 'checked');
            }
            $('.contenuBlockCatalogue span input').prop("disabled", true);

            $('.contenuBlockCatalogue:eq(0) span input').prop("disabled", false);

        } else {
            $('#unCatalogue_' + numeroCatalogueSelectionner + ' span input').removeClass('choixCatalogueNonCocher');
            $('#unCatalogue_' + numeroCatalogueSelectionner + ' span input').addClass('choixCatalogueCocher');
            $('#unCatalogue_' + numeroCatalogueSelectionner + ' span input').prop('checked', true);
            if (typeCatalogue != 'Type 5') {
                $('#unCatalogue_' + numeroCatalogueSelectionner).find('.cocherOuNon').removeClass('icon-ic-check-vide');
                $('#unCatalogue_' + numeroCatalogueSelectionner).find('.cocherOuNon').addClass('icon-ic-check');
                //en Mono catalogue cocher le catalogue préselectionné par defaut
                $('#unCatalogue_' + numeroCatalogueSelectionner).removeClass('choixCatalogueNonCocher');
                $('#unCatalogue_' + numeroCatalogueSelectionner).addClass('choixCatalogueCocher');
            }
            $('.contenuBlockCatalogue span input').prop("disabled", true);
            $('#unCatalogue_' + numeroCatalogueSelectionner + ' span input').prop("disabled", false);

            $('#catalogue' + numeroCatalogueSelectionner).prop('checked', 'checked');
            $('#contenuBlock_catalogue_' + numeroCatalogueSelectionner + ' span input').prop("disabled", false);
            if (typeCatalogue == 'Type 5') {
                $('.contenuBlockCatalogue span input').removeAttr('disabled');//// activer les filtres famille de catalogue si le theme 5
            }
        }
    }

    pageSelectionnees = new Array();
    // si date de livraison superieur a datePeremption ou inferieur a dateExpeditionPrevue 
    $('.masquerCatalogue input').each(function () {
        $(this).prop("disabled", true);
        numCatalogue = $(this).attr('id').substring(9, $(this).attr('id').length);
        $('#contenuBlock_catalogue_' + numCatalogue + ' span input').prop("disabled", true);
        $('#contenuBlock_catalogue_' + numCatalogue + ' .surFamilleBox').css('opacity', '0.5');
        $('#contenuBlock_catalogue_' + numCatalogue + ' .familleBox').css('opacity', '0.5');
        if ($('#catalogue' + numCatalogue).is(':checked')) {
            $('#catalogue' + numCatalogue).removeAttr('checked');
        }

        $('#unCatalogue_' + numCatalogue).toggleClass('choixCatalogueNonCocher');
        $('#unCatalogue_' + numCatalogue).toggleClass('choixCatalogueCocher');
        $('#unCatalogue_' + numCatalogue).find('.cocherOuNon').toggleClass('icon-ic-check-vide');
        $('#unCatalogue_' + numCatalogue).find('.cocherOuNon').toggleClass('icon-ic-check');

        $('#contenuBlock_catalogue_' + numCatalogue + ' .surFamilleBox input').removeAttr('checked');
        $('#contenuBlock_catalogue_' + numCatalogue + ' .familleBox input').removeAttr('checked');
    });

    $('.libelleDejaCloture').each(function () {
        $(this).parent().parent().parent().parent().css({ 'opacity': '0.7', 'z-index': '13' });

        numCatalogue = $(this).parent().parent().parent().parent().attr('id').substring(12, $(this).parent().parent().parent().parent().attr('id').length);
        $('#unCatalogue_' + numCatalogue).addClass('catCloture');
        $('#contenuBlock_catalogue_' + numCatalogue + ' span input').prop("disabled", true);
        $('#contenuBlock_catalogue_' + numCatalogue + ' .surFamilleBox').css('opacity', '0.5');
        $('#contenuBlock_catalogue_' + numCatalogue + ' .familleBox').css('opacity', '0.5');
        $('#catalogue' + numCatalogue).removeAttr('checked');
        $('#catalogue' + numCatalogue).prop("disabled", true);
        $('#catalogue' + numCatalogue).parent().css('opacity', '0.7');
        $('#catalogue' + numCatalogue).parent().next().css('opacity', '0.7');

        $('#unCatalogue_' + numCatalogue).toggleClass('choixCatalogueNonCocher');
        $('#unCatalogue_' + numCatalogue).toggleClass('choixCatalogueCocher');
        $('#unCatalogue_' + numCatalogue).find('.cocherOuNon').toggleClass('icon-ic-check-vide');
        $('#unCatalogue_' + numCatalogue).find('.cocherOuNon').toggleClass('icon-ic-check');
        $('#contenuBlock_catalogue_' + numCatalogue + ' .surFamilleBox input').removeAttr('checked');
        $('#contenuBlock_catalogue_' + numCatalogue + ' .familleBox input').removeAttr('checked');
    });
    $((typeCatalogue != 'Type 5' || (typeCatalogue == 'Type 5' && COMMANDE_MONO_CATALOGUE == 'OUI')) ? '.choixCatalogueCocher' : '.checkboxCatalogueType5').each(function () {
        catalogueCocher.push(typeCatalogue != 'Type 5' ? $(this).find('.numeroCatalogue').text() : $(this).val());
    });
    catalogueCocherStringify = JSON.stringify(catalogueCocher);
    
    
    etatTableauPourMosaique = tableauListeDesProduits;
    if (etatTableauPourMosaique != '""' && etatTableauPourMosaique != null) {
        etatTableauPourMosaique = etatTableauPourMosaique.split("\\").join("");
        etatTableauPourMosaique = etatTableauPourMosaique.split("^(").join("");
        etatTableauPourMosaique = etatTableauPourMosaique.split(")$").join("");
        oState = JSON.parse(etatTableauPourMosaique);
        if (oState.hasOwnProperty('iLength') && typeof oState.iLength !== 'undefined') {
            $(".nombreProduitsAAfficher option").filter(function () {
                //may want to use $.trim in here
                return $(this).text() == oState.iLength;
            }).attr('selected', true);
        }
    }
    if (nombreDeProduitsMosaique != null && nombreDeProduitsMosaique != "") {
        $('.nombreProduitsAAfficher').val(nombreDeProduitsMosaique);
    }
    pageCouranteMozaique = 1;
    reinitialiserPaginationListeProduit = true;
    valeurTri = $('#selectTri option:selected').val();

    var filtreDescriptifOffset = $('#filtreDescriptif').offset(); // Obliger de déclarer à l'extérieur car qd on scroll, donc qd on rentre ds la fct alors la position diffère de la position initiale. L'offset donne un chiffre par rapport au bout de page visible et non sur l'ensemble la page
    var conteneurEnteteNavigateurZoneFiltre = $('.conteneurEnteteNavigateurZoneFiltre').offset();
    var cumulsEmballages = $('#cumulsEmballages').offset();
    var navigateurFireFox = navigator.userAgent.search("Firefox");
    var divEnteteETCatalogue = $('#entete').height() + $('#catalogues').height();

    $(window).scroll(function (event) {
        if (templatePersonnalise == "") {
            $('#blockGauche').height(Math.max($('#blockDroite').height(), $('#filtreDescriptif').height()) + 50); // calcule dynamique de hauteur blockGauche
        }
        var scrollTop = $(window).scrollTop();
        if (scrollTop >= divEnteteETCatalogue) {
            $('.conteneurEnteteNavigateurZoneFiltre').css('top', (navigateurFireFox > -1 ? scrollTop - conteneurEnteteNavigateurZoneFiltre.top - 4 : scrollTop - conteneurEnteteNavigateurZoneFiltre.top));
            $('.listeProduitsContenu .top').css('top', scrollTop - conteneurEnteteNavigateurZoneFiltre.top);
            if (templatePersonnalise != "") {
                $('.barrePagination').css('top', scrollTop - conteneurEnteteNavigateurZoneFiltre.top - 74);
                $('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-headers').css('top', (scrollTop - conteneurEnteteNavigateurZoneFiltre.top) - 16);
                $('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar').css('top', (scrollTop - conteneurEnteteNavigateurZoneFiltre.top) - 72);// (navigateurFireFox > -1 ? 25 : 20) // 72 la taille entre la zone filtre et le header

            } else {
                $('.paginationProduit').css('top', scrollTop - conteneurEnteteNavigateurZoneFiltre.top - 41);
                $('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-headers').css('top', (scrollTop - conteneurEnteteNavigateurZoneFiltre.top) + 7);// (navigateurFireFox > -1 ? 25 : 20) // 72 la taille entre la zone filtre et le header
                $('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar').css('top', (scrollTop - conteneurEnteteNavigateurZoneFiltre.top) - 43);// (navigateurFireFox > -1 ? 25 : 20) // 72 la taille entre la zone filtre et le header
            }
            $('#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-pager').css('top', scrollTop - conteneurEnteteNavigateurZoneFiltre.top - 35);
            $('.blockRecherche').css('top', (navigateurFireFox > -1 ? scrollTop - filtreDescriptifOffset.top - 4 : scrollTop - filtreDescriptifOffset.top));
            $('.blockRecherche,.annulerRechercheWebshop').css('padding', '18px 0px');
            //$('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-headers').css('top', (scrollTop - conteneurEnteteNavigateurZoneFiltre.top) + 7);// (navigateurFireFox > -1 ? 25 : 20) // 72 la taille entre la zone filtre et le header

            $('#cumulsEmballages').css('top', (navigateurFireFox > -1 ? scrollTop - cumulsEmballages.top - 4 : scrollTop - cumulsEmballages.top));
            $('.vide').css('top', (navigateurFireFox > -1 ? scrollTop - conteneurEnteteNavigateurZoneFiltre.top - 4 : scrollTop - conteneurEnteteNavigateurZoneFiltre.top) - 42);
            $('.vide').css('z-index', 1);
            //if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == "True") {
            //    $('.vide').css('z-index', 3);
            //} else {
            //    $('.vide').css('z-index', 1);
            //}

            event.preventDefault();
        } else {
            if (templatePersonnalise == "") {
                $('.conteneurEnteteNavigateurZoneFiltre').css('top', -2);
                $('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-headers').css('top', 9);
                $('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar').css('top', -48);
            } else {
                $('.conteneurEnteteNavigateurZoneFiltre').css('top', 0);
                $('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-headers').css('top', 0);
                $('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar').css('top', -72);
            }
            //$('#tableauListeDesProduitsDX >.dx-datagrid>.dx-datagrid-headers').css('top', 9);

            if (templatePersonnalise != "") {
                $('.barrePagination').css('top', -71);
            } else {
                $('.paginationProduit').css('top', -38);
            }
            $('#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-pager').css('top', -38);
            $('.blockRecherche').css('top', 0);
            $('.blockRecherche,.annulerRechercheWebshop').css('padding', '0px');
            $('.vide').css('top', -40);
            $('.vide').css('z-index', 1);
            //if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == "True") {
            //    $('.vide').css('z-index', 1);
            //} else {
            //    $('.vide').css('z-index', 1);
            //}
        }
    });





    if (appelExterneFait == false && numeroCatalogueLigneUrl != "" && typeGestionTarifs != "") {
        appelExterneFait = true;
        voirDetailsProduit(numeroCatalogueLigneUrl, typeGestionTarifs, modeEmballageOuUnite, 'appelExterneFait', numeroCatalogueUrl, numeroExterneCatalogueLigneUrl, numeroExterneArticleUrl);
    } else if (numeroArticleVisibleEnDetail > 0 && typeGestionTarifs != "") {
        voirDetailsProduit(numeroArticleVisibleEnDetail, typeGestionTarifs, modeEmballageOuUnite, 'appelExterneFait', numeroCatalogueUrl, numeroExterneCatalogueLigneUrl, numeroExterneArticleUrl);
    } else if (appelExterneFait == false && numeroCatalogueUrl != "") {
        appelExterneFait = true;
        numeroCatalogueCocheParAppelExterne = numeroCatalogueUrl;
        cocherDecocherTousLesCatalogues(null, numeroCatalogueUrl);
    } else if (numeroCatalogueCocheParAppelExterne > 0) {
        appelExterneFait = true;
        cocherDecocherTousLesCatalogues(null, numeroCatalogueCocheParAppelExterne);
    } else {
        if (modeDAffichage != VALEUR_LISTE) {
            afficherListeProduitsMosaique(pageCouranteMozaique, "", valeurTri, $('.nombreProduitsAAfficher option:selected').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT); // 1 => page numero 1
            setTimeout(function () { $(document).scrollLeft(0); if (templatePersonnalise == "") { $('#blockGauche').height($('body').height() + 620); } $('body').removeClass("bodyOverflowAuto").addClass("bodyOverflowHidden"); }, 300);
        } else {
            setTimeout(function () { afficherListeProduits(); }, 0);
        }
    }



    $('.boutonRecherche').click(function (e) {
        pageCouranteMozaique = 1;
        reinitialiserPaginationListeProduit = true;
        zoneDeRecherche = $('#rechercheLignes').val();
        if (modeDAffichage == VALEUR_LISTE) {
            //oTable = $('#tableauListeDesProduits').dataTable();
            //oTable.fnFilter($('#rechercheLignes').val());
            //modifierModeDAffichageWebShop('Liste', true)
            filtrerProduitDX();
        } else {
            afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher option:selected').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
        }

    });

    $('#selectTri').change(function () {
        valeurTri = $('#selectTri option:selected').val();
        pageCouranteMozaique = 1;
        afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher option:selected').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
    });
    $('.nombreProduitsAAfficher ').change(function () {
        nombreProduitsParPage = $('.nombreProduitsAAfficher').val();
        pageCouranteMozaique = 1;
        if ($("#tableauListeDesProduitsDX").length == 1) {
            $("#tableauListeDesProduitsDX").dxDataGrid("instance").pageSize(nombreProduitsParPage);
        } else {
            afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, nombreProduitsParPage, catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
            if (templatePersonnalise == "") { setTimeout(function () { $('#blockGauche').height($('body').height() + 620); }, 300); }
        }
    });


    $('.conteneurDetailsCatalogue').click(function (evt) {
        if (!evt) evt = window.event;
        if (evt.stopPropagation) {
            evt.stopPropagation();
        }
        if (evt.cancelBubble != null) evt.cancelBubble = true;
    });
    // click sur catalogue (cocher/decocher)
    $((typeCatalogue == 'Type 5' ? '.contenuBlockMesCatalogues .checkbox' : '.choixCatalogue')).click(function (evt) {
        afficherChargement();
        if ($(this).hasClass('catCloture')) {
            if (!evt) evt = window.event;
            if (evt.stopPropagation) {
                evt.stopPropagation();
            }
            if (evt.cancelBubble != null) evt.cancelBubble = true;
        } else if ($(this).hasClass('choixCatalogueCocher') && typeCatalogue == 'Type 5' && COMMANDE_MONO_CATALOGUE == 'OUI') {
            if (!evt) evt = window.event;
            if (evt.stopPropagation) {
                evt.stopPropagation();
            }
            if (evt.cancelBubble != null) evt.cancelBubble = true;
            $(this).prop('checked', true);
            masquerChargement();
        } else {

            if (COMMANDE_MONO_CATALOGUE != 'OUI') {
                if ($(this).is(':checked')) {
                    catalogueCocher = [];
                }
                if (typeCatalogue == 'Type 5') {
                    if ($(this).is(':checked')) {
                        $(this).addClass('choixCatalogueCocher');
                        $(this).removeClass('choixCatalogueNonCocher');
                    } else {
                        $(this).removeClass('choixCatalogueCocher');
                        $(this).toggleClass('choixCatalogueNonCocher');
                    }

                } else {
                    $(this).toggleClass('choixCatalogueNonCocher');
                    $(this).toggleClass('choixCatalogueCocher');
                    $(this).find('.cocherOuNon').toggleClass('icon-ic-check-vide');
                    $(this).find('.cocherOuNon').toggleClass('icon-ic-check');
                }
                $('.choixCatalogueNonCocher').each(function () {

                    numeroCatalogue = typeCatalogue != 'Type 5' ? $(this).find('.numeroCatalogue').text() : $(this).val();

                    index = catalogueCocher.indexOf(numeroCatalogue);

                    if (index > -1) {
                        catalogueCocher.splice(index, 1);
                        if (typeCatalogue != 'Type 5') {
                            $('.contenuBlock_catalogue_' + numeroCatalogue + ' span input').prop('disabled', true); // desactiver les filtres famille de catalogue deselectionner
                            $('.contenuBlock_catalogue_' + numeroCatalogue + ' span input').removeAttr('checked');
                            filtresCocher = [];
                            filtersStringify = JSON.stringify(filtresCocher);
                        }
                    }
                });
                $('.choixCatalogueCocher').each(function () {
                    numeroCatalogue = typeCatalogue != 'Type 5' ? $(this).find('.numeroCatalogue').text() : $(this).val();
                    index = catalogueCocher.indexOf(numeroCatalogue);

                    if (index == -1) {
                        catalogueCocher.push(numeroCatalogue);
                        $('.contenuBlock_catalogue_' + numeroCatalogue + ' span input').prop('disabled', false); // activer les filtres famille de catalogue selectionner

                    }
                });

                afficherBlockFiltrerPar(this.id);

            } else {
                if (echapperLeChangementDeCatalogue != 'OUI') {
                    currentId = typeCatalogue != 'Type 5' ? $(this).find('.numeroCatalogue').text() : $(this).val();
                    catalogueCocher = [];
                    catalogueCocher.push(currentId);
                    if (typeCatalogue == 'Type 5') {
                        if ($(this).is(':checked')) {
                            $(this).addClass('choixCatalogueCocher');
                            $(this).removeClass('choixCatalogueNonCocher');
                        } else {
                            $(this).removeClass('choixCatalogueCocher');
                            $(this).toggleClass('choixCatalogueNonCocher');
                        }
                    } else {
                        $(this).addClass('choixCatalogueCocher');
                        $(this).removeClass('choixCatalogueNonCocher');
                        $(this).find('.cocherOuNon').addClass('icon-ic-check');
                        $(this).find('.cocherOuNon').removeClass('icon-ic-check-vide');
                    }


                    $('#contenuBlock_catalogue_' + currentId).show();
                    $('#contenuBlock_catalogue_' + currentId).prev('.designationCatalogue').removeClass('catalogueNonSelectionnerDesktop');
                    $('#contenuBlock_catalogue_' + currentId).prev('.designationCatalogue').addClass('catalogueSelectionnerDesktop');

                    $((typeCatalogue == 'Type 5' ? '.contenuBlockMesCatalogues .checkbox' : '.choixCatalogue')).each(function () {
                        var numCat = typeCatalogue != 'Type 5' ? $(this).find('.numeroCatalogue').text() : $(this).val();
                        if (numCat != currentId) {

                            $(this).removeClass('choixCatalogueCocher');
                            $(this).addClass('choixCatalogueNonCocher');
                            if (typeCatalogue != 'Type 5') {
                                $(this).find('.cocherOuNon').addClass('icon-ic-check-vide');
                                $(this).find('.cocherOuNon').removeClass('icon-ic-check');
                            } else {
                                if ($(this).is(':checked')) {
                                    $(this).removeAttr('checked');
                                }
                            }
                            if (typeCatalogue != 'Type 5') {
                                //$('.designationCatalogue').next('#contenuBlock_catalogue_' + $(this).find('.numeroCatalogue').text()).hide(); // depiler /repiler famille
                                $('#contenuBlock_catalogue_' + numCat).hide();
                            }
                            $('#contenuBlock_catalogue_' + numCat).prev('.designationCatalogue').removeClass('catalogueSelectionnerDesktop');
                            $('#contenuBlock_catalogue_' + numCat).prev('.designationCatalogue').addClass('catalogueNonSelectionnerDesktop');
                            if (typeCatalogue != 'Type 5') {
                                $('#contenuBlock_catalogue_' + numCat + ' span input').prop("disabled", true);
                            }
                        }
                    });
                    if (typeCatalogue != 'Type 5') {
                        $('.contenuBlockCatalogue span input').removeAttr('checked');
                        $('.contenuBlock_catalogue_' + currentId + ' span input').prop("disabled", false);
                        $('.zoneFiltrerLigneCatalogueWebshop .listeFiltreLigneCatalogueWebshop').html('');
                        filtresCocher = [];
                        listeNomFiltreCritereValeur = [];
                        listeIdFiltreCritereValeur = [];
                        filtresArticleCritereXXCocher = [];
                        filtresTaillePresentationCocher = [];
                        listeNomCritereArticle = [];
                        filtersStringify = JSON.stringify(filtresCocher);
                    }
                } else {
                    $(this).prop('checked', false);
                    if (!evt) evt = window.event;
                    if (evt.stopPropagation) {
                        evt.stopPropagation();
                    }
                    if (evt.cancelBubble != null) evt.cancelBubble = true;
                }

            }
            if (echapperLeChangementDeCatalogue != 'OUI') {
                catalogueCocherStringify = JSON.stringify(catalogueCocher);
                pageCouranteMozaique = 1;
                reinitialiserPaginationListeProduit = true;
                afficherChargement();
                if (modeDAffichage != VALEUR_LISTE) {
                    afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher option:selected').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
                } else {
                    filtrerProduitDX();
                }
                masquerChargement();
            }
            rechargerFiltreCriteresWebshop();
        }

    });

    rechargerFiltreCriteresWebshop();
    //suiteRechargerFiltre();
    $('.divDetailCatalogue').mouseenter(function () {

        $(this).siblings('img').attr('src', '/ressource/image/commun/replier.png');

    }).mouseleave(function () {
        $(this).siblings('img').attr('src', '/ressource/image/commun/deplier.png');
    });

    // si on a un parametre Valeurs criteres visibles par defaut à OUI on affiche le block
    $('.critereArticleSelectionnerDesktop').each(function () {
        $(this).next('.contenuBlockCritere').show();
    });
    $('.catalogueSelectionnerDesktop').each(function () {

        $(this).next('.contenuBlockCatalogue').show();

    });
    $('.mesCataloguesSelectionnerDesktop').each(function () {

        $(this).next('.contenuBlockMesCatalogues').show();

    });
    

    $('.libelleMesCatalogues').click(function () {// depiler /repiler 
        $(this).next('.contenuBlockMesCatalogues').toggle();
        $(this).toggleClass('mesCataloguesNonSelectionnerDesktop');
        $(this).toggleClass('mesCataloguesSelectionnerDesktop');

    });

    $('.designationCatalogue').click(function () {// depiler /repiler catalogue
        $(this).next('.contenuBlockCatalogue').toggle();
        $(this).toggleClass('catalogueNonSelectionnerDesktop');
        $(this).toggleClass('catalogueSelectionnerDesktop');

    });

    //prise en charge des états
    tableauListeDesProduits = null;
    tableauListeDuPanier = null;
    initialiserLesVariablesConfigurationTableaux();

    $('#blockIdentification input').keyup(function (event) {
        if (event.keyCode == CODE_TOUCHE_ENTREE) {
            seConnecterWebShop();
        }
    });
    $('#identificationLogin input').keyup(function (event) {
        if (event.keyCode == CODE_TOUCHE_ENTREE) {
            seConnecterWebShop("", "box");
        }
    });
    $('#rechercheLignes').keyup(function (event) {
        zoneDeRecherche = $('#rechercheLignes').val().trim();
        if (event.keyCode == CODE_TOUCHE_ENTREE) {
            pageCouranteMozaique = 1;
            reinitialiserPaginationListeProduit = true;
            if (modeDAffichage == VALEUR_LISTE) {
                //changements syrine
                //                oTable = $('#tableauListeDesProduits').dataTable();
                //                oTable.fnFilter($('#rechercheLignes').val());
                //afficherListeProduits($('#rechercheLignes').val());
                zoneDeRecherche = $('#rechercheLignes').val();
                filtrerProduitDX();
            } else {
                afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
            }
        }
    });
    $('.filtreCritereArticleValeur').removeAttr('checked');
    // Drag and drop ligne sur commande
    $(".blockPanierTroisTiers").droppable({
        drop: deposerLigneSurCommande,
        over: function (event, ui) {
            $("#conteneurDraggable ,#conteneurDraggable img").css("cursor", "url(/ressource/image/webshop/drag-shop.png),auto");
        },

        out: function (event, ui) {
            $("#conteneurDraggable ,#conteneurDraggable img").css("cursor", "move");
        }
    });

    $("#rechercheLignes").keyup(function () {
        if ($(this).val() == "") {
            $('.annulerRechercheWebshop').hide();
        } else {
            $('.annulerRechercheWebshop').show();
        }
    });
    $('#rechercheLignes').bind('input propertychange', function () {
        $('.annulerRechercheWebshop').show();
    });
    $('.annulerRechercheWebshop').click(function () {
        $('#rechercheLignes').val('');
        $('.annulerRechercheWebshop').hide();
        zoneDeRecherche = "";
        pageCouranteMozaique = 1;
        reinitialiserPaginationListeProduit = true;
        if (modeDAffichage == VALEUR_LISTE) {
            //syrine
            //            oTable = $('#tableauListeDesProduits').dataTable();
            //            oTable.fnFilter($('#rechercheLignes').val());
            //afficherListeProduits($('#rechercheLignes').val());
            filtrerProduitDX();
        } else {
            afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
        }
    });

    if (typeof (messageDeRetourPaiement) != 'undefined' && messageDeRetourPaiement.length > 0) {
        alerte(messageDeRetourPaiement);
    } else if (typeof (messageErreurAccesExterne) != 'undefined' && messageErreurAccesExterne.length > 0) {
        alerte(messageErreurAccesExterne);
    }
    if ((typeof ($('#dateLivraison').val()) != "undefined") && dateLivraisonEncours != '') {
        $('#dateLivraison').datepicker("setDate", formaterDatePourDatePicker(dateLivraisonEncours));
    }
    if (typeof saisieEnModeSemaine == "undefined" || saisieEnModeSemaine !== "True") {
        if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True' && $('#dateLivraison').val() == '' && changementDateDeLivraison == "False") {
            if (preinitialiserDateLivraison == "False") {
                if (sourceChargement == "") {
                    if (obligatoireInitialiserDate == "False") {
                        alerte(MERCI_DE_COMMENCER_PAR_SAISIR_UNE_DATE_DE_LIVRAISON, 'temporaire');
                        jQuery('#dateLivraison').datepicker("show");
                    } else {
                        jQuery('#dateLivraison').datepicker("show");
                        activerModeModal();
                        //modal
                    }
                } else {
                    if (obligatoireInitialiserDate != "False") {
                        jQuery('#dateLivraison').datepicker("show");
                        activerModeModal();
                        //modal
                    }
                }
            } else {
                $('#dateLivraison').datepicker('setDate', dateDeLivraisonPreinitialisee);
            }
        } else if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True' && $('#dateLivraison').val() != '' && changementDateDeLivraison == "False") {
            viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'accueil');
        }
    }

    $('.boutonChoixLangue').click(function () {
        $('.dropdown-Langue').toggle();
    });
    $('.boutonMenuCompte').click(function () {
        $('.blockMenuConnection').toggle();
    });

    // Technique utilisée pour contrer les robots : ceux-ci ne regarde pas le code JS ni CSS. Donc l'ajout d'un checkbox en JS fait que les robots ne le rempliront pas.
    // De plus double sécurité, je passe un token au client généré depuis le serveur. Qd le client soumet les données il envoie ce token au serveur et on controle qu'il est correct. Ceci car les robots bombardent sans faire d'appels serveur.
    $('<div class="ligneLabelEtInputWebshop inputRobot"><label for"jeNeSuisPasUnRobot">' + JE_NE_SUIS_PAS_UN_ROBOT + '</label><input type="checkbox" id="jeNeSuisPasUnRobot" value="' + TOKEN_PAGE_ACCUEIL_WEBSHOP + '" /></div>').insertBefore('#fenetreInscriptionWebshop .ligneLabelEtInputWebshop:last-child');

    // tester si le navigateur est IE ou Edge
    if (testSurIE == false && (document.documentMode || /Edge/.test(navigator.userAgent))) {
        testSurIE = true;
        alerte(LE_SITE_EST_OPTIMISE_POUR_CHROME_ET_FIREFOX, 'info');
    }
    $('.chiffreUniquement').keyup(function () {
        if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
            alerte(MERCI_DE_SAISIR_UN_NOMBRE_ENTIER);
        }
    });
}
function filtrerProduitDX() {
    var dataGrid = $("#tableauListeDesProduitsDX").dxDataGrid("instance");
    initializedDX = false;
    dataGrid.refresh();
}
var variableGlobale_numeroExterneCatalogueLigne;
var variableGlobale_numeroCatalogue;
var variableGlobale_quantiteSaisi;
function deposerLigneSurCommande(event, ui) {
    if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True') {
        ligneCatalogue = ui.draggable;
        if (ligneCatalogue.hasClass('ligneDraggable')) {
            alerte(VOULEZ_VOUS_RAJOUTER_CETTE_LIGNE_AU_COMMANDE + ' ?', 'confirmationUtilisateur', 'validerAjoutLigne');
        }
    }
}

function validerAjoutLigne() {
    messageErreur = '';
    if (validerDateLivraison()) {
        if (($('#dateLivraison').val() == '' || typeof ($('#dateLivraison').val()) == "undefined") && (typeof saisieEnModeSemaine == 'undefined' || saisieEnModeSemaine != "True")) {
            messageErreur = MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON;
        } else {
            if (typeof saisieEnModeSemaine == 'undefined' || saisieEnModeSemaine != "True") {
                dateDeJour = new Date();
                dateDeJour.setDate(dateDeJour.getDate() - 1);
                dateDeJour.setHours(23);
                dateDeJour.setMinutes(59);
                dateDeJour.setSeconds(59);


                var partiesDeLaDate = dateDeLivraisonPreinitialisee.split(' ')[0].split('/');
                dateDeLivraisonPreinitialiseeFormattee = new Date(partiesDeLaDate[2], partiesDeLaDate[1] - 1, partiesDeLaDate[0]);
                dateDeLivraisonPreinitialiseeFormattee.setHours(00);
                dateDeLivraisonPreinitialiseeFormattee.setMinutes(00);
                dateDeLivraisonPreinitialiseeFormattee.setSeconds(00);

                if (preinitialiserDateLivraison == "False") {
                    if ($('#dateLivraison').val() != '' && $('#dateLivraison').datepicker("getDate") <= dateDeJour) {
                        messageErreur = MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON_SUPEREUR_A_DATE_D_AUJOURDHUI;
                    }
                } else if ($('#dateLivraison').val() != '' && $('#dateLivraison').datepicker("getDate") < dateDeLivraisonPreinitialiseeFormattee) {
                    messageErreur = MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON_SUPEREUR_OU_EGALE_AU + " " + dateDeLivraisonPreinitialisee;

                }
            }
        }
        modeExpedition = '';
        if (typeof ($('#modeExpeditionSelection')) != 'undefined') {
            modeExpedition = $('#modeExpeditionSelection').val();
        }
        codePartenaire = autoriserLaModificationDuCodePartenaire !== "" ?
            (typeof $('.panierCodePartenaire' + numeroExterneCatalogue).val() !== 'undefined')
                ? ($('.panierCodePartenaire' + numeroExterneCatalogue).length == 0 ? "" : $('.panierCodePartenaire' + numeroExterneCatalogue).val().trim())
                : ($('.panierCodePartenaire' + numeroExterneCatalogue).length === 0 ? "" : $('.panierCodePartenaire' + numeroExterneCatalogue).val().trim()) : "-1";
        codeEAN = autoriserLaModificationDuCodeBarreReferencement !== "" ? (typeof $('.panierCodeEAN' + numeroExterneCatalogue).val() !== 'undefined') ? ($('.panierCodeEAN' + numeroExterneCatalogue).length === 0 ? "" : $('.panierCodeEAN' + numeroExterneCatalogue).val().trim()) : ($('.panierCodeEAN' + numeroExterneCatalogue).length === 0 ? "" : $('.panierCodeEAN' + numeroExterneCatalogue).val().trim()) : "-1";
        // numeroExterneCatalogueLigne,numeroCatalogue,quantite,prixEtiquettes,commentaireEtiquettes,prixUnitaireHTDansDeviseClient
        chaineDesValeurs = variableGlobale_numeroExterneCatalogueLigne + ";" + variableGlobale_numeroCatalogue + ";incrementale;" + 0 + ";;" + 0 + ";" + codePartenaire + ";" + codeEAN;
        var dateLivraison;
        if (typeof saisieEnModeSemaine !== 'undefined' && saisieEnModeSemaine == "True") {
            //dateLivraison = dateLivraisonEncours;
            dateLivraison = $('#semaineDateLivraison').data("datelivraison");
        }
        else {
            dateLivraison = ($('#dateLivraison').val() != '' ? $('#dateLivraison').val() : '');
        }

        if (messageErreur == '') {
            afficherChargement();
            $.ajax({
                url: '/OperationDesktop/ajouterAuPanier',
                data: {
                    'chaineDesValeurs': chaineDesValeurs,
                    'dateLivraison': dateLivraison,
                    'modeExpedition': modeExpedition
                },
                success: function (retourServeur) {
                    quantiteEtMontantEtMessage = retourServeur.ResultatJ; //contient => quantite|montant|message = position 0|1|2
                    tableauValeurs = quantiteEtMontantEtMessage.split("|");
                    if (tableauValeurs.length > 1) {
                        quantite = tableauValeurs[0];
                        montant = tableauValeurs[1];
                        message = tableauValeurs[2];
                        if (quantiteProduitsDescktop == quantite) {
                            alerte(LA_QUANTITE_DE_CE_PRODUIT_A_BIEN_ETE_MODIFIEE);
                        } else if (message != "") {
                            alerte(message);
                        } else {
                            alerte(LE_PRODUIT_A_BIEN_ETE_AJOUTE_AU_PANIER, 'confirmation');
                        }
                        $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(quantite));

                        tableauValeursPanier = nombreAvecDesEspaces(montant).replace(',', '.').split('.');

                        $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                        $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);
                        //Mettre à jour la valeur densité si le paramètre affichage de la surface est actif
                        if (affichageDeLaSurfaceBool == 'True' && typeof tableauValeurs[3] !== "undefined" && tableauValeurs[3] != "") {
                            $('.valeurDensite').html(tableauValeurs[3] + "&nbsp;");
                        }
                        rafraichirCumulsEmballage();
                        if ($('.conteneurBlocProduitEnMosaique').height() != null) {
                            modifierModeDAffichageWebShop('Miniature');
                        } else {
                            modifierModeDAffichageWebShop(VALEUR_LISTE);
                        }
                        if (typeof saisieEnModeSemaine !== 'undefined' && saisieEnModeSemaine == "True") {
                            if ($('#semaineDateLivraison').find(":selected").hasClass("selectedSemaineLivraison") == false) {
                                $('#semaineDateLivraison').find(":selected").addClass('selectedSemaineLivraison');
                            }
                        }

                    } else { // dans le cas y a pas de quantite|montant donc il y a que message sera dans la position 0 du tableau
                        if (retourServeur == 'operationEncoursExistante') {
                            //                        alerte(UNE_OPERATION_EST_DEJA_EN_COURS_DE_SAISIE_VOULEZ_VOUS_AJOUTER_CE_PRODUIT_DANS_L_OPERATION_EN_COURS + ' ?', 'confirmationUtilisateur', 'ajouterAuPanier',
                            //                            numeroExterneCatalogueLigne, '"' + mode + '"', prixUnitaireHTDansDeviseClient, numeroCatalogue, 'oui'
                            //                        );
                        } else {
                            if (tableauValeurs[0].indexOf("MESSAGE:") == 0) {// tableauValeurs[0] : retour message avec un mot clé MESSAGE dans la position 0
                                alerte(tableauValeurs[0].substring(8), 'confirmationUtilisateur', 'validerRechargePageAccueil'); //8 le nombre de caractere de mot clé MESSAGE:
                            } else if (tableauValeurs[0].indexOf("MESSAGESANSACTIONS:") == 0) {
                                alerte(tableauValeurs[0].substring(19), 'confirmationUtilisateur'); //19 le nombre de caractere de mot clé MESSAGESANSACTIONS:
                            } else {
                                alerte(tableauValeurs[0], 'erreur');
                            }
                        }
                    }

                }
            });
        } else {
            alerte(messageErreur, 'erreur');
        }
    }
    masquerChargement();
}

function afficherBlockDocuments(evt) {

    $('.blockDocuments').fadeToggle(200);
    if (!evt) evt = window.event;
    if (evt.stopPropagation) {
        evt.stopPropagation();
    }
    if (evt.cancelBubble != null) evt.cancelBubble = true;
}

function afficherUnDocument(evt) {
    if (!evt) evt = window.event;
    if (evt.stopPropagation) {
        evt.stopPropagation();
    }
    if (evt.cancelBubble != null) evt.cancelBubble = true;
}

function afficherBlockCatalogue(evt) {
    //pour stopper l'action de tri sur chekcbox en cliquant sur cochertous
    if (!evt) evt = window.event;
    if (evt.stopPropagation) {
        evt.stopPropagation();
    }
    if (evt.cancelBubble != null) evt.cancelBubble = true;
}

function filtrerListesParCritereValeur() {

    $('.zoneFiltrerLigneCatalogueWebshop .listeFiltreLigneCatalogueWebshop').html('');
    filtresCocher = [];
    listeNomFiltreCritereValeur = [];
    listeIdFiltreCritereValeur = [];
    filtreCritereValeurCocher = [];
    filtresArticleCritereXXCocher = [];
    filtresTaillePresentationCocher = [];
    listeNomCritereArticle = [];
    listecodeFamillesSelectionnee = [];
    listeCatalogueChoisiePourFiltreSelectionne = new Array();
    if (typeCatalogue != 'Type 5') {
        catalogueCocher = [];
    }

    $('.choixCatalogueCocher').each(function () {

        if (catalogueCocher.indexOf(typeCatalogue != 'Type 5' ? $(this).find('.numeroCatalogue').text() : $(this).val()) === -1) {
            catalogueCocher.push(typeCatalogue != 'Type 5' ? $(this).find('.numeroCatalogue').text() : $(this).val());
        }
    });
    if (typeCatalogue == 'Type 5') {
        if (catalogueCocher.length == 0) {
            $('.checkboxCatalogueType5').each(function () {
                $(this).removeClass('choixCatalogueNonCocher');
                $(this).removeClass('choixCatalogueCocher');

            });
            $('.checkboxCatalogueType5').each(function () {

                catalogueCocher.push($(this).val());

            });
        }
    }

    catalogueCocherStringify = JSON.stringify(catalogueCocher);
    $('#listeFiltreFamille .filtreFamille:checked').each(function () {
        indexFiltre = filtresCocher.indexOf($(this).val());
        if (indexFiltre == -1) {
            filtresCocher.push($(this).val());
        }
        if ($(this).val() != '-1') {
            listecodeFamillesSelectionnee.push($(this).parent().attr('class'));
        }
        idFiltreFamille = $(this).parent().attr('id');
        numeroCatalogueDeFiltre = idFiltreFamille.substring(19, idFiltreFamille.length);

        listeCatalogueChoisiePourFiltreSelectionne.push(numeroCatalogueDeFiltre);
    });
    listeCatalogueChoisiePourFiltreSelectionneStringify = JSON.stringify(listeCatalogueChoisiePourFiltreSelectionne);

    filtersStringify = JSON.stringify(filtresCocher);

    $("#listeCriteresWebshop input[type='checkbox']:checked").each(function () {
        filtreCritereValeurCocher.push($(this).attr('value'));
        listeNomFiltreCritereValeur.push($(this).parent().attr('class'));
        listeIdFiltreCritereValeur.push($(this).attr('id'));
    });
    filtreCritereValeurCocherStringify = JSON.stringify(filtreCritereValeurCocher);

    $("#listeCritresArticles input[type='checkbox']:checked").each(function () {

        filtresArticleCritereXXCocher.push($(this).attr('value'));
        nomCritere = $(this).parent().parent().parent().find('.libelleCritereArticle').text();
        listeNomCritereArticle.push(nomCritere);
    });
    filtresArticleCritereXXCocherStringify = JSON.stringify(filtresArticleCritereXXCocher);

    $("#listeFiltreTaillePresentation input[type='checkbox']:checked").each(function () {
        filtresTaillePresentationCocher.push($(this).attr('value'));
        nomTaillePresentation = $(this).parent().parent().parent().find('.libelleTaillePresentation').text();
        listeNomTaillePresentation.push(nomTaillePresentation);
    });
    filtresTaillePresentationCocherStringify = JSON.stringify(filtresTaillePresentationCocher);

    if ($('#filtreQuantite').length > 0) {
        maxQuantiter = $('#filtreQuantite').slider("values", 1);
        minQuantiter = $('#filtreQuantite').slider("values", 0);
    } else {
        maxQuantiter = -1;
        minQuantiter = -1;
    }

    pageCouranteMozaique = 1;
    reinitialiserPaginationListeProduit = true;
    if (modeDAffichage == VALEUR_LISTE) {
        //afficherListeProduits();
        filtrerProduitDX();
    } else {
        afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher option:selected').val(), (listeCatalogueChoisiePourFiltreSelectionneStringify == "[]" || typeCatalogue == "Type 5") ? catalogueCocherStringify : listeCatalogueChoisiePourFiltreSelectionneStringify, filtersStringify, filtreCritereValeurCocherStringify, maxQuantiter, minQuantiter);
    }

    entrerFiltreCocher = false;

    for (i = 0; i < listecodeFamillesSelectionnee.length; i++) {
        if (i == 0) {
            $('.zoneFiltrerLigneCatalogueWebshop .listeFiltreLigneCatalogueWebshop').append('<span> ' + listecodeFamillesSelectionnee[i] + '</span>');
        } else {
            $('.zoneFiltrerLigneCatalogueWebshop .listeFiltreLigneCatalogueWebshop').append(' > <span> ' + listecodeFamillesSelectionnee[i] + '</span>');
        }
        entrerFiltreCocher = true;
    }
    for (i = 0; i < listeNomFiltreCritereValeur.length; i++) {
        if (i == 0 && entrerFiltreCocher == false) {
            $('.zoneFiltrerLigneCatalogueWebshop .listeFiltreLigneCatalogueWebshop').append('<span> ' + listeNomFiltreCritereValeur[i] + '</span>');
        } else {
            $('.zoneFiltrerLigneCatalogueWebshop .listeFiltreLigneCatalogueWebshop').append(' > <span> ' + listeNomFiltreCritereValeur[i] + '</span>');
        }
    }
}

function afficherListeProduitsMosaique(numeroPage, variableDeRecherche, valeurTri, nombreProduitsParPage, listNumeroCatalogue, listeValeurFiltre, listeFiltreCritereValeur, maxQuantiter, minQuantiter, forcerScrollTop) {
    afficherChargement();
    var cpt = 0;
    aAssortiment = false;
    while (cpt < catalogueCocher.length) {
        if (catalogueCocher[cpt] != "" && $('#unCatalogue_' + catalogueCocher[cpt] + ' .aAssortiment').text() == 1) {
            aAssortiment = true;
        }
        cpt++;
    }
    $.ajax({
        url: '/webshop/listeProduitsModeMosaique?numeroSociete=' + numeroSociete + '&numeroBoutique=' + numeroBoutique,
        data: {
            'numeroPage': numeroPage,
            'rechercher': variableDeRecherche,
            'tri': valeurTri,
            'nombreProduitsParPage': nombreProduitsParPage,
            'listeNumeroCatalogues': listNumeroCatalogue,
            'filtres': ($('#listeFiltreFamille input:checked').length == $('#listeFiltreFamille input').length) ? new Array() : listeValeurFiltre,
            'listeFiltreCritereValeur': filtreCritereValeurCocherStringify,
            'listefiltresArticleCritereXX': filtresArticleCritereXXCocherStringify,
            'listefiltresTaillePresentation': filtresTaillePresentationCocherStringify,
            'maxQuantite': maxQuantiter,
            'minQuantite': minQuantiter,
            'modeDAffichage': VALEUR_MINIATURE,
            'aAssortiment': aAssortiment == true ? '1' : '0',
            'dateLivraison': nouvelleDateDeLivraison
        },
        beforeSend: function (jqXHR, settings) {
            //afficherChargement();
            jqXHR.url = settings.url;
            //ATTENTION !!! ne jamais toucher au settings.data en append ni en écrasement car il génère un bug sur upload des fichiers !!!!!! Si paramètre à ajouter le faire sur settings.url 

            if (settings.url.indexOf('?') < 0) {
                settings.url += "?versionCode=" + VERSION_CODE + "&numeroSocieteFournisseurEncours=" + numeroSociete + "&numeroBoutiqueEncours=" + numeroBoutique;
            } else {
                settings.url += "&versionCode=" + VERSION_CODE + "&numeroSocieteFournisseurEncours=" + numeroSociete + "&numeroBoutiqueEncours=" + numeroBoutique;
            }
            if (typeAnnulation != 1) {
                annulerLesAppelsEnAttente();
            }
        },
        success: function (retourServeur) {
            masquerChargement();
            //console.log("afficherListeProduitsMosaique end")
            if (saisiQuantiteEnModeMosaique != valeurOui) {
                $('.boutonAjoutGlobal').hide();
            }
            if (typeof forcerScrollTop !== 'undefined') {
                allerVersLeHaut(forcerScrollTop);
            } else {
                allerVersLeHaut();
            }
            $('.nombreProduits').show();
            $('.labelTrier').show();
            $('#selectTri').show();
            if (templatePersonnalise != "") {
                $('#selectTri').prop('disabled', false);
            }
            $('.boutonRecherche').show();
            $('#rechercheLignes').val(zoneDeRecherche);
            $('.listeProduitsContenu').html(retourServeur);

            $('#listeProduits').addClass('conteneurBlocProduitEnMosaique');
            $('.listeProduitsContenu').addClass('listeProduitsContenuEnMosaique');

            $('.quantiteProduit').keypress(function (event) {
                charCode = (event.which) ? event.which : event.keyCode;
                saisiValide = true;
                if (charCode == 46 || charCode == 44) {
                    if ($(this).val().indexOf(',') == -1 && $(this).val().indexOf('.') == -1 && !$(this).hasClass('chiffreUniquement')) {
                        saisiValide = true;
                    } else {
                        saisiValide = false;
                    }
                } else if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                    saisiValide = false;
                } else {
                    saisiValide = true;
                }
                return saisiValide;
            });
            $('.chiffreUniquement').keyup(function () {
                if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
                    alerte(MERCI_DE_SAISIR_UN_NOMBRE_ENTIER);
                }
            });
            $('.quantiteProduit').on('blur', function (e) {
                //gererLignesOperation(this, 'produit');
                stockerLignesOperation(this, false, 'produit');
            });
            if (templatePersonnalise == "") {
                gererLeTraitementDesTarifs("Miniature");
            } else {
                gererLeTraitementDesTarifs("Miniature", "traitementNormal");
                $('.unProduit').each(function () {
                    var id = this.id;
                    if ($('#' + id).find('.detailsProduit').find('.grilleTarifaireVisibility').length > 0) {
                        $('#' + id).mouseenter(function () {
                            $(this).find('.detailsProduit').find('.grilleTarifaireVisibility').fadeIn("slow", function gererLeTraitementDunTarif() {
                            });
                        });
                        $('#' + id).mouseleave(function () {
                            $(this).find('.detailsProduit').find('.grilleTarifaireVisibility').fadeOut(1000);
                        });
                    }
                });
                $('[data-async-url]').not(".traitementNormal").each(function () {
                    var $this = $(this);
                    var request;
                    $this.parent().parent().mouseenter(function () {
                        var url = $this.data('async-url');
                        if (typeof $this.data("status") === 'undefined') {
                            request = $.ajax({
                                url: url,
                                dataType: 'html',
                                type: 'get',
                                success: function (html) {
                                    $this.html(html);
                                    $this.data("status", 200);
                                    $this.fadeIn("slow");
                                    if ($this.find('.grilleTarifaireVisibility').length > 0) {
                                        $this.find('.grilleTarifaireVisibility').show();
                                    }
                                    masquerChargement();
                                }
                            });
                        } else {
                            $this.fadeIn("slow");
                        }
                    });
                    $this.parent().parent().mouseleave(function () {
                        if (typeof request !== 'undefined' && request.readyState < 4)
                            request.abort();
                        $this.fadeOut(1000);
                    });
                });

            }


        }

    });

}

function gererLeTraitementDesTarifs(mode, classe) {

    nombreLignesTraites = $('[data-async-url]').length;
    var compteurTraitement = 0;

    $('[data-async-url]').each(function () {
        if (typeof classe === 'undefined' ||
            (typeof classe !== 'undefined' && ($(this).hasClass(classe) || $(this).find(classe).length > 0))) {
            compteurTraitement++;

            var $this = $(this), url = $this.data('async-url');
            var request = $.ajax({
                url: url,
                dataType: 'html',
                type: 'get',
                success: function (html) {
                    masquerChargement();
                    $this.html(html);
                }
            });
            if (mode == 'Miniature' && typeAnnulation == 1) {
                $(this).on("remove", function () {
                    if (request.readyState < 4)
                        request.abort();
                });
            } else {
                XHR.push(request);
            }


        }
    });


}
function annulerLesAppelsEnAttente() {
    XHR.forEach(function (e) {
        if (e.readyState < 4) {
            e.abort();
        }
    });
    XHR = [];
}


//function gererLeTraitementDesTarifs() {
//    var delai = 0;
//    var nombreDAppels = 0;
//    $('[data-async-url]').each(function () {
//        nombreDAppels++;
//        var $this = $(this), url = $this.data('async-url');
//        setTimeout(function () { appelAsynchrone($this, url); }, delai);
//        if (nombreDAppels <= 10) {
//            delai += 100;
//        } else {
//            delai = 0;
//        }
//        
//    });
//}
//function appelAsynchrone($this, url) {
//    if ($this.length > 0) {

//        var request = $.ajax({
//            url: url,
//            dataType: 'html',
//            type: 'get',
//            beforeSend: function () {
//                masquerChargement();
//            },
//            success: function (html) {
//                $this.html(html);
//            }
//        });

//        $this.on("remove", function () {
//            if (request.readyState < 4)
//                request.abort();
//        });
//    }
//}
function afficherListeProduits(rechercheLignes, forcerScrollTop) {
     //console.log("afficherListeProduitsModeListe")
    if (templatePersonnalise != "") {
        $('#selectTri').prop('disabled', 'disabled');
    } else {
        $('#selectTri').hide();
        $('.labelTrier').hide();
    }
    afficherChargement();
    if (typeof rechercheLignes !== 'undefined') {
        zoneDeRecherche = rechercheLignes;
    }
    var cpt = 0;
    while (cpt < catalogueCocher.length) {
        if (catalogueCocher[cpt] != "" && $('#unCatalogue_' + catalogueCocher[cpt] + ' .aAssortiment').text() == 1) {
            aAssortiment = true;
        }
        cpt++;
    }
    $.ajax({
        url: '/webshop/listeProduitsModeListe?numeroSociete=' + numeroSociete + '&numeroBoutique=' + numeroBoutique + '&aAssortiment=' + (aAssortiment == true ? '1' : '0'),
        data: {
            'modeDAffichage': VALEUR_LISTE,
            'numeroSocieteFournisseur': numeroSociete,
            'recherche': zoneDeRecherche
        },
        'beforeSend': function (request) {
            annulerLesAppelsEnAttente();

        },
        success: function (retourServeur) {
            if (EST_CONNECTE == 'True' && EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True') {
                $('.boutonAjoutGlobal').show();
            }
            $('#rechercheLignes').val(zoneDeRecherche);
            $('.nombreProduits').hide();
            //            $('#selectTri').hide();
            //            $('.labelTrier').hide();
            /*$('.boutonRecherche').hide();
            $('#rechercheLignes').hide();*/
            $('.listeProduitsContenu').html(retourServeur);

            $('#listeProduits').removeClass('conteneurBlocProduitEnMosaique');
            $('.listeProduitsContenu').removeClass('listeProduitsContenuEnMosaique');
            if (typeof forcerScrollTop !== 'undefined') {
                allerVersLeHaut(forcerScrollTop);
            }
			refreshPagerListeProduitDX();
            masquerChargement();
        }
    });
}
function fermerLayoutFiltre() {
    $('#layoutFiltre').fadeOut(200);
    $('#detailsFiltre').fadeOut(200);
}
function seConnecterWebShop(numeroSocieteGenerique, source) {
    authentificationGenerique = false;
    filtresCocher = [];
    //catalogueCocher = [];
    listeNomFiltreCritereValeur = [];
    listeIdFiltreCritereValeur = [];
    filtreCritereValeurCocher = [];
    listeNomCritereArticle = [];
    filtresArticleCritereXXCocher = [];
    filtresArticleCritereXXCocherStringify = [];
    filtresTaillePresentationCocherStringify = [];
    filtreCritereValeurCocherStringify = [];
    listecodeFamillesSelectionnee = [];
    filtersStringify = [];
    zoneDeRecherche = '';
    login = "";
    motDePasse = "";
    resterConnecter = "";
    $('#rechercheLignes').val('');
    $('#listeFiltreFamille input[type="checkbox"]').each(function () {
        $(this).attr('checked', false);
    });
    $('#listeCriteresWebshop input[type="checkbox"]').each(function () {
        $(this).attr('checked', false);
    });
    $('#listeCritresArticles input[type="checkbox"]').each(function () {
        $(this).attr('checked', false);
    });
    if (typeof numeroSocieteGenerique !== 'undefined' && numeroSocieteGenerique != "") {
        authentificationGenerique = true;
    }
    if (typeof source !== 'undefined' && source != "") {
        login = $('#loginBox').val().trim();
        motDePasse = $('#motDePasseBox').val().trim();
        resterConnecter = ($('#resterConnecterLogin[type]').is(':checked') ? 'oui' : 'non');
    } else {
        login = $('#login').val().trim();
        motDePasse = $('#motDePasse').val().trim();
        resterConnecter = ($('#resterConnecter[type]').is(':checked') ? 'oui' : 'non');
    }
    if ((login != "" && motDePasse != "") || authentificationGenerique) {
        //        url = $(location).attr('href');
        //        if (url.indexOf("numeroSociete") >= 0) {
        //            position = url.indexOf('=');
        //            numeroSociete = url.substring(position + 1);
        $.ajax({
            url: '/webshop/seConnecter',
            type: 'POST',
            data: {
                'identifiant': login,
                'motDePasse': motDePasse,
                'numeroSocieteClient': (authentificationGenerique == true ? numeroSocieteGenerique : ""),
                'resterConnecter': resterConnecter,
                'numeroSociete': numeroSociete,
                'numeroBoutique': numeroBoutique,
                'numeroArticleVisibleEnDetail': numeroArticleVisibleEnDetail
            },
            success: function (retourServeur) {
                masquerChargement();
                if (retourServeur.indexOf('authentificationEchouee') == -1 && retourServeur.indexOf('compteDesactive') == -1 && retourServeur.indexOf('societeDesactive') == -1 && retourServeur != 'compteProspect') {
                    $('body').html(retourServeur);
                    initialiserLayoutWebShop();
                    if (typeof rechargerPageVar !== 'undefined' && rechargerPageVar == "True") {
                        location.reload();
                    }
                    //                        if (!$('#resterConnecter[type]').is(':checked')) {
                    //                            demarrerOuRedemarrerCompteurTimeOut();
                    //                        }
                } else if (retourServeur.indexOf('compteDesactive') >= 0) {
                    valeurs = retourServeur.split('|');
                    if (typeof source !== 'undefined' && source != "") {
                        $('#messageErreurLoginBox').html(COMPTE_DESACTIVE + ' !');
                    } else {
                        $('#messageErreurLogin').html(COMPTE_DESACTIVE + ' !');
                    }

                    if (valeurs.length > 1) {
                        alerte(valeurs[1], 'erreur');
                    } else {
                        alerte(COMPTE_CORRESPONDANT_AU_LOGIN_DESACTIVE, 'erreur')
                    }
                } else if (retourServeur.indexOf('societeDesactive') >= 0) {
                    valeurs = retourServeur.split('|');
                    if (typeof source !== 'undefined' && source != "") {
                        $('#messageErreurLoginBox').html(SOCIETE_DESACTIVEE + ' !');
                    } else {
                        $('#messageErreurLogin').html(SOCIETE_DESACTIVEE + ' !');
                    }
                    if (valeurs.length > 1) {
                        alerte(valeurs[1], 'erreur');
                    } else {
                        alerte(SOCIETE_RATTACHEE_AU_LOGIN_DESACTIVE, 'erreur')
                    }
                } else if (retourServeur.indexOf('compteProspect') >= 0) {
                    alerte(IMPOSSIBLE_DE_SE_CONNECTER_AVEC_CE_TYPE_DE_COMPTE + ' !', 'erreur')
                } else {
                    if (typeof source !== 'undefined' && source != "") {
                        if (templatePersonnalise != "") {
                            $('#loginBoxErreur').html(LOGIN_OU_MOT_DE_PASSE_INCORRECT);
                            $('#loginBoxErreur').show();
                            $('#motDePasseBox').addClass('error');
                            $('#loginBox').addClass('error');
                        } else {
                            $('#motDePasseBox').val("");
                            $('#loginBox').val(LOGIN_OU_MOT_DE_PASSE_INCORRECT);
                            $('#loginBox').css('color', 'red');
                        }
                    } else {
                        if (templatePersonnalise != "") {
                            $('#loginErreur').html(LOGIN_OU_MOT_DE_PASSE_INCORRECT);
                            $('#loginBoxErreur').show();
                            $('#motDePasse').addClass('error');
                            $('#login').addClass('error');
                        } else {
                            $('#motDePasse').val("");
                            $('#login').val(LOGIN_OU_MOT_DE_PASSE_INCORRECT);
                            $('#login').css('color', 'red');
                        }
                    }

                }
            },
            error: function (jqXHR, status, erreur) {

                masquerChargement();
                if (jqXHR.responseText.indexOf('<title>') != -1) {
                    exception = jqXHR.responseText.split('<title>')[1].split('</title>')[0];
                    if (exception.substring(0, 4) == '2000') {
                        exceptionUtilisateur = true;
                        alerte(ERREUR_CONNECTION, 'erreur');
                    } else if (exception.substring(0, 4) == '1000') {
                        alerte(exception.replace('1000:', ''));
                    } else if (exception.substring(0, 4) == '3000') {
                        alerte(exception.replace('3000:', ''), 'confirmationUtilisateur', 'rechargerPage');
                    }
                } else {
                    alerte(ERREUR_CONNECTION, 'erreur');
                }


            }

        });
        //        }
    } else {
        if (typeof source !== 'undefined' && source != "") {
            if (templatePersonnalise != "") {
                $('#loginBoxErreur').html(LOGIN_OU_MOT_DE_PASSE_INCORRECT);
                $('#loginBoxErreur').show();
                $('#motDePasseBox').addClass('error');
                $('#loginBox').addClass('error');
            } else {
                $('#loginBox').val(LOGIN_OU_MOT_DE_PASSE_INCORRECT);
                $('#loginBox').css('color', 'red');
            }
        } else {
            if (templatePersonnalise != "") {
                $('#loginErreur').html(LOGIN_OU_MOT_DE_PASSE_INCORRECT);
                $('#loginErreur').show();
                $('#motDePasse').addClass('error');
                $('#login').addClass('error');
            } else {
                $('#login').val(LOGIN_OU_MOT_DE_PASSE_INCORRECT);
                $('#login').css('color', 'red');
            }
        }
    }
}
function filtrerListeProduitsParUneSeuleFamille(idFiltreFamille, nomFiltreFamille, indiceCatalogue, evt) {
    index = catalogueCocher.indexOf(indiceCatalogue);
    if (index != -1 || (typeCatalogue == 'Type 5' && echapperLeChangementDeCatalogue != 'OUI')) {
        if (typeCatalogue == 'Type 5') {
            $('[id^=nomCata_]').not("#nomCata_" + indiceCatalogue).each(function () { $(this).removeAttr('checked'); })
            //$("#nomCata_" + indiceCatalogue).prop("checked", true);
            $("#nomCata_" + indiceCatalogue).trigger('click');
            catalogueCocher = [];
            catalogueCocher[0] = indiceCatalogue;
            $('[class^=filtreCatnomCata_]').not(".filtreCatnomCata_" + indiceCatalogue).remove();
            listeNomCatalog = [];
            listeNomCatalog[0] = $('#unCatalogue_' + indiceCatalogue + ' .libelleCatalogue').text();
            $("#nomCata_" + indiceCatalogue).addClass('choixCatalogueCocher');
            if ($(".filtreCatnomCata_" + indiceCatalogue).length <= 0) {
                if (echapperLeChangementDeCatalogue != 'OUI')
                    afficherBlockFiltrerPar($("#nomCata_" + indiceCatalogue).attr("id"), indiceCatalogue);
            }

        }
        $('.zoneFiltrerLigneCatalogueWebshop .listeFiltreLigneCatalogueWebshop').html('');
        filtresCocher = [];
        //catalogueCocher = [];
        listeNomFiltreCritereValeur = [];
        listeIdFiltreCritereValeur = [];
        listeNomCritereArticle = [];
        listeNomTaillePresentation = [];
        filtreCritereValeurCocher = [];
        filtresArticleCritereXXCocher = [];
        filtresTaillePresentationCocher = [];
        listecodeFamillesSelectionnee = [];
        filtresCocher.push(idFiltreFamille);
        listecodeFamillesSelectionnee.push(nomFiltreFamille);
        filtersStringify = JSON.stringify(filtresCocher);
        seulCatalogueChoisie = new Array();
        seulCatalogueChoisie.push(indiceCatalogue);
        $('.filtreFamille').removeAttr('checked');
        $('.surFamille').removeAttr('checked');
        //$('.catalogueFiltreFamilleInput').removeAttr('checked');
        seulCatalogueChoisieStringify = JSON.stringify(seulCatalogueChoisie);
        $('.catalogueFiltreFamille').removeClass('catalogueFiltreFamilleGriser');


        pageCouranteMozaique = 1;
        reinitialiserPaginationListeProduit = true;
        if (modeDAffichage == VALEUR_LISTE) {
            //afficherListeProduits();
            filtrerProduitDX();
        } else {
            afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher').val(), seulCatalogueChoisieStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
        }
        $('#catalogue' + indiceCatalogue).prop("checked", true);
        if (typeCatalogue == 'Type 5') {
            $('.filtreFamille:input').filter(function () { return this.value == idFiltreFamille }).prop("checked", true);
            $('[class^=ligneFamilleValeur]').each(function () { $(this).find('[class^=supprimerFamille]').trigger('click') });
            afficherBlockFiltrerPar($('.filtreFamille:input').filter(function () { return this.value == idFiltreFamille }).attr("id"));
        } else {
            $('#cat_' + indiceCatalogue + '_filtreFamille_' + idFiltreFamille).prop("checked", true);
        }
        if (typeCatalogue != 'Type 5') {
            if ($('#contenuBlock_catalogue_' + indiceCatalogue + ' .filtreFamille').length > 1) {
                $('#catalogue' + indiceCatalogue).siblings('.catalogueFiltreFamille').addClass('catalogueFiltreFamilleGriser');
            }

            $('.zoneFiltrerLigneCatalogueWebshop .listeFiltreLigneCatalogueWebshop').append('<span> ' + listecodeFamillesSelectionnee[0] + '</span>');
        } else {
            $('.labelsurFamille').removeClass('catalogueFiltreFamilleGriser');
            if ($('.filtreFamille:input').filter(function () { return this.value == idFiltreFamille }).length != 0) {
                if ($('.filtreFamille:input').filter(function () { return this.value == idFiltreFamille }).parent().siblings().find('.filtreFamille:input').length > $('.filtreFamille:input').filter(function () { return this.value == idFiltreFamille }).parent().siblings().find('.filtreFamille input:checked').length) {
                    $('.filtreFamille:input').filter(function () { return this.value == idFiltreFamille }).parent().siblings('.surFamilleBox').find('.labelsurFamille').addClass('catalogueFiltreFamilleGriser');
                }
                $('.filtreFamille:input').filter(function () { return this.value == idFiltreFamille }).parent().siblings('.surFamilleBox').find('.surFamille').prop("checked", true);
            }
        }
    }

    if (!evt) evt = window.event;
    if (evt.stopPropagation) {
        evt.stopPropagation();
    }
    if (evt.cancelBubble != null) evt.cancelBubble = true;
}

function initialiserListeProduitsMosaique() {
    modeDAffichage = VALEUR_MINIATURE;
    $('.paginationProduit li').click(function () {
        // if (!$(this).hasClass('nombreDePage')) {
        variableDeRecherche = $('#rechercheLignes').val().trim();
        if ($(this).text() != 'prev' && $(this).text() != 'next') {
            pageCouranteMozaique = $(this).text();
            if ($("#tableauListeDesProduitsDX").length == 1) {
                $("#tableauListeDesProduitsDX").dxDataGrid("instance").pageIndex($('.nombreProduitsAAfficher').val());
            } else {
                afficherListeProduitsMosaique(pageCouranteMozaique, variableDeRecherche, valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT, true); // true est pour le forçage du scroll trop dans aller vers le haut
            }
        } else {
            if ($(this).text() == 'prev') {
                numeroPage = parseInt($('.pageCourante').first().text()) - 1;
                if (numeroPage > 0) {
                    pageCouranteMozaique = numeroPage;
                    afficherListeProduitsMosaique(pageCouranteMozaique, variableDeRecherche, valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT, true); // true est pour le forçage du scroll trop dans aller vers le haut
                }
            } else {
                numeroPage = parseInt($('.pageCourante').first().text()) + 1;
                if (numeroPage <= $('.paginationProduit span.nombreDePage').attr('id')) {
                    pageCouranteMozaique = numeroPage;
                    afficherListeProduitsMosaique(pageCouranteMozaique, variableDeRecherche, valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT, true); // true est pour le forçage du scroll trop dans aller vers le haut
                }
            }
        }
        // }
    });

    // Draguer produit en mode mosaique
    conteneurDeDrop = $(".ligneDraggable");
    $('.ligneDraggable').draggable({
        cursor: 'move',
        containment: 'document',
        start: function (event, ui) {
            $(this).draggable('instance').offset.click = {
                left: Math.floor((ui.helper.width() / 2) - 25),
                top: Math.floor((ui.helper.height() / 2) - 25)
            };
        },
        helper: copierElementEnDeplacement
    });

    $('.quantiteProduit').each(function () {
        numeroExterneCatalogue = $(this).data('numeroexterne');
        expression = "^" + numeroExterneCatalogue + ";";
        reg = new RegExp(expression, 'g');
        trouverLigne = false;
        nbLignes = lignesPanier.length;
        i = 0;
        valeurs = [];
        while (!trouverLigne && i < nbLignes) {
            if (lignesPanier[i].match(reg)) {
                //numeroExterneCatalogue + ";" + numeroCatalogue + ";" + quantite + ";" + prixEtiquettes + ";" + commentaireEtiquettes + ";" + prixHt
                valeurs = lignesPanier[i].split(";");
                $(this).val(valeurs[2]);
                trouverLigne = true;
            }
            i++;
        }
    });


    // Validation d'ajout au panier avec touche entrée
    $('.quantiteProduit').keyup(function (event) {
        if (event.keyCode == CODE_TOUCHE_ENTREE) {
            //$(this).parent().parent().find('.ajoutPanier').click();
            stockerLignesOperation(this, true, 'produit');

        }
    });
}

function copierElementEnDeplacement(event) {

    if ($(this).hasClass('ligneDraggable')) {
        variableGlobale_numeroExterneCatalogueLigne = $(this).attr('id').split('_')[0];
        variableGlobale_numeroCatalogue = $(this).attr('id').split('_')[1];
    }
    return '<div id="conteneurDraggable" >' + $(this).find("img").parent().html() + '<br/>' + $(this).find("img").parent().data('designation') + '</div>';
}


function modifierModeDAffichageWebShop(modeDAffichage, forcerScroll) {

    if (typeof (forcerScroll) === 'undefined') {
        forcerScroll = false;
    }
    if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True') {

        $(".enregistrerEtatTableauDeBaseSpan").remove();
        etatTableauPourMosaique = tableauListeDesProduits;
        if (etatTableauPourMosaique != '""' && etatTableauPourMosaique != null) {
            etatTableauPourMosaique = etatTableauPourMosaique.split("\\").join("");
            etatTableauPourMosaique = etatTableauPourMosaique.split("^(").join("");
            etatTableauPourMosaique = etatTableauPourMosaique.split(")$").join("");
            oState = JSON.parse(etatTableauPourMosaique);
            if (oState.hasOwnProperty('iLength') && typeof oState.iLength !== 'undefined') {
                $('select[name="tableauListeDesProduits_length"] option').filter(function () {
                    //may want to use $.trim in here
                    return $(this).text() == oState.iLength;
                }).attr('selected', true);
            }
        }
    }
    zoneDeRecherche = $('#rechercheLignes').val();
    if (modeDAffichage != VALEUR_LISTE) {
        $("#pagerListeProduit").hide();
        if ($("#iconeInitialiserTableauProduits").length > 0) {
            $("#iconeInitialiserTableauProduits").remove();
        }
        if ($("#iconeInitialiserTriTableauProduits").length > 0) {
            $("#iconeInitialiserTriTableauProduits").remove();
        }
        if (templatePersonnalise != "") {
            $(".enteteNavigateur").find("#mosaique").addClass('icon-ic-mosaique-active').removeClass('icon-ic-mosaique');
            $(".enteteNavigateur").find("#liste").addClass('icon-ic-liste').removeClass('icon-ic-liste-active');
        }

        afficherListeProduitsMosaique(pageCouranteMozaique, zoneDeRecherche, valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT, forcerScroll);
        setTimeout(function () { $(document).scrollLeft(0); if (templatePersonnalise == "") { $('#blockGauche').height($('body').height() + 620); } $('body').removeClass("bodyOverflowAuto").addClass("bodyOverflowHidden"); }, 300);
        //$(".labelTrier").show();

    } else {
        if (templatePersonnalise == "") {
            $(".labelTrier").hide();
        }
        //syrine
        //        oTable = $('#tableauListeDesProduits').dataTable();
        //        oTable.fnFilter($('#rechercheLignes').val());
        if (templatePersonnalise != "") {
            $(".enteteNavigateur").find("#liste").addClass('icon-ic-liste-active').removeClass('icon-ic-liste');
            $(".enteteNavigateur").find("#mosaique").addClass('icon-ic-mosaique').removeClass('icon-ic-mosaique-active');
        }
        afficherListeProduits($('#rechercheLignes').val(), forcerScroll );
        setTimeout(function () {
            if (templatePersonnalise == "") {
                $('#blockGauche').height($('body').height() + 620);
            } $('body').removeClass("bodyOverflowHidden").addClass("bodyOverflowAuto");
        }, 600);

    }
}

function afficherInscriptionWebshop() {
    $('#layoutInscriptionWebshop').fadeIn(200);
    $('#fenetreInscriptionWebshop').fadeIn(200);
}
function fermerLayoutInscriptionWebshop() {
    $('#layoutInscriptionWebshop').fadeOut(200);
    $('#fenetreInscriptionWebshop').fadeOut(200);
    $('body').css("overflow-y", "scroll");
}
function afficherLogin() {
    $('#layoutLogin').fadeIn(200);
    $('#fenetreLogin').fadeIn(200);
}
function inscriptionWebshop() {
    var erreur = false;
    var messageErreur = '';
    $('.obligatoire').each(function () {
        if ($(this).val() != '') {
            $(this).removeClass('erreurSaisie');
        } else {
            erreur = true;
            $(this).addClass('erreurSaisie');
        }
    });
    if (erreur) {
        messageErreur = CHAMP_OBLIGATOIRE_DOIT_ETRE_REMPLI + '.<br/>';
    }
    // On fait la vérif du checkbox qd tout est ok ("captcha", checkbox généré en JS donc les robots ne le voient pas et ne le cochent pas)
    if (!erreur) {
        if ($('#emailCompte').val() !== undefined) {
            if (verifierEmail.exec($('#emailCompte').val().trim().toLowerCase()) == null) {
                messageErreur = EMAIL_COMPTE_INCORRECT + '.<br/>';
                $('#emailCompte').addClass('erreurSaisie');
            }
        }
        if (!$('#jeNeSuisPasUnRobot').is(':checked')) {
            $('#jeNeSuisPasUnRobot').addClass('erreurSaisie');
            messageErreur += MERCI_DE_COCHER_JE_NE_SUIS_PAS_UN_ROBOT + '.<br/>';
        }
    }
    if (messageErreur == '') {
        $.ajax({
            url: '/webshop/envoyerMailInscriptionSurWebShop',
            data: {
                'numeroSociete': numeroSociete,
                'numeroBoutique': numeroBoutique,
                'denominationSociete': $('#denominationSociete').val(),
                'nomClient': $('#nom').val(),
                'prenomClient': $('#prenom').val(),
                'emailClient': $('#emailCompte').val(),
                'telephoneClient': $('#telephone1Compte').val(),
                'mobileClient': $('#mobile').val(),
                'commentaireClient': $('#commentaire').val(),
                'adresse1': $('#adresse1').val(),
                'adresse2': $('#adresse2').val(),
                'codePostal': $('#codePostal').val(),
                'ville': $('#ville').val(),
                'numeroSiret': $('#numeroSiret').val(),
                'identificationTVA': $('#identificationTVA').val(),
                'jeNeSuisPasUnRobot': $('#jeNeSuisPasUnRobot').is(':checked') ? $('#jeNeSuisPasUnRobot').val() : ""
            },
            success: function (retourServeur) {
                masquerChargement();
                if (retourServeur.substring(0, 7) == 'erreur;') {
                    alerte(retourServeur.split('erreur;')[1]);
                } else {
                    fermerLayoutInscriptionWebshop();
                    $('#contenuPopupInscription input').not(':input[type=button], :input[type=checkbox]').each(function () {
                        $(this).val('');
                    });
                    $("#commentaire").val('');
                    $("#jeNeSuisPasUnRobot").attr("checked", false);
                    alerte(MERCI_VOTRE_DEMANDE_INSCRIPTION_A_ETE_PRISE_EN_COMPTE);
                }
            }
        });
    } else {

        alerte(messageErreur);
    }
}

var lignesPanier = [];
var enteteProduitsInitialisee = false;
var tableauListeDesProduitsInitialise = false;
function initialisationPageProduits() {
    tableauListeDesProduitsInitialise = false;
    $('#listeLargeursColonnes_tableauListeDesProduitsDX').draggable({
        handle: "div.titrePopup"
    });
    modeDAffichage = VALEUR_LISTE;
    enteteProduitsInitialisee = false;
    $('.contenuPage').hide();
    tableauindice = retournerIndiceTableau('tableauListeDesProduits');
    idTableauHtml = 'tableauListeDesProduits';
    etatDuTableau = tableauListeDesProduits;
    if (reinitialiserPaginationListeProduit == false) {
        pageSelectionnee = retournerdebutPage(tableauindice);
    } else {
        pageSelectionnee = 0;
        reinitialiserPaginationListeProduit = false;
    }

    if ($('#filtreQuantite').length > 0) {
        maxQuantiter = $('#filtreQuantite').slider("values", 1);
        minQuantiter = $('#filtreQuantite').slider("values", 0);
    } else {
        maxQuantiter = -1;
        minQuantiter = -1;
    }
    etatATranstiper = tableauListeDesProduits;
    if (etatATranstiper != '""' && etatATranstiper != null) {
        etatATranstiper = etatATranstiper.split("\\").join("");
        etatATranstiper = etatATranstiper.split("^(").join("");
        etatATranstiper = etatATranstiper.split(")$").join("");
        oState = JSON.parse(etatATranstiper);
        nombreDesTupleFournisseur = oState.iLength;
    } else {
        nombreDesTupleFournisseur = 10;
    }

    $('.choixCatalogueCocher .aAssortiment').each(function () {
        if ($(this).text() == 1) {
            aAssortiment = true;
        }
    });

    // Cabler la librairie dataTables sur le tableau
    tableauProduits = $('#tableauListeDesProduits').DataTable({
        'serverSide': true,
        'ajax': {
            'url': '/webshop/peuplementListeDesProduitsDX?filtreEtatTableau=tableauListeDesProduits&numeroSocieteFournisseur=' + numeroSociete + '&numeroBoutique=' + numeroBoutique + '&listeDesCatalogues=' + catalogueCocherStringify + '&listeDesCodesFamilles=' + filtersStringify + '&listeDesCritereValeurs=' + filtreCritereValeurCocherStringify + '&maxQuantite=' + maxQuantiter + '&minQuantite=' + minQuantiter + '&rechercheGlobale=' + zoneDeRecherche.replace('+', '%2B') + '&aAssortiment=' + (aAssortiment == true ? '1' : '0') + '&dateLivraison=' + nouvelleDateDeLivraison,
            'type': 'POST',
            error: function (xhr, error, thrown) {
                if (xhr.responseText.indexOf('<title>') != -1) {
                    exception = xhr.responseText.split('<title>')[1].split('</title>')[0];
                    if (exception.substring(0, 4) == '1000') {
                        alerte(exception.replace('1000:', ''), 'erreur');
                    } else if (exception.substring(0, 4) == '3000') {
                        alerte(exception.replace('3000:', ''), 'confirmationUtilisateur', 'rechargerPage');
                    }
                }
            },
            'beforeSend': function (request) {
                afficherChargement();
                annulerLesAppelsEnAttente();
                $('#tableauListeDesProduits').hide();

            }
        },
        'iDisplayLength': (nombreDesTuplesClient != -1) ? nombreDesTuplesClient : nombreDesTupleFournisseur,
        // Spécifier le trie initial par défaut. Si paramètre spécifié mais vide, alors pas de trie, on reste sur le chargement initial
        // Si paramètre non spécifié, dataTables trie sur la 1ère colonne automatiquement
        'order': [],
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'columns': [
            { 'name': '0', 'className': 'width40 numeriqueTri' },
            { 'name': '1', 'className': 'width135 image', 'orderable': false },
            { 'name': '2', 'className': 'width135 genre' },
            { 'name': '3', 'className': 'width135 espece' },
            { 'name': '4', 'className': 'width135 variete' },

            { 'name': '5', 'className': 'width135' },
            { 'name': '6', 'className': 'width135', 'orderable': false },
            { 'name': '7', 'className': 'width135', 'orderable': false },
            { 'name': '8', 'className': 'width135' },

            { 'name': '9', 'className': 'width135 numeriqueTri' },
            { 'name': '10', 'className': 'width135 numeriqueTri' },
            { 'name': '11', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135  inactif' : 'width135 '), 'visible': (EST_CONNECTE == 'True' ? true : false), 'orderable': false },
            { 'name': '12', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135  inactif' : 'width135 '), 'visible': (EST_CONNECTE == 'True' ? true : false), 'orderable': false },

            { 'name': '13', 'className': 'width135 numeriqueTri' },
            { 'name': '14', 'className': 'width135 numeriqueTri' },
            { 'name': '15', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135  inactif' : 'width135 '), 'visible': (EST_CONNECTE == 'True' ? true : false), 'orderable': false },

            { 'name': '16', 'className': 'width135 numeriqueTri' },
            { 'name': '17', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135 colonneQuantite inactif numeriqueTri' : 'width135 colonneQuantite numeriqueTri'), 'visible': (EST_CONNECTE == 'True' ? true : false), 'orderable': false },
            { 'name': '18', 'className': 'width135 prixStyle numeriqueTri', 'visible': (EST_CONNECTE == 'True' && !(catalogueSansPrix == valeurOui || (clientGenerique == 'True' && afficherPrixDansLesDemandeDeDevis == valeurNon)) ? true : (catalogueSansPrix != valeurOui ? true : false)) },
            { 'name': '19', 'className': 'width135' },
            { 'name': '20', 'className': 'width135 designation' },
            { 'name': '21', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135  inactif' : 'width135 '), 'visible': (EST_CONNECTE == 'True' ? true : false), 'orderable': false },
            { 'name': '22', 'className': 'width135', 'orderable': false },
            { 'name': '23', 'className': 'width135', 'orderable': false },
            { 'name': '24', 'className': 'width135', 'orderable': false },
            { 'name': '25', 'className': 'width135', 'orderable': false },
            { 'name': '26', 'className': 'width135', 'orderable': false },
            { 'name': '27', 'className': 'width135' },
            { 'name': '28', 'className': 'width135 numeriqueTri' },
            { 'name': '29', 'className': 'width135 libellewebshop1', 'visible': true, 'bSortable': true },
            { 'name': '30', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '31', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '32', 'className': 'width40 colonneAjoutPanier', 'visible': (EST_CONNECTE == 'True' ? true : false) },
            { 'name': '33', 'className': 'width40', 'visible': false }

        ],
        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"CltpR>rt',
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        'paginationType': 'full_numbers',

        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        // Spécifier la première page d'affichage
        'displayStart': parseInt(pageSelectionnee),
        // Options sur les filtres
        'oColumnFilterWidgets': {
            //  'bGroupTerms': true, // pour activer le groupage sur les filtres
            'aiExclude': [1] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        },
        // Options sur la visibilité des colonnes
        'colVis': {
            'exclude': [17, 32, 33], // spécifier les colonnes qui ne figurent pas dans la visibilité des colonnes
            'buttonText': AFFICHER_MASQUER_COLONNES,
            //Gestion Des Filtres Par Colonne Et Visibilite
            'fnStateChange': function (iColumn, bVisible) {
                gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, tableauProduits.settings()[0]);
            }
        },
        'colReorder': {
            'realtime': true

        },

        'headerCallback': function (thead, data, start, end, display) {
            if (enteteProduitsInitialisee == false || tableauDesLargeuresEtIndicesProduits == "reinitialisé") {
                enteteProduitsInitialisee = true;
                titresColonnesSauveguarde = titresColonnesProduits;
                titresColonnesProduits = [];
                largeurParDefaut = 0;
                tableauDesLargeuresEtIndicesChargementProduits = [];
                indiceColonnes = 0;
                $(thead).find('th').each(function () {
                    if (tableauDesLargeuresEtIndicesProduits == "reinitialisé") {
                        largeurParDefaut = titresColonnesSauveguarde[indiceColonnes].split(";")[2];
                        indiceColonnes++;
                    } else {
                        largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                        largeurParDefaut = (largeurParDefaut == null ? 0 : largeurParDefaut[0].replace("width", ""));
                    }
                    largeurActuellementAppliquee = (tableauDesLargeuresEtIndicesProduits == "reinitialisé" ? largeurParDefaut : largeurActuel(idTableauHtml, etatDuTableau, $(this).data("origColHeader"), largeurParDefaut));

                    titresColonnesProduits.push($(this).html().ltrim().rtrim() + ";" + $(this).data("origColHeader") + ";" + largeurParDefaut + ";" + largeurActuellementAppliquee);

                });
                titresColonnesProduits = colonnesVisiblesOuPas(etatDuTableau, titresColonnesProduits, idTableauHtml);
                indiceCase = 0;
                $(thead).find('th').each(function () {
                    titresColonnesProduits[indiceCase] = titresColonnesProduits[indiceCase] + ";" + ($(this).data("origNameHeader") === undefined ? "" : $(this).data("origNameHeader"));
                    indiceCase++;
                });
                tableau = [];
                for (i = 0; i < titresColonnesProduits.length; i++) {
                    tableau = titresColonnesProduits[i].split(";");
                    tableauDesLargeuresEtIndicesChargementProduits.push(tableau[1] + ";" + tableau[3]);

                }
                tableauDesLargeuresEtIndicesProduits = (tableauDesLargeuresEtIndicesProduits != "reinitialisé" ? tableauDesLargeuresEtIndicesChargementProduits.join('|') : tableauDesLargeuresEtIndicesProduits);

            }
        },
        'initComplete': function (oSettings, oData) {
            fnOrdonnerColonnes('tableauListeDesProduits', tableauListeDesProduits);
            //$(this).css('visibility', 'visible');
            materialiserChampsDeRecherche('tableauListeDesProduits', true);
            initialiserCoVis('tableauListeDesProduits');

            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(tableauProduits, true, 'tableauListeDesProduits', tableauListeDesProduits, "", (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? false : true)); }, 0);
            tableauProduits.ajax.url('/webshop/peuplementListeDesProduitsDX?numeroSocieteFournisseur=' + numeroSociete
                + '&numeroBoutique=' + numeroBoutique
                + '&listeDesCatalogues=' + catalogueCocherStringify +
                '&listeDesCodesFamilles=' + filtersStringify +
                '&listeDesCritereValeurs=' + filtreCritereValeurCocherStringify +
                '&listefiltresArticleCritereXX=' + filtresArticleCritereXXCocherStringify +
                '&listefiltresTaillePresentation=' + filtresTaillePresentationCocherStringify +
                '&maxQuantite=' + maxQuantiter +
                '&minQuantite=' + minQuantiter +
                '&dateLivraison=' + ($('#dateLivraison').val() != '' && typeof $('#dateLivraison').val() !== 'undefined' ? $('#dateLivraison').val() : '') +
                '&rechercheGlobale=' + zoneDeRecherche.replace('+', '%2B') +
                '&aAssortiment=' + (aAssortiment == true ? '1' : '0') +
                '&versionCode=' + VERSION_CODE + '&numeroSocieteFournisseurEncours=' + numeroSociete + '&numeroBoutiqueEncours=' + numeroBoutique);

            if (EST_CONNECTE == 'True') {
                //$("#tableauListeDesProduits_filter label").css("left", "-125px");
                if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True') {

                    $("#tableauListeDesProduits_wrapper .ColVis").hide();
                } else {
                    $(".enregistrerEtatTableauDeBaseSpan").appendTo(".enteteNavigateur");
                    $(".enteteNavigateur").find("#iconeInitialiserTableauProduits").remove();
                    $("#iconeInitialiserTableauProduits").appendTo(".enteteNavigateur");
                    $(".enteteNavigateur").find("#iconeInitialiserTriTableauProduits").remove();
                    $("#iconeInitialiserTriTableauProduits").appendTo(".enteteNavigateur");
                }
            } else {
                $("#tableauListeDesProduits_filter label").css("left", "-300px");
                $("#tableauListeDesProduits_wrapper .ColVis").hide();
            }
            //Ajouter un div qui englope le tableau apres le div .top => pour régler le probleme de deplacement de pagination
            $('#tableauListeDesProduits_wrapper .top').next().wrap('<div id="divPourPositionnerLePaginationDataTable">');

            //$('.imageProduitEnteteAssortimentModeListe').parent().parent().not('.colonneAjoutPanier').css('background-color', '#FF866A !important');


            $('#tableauListeDesProduits_wrapper').find('.top').find('.ColVis').find('.ColVis_Button').attr("id", "colVisButtonProduits");

            $('#tableauListeDesProduits_length').find('select').val(nombreDesTuplesClient != -1 ? nombreDesTuplesClient : nombreDesTupleFournisseur);
            $('#tableauListeDesProduits_paginate').append('<span>' + oData.recordsTotal + ' ' + ELEMENTS + ' </label>');
            tableauProduits.settings()[0]._iDisplayLength = nombreDesTuplesClient != -1 ? nombreDesTuplesClient : nombreDesTupleFournisseur;
            if (EST_CONNECTE == 'True') {
                fnAfficherCacherColonneOrigCol('tableauListeDesProduits', 17, true);
            }
            if (catalogueSansPrix == valeurOui || (clientGenerique == 'True' && afficherPrixDansLesDemandeDeDevis == valeurNon) || (EST_CONNECTE != 'True' && catalogueSansPrix == valeurOui)) {
                fnAfficherCacherColonneOrigCol('tableauListeDesProduits', 18, false);
            } else if (EST_CONNECTE != 'True' && catalogueSansPrix != valeurOui) {
                fnAfficherCacherColonneOrigCol('tableauListeDesProduits', 18, true);
            }

            if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'False') {
                $('select[name="tableauListeDesProduits_length"]').on("change", function (event) {
                    afficherChargement();
                    $.ajax({
                        url: '/webshop/miseEnSessionDeNombreDeTupleDT',
                        data: {
                            'nombreDesTuplesDT': $('select[name="tableauListeDesProduits_length"]').val()
                        },
                        success: function (resultat) {
                            masquerChargement();
                        }
                    });
                });
            }

            masquerChargement();
            setTimeout(function () { $('#tableauListeDesProduits').show(); tableauListeDesProduitsInitialise = true; }, 0);
            setTimeout(function () {
                if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True') {
                    $("#tableauListeDesProduits thead ").prepend('<div class="descativationClient"></div>')
                }
                $("#tableauListeDesProduits thead ").prepend('<div class="vide"></div>')
            }, 0);




        },
        "rowCallback": function (nRow, aData, iDisplayIndex) {
            inputQuantiteProduit = $('td', nRow).find('.quantiteProduit');
            $(nRow).find("img").parent().attr("id", inputQuantiteProduit.data('numeroexterne') + "_" + inputQuantiteProduit.data('numerocatalogue'));
            $(nRow).find("img").parent().attr("data-designation", aData[20]);
            //            $(nRow).find("img").parent().click(function () {
            //                voirDetailsProduit(aData[0], 0 , 'Unite');
            //            });
            inputCommentaireEtiquette = $('td', nRow).find('.commentaireEtiquettes');
            inputPrixEtiquettes = $('td', nRow).find('.prixEtiquettes');
            inputCodeEAN = $('td', nRow).find('.codeEAN');
            inputCodePartenaire = $('td', nRow).find('.codePartenaireInput');
            if (inputQuantiteProduit.length > 0) {
                numeroExterneCatalogue = inputQuantiteProduit.data('numeroexterne');
                expression = "^" + numeroExterneCatalogue + ";";
                reg = new RegExp(expression, 'g');
                trouverLigne = false;
                nbLignes = lignesPanier.length;
                i = 0;
                valeurs = [];
                while (!trouverLigne && i < nbLignes) {
                    if (lignesPanier[i].match(reg)) {
                        //numeroExterneCatalogue + ";" + numeroCatalogue + ";" + quantite + ";" + prixEtiquettes + ";" + commentaireEtiquettes + ";" + prixHt
                        valeurs = lignesPanier[i].split(";");
                        unNumeroExterneCatalogue = valeurs[0];
                        if (inputPrixEtiquettes.length > 0) {
                            inputPrixEtiquettes.val(valeurs[3]);
                        }
                        if (inputCommentaireEtiquette.length > 0) {
                            inputCommentaireEtiquette.val(valeurs[4]);
                        }
                        if (inputCodeEAN.length > 0) {
                            inputCodeEAN.val(valeurs[7]);
                        }
                        if (inputCodePartenaire.length > 0) {
                            inputCodePartenaire.val(valeurs[6]);
                        }
                        inputQuantiteProduit.val(valeurs[2]);


                        trouverLigne = true;

                    }
                    i++;

                }
            }

        },
        'drawCallback': function (oSettings) {
            $("#tableauListeDesProduits tr img.imageProduitModeListe").parent().addClass('ligneDraggable');
            forcerCablagePagination('tableauListeDesProduits');
            if (etatDuTableau != '""' && etatDuTableau != null && tableauDesLargeuresEtIndicesProduits != "reinitialisé") {
                etatDuTableau = etatDuTableau.split("\\").join("");
                etatDuTableau = etatDuTableau.split("^(").join("");
                etatDuTableau = etatDuTableau.split(")$").join("");
                oState = JSON.parse(etatDuTableau);
                if (oState.hasOwnProperty('ColWidth') && typeof oState.ColWidth !== 'undefined') {
                    if (oState.ColWidth.length > 0) {
                        setTimeout(function () { appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesProduits); }, 0);

                    }
                }
            } else if (tableauDesLargeuresEtIndicesProduits == "reinitialisé") {

                indiceColonne = 1;
                $('#' + idTableauHtml).find('thead').find('tr:nth-child(1)').find('th').each(function () {
                    largeurParDefaut = "width" + $(this).data("widthHeader");
                    $('#' + idTableauHtml).find('tfoot').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('tbody').find('td:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('thead').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    indiceColonne++;

                });

                tableauDesLargeuresEtIndicesChargementProduits = [];
                for (i = 0; i < titresColonnesProduits.length; i++) {
                    tableau = titresColonnesProduits[i].split(";");
                    tableauDesLargeuresEtIndicesChargementProduits.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesProduits = tableauDesLargeuresEtIndicesChargementProduits.join('|');
            } else {
                appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesProduits);
            }


            setTimeout(function () {

                if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' || EST_CONNECTE != 'True') {
                    $('.descativationClient').height($("#tableauListeDesProduits thead").height());
                }
            }, 250);
            $('.imageProduitEnteteAssortimentModeListe').parent().parent().addClass('enteteAssortiment');
            $('.imageProduitDetailsAssortimentModeListe').parent().parent().addClass('detailsAssortiment');
            $('.detailsAssortiment img').parent().removeClass('ligneDraggable');
            $(".ligneDraggable img").parent().draggable({
                cursor: 'move',
                containment: 'document',
                helper: copierElementEnDeplacement
            });
            $('.existePanier').parent().siblings().not('.colonneAjoutPanier').addClass('produitDansLePanier');
            $('.existePanier').parent().addClass('produitDansLePanier');
            $('.existePanier').parent().parent().find('.prixStyle').addClass('prixStyleBlanc');

            ////////////////////////////////////////////////////////////////////////////
            if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True') {
                gererLesInputDeSaisi('produit');
            }

            // Validation d'ajout au panier avec touche entrée
            $('.quantiteProduit').keyup(function (event) {
                if (event.keyCode == CODE_TOUCHE_ENTREE) {
                    //$(this).parent().parent().find('.ajoutPanier').click();
                    stockerLignesOperation(this, true, 'produit');

                }
            });
            $('.voirTarifsDeconnecte').click(function () {
                afficherLogin();
            });


            $('#tableauListeDesProduits')
                .on('page.dt', function () { allerVersLeHaut(true); })
                .DataTable();

            $('#rechercheLignes').val(zoneDeRecherche);
            allerVersLeHaut();
            if (tableauListeDesProduitsInitialise == true) {
                masquerChargement();

                setTimeout(function () { $('#tableauListeDesProduits').show(); }, 0);
            }

            if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True') {
                gererLeTraitementDesTarifs("Liste");
                $('.grilleTarifaireModeColonne').parent().parent().parent().find('.prixStyle').addClass('grilleListe');
                $('.grilleTarifaireModeColonne').parent().parent().parent().parent().find('.prixStyle').addClass('grilleListe');
                var newWidth = $('.enTeteColonneCliquable.prixStyle').outerWidth();
                setTimeout(function () {
                    $('.grilleListe').css('width', newWidth + 'px');
                    $('.grilleListe').css('min-width', newWidth + 'px');
                    $('.grilleListe').css('max-width', newWidth + 'px');
                }, 0);
            }
        }


    });
    // Ne pas tenir compte des filtres dans la sauvegarde d'état du tableau
    // Je n'ai pas l'explication mais si l'appel à la méthode se fait en dehors d'un setTimeout alors exception JS

    $('.enTeteColonneCliquable').attr('title', CLIQUER_POUR_TRIER_SUR_LA_COLONNE_OU_MAINTENIR_POUR_DEPLACER_LA_COLONNE);
    navigationInputParFlecheDansTableau('tableauListeDesProduits');

}

function initialisationPageProduitsDX() {
    tableauListeDesProduitsInitialise = false;
    $('#listeLargeursColonnes_tableauListeDesProduitsDX').draggable({
        handle: "div.titrePopup"
    });
    modeDAffichage = VALEUR_LISTE;

    $('.contenuPage').hide();

    //if (reinitialiserPaginationListeProduit == false) {
    //    pageSelectionnee = retournerdebutPage(tableauindice);
    //} else {
    //    pageSelectionnee = 0;
    //    reinitialiserPaginationListeProduit = false;
    //}

    if ($('#filtreQuantite').length > 0) {
        maxQuantiter = $('#filtreQuantite').slider("values", 1);
        minQuantiter = $('#filtreQuantite').slider("values", 0);
    } else {
        maxQuantiter = -1;
        minQuantiter = -1;
    }
    if (configurationTableauxDx.some(function (item) { if (item.idGrid == "tableauListeDesProduitsDX" && item.numeroBoutique == numeroBoutique) { return item; } })) {
        // nombreDesTupleFournisseur = configurationTableauxDx.find(function (item) { if (item.idGrid == "tableauListeDesProduitsDX" && item.numeroBoutique == numeroBoutique) { return item; } }).structuredEtatDatagrid.pageSize;
        nombreDesTupleFournisseur = (configurationTableauxDx.filter(function (item) { return item.idGrid === "tableauListeDesProduitsDX" && item.numeroBoutique == numeroBoutique })[0]).structuredEtatDatagrid.pageSize;
    } else {
        nombreDesTupleFournisseur = 10;
    }
    $('.choixCatalogueCocher .aAssortiment').each(function () {
        if ($(this).text() == 1) {
            aAssortiment = true;
        }
    });
    $.ajax({
        url: '/webshop/colonnesConfigProduits',
        async: false,
        dataType: "json",
        success: function (resultat) {
            masquerChargement();
            conf = resultat;

            $("#tableauListeDesProduitsDX").data({ conf: resultat });
            $(function () {
                var produitsStore = new DevExpress.data.CustomStore({
                    load: function (loadOptions) {
                        var deferred = $.Deferred(),
                            filter = [];
                        filterHeader = [];
                        chargerFiltres(myTableProduits, loadOptions, filter, filterHeader);
                        //paramètres d'exports spécifiques !! évitez les espaces !!

                        $.ajax({
                            url: '/webshop/peuplementListeDesProduitsDX?filtreEtatTableau=tableauListeDesProduits&numeroSocieteFournisseur=' + numeroSociete +
                                '&numeroBoutique=' + numeroBoutique + '&listeDesCatalogues=' + catalogueCocherStringify
                                + '&listeDesCodesFamilles=' + filtersStringify +
                                '&listeDesCritereValeurs=' + filtreCritereValeurCocherStringify +
                                '&listefiltresArticleCritereXX=' + filtresArticleCritereXXCocherStringify +
                                '&listefiltresTaillePresentation=' + filtresTaillePresentationCocherStringify +
                                '&maxQuantite=' + maxQuantiter + '&minQuantite=' + minQuantiter +
                                '&rechercheGlobale=' + zoneDeRecherche.replace('+', '%2B') +
                                '&aAssortiment=' + (aAssortiment == true ? '1' : '0') +
                                '&dateLivraison=' + nouvelleDateDeLivraison,

                            dataType: "json",
                            data: {
                                filter: JSON.stringify(filter),
                                filterHeader: JSON.stringify(filterHeader),
                                sort: JSON.stringify(loadOptions.sort == null ? [] : loadOptions.sort),
                                skip: loadOptions.skip,
                                take: loadOptions.take
                            },
                            'beforeSend': function (request) {
                                annulerLesAppelsEnAttente();
                                if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True') {
                                    if (largeurTableau == 0 && $('#tableauListeDesProduitsDX>.dx-gridbase-container').width() > 0) {
                                        largeurTableau = $('#tableauListeDesProduitsDX>.dx-gridbase-container').width();
                                    }
                                }
                            },
                            success: function (result) {
                                nbElements = result.totalCount;
                                deferred.resolve(result.items, { totalCount: result.totalCount });
                            },
                            error: function () {
                                deferred.reject("Data Loading Error");
                            }
                        });

                        return deferred.promise();
                    }
                });

                myTableProduits = $("#tableauListeDesProduitsDX").dxDataGrid({
                    dataSource: {
                        store: produitsStore
                    },
                    paging: {
                        pageSize: parseInt(nombreDesTuplesClient) != -1 ? parseInt(nombreDesTuplesClient) : nombreDesTupleFournisseur
                    },
                    pager: {
                        visible: false,
                    },
                    filterRow: {
                        visible: false
                    },
                    columnChooser: {
                        enabled: true,

                    },
                    remoteOperations: {
                        filtering: $("#tableauListeDesProduitsDX").data("enableheader") == "True",
                        sorting: $("#tableauListeDesProduitsDX").data("enableheader") == "True",
                    },
                    allowColumnReordering: $("#tableauListeDesProduitsDX").data("enableheader") == "True",
                    // allowColumnResizing: $("#tableauListeDesProduitsDX").data("enableheader") == "True",
                    allowColumnFiltering: $("#tableauListeDesProduitsDX").data("enableheader") == "True",
                    allowSearch: $("#tableauListeDesProduitsDX").data("enableheader") == "True",

                    columns: [
                        {
                            dataField: "numeroCatalogueLigne",
                            caption: "numeroCatalogueLigne",
                            allowEditing: false,
                            width: 40
                        }
                        , {
                            caption: "imageMedia",
                            dataField: "imageMedia",
                            allowEditing: false,
                            width: 135,
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                $(container).addClass("image").addClass("ligneDraggable");
                                $(container).attr('id', options.data.numeroExterneProduit + "_" + options.data.numeroCatalogue);
                                $(container).attr('data-designation', options.data.designationArticle);
                                $(options.value)
                                    .appendTo(container);
                            }

                        }
                        , {
                            caption: "imageCatalogue",
                            dataField: "imageCatalogue",
                            width: 135,
                            allowEditing: false,
                            cellTemplate: function (container, options) {
                                $(options.value)
                                    .appendTo(container);
                            }

                        }
                        , {
                            caption: "quantitePanier",
                            dataField: "quantitePanier",
                            width: 135,
                            allowEditing: false,
                            visible: false,
                            cellTemplate: function (container, options) {
                                $(container).addClass("noColor");
                                $(options.value).appendTo(container);
                            }
                        }
                        , {
                            caption: "genre",
                            dataField: "genre",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                $(container).addClass("genre");
                                $("<span />").text(options.value).appendTo(container);
                            }

                        },
                        {
                            caption: "espece",
                            dataField: "espece",
                            allowEditing: false,
                            width: 135,
                            alignment: "left",
                            cellTemplate: function (container, options) {
                                $(container).addClass("espece");
                                $("<span />").text(options.value).appendTo(container);
                            }

                        },
                        {
                            caption: "variete",
                            dataField: "variete",
                            allowEditing: false,
                            width: 135,
                            alignment: "left",
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                $(container).addClass("variete");
                                $("<span />").text(options.value).appendTo(container);
                            }

                        },
                        {
                            caption: "presentationMillesime",
                            dataField: "presentationMillesime",
                            allowEditing: false,
                            width: 135,
                            alignment: "left"

                        },
                        {
                            caption: "tailleUniteVente",
                            dataField: "tailleUniteVente",
                            allowEditing: false,
                            width: 135,
                            alignment: "left"
                        },
                        {
                            caption: "designationArticle",
                            dataField: "designationArticle",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",

                        },
                        {
                            caption: "designation",
                            dataField: "designation",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                $(container).addClass("designation");
                                $("<span />").text(options.value).appendTo(container);
                            }

                        },
                        {
                            caption: "quantiteProduits",
                            dataField: "quantiteProduits",
                            width: 135,
                            allowEditing: true,
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                var clone;
                                if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                                    expression = "^" + options.data.numeroExterneProduit + ";";
                                    reg = new RegExp(expression, 'g');
                                    uneLigne = lignesPanier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                        undefined;

                                    //find(function (item) { if (item.match(reg)) { return item } });
                                    if (typeof uneLigne !== 'undefined') {
                                        valeurs = uneLigne.split(";");
                                        clone = $(options.data.quantiteProduits).clone().val(valeurs[2]);
                                    } else {
                                        clone = options.value;
                                    }
                                } else {
                                    clone = options.value;
                                }

                                $(clone).appendTo(container);
                            },
                            alignment: "right",
                        },
                        {
                            caption: "quantiteLivree",
                            dataField: "quantiteLivree",
                            allowEditing: true,
                            width: 135,
                            alignment: "right",
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                $(container).attr('class', (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? ' colonneQuantite inactif numeriqueTri' : ' colonneQuantite numeriqueTri'));

                                //$(options.value.toString()).appendTo(container);
                                container.append(options.value.toString());
                            },

                        },
                        {
                            caption: "colonnePrix",
                            dataField: "colonnePrix",
                            width: 135,
                            allowEditing: false,
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                var clone = $(options.data.colonnePrix).clone();
                                $(container).attr('class', 'prixStyle numeriqueTri');
                                if (typeof clone.data('async-url') !== 'undefined') {
                                    url = clone.data('async-url');
                                    var request = $.ajax({
                                        url: url,
                                        dataType: 'html',
                                        type: 'get',
                                        success: function (html) {
                                            $(clone).replaceWith(html);
                                            masquerChargement();
                                        }
                                    });
                                    XHR.push(request);
                                    $(clone).appendTo(container);
                                } else if ($(options.value).find("table").length > 0 || $(options.value).hasClass("voirTarifsDeconnecte") || $(options.value).hasClass("voirTarifs")) {
                                    $(options.value).appendTo(container);
                                } else {
                                    $("<span />").text(options.value).appendTo(container);
                                }


                            },
                            alignment: "right",
                        },
                        {
                            caption: "commentaireEtiquettes",
                            dataField: "commentaireEtiquettes",
                            width: 135,
                            allowEditing: true,
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                var clone;
                                if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                                    expression = "^" + options.data.numeroExterneProduit + ";";
                                    reg = new RegExp(expression, 'g');
                                    uneLigne = lignesPanier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                        undefined;
                                    //find(function (item) { if (item.match(reg)) { return item } });
                                    if (typeof uneLigne !== 'undefined') {
                                        valeurs = uneLigne.split(";");


                                        if ($(options.data.commentaireEtiquettes).hasClass("commentaireEtiquettes")) {

                                            clone = $(options.data.commentaireEtiquettes).clone().val(valeurs[4]);

                                        }

                                    } else {
                                        clone = options.value;
                                    }
                                } else {
                                    clone = options.value;
                                }


                                $(clone)
                                    .appendTo(container);
                            },
                            alignment: "right",
                        },
                        {
                            caption: "prixEtiquettes",
                            dataField: "prixEtiquettes",
                            width: 135,
                            allowEditing: true,
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                var clone;
                                if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                                    expression = "^" + options.data.numeroExterneProduit + ";";
                                    reg = new RegExp(expression, 'g');
                                    uneLigne = lignesPanier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                        undefined;
                                    //find(function (item) { if (item.match(reg)) { return item } });
                                    if (typeof uneLigne !== 'undefined') {
                                        valeurs = uneLigne.split(";");


                                        if ($(options.data.prixEtiquettes).hasClass("prixEtiquettes")) {

                                            clone = $(options.data.prixEtiquettes).clone().val(valeurs[3]);

                                        }

                                    } else {
                                        clone = options.value;
                                    }
                                } else {
                                    clone = options.value;
                                }


                                $(clone)
                                    .appendTo(container);
                            },
                            alignment: "right",
                        },
                        {
                            caption: "codeEAN",
                            dataField: "codeEAN",
                            allowEditing: true,
                            width: 135,
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                var clone;
                                if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                                    expression = "^" + options.data.numeroExterneProduit + ";";
                                    reg = new RegExp(expression, 'g');
                                    uneLigne = lignesPanier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                        undefined;
                                    //find(function (item) { if (item.match(reg)) { return item } });
                                    if (typeof uneLigne !== 'undefined') {
                                        valeurs = uneLigne.split(";");


                                        if ($(options.data.codeEAN).hasClass("codeEAN")) {

                                            clone = $(options.data.codeEAN).clone().val(valeurs[7]);

                                        }

                                    } else {
                                        clone = options.value.toString().replace("(", "").replace(")", "");
                                    }
                                } else {
                                    clone = options.value.toString().replace("(", "").replace(")", "");
                                }
                                container.append(clone);
                                //$(clone).appendTo(container);
                            },
                            alignment: "left"

                        },
                        {
                            caption: "codePartenaire",
                            dataField: "codePartenaire",
                            width: 135,
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                var clone;

                                if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                                    expression = "^" + options.data.numeroExterneProduit + ";";
                                    reg = new RegExp(expression, 'g');
                                    uneLigne = lignesPanier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                        undefined;
                                    //find(function (item) { if (item.match(reg)) { return item } });
                                    if (typeof uneLigne !== 'undefined') {
                                        valeurs = uneLigne.split(";");


                                        if ($(options.data.codePartenaire).hasClass("codePartenaireInput")) {

                                            clone = $(options.data.codePartenaire).clone().val(valeurs[6]);

                                        }

                                    } else {
                                        clone = options.value;
                                    }
                                } else {
                                    clone = options.value;
                                }

                                container.append(clone);
                                //$(clone).appendTo(container);
                            },
                            alignment: "left",

                        },
                        {
                            caption: "numeroExterne",
                            dataField: "numeroExterne",
                            allowEditing: false,
                            width: 135,
                            alignment: "left"
                        },
                        {
                            caption: "codeArticle",
                            dataField: "codeArticle",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",

                        },
                        {
                            caption: "pcb",
                            dataField: "pcb",
                            allowEditing: false,
                            width: 100,
                            alignment: "right",
                        },
                        {
                            caption: "quantiteArticleParEmballage",
                            dataField: "quantiteArticleParEmballage",
                            allowEditing: false,
                            width: 135,
                            alignment: "right",
                        },
                        {
                            caption: "codeEmballage3",
                            dataField: "codeEmballage3",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",

                        },
                        {
                            caption: "croisementEmballage2Vers3",
                            dataField: "croisementEmballage2Vers3",
                            allowEditing: false,
                            width: 135,
                            alignment: "left"
                        },
                        {
                            caption: "codeEmballage2",
                            dataField: "codeEmballage2",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",

                        },
                        {
                            caption: "croisementEmballage1Vers2",
                            dataField: "croisementEmballage1Vers2",
                            allowEditing: false,
                            width: 135,
                            alignment: "left"
                        },
                        {
                            caption: "codeEmballage1",
                            dataField: "codeEmballage1",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",

                        },
                        {
                            caption: "codeEmballage4",
                            dataField: "codeEmballage4",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",

                        },
                        {
                            caption: "prix2",
                            dataField: "prix2",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",
                        },
                        {
                            caption: "libelleWebshop1",
                            dataField: "libelleWebshop1",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",
                            renderAsync: true,
                            cellTemplate: function (container, options) {
                                $(container).addClass("libellewebshop1");
                                $("<span />").text(options.value).appendTo(container);
                            }
                        },
                        {
                            caption: "libelleWebshop2",
                            dataField: "libelleWebshop2",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",

                        },
                        {
                            caption: "libelleWebshop3",
                            dataField: "libelleWebshop3",
                            width: 135,
                            allowEditing: false,
                            alignment: "left",
                        },
                        {
                            caption: "codeCritere1",
                            dataField: "codeCritere1",
                            allowEditing: false,
                            width: 135,
                            alignment: "left"
                        },
                        {
                            caption: "inputBoutonOuIconeAjouterAuPanier",
                            dataField: "inputBoutonOuIconeAjouterAuPanier",
                            width: 80,
                            allowEditing: false,
                            renderAsync: true,
                            cssClass: "largeurBoutonAjoutPanier",
                            cellTemplate: function (container, options) {
                                $(options.value)
                                    .appendTo(container);
                            }
                        }
                    ],
                    onSelectionChanged: function (selectedItems) {
                        var idGrid = selectedItems.component.element()[0].id;
                        var data = selectedItems.selectedRowsData[0];

                    },
                    onInitialized: function (e) {
                        initialized(e);
                        var dataGrid = e.component;
                        $('#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar');
                        if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' && EST_CONNECTE == 'True') {
                            $('#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar').addClass("fournisseur");
                        } else {
                            $('#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar').addClass("videClient");
                            dataGrid.option("allowColumnResizing", false);
                        }
                        dataGrid.option("columnChooser.enabled", false);
                        setTimeout(function () {
                            refreshPagerListeProduitDX()
                            
                        }, 2000);

                    },
                    onOptionChanged: function (e) {
                        if (e.name == "paging") {
                            refreshPagerListeProduitDX();
                        }
                    },
                    onContentReady: function (e) {
                        //var dataGrid = e.component;
                        //var pager = e.component.getView("pagerView").element().dxPager("instance");


                        //pager.option("lightModeEnabled", true);
                        //setTimeout(function () {
                        //    if ($(".dx-affichage-avant").length == 0) {
                        //        $("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes").prepend("<label class='dx-affichage-avant'>Montrer </label>");
                        //        $("<span class='dx-affichage-apres'> par page</span><span class='dx-affichage-apres2'>Page </span>").insertAfter("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes>.dx-selectbox");
                        //        $("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-header-panel").prepend("<div class='vide' ></div>");

                        //        $("<span id='dxInfo'/>").text("(" + nbElements + " éléments)").appendTo(".dx-pages");
                        //    }

                        //});
                        //YTR Développement d’un pager factorisé pour les modes ( liste et mosaïques) 
                        if (initializedDX == false) {
                            refreshPagerListeProduitDX();
                            initializedDX = true;
                        }

                        if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True') {
                            gererLesInputDeSaisi('produit');
                            //pour résoudre le problème de la derniere colonne qui disparait
                            if (largeurTableau > 0) {
                                $('#tableauListeDesProduitsDX>.dx-gridbase-container').width(largeurTableau);
                            }


                        }
                        // Validation d'ajout au panier avec touche entrée
                        $('.quantiteProduit').keyup(function (event) {
                            if (event.keyCode == CODE_TOUCHE_ENTREE) {
                                //$(this).parent().parent().find('.ajoutPanier').click();
                                stockerLignesOperation(this, true, 'produit');

                            }
                        });
                        if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'False' || EST_CONNECTE == 'False') {
                            $('#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar>.dx-toolbar-items-container>.dx-toolbar-before').hide();
                        }
                        $('.voirTarifsDeconnecte').click(function () {
                            afficherLogin();
                        });
                        if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'False') {
                            if (pageSize != e.component.pageSize()) {
                                if (pageSize === undefined) {
                                    pageSize = e.component.pageSize();
                                }
                                else {
                                    pageSize = e.component.pageSize();
                                    afficherChargement();
                                    $.ajax({
                                        url: '/webshop/miseEnSessionDeNombreDeTupleDT',
                                        data: {
                                            'nombreDesTuplesDT': e.component.pageSize()
                                        },
                                        success: function (resultat) {
                                            masquerChargement();
                                        }
                                    });
                                }
                            }


                        }

                        $('.imageProduitEnteteAssortimentModeListe').parent().parent().addClass('enteteAssortiment');
                        $('.imageProduitDetailsAssortimentModeListe').parent().parent().addClass('detailsAssortiment');
                        $('.detailsAssortiment img').parent().removeClass('ligneDraggable');

                        $('.existePanier').parent().siblings().not('.colonneAjoutPanier').addClass('produitDansLePanier');
                        $('.existePanier').parent().addClass('produitDansLePanier');
                        $('.existePanier').parent().parent().find('.prixStyle').addClass('prixStyleBlanc');

                        $(".ligneDraggable").draggable({
                            cursor: 'move',
                            appendTo: "body",
                            containment: 'document',
                            helper: copierElementEnDeplacement
                        });

                        $('#rechercheLignes').val(zoneDeRecherche);
                        allerVersLeHaut();

                        $('.contenuPage').show();
                        masquerChargement();
                        if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True') {
                            //gererLeTraitementDesTarifs("Liste");
                            $('.grilleTarifaireModeColonne').parent().parent().parent().find('.prixStyle').addClass('grilleListe');
                            $('.grilleTarifaireModeColonne').parent().parent().parent().parent().find('.prixStyle').addClass('grilleListe');
                            var newWidth = $('.enTeteColonneCliquable.prixStyle').outerWidth();
                            setTimeout(function () {
                                $('.grilleListe').css('width', newWidth + 'px');
                                $('.grilleListe').css('min-width', newWidth + 'px');
                                $('.grilleListe').css('max-width', newWidth + 'px');

                            }, 0);

                            if (templatePersonnalise != "") {
                                if ($("#tableauGrilleTarifaireModeListe").length > 0) {
                                    $("td.grilleListe").ClassyScroll();
                                }
                            }
                        }

                        e.component.updateDimensions();
                    },
                    onRowPrepared: function (e) {
                        /*var element = (e.rowElement)[0];
                        //console.log(element);
                        //console.log($(element).find('.commentaireEtiquettes'));*/
                    },
                    onCellClick: function (e) {
                        //YTR Développement d’un pager factorisé pour les modes ( liste et mosaïques)
                        //var pager = e.component.getView("pagerView").element().dxPager("instance");
                        //pager.option("lightModeEnabled", true);
                        //setTimeout(function () {
                        //    if ($(".dx-affichage-avant").length == 0) {
                        //        $("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes").prepend("<label class='dx-affichage-avant'>Montrer </label>");
                        //        $("<span class='dx-affichage-apres'> par page</span><span class='dx-affichage-apres2'>Page </span>").insertAfter("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes>.dx-selectbox");
                        //        $("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-header-panel").prepend("<div class='vide' ></div>");
                        //        $("<span id='dxInfo'/>").text("(" + nbElements + " éléments)").appendTo(".dx-pages");
                        //    }

                        //});
                    },
                    onRowClick: function (selectedItems) {
                        //YTR Développement d’un pager factorisé pour les modes ( liste et mosaïques) 
                        //var dataGrid = selectedItems.component;
                        //var pager = dataGrid.getView("pagerView").element().dxPager("instance");

                        //pager.option("lightModeEnabled", true);
                        ////setTimeout(function () {
                        //if ($(".dx-affichage-avant").length == 0) {
                        //    $("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes").prepend("<label class='dx-affichage-avant'>Montrer </label>");
                        //    $("<span class='dx-affichage-apres'> par page</span><span class='dx-affichage-apres2'>Page </span>").insertAfter("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes>.dx-selectbox");
                        //    $("#tableauListeDesProduitsDX>.dx-datagrid>.dx-datagrid-header-panel").prepend("<div class='vide' ></div>");
                        //    $("<span id='dxInfo'/>").text("(" + nbElements + " éléments)").appendTo(".dx-pages");
                        //}

                        ////});


                    },
                    onKeyDown: function (e) {
                        var $target = $(e.event.target);
                        if (e.event.keyCode === 37 || e.event.keyCode === 39) {
                            e.event.preventDefault();
                        }
                        var visibleColumns = e.component.getController("columns").getVisibleColumns();
                        if (e.event.keyCode === 9) {
                            columnIndex = $target.is("input") ? $target.parent().index() + 1 : $target.index() + 1;


                            if (!e.event.shiftKey && $target.is("input") && visibleColumns[columnIndex] && !visibleColumns[columnIndex].allowEditing) {
                                nextRow = columnIndex == visibleColumns.length ? true : false;

                                if (nextRow) {
                                    nextRow = false;
                                    $nextTarget = $target.parent().parent().next().find(".td:first-child");
                                } else {
                                    $nextTarget = $target.parent().next();

                                }
                                while ($nextTarget.find("input").length == 0) {

                                    $nextTarget = $nextTarget.next();

                                }
                                e.event.target = $nextTarget;
                            } else {
                            }
                        }
                        if (e.event.keyCode === 40) {
                            columnIndex = $target.is("input") ? $target.parent().index() : $target.index();

                            var row = $target.parent().parent().next();

                            if (!e.event.shiftKey && $target.is("input") && visibleColumns[columnIndex] && (!visibleColumns[columnIndex].allowEditing || $($(row.get(0)).find("td")[6]).find("input").length == 0)) {// 


                                $nextTarget = $($($target.parent().parent().next().get(0)).find("td")[columnIndex]);


                                while ($nextTarget.length > 0 && $nextTarget.find("input").length == 0) {
                                    $nextTarget = $($($nextTarget.parent().next().get(0)).find("td:not('.nonNaviguable')")[columnIndex]);
                                }


                                e.event.target = $nextTarget;
                                setTimeout(function () { $nextTarget.find("input").focus(); }, 100);
                            } else {

                                setTimeout(function () { $($($target.parent().parent().next().get(0)).find("td:not('.nonNaviguable')")[columnIndex]).find("input").focus(); }, 100);
                            }
                        }
                        if (e.event.keyCode === 38) {
                            columnIndex = $target.is("input") ? $target.parent().index() : $target.index();

                            var row = $target.parent().parent().prev();

                            if (!e.event.shiftKey && $target.is("input") && visibleColumns[columnIndex] && (!visibleColumns[columnIndex].allowEditing || $($(row.get(0)).find("td")[6]).find("input").length == 0)) {// 


                                $nextTarget = $($($target.parent().parent().prev().get(0)).find("td")[columnIndex]);


                                while ($nextTarget.length > 0 && $nextTarget.find("input").length == 0) {
                                    $nextTarget = $($($nextTarget.parent().prev().get(0)).find("td:not('.nonNaviguable')")[columnIndex]);
                                }


                                e.event.target = $nextTarget;
                                setTimeout(function () { $nextTarget.find("input").focus(); }, 100);
                            } else {

                                setTimeout(function () {
                                    $($($target.parent().parent().prev().get(0)).find("td:not('.nonNaviguable')")[columnIndex]).find("input").focus();
                                }, 100);
                            }
                        }
                    },

                }).dxDataGrid("instance");
            });
            setTimeout(function () { initialisationRenommageColonne(resultat, "tableauListeDesProduitsDX", configRenommageProduit); }, 0);

        }
    });

}

function initialisationPagerListe() {
    //YTR Développement d’un pager factorisé pour les modes ( liste et mosaïques) 
    //console.log("initialisationPagerListe")    
    $('#pagerListeProduit .paginationProduit li').click(function () {

        numeroPage = $(this).text();
        variableDeRecherche = $('#rechercheLignes').val().trim();
        if ($(this).text() != 'prev' && $(this).text() != 'next') {
            if ($("#tableauListeDesProduitsDX").length == 1) {
                allerALapageTableauListeProduitDX(numeroPage);
            } else {
                pageCouranteMozaique = $(this).text();
                afficherListeProduitsMosaique(pageCouranteMozaique, variableDeRecherche, valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT, true, null); // true est pour le forçage du scroll trop dans aller vers le haut
            }
        } else {
            if ($(this).text() == 'prev') {
                numeroPage = parseInt($('.pageCourante').first().text()) - 1;
                if (numeroPage > 0) {
                    if ($("#tableauListeDesProduitsDX").length == 1) {
                        allerALapageTableauListeProduitDX(numeroPage);
                    } else {
                        pageCouranteMozaique = numeroPage;
                        afficherListeProduitsMosaique(pageCouranteMozaique, variableDeRecherche, valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT, true, null); // true est pour le forçage du scroll trop dans aller vers le haut
                    }
                }
            } else {
                numeroPage = parseInt($('.pageCourante').first().text()) + 1;
                if (numeroPage <= $('#pagerListeProduit .paginationProduit span.nombreDePage').attr('id')) {
                    if ($("#tableauListeDesProduitsDX").length == 1) {
                        allerALapageTableauListeProduitDX(numeroPage);
                    } else {
                        pageCouranteMozaique = numeroPage;
                        afficherListeProduitsMosaique(pageCouranteMozaique, variableDeRecherche, valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT, true, null); // true est pour le forçage du scroll trop dans aller vers le haut
                    }
                }
            }
        }
    });

}
function allerALapageTableauListeProduitDX(numeroPage) {
    //console.log("allerALapageTableauListeProduitDX numeroPage-1", numeroPage-1)
    //YTR modifier l'index de la page de la liste DX
    $('#tableauListeDesProduitsDX').dxDataGrid("instance").pageIndex(numeroPage - 1);
     //console.log("Pour garder la datagrid avec numero de page currente ****")
}
function refreshPagerListeProduitDX(dataGridInst) {
    //YTR refresh du block html du pager après modification du numero de page ou du nombre de produit par page
    dataGridInst = dataGridInst != undefined ? dataGridInst : $('#tableauListeDesProduitsDX').dxDataGrid("instance");

    //Pour garder la dataGrid avec numero de page courrente

    allerALapageTableauListeProduitDX(numeroPage);  
    var currentPage = dataGridInst.pageIndex() + 1;
   

    var pageSizeDx = dataGridInst.pageSize();

    //console.log("refreshPagerListeProduitDX currentPage pageSizeDx", currentPage, pageSizeDx)
    $.ajax({
        url: '/webshop/pagerlisteProduits',
        async: true,
        data: {
            pageCourante: currentPage,
            nombreDePageCeil: pageSizeDx,
            nombreTotalLigneCatalogues: nbElements,
        },
        success: function (result) {
            $("#pagerListeProduit").show();
            $('.nombreProduits').show();
            $("#pagerListeProduit").html(result);
            $('.nombreProduitsAAfficher').val(pageSizeDx);
            masquerChargement();
        },
        error: function (error) {
            console.log("error refreshPagerListeProduitDX", error)
        }
    });
}
function afficherDetailsPanier(evt) {
    if (evt.ctrlKey) {
        afficherChargement();
        $.ajax({
            url: '/webshop/detailsPanier',
            success: function (resultat) {

                $('#detailsPanier').html(resultat);
                $('#divScrollTableau table').css('visibility', 'visible');

                $('#divScrollTableau').css('width', 'auto');

                $('#detailsPanier').show();


                masquerChargement();
            }
        });
    }

}

function afficherJustification(numeroOperation, numeroOperationLigne) {
    afficherChargement();
    $.ajax({
        url: '/webshop/afficherJustification',
        data: {
            'numeroOperation': numeroOperation,
            'numeroOperationLigne': numeroOperationLigne
        },
        success: function (resultat) {
            $('#justificationsPrix').html(resultat);
            $('#divScrollTableau table').css('visibility', 'visible');

            $('#divScrollTableau').css('width', 'auto');

            $('#justificationsPrix').show();


            masquerChargement();
        }
    });
}
function changerLangue(idLangue) {
    afficherChargement();
    $.ajax({
        url: '/webshop/accueil?numeroSociete=' + numeroSociete, // On n'attend pas l'appel ajax sur cette méthode en vérité, mais on l'attend sur le super controleur utilisateur. Astuce pour déclencher un appel serveur.
        cache: false,
        type: 'POST',
        data: {
            'langue': idLangue
        },
        success: function (resultat) {
            masquerChargement();
            $('body').html(resultat);
            $('.dropdown-Langue').hide();
            $('.langueChoisie').text((idLangue == 'en' ? 'English' : 'Français'));
        }
    });
}
function isNumber(evt, element) {

    var charCode = (evt.which) ? evt.which : event.keyCode

    if (
        (charCode != 45 || $(element).val().indexOf('-') != -1) &&      // “-” CHECK MINUS, AND ONLY ONE.
        (charCode != 46 || $(element).val().indexOf('.') != -1) &&      // “.” CHECK DOT, AND ONLY ONE.
        (charCode < 48 || charCode > 57))
        return false;

    return true;
}

function afficherBlockMenuConnection() {
    $('.blockMenuConnection').show();
    $('.blockMenuConnection').css('display', 'block');
    $('.menuBlockConnection').addClass('fermerPopupBlockMenuConnection');
    $('.menuBlockConnection').attr('src', '/ressource/image/webshop/ic_fermer_compte.png');
    $('.menuBlockConnection').attr('onClick', 'fermerBlockMenuConnection();');

}
function fermerBlockMenuConnection() {
    $('.blockMenuConnection').hide();
    $('.menuBlockConnection').attr('src', '/ressource/image/webshop/ic_menu.png');
    $('.menuBlockConnection').removeClass('fermerPopupBlockMenuConnection');
    $('.menuBlockConnection').attr('onClick', 'afficherBlockMenuConnection();');
}
function rafraichirOperation() {
    modeExpedition = '';
    if (typeof ($('#modeExpeditionSelection')) != 'undefined') {
        modeExpedition = $('#modeExpeditionSelection').val();
    }
    afficherChargement();
    $.ajax({
        url: '/OperationDesktop/rafraichirOperation',
        data: {
            'modeExpedition': modeExpedition
        },
        success: function (quantiteEtMontant) {
            masquerChargement();
            tableauValeurs = quantiteEtMontant.split("|");
            if (tableauValeurs.length > 1) {
                quantite = tableauValeurs[0];
                montant = tableauValeurs[1];
                masquerChargement();
                $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(quantite));

                tableauValeursPanier = nombreAvecDesEspaces(montant).replace(',', '.').split('.');

                $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);

                rafraichirCumulsEmballage();
            } else {
                masquerChargement();
                alerte(tableauValeurs, 'erreur');
                
            }
        }
    });

}

function changerTypeOperationOperation() {
    typeOperation = '';
    if (typeof ($('#typeOperationSelection')) != 'undefined') {
        typeOperation = $('#typeOperationSelection').val();
    }
    afficherChargement();
    $.ajax({
        url: '/webshop/changerTypeOperationOperation',
        data: {
            'typeOperation': typeOperation
        },
        success: function () {
            retourCatalogue();
            visualiserPanier();

            masquerChargement();
        }
    });

}

function rechargerCataloguesWebshop(message) {
    afficherChargement();
    if (typeof saisieEnModeSemaine !== 'undefined' && saisieEnModeSemaine == "True") {
        dateLivraison = dateLivraisonEncours;
        //console.log("rechargerCataloguesWebshop dateLivraison", dateLivraison);
    } else {
        dateLivraison = $('#dateLivraison').val();
    }
    $.ajax({
        url: '/webshop/accueil',
        data: {
            'dateDeLivraisonChoisie': dateLivraison,
            'numeroSociete': numeroSociete,
            'source': 'rechargerCataloguesWebshop',
            'numeroArticleVisibleEnDetail': numeroArticleVisibleEnDetail
        },
        success: function (retourServeur) {

            $('body').html(retourServeur);
            if (typeof saisieEnModeSemaine == 'undefined' || saisieEnModeSemaine != "True") {
                $('#dateLivraison').val(dateLivraison);
            }
            masquerChargement();
            if (typeof (message) !== 'undefined' && message != "") {
                alerte(message + ' .</br>', 'confirmation');
            }
        }
    });
}

function afficherCloturerCatalogue(numeroCatalogue) {
    //    $('#layoutSupprimerWebshop').fadeIn(200);
    //    $('#fenetreSupprimerWebshop').fadeIn(200);
    //    $('#fenetreSupprimerWebshop .phrasePopup').text('Voulez-vous cloturer ce catalogue ?');
    //    $('.validationOuAnnulerPopup #boutonSupprimer').attr('onclick', 'cloturerCatalogue(' + numeroCatalogue + ');');
    alerte('Voulez-vous cloturer ce catalogue ?', 'confirmationUtilisateur', 'cloturerCatalogue', numeroCatalogue);
}



function cloturerCatalogue(numeroCatalogue) {
    $.ajax({
        url: '/webshop/cloturerCatalogue',
        data: {
            'numeroCatalogue': numeroCatalogue,
            'numeroSociete': numeroSociete
        },
        success: function (retourServeur) {
            $('body').html(retourServeur);
            //$('#unCatalogue_' + numeroCatalogue).css({'opacity': '0.7', 'z-index': '15'});

            masquerChargement();
        }
    });

}

function afficherTarifsQuantitatifs(elementClique, numeroCatalogueLigne, typeGestionTarifs) {
    if ($(elementClique).hasClass('tarifsAAfficher')) {
        $(elementClique).removeClass('tarifsAAfficher');
        $(elementClique).addClass('tarifsAMasquer');
    } else {
        $(elementClique).addClass('tarifsAAfficher');
        $(elementClique).removeClass('tarifsAMasquer');
    }
    $.ajax({
        url: '/webshop/afficherTarifsQuantitatifs',
        data: {
            'numeroCatalogueLigne': numeroCatalogueLigne,
            'typeGestionTarifs': typeGestionTarifs
        },
        success: function (resultat) {
            $('#conteneurPrixQuantitatifs-' + numeroCatalogueLigne).html(resultat);
            $('#conteneurPrixQuantitatifs-' + numeroCatalogueLigne).slideToggle('slow');
        }
    });

}

function afficherCumulsEmballages() {
    afficherChargement();
    $.ajax({
        url: '/webshop/cumulsEmballages',
        success: function (resultat) {
            $('#cumulsEmballages').html(resultat);
            $('#divScrollTableau table').css('visibility', 'visible');

            $('#divScrollTableau').css('width', 'auto');

            $('#cumulsEmballages').show();


            masquerChargement();
        }
    });
}

function rafraichirCumulsEmballage() {
    $.ajax({
        url: '/webshop/cumulsEmballages',
        success: function (resultat) {
            $('#cumulsEmballages').html(resultat);
            masquerChargement();
        }
    });
}

function materialiserLesLignesInvalidesDansLePanier() {
    if ($('#tableauListePanierDX').length > 0) {
        nombrelignes = listeDesNumerosExterneCataloguesNonValides.length;
        $('#tableauListePanierDX > .dx-datagrid > .dx-datagrid-rowsview > .dx-scrollable-wrapper >.dx-scrollable-container >.dx-scrollable-content > .dx-datagrid-content > table.dx-datagrid-table tbody  tr').each(function () {
            $(this).removeClass("catalogueInvalide");
        });
        for (var i = 0; i < nombrelignes; i++) {
            $('#tableauListePanierDX > .dx-datagrid > .dx-datagrid-rowsview > .dx-scrollable-wrapper >.dx-scrollable-container >.dx-scrollable-content > .dx-datagrid-content > table.dx-datagrid-table tbody').find('[data-numero-externe-catalogue="' + listeDesNumerosExterneCataloguesNonValides[i] + '"]').addClass("catalogueInvalide");
        }
    }
}

function afficherListeOperationWebshop() {
    desactiverModeModal();
    $('#contenuPanier').hide();
    $('#contenuBlockBas').hide();

    fermerBlockMenuConnection();
    afficherChargement();
    $.ajax({
        url: '/webshop/listeOperationsWebshop',
        success: function (resultat) {
            $('#catalogues').hide();
            $('#listeProduits').hide();
            $('#blockMonCompteAccueil').html(resultat);
            $('#blockMonCompteAccueil').show();
            $('#affichagePageDesCommandes').hide();
            masquerChargement();
        }
    });
}

function afficherBlockFiltrerPar(element,idcatalogue='') {
    if (element.indexOf(typeCatalogue == 'Type 5' ? 'nomCata_' : 'unCatalogue') != -1) {
        if (typeCatalogue == 'Type 5') {
            if ($('#' + element).hasClass('choixCatalogueCocher')) {
                if (catalogueCocher.length != 0) {
                    var cpt1 = 0;
                    $('#filtreActifs').show();
                    while (cpt1 < catalogueCocher.length) {
                        nomCate = typeCatalogue == 'Type 5' ? $('#' + element).parent().find('.nomCatalogue .libelleCatalogue').text() : $('#' + element).find('.nomCatalogue .libelleCatalogue').text();
                        idCatalog = typeCatalogue == 'Type 5' ? $('#' + element).val() : $('#' + element).val().split('_');

                        index = listeNomCatalog.indexOf(nomCate);
                        if (index == -1) {
                            listeNomCatalog.push(nomCate);
                        }
                        cpt1++;
                    }
                    //$('#filtreActifs .filtreListeCata').append('<span class="filtreCat' + element + '"><span class="supprimerFiltreCat' + element + '" onClick="supprimerFiltreCatalogue(\'' + element + '\',\'' + nomCate.replace("'", "\\'") + '\')">X</span><span class="nomCatalogueActif' + element + '"> Catalogues :</span><span class="nomCatalogueValeurActif' + element + '"> ' + nomCate + '</span></span>');
                }
            } else {

                supprimerFiltreCatalogue(element, typeCatalogue == 'Type 5' ? $('#' + element).parent().find('.nomCatalogue .libelleCatalogue').text().replace("'", "\\'") : $('#' + element).find('.nomCatalogue .libelleCatalogue').text().replace("'", "\\'"));
               
            }
        }
    } else if (element.indexOf('Famille') != -1) {
        if (typeCatalogue == 'Type 5') {
            if ($('#' + element).is(":checked")) {
                var cpt = 0;
                if (filtresCocher.length != 0) {
                    $('#filtreActifs').show();
                    if (element.indexOf('surFamille') != -1) {
                        $('#filtreActifs .filtreListeFam').append('<span class="ligneFamilleValeur' + $('#' + element).val() + '"><span class="supprimerFamille' + $('#' + element).val() + '" onClick="supprimerFamille(\'' + element + '\',\'' + $('#' + element).next().text() + '\')">X</span><span class="nomFamilleActif' + $('#' + element).val() + '"> Sur-Familles :</span><span class="nomFamilleValeurActif' + $('#' + element).val() + '"> ' + $('#' + element).next().text() + '</span></span>');
                        listeNomSurFamille.push($('#' + element).next().text());

                    } else {
                        while (cpt < filtresCocher.length) {
                            nomFamille = $('#' + element).next().text();
                            index = listeNomFamille.indexOf(nomFamille);
                            if (index == -1) {
                                listeNomFamille.push(nomFamille);
                            }
                            cpt++;
                        }
                        domCatalogue = $('#' + element).parent().parent().parent().attr('id');
                        indiceDUnCatalogue = domCatalogue.substring(23, domCatalogue.length);
                        surFamilleBlock2 = $('#' + element).parent().parent().attr('id');
                        if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock2 + ' .familleBox input:checked').length == $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock2 + ' .familleBox input').length) {

                            $('.ligneFamilleValeur_' + surFamilleBlock2).remove();
                            $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock2 + ' .familleBox .labelFiltreFamille').each(function () {
                                var index3 = listeNomFamille.indexOf($(this).text());
                                if (index3 > -1) {
                                    listeNomFamille.splice(index3, 1);
                                }
                            });
                            listeNomSurFamille.push($('#' + element).parent().parent().find('.labelsurFamille').text());
                            $('#filtreActifs .filtreListeFam').append('<span class="ligneFamilleValeur' + $('#' + element).parent().parent().find('.surFamille').val() + '"><span class="supprimerFamille' + $('#' + element).parent().parent().find('.surFamille').val() + '" onClick="supprimerFamille(\'' + $('#' + element).parent().parent().find('.surFamille').attr('id') + '\',\'' + $('#' + element).parent().parent().find('.labelsurFamille').text() + '\')">X</span><span class="nomFamilleActif' + $('#' + element).parent().parent().find('.surFamille').val() + '"> Sur-Familles :</span><span class="nomFamilleValeurActif' + $('#' + element).parent().parent().find('.surFamille').val() + '"> ' + $('#' + element).parent().parent().find('.labelsurFamille').text() + '</span></span>');
                        } else {
                            $('#filtreActifs .filtreListeFam').append('<span class="ligneFamilleValeur' + element + ' ligneFamilleValeur_' + surFamilleBlock2 + '"><span class="supprimerFamille' + $('#' + element).val() + '" onClick="supprimerFamille(\'' + element + '\',\'' + $('#' + element).next().text() + '\')">X</span><span class="nomFamilleActif' + $('#' + element).val() + '"> Familles :</span><span class="nomFamilleValeurActif' + $('#' + element).val() + '"> ' + $('#' + element).next().text() + '</span></span>');
                        }
                    }

                } else {
                    $('#filtreActifs').hide();
                    //$('#filtreActifs').html('');
                }

            } else {
                supprimerFamille(element, $('#' + element).next().text());
            }
        }
    } else if (element.indexOf('filtreCritereArticle') != -1){
        if ($('#' + element).is(":checked")) {
            var cpt = 0;
            if (filtresArticleCritereXXCocher.length != 0) {
                $('#filtreActifs').show();
                while (cpt < filtresArticleCritereXXCocher.length) {

                    nomCritere = $('#' + element).parent().parent().parent().find('.libelleCritereArticle').text();
                    idCritere = $('#' + element).val();

                    index = listeNomCritereArticle.indexOf(nomCritere);
                    if (index == -1) {
                        listeNomCritereArticle.push(nomCritere);
                    }
                    cpt++;
                }
                $('#filtreActifs .filtreListeCritArticle').append('<span class="ligneCritereArticle' + $('#' + element).val() + '"><span class="supprimerCritere' + $('#' + element).val() + '" onClick="supprimerCritereArticle(\'' + $('#' + element).val() + '\',\'' + nomCritere + '\',\'' + element + '\')">X</span><span class="nomCritereActif' + $('#' + element).val() + '"> ' + nomCritere + ':</span><span class="nomCritereValeurActif' + $('#' + element).val() + '"> ' + $('#' + element).next().text() + '</span></span>');
            } else {
                $('#filtreActifs').hide();
                //$('#filtreActifs').html('');
            }
        } else {
            supprimerCritereArticle($('#' + element).val(), $('#' + element).parent().parent().parent().find('.libelleCritereArticle').text(), element);
        }
    } else if (element.indexOf('filtreTaillePresentation') != -1) {
        if ($('#' + element).is(":checked")) {
            var cpt = 0;
            if (filtresTaillePresentationCocher.length != 0) {
                $('#filtreActifs').show();
                while (cpt < filtresTaillePresentationCocher.length) {

                    nomCritere = $('#' + element).parent().parent().parent().find('.libelleTaillePresentation').text();
                    idCritere = $('#' + element).val();

                    index = listeNomTaillePresentation.indexOf(nomCritere);
                    if (index == -1) {
                        listeNomTaillePresentation.push(nomCritere);
                    }
                    cpt++;
                }
                $('#filtreActifs .filtreListeTailPres').append('<span class="ligneTaillePresentation' + $('#' + element).val() + '"><span class="supprimerCritere' + $('#' + element).val() + '" onClick="supprimerTaillePresentation(\'' + $('#' + element).val() + '\',\'' + nomCritere + '\',\'' + element + '\')">X</span><span class="nomCritereActif' + $('#' + element).val() + '"> ' + nomCritere + ':</span><span class="nomCritereValeurActif' + $('#' + element).val() + '"> ' + $('#' + element).next().text() + '</span></span>');
            } else {
                $('#filtreActifs').hide();
                //$('#filtreActifs').html('');
            }
        } else {
            supprimerTaillePresentation($('#' + element).val(), $('#' + element).parent().parent().parent().find('.libelleTaillePresentation').text(), element);
        }
    } else {
        if ($('#' + element).is(":checked")) {
            var cpt = 0;
            if (listeIdFiltreCritereValeur.length != 0) {
                $('#filtreActifs').show();
                while (cpt < listeIdFiltreCritereValeur.length) {
                    nomCritere = $('#' + element).parent().parent().parent().find('.libelleCritere').text();
                    idCritere = $('#' + element).val().split('-');

                    index = listeNomCritere.indexOf(nomCritere);
                    if (index == -1) {
                        listeNomCritere.push(nomCritere);
                    }
                    cpt++;
                }
                $('#filtreActifs .filtreListeCrit').append('<span class="ligneCritereValeur' + $('#' + element).val() + '"><span class="supprimerCritere' + $('#' + element).val() + '" onClick="supprimerCritere(\'' + $('#' + element).val() + '\',\'' + nomCritere + '\')">X</span><span class="nomCritereActif' + $('#' + element).val() + '"> ' + nomCritere + ':</span><span class="nomCritereValeurActif' + $('#' + element).val() + '"> ' + $('#' + element).next().text() + '</span></span>');
                // $('#filtreActifs').append('<br/>');
            } else {
                $('#filtreActifs').hide();
                //$('#filtreActifs').html('');
            }
        } else {
            supprimerCritere($('#' + element).val(), $('#' + element).parent().parent().parent().find('.libelleCritere').text());
        }
    }
}

function supprimerFiltreCatalogue(element, nomCatalogue) {
    if (typeCatalogue == 'Type 5') {
        idCata = element.split('_');
        $('#nomCata_' + idCata[1]).removeAttr('checked');
        var index = listeNomCatalog.indexOf(nomCatalogue.replace("\\'", "'"));

        if (index > -1) {
            listeNomCatalog.splice(index, 1);
        }
        var ind = catalogueCocher.indexOf(idCata[1]);
        if (ind > -1) {
            catalogueCocher.splice(ind, 1);
        }
        $('.filtreCat' + element).remove();
        $('#nomCata_' + idCata[1]).removeClass('choixCatalogueCocher');
        if (catalogueCocher.length == 0) {
            $('.checkboxCatalogueType5').each(function () {
                $(this).removeClass('choixCatalogueNonCocher');
                $(this).removeClass('choixCatalogueCocher');
            });
        }
        filtrerListesParCritereValeur();

        if (listeIdFiltreCritereValeur.length == 0 && listeNomCatalog.length == 0 && listeNomFamille.length == 0 && listeNomSurFamille.length == 0 && listeNomCritereArticle.length == 0 && listeNomTaillePresentation.length == 0) {
            $('#filtreActifs').hide();
        }
    }
}
function supprimerCritere(idCritere, nomCritere) {
    idCritere2 = idCritere.split('-');
    $('#nomValeur_' + idCritere2[1]).removeAttr('checked');

    var index = listeNomCritere.indexOf(nomCritere);
    if (index > -1) {
        listeNomCritere.splice(index, 1);
    }

    $('.ligneCritereValeur' + idCritere).remove();

    //$('#filtreActifs br').remove();
    // $('.nomCritereActif' + idCritere).remove();
    // $('.nomCritereValeurActif' + idCritere).remove();

    filtrerListesParCritereValeur();

    if (listeIdFiltreCritereValeur.length == 0 && listeNomCatalog.length == 0 && listeNomFamille.length == 0 && listeNomSurFamille.length == 0 && listeNomCritereArticle.length == 0 && listeNomTaillePresentation.length == 0) {
        $('#filtreActifs').hide();
    }
}
function supprimerCritereArticle(idCritere, nomCritere, element) {
    $('#' + element).removeAttr('checked');

    var index = listeNomCritereArticle.indexOf(nomCritere);
    if (index > -1) {
        listeNomCritereArticle.splice(index, 1);
    }

    $('.ligneCritereArticle' + idCritere).remove();

    filtrerListesParCritereValeur();

    if (listeIdFiltreCritereValeur.length == 0 && listeNomCatalog.length == 0 && listeNomFamille.length == 0 && listeNomSurFamille.length == 0 && listeNomCritereArticle.length == 0 && listeNomTaillePresentation.length == 0) {
        $('#filtreActifs').hide();
    }
}
function supprimerTaillePresentation(idCritere, nomCritere, element) {
    $('#' + element).removeAttr('checked');

    var index = listeNomTaillePresentation.indexOf(nomCritere);
    if (index > -1) {
        listeNomTaillePresentation.splice(index, 1);
    }

    $('.ligneTaillePresentation' + idCritere).remove();

    filtrerListesParCritereValeur();

    if (listeIdFiltreCritereValeur.length == 0 && listeNomCatalog.length == 0 && listeNomFamille.length == 0 && listeNomSurFamille.length == 0 && listeNomCritereArticle.length == 0 && listeNomTaillePresentation.length == 0) {
        $('#filtreActifs').hide();
    }
}
function supprimerFamille(element, nomFamille, idCatalogue = '') {
    if (typeCatalogue == 'Type 5') {
        if (element.indexOf('surFamille') != -1) {
            $('#' + element).removeAttr('checked');
            var index = listeNomSurFamille.indexOf(nomFamille);
            if (index > -1) {
                listeNomSurFamille.splice(index, 1);
            }
            domCatalogue = $('#' + element).parent().parent().parent().attr('id');
            indiceDUnCatalogue = domCatalogue != undefined ? domCatalogue.substring(23, domCatalogue.length) : idCatalogue;
            var surFamilleBlock = $('#' + element).parent().parent().attr('id');
            $('.ligneFamilleValeur' + $('#' + element).val()).remove();
            $('.ligneFamilleValeur_' + surFamilleBlock).remove();
            $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock + ' .familleBox .labelFiltreFamille').each(function () {
                var index3 = listeNomFamille.indexOf($(this).text());
                if (index3 > -1) {
                    listeNomFamille.splice(index3, 1);
                }
            });
            $('#' + surFamilleBlock + ' .surFamilleBox .labelsurFamille').removeClass('catalogueFiltreFamilleGriser');
            $('#' + surFamilleBlock + ' span .filtreFamille').prop('checked', $('#' + element).prop("checked"));
        } else {
            domCatalogue = $('#' + element).parent().parent().parent().attr('id');
            indiceDUnCatalogue = domCatalogue != undefined ? domCatalogue.substring(23, domCatalogue.length) : idCatalogue;
            surFamilleBlock = $('#' + element).parent().parent().attr('id');
            if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock + ' .familleBox input').length == 1) {
                element = $('#' + element).parent().parent().find('.surFamille').attr('id');
                nomFamille = $('#' + element).parent().parent().find('.labelsurFamille').text();
                $('#' + element).removeAttr('checked');
                var index = listeNomSurFamille.indexOf(nomFamille);
                if (index > -1) {
                    listeNomSurFamille.splice(index, 1);
                }
                $('.ligneFamilleValeur' + $('#' + element).val()).remove();
                var surFamilleBlock = $('#' + element).parent().parent().attr('id');
                $('#' + surFamilleBlock + ' span .filtreFamille').prop('checked', $('#' + element).prop("checked"));
            } else {
                $('#' + element).removeAttr('checked');
                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .familleBox input:checked').length == 0) {
                    $('#catalogue' + indiceDUnCatalogue).removeAttr('checked');
                    $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .surFamille').removeAttr('checked');
                }
                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock + ' .familleBox input:checked').length == 0) {
                    $('#' + surFamilleBlock + ' .surFamilleBox .labelsurFamille').removeClass('catalogueFiltreFamilleGriser');
                }
                var index2 = listeNomFamille.indexOf(nomFamille);
                if (index2 > -1) {
                    listeNomFamille.splice(index2, 1);
                }
                $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock + ' .familleBox input:checked').each(function () {
                    var index3 = listeNomFamille.indexOf($(this).next().text());
                    if (index3 == -1) {
                        listeNomFamille.push($(this).next().text());
                        $('#filtreActifs .filtreListeFam').append('<span class="ligneFamilleValeur' + $(this).attr('id') + ' ligneFamilleValeur_' + surFamilleBlock + '"><span class="supprimerFamille' + $(this).val() + '" onClick="supprimerFamille(\'' + $(this).attr('id') + '\',\'' + $(this).next().text() + '\')">X</span><span class="nomFamilleActif' + $(this).val() + '"> Familles :</span><span class="nomFamilleValeurActif' + $(this).val() + '"> ' + $(this).next().text() + '</span></span>');
                    }
                });
                var index4 = listeNomSurFamille.indexOf($('#' + element).parent().parent().find('.labelsurFamille').text());
                if (index4 > -1) {
                    listeNomSurFamille.splice(index4, 1);
                }
                $('.ligneFamilleValeur' + element).remove();
                $('.ligneFamilleValeur' + $('#' + element).parent().parent().find('.surFamille').val()).remove();
            }
        }

        filtrerListesParCritereValeur();

        if (listeIdFiltreCritereValeur.length == 0 && listeNomCatalog.length == 0 && listeNomFamille.length == 0 && listeNomSurFamille.length == 0 && listeNomCritereArticle.length == 0 && listeNomTaillePresentation.length == 0) {
            $('#filtreActifs').hide();
        }
    }
}

function afficherConditionGeneralFooter() {
    $("#layoutPopupConditionGeneral").height($("#contenuPage").height());
    $('#layoutPopupConditionGeneral').fadeIn(200);
    $('#popupConditionGeneral').fadeIn(200);
    $('#bouttonValiderPopup').hide();
    $('#bouttonAnnulerPopup').hide();
    $('#bouttonFermerPopup').show();
    $('#lienPdf').hide();
    $('#popupConditionGeneral #messageConditionGeneral').html($('.messageConditionGeneral').text());
}

function allerVersLeHaut(forcer) {
    if ((typeof forcer === 'undefined' || forcer == false) && activerAllerVersLeHaut == 'True') {
        $('html, body').animate({
            scrollTop: 0
        }, 700);
    } else if (typeof forcer !== 'undefined' && forcer == true) {
        $('html, body').animate({
            scrollTop: 0
        }, 700);
    }
}

function fermerPopupPasswordOublier() {
    $('#formulaireMotDePasseOublie').fadeOut(200);
    $('#layoutPopup').fadeOut(200);
    $('body').css("overflow-y", "scroll");
}


function afficherListeClientsWebshop() {
    $('#contenuPanier').hide();
    $('#contenuBlockBas').hide();

    fermerBlockMenuConnection();
    afficherChargement();
    $.ajax({
        url: '/webshop/listeClientsWebshopNew',
        success: function (resultat) {
            $('#catalogues').hide();
            $('#listeProduits').hide();
            $('#blockMonCompteAccueil').html(resultat);
            $('#blockMonCompteAccueil').show();
            initialiserListeClientsWebshopDX();
            masquerChargement();
        }
    });
}
function retourAuMenu() {
    $('#blockMonCompteAccueil').hide();
    $('#affichagePageDesCommandes').show();
    $('#tableauListeClientsWebshop').show();
    $('#labelListeDesClients').show();
}
function soumissionFormulaireMotDePasseOublie() {
    messageErreur = '';
    // Verification Email
    if (verifierEmail.exec($('#emailMPO').val().toLowerCase().trim()) == null) {
        messageErreur += EMAIL_PAS_CORRECTE + '.<br/>';
    }

    if (messageErreur == '') {
        afficherChargement();
        $.ajax({
            url: '/webshop/soumissionFormulaireMotDePasseOublie',
            cache: false,
            async: false,
            type: 'POST',
            data: {
                'email': $('#emailMPO').val().toLowerCase().trim(),
                'numeroSocieteFournisseur': numeroSociete
            },
            success: function (resultat) {
                masquerChargement();
                if (resultat == "aucuneCorrespondance") {
                    alerte(AUCUNE_CORRESPONDANCE_MAIL, 'erreur');
                } else if (resultat == "emailEnvoye") {
                    $('#emailMPO').val(''); // Effacer la saisie
                    alerte(IDENTIFIANT_ENVOYE, 'confirmation');
                    fermerPopupPasswordOublier();
                }
            }
        });
    } else {
        alerte(messageErreur, 'erreur');
    }
}

function validerRechargePageAccueil() {
    lignesPanierAModifier = [];
    lignesPanier = [];
    location.reload();
}

function reinitialiserTriTableauProduit() {
    oTableSettings = $('#tableauListeDesProduits').DataTable().settings()[0];
    oTableSettings.aaSorting = [];
    $('#tableauListeDesProduits').DataTable().draw();
}

function rechargerFiltreCriteresWebshop() {   
    $.ajax({
        url: '/webshop/afficherFiltreCriteresWebshop',
        cache: false,
        async: false,
        type: 'POST',
        data: {
            'listeNumeroCatalogues': catalogueCocherStringify,
            'numeroSociete': numeroSociete,
            'numeroBoutique': numeroBoutique
        },
        success: function (resultat) {
            masquerChargement();
            $('#listeCriteresWebshop').html(resultat);
        }
    });
    $.ajax({
        url: '/webshop/afficherFiltreTaillePresentation',
        cache: false,
        async: false,
        type: 'POST',
        data: {
            'listeNumeroCatalogues': catalogueCocherStringify,
            'numeroSociete': numeroSociete,
            'numeroBoutique': numeroBoutique
        },
        success: function (resultat) {
            masquerChargement();
            $('#listeFiltreTaillePresentation').html(resultat);
        }
    });
    $.ajax({
        url: '/webshop/afficherFiltreCriteresArticle',
        cache: false,
        async: false,
        type: 'POST',
        data: {
            'listeNumeroCatalogues': catalogueCocherStringify,
            'numeroSociete': numeroSociete,
            'numeroBoutique': numeroBoutique
        },
        success: function (resultat) {
            masquerChargement();
            $('#listeCritresArticles').html(resultat);
        }
    });
    if (typeCatalogue == 'Type 5') {
        $.ajax({
            url: '/webshop/afficherFiltreFamilleSurFamille',
            cache: false,
            async: false,
            type: 'POST',
            data: {
                'listeNumeroCatalogues': catalogueCocherStringify,
                'numeroSociete': numeroSociete,
                'numeroBoutique': numeroBoutique,
                'typeCatalogue': typeCatalogue
            },
            success: function (resultat) {
                masquerChargement();
                $('#listeFiltreFamille').html(resultat);
            }
        });
        
    }
    var cpt1 = 0;
    while (cpt1 < filtreCritereValeurCocher.length) {
        var uneValeur = filtreCritereValeurCocher[cpt1].split('-')[1];
        $('#nomValeur_' + uneValeur).prop('checked', 'checked');
        cpt1++;
    }
    var cptt2 = 0;
    while (cptt2 < filtresArticleCritereXXCocher.length) {
        var uneValeur = filtresArticleCritereXXCocher[cptt2];
        $('#filtreCritereArticle_' + uneValeur).prop('checked', 'checked');
        cptt2++;
    }
    var cptt4 = 0;
    while (cptt4 < filtresTaillePresentationCocher.length) {
        var uneValeur = filtresTaillePresentationCocher[cptt4];
        $('#filtreTaillePresentation_' + uneValeur).prop('checked', 'checked');
        cptt4++;
    }
    
    $('.critereSelectionnerDesktop').each(function () {
        $(this).next('.contenuBlockCritere').show();
    });
    $('.surFamilleAfficher').each(function () {

        $(this).next('.contenuBlockCatalogue').show();

    });

    $('.familleAfficher').each(function () {

        $(this).siblings('.familleBox').show();

    });
    $('.designationCatalogueType5').click(function () {// depiler /repiler sur-famille
        $(this).next('.contenuBlockCatalogue').toggle();
        $(this).toggleClass('surFamilleNonAfficher');
        $(this).toggleClass('surFamilleAfficher');

    });
    $('.surFamilleBox').click(function () {// depiler /repiler famille valeur
        $(this).siblings('.familleBox').toggle();
        $(this).toggleClass('familleAfficher');
        $(this).toggleClass('familleNonAfficher');
    });
    $('.libelleCritere').click(function () {// depiler /repiler critere valeur
        $(this).next('.contenuBlockCritere').toggle();
        $(this).toggleClass('critereNonSelectionnerDesktop');
        $(this).toggleClass('critereSelectionnerDesktop');
    });
    $('.critereArticleSelectionnerDesktop').each(function () {
        $(this).next('.contenuBlockCritere').show();
    });
    if (typeof ($('#listeCritresArticles .libelleCritereArticle').get(0)) != 'undefined') {
        if ($._data($('.libelleCritereArticle').get(0), "events") == undefined) {
            $('.libelleCritereArticle').click(function () {// depiler /repiler critere valeur
                $(this).next('.contenuBlockCritere').toggle();
                $(this).toggleClass('critereArticleNonSelectionnerDesktop');
                $(this).toggleClass('critereArticleSelectionnerDesktop');
            });
        }
    }
    $('.libelleTaillePresentation').click(function () {// depiler /repiler critere valeur
        $(this).next('.contenuBlockCritere').toggle();
        $(this).toggleClass('critereArticleNonSelectionnerDesktop');
        $(this).toggleClass('critereArticleSelectionnerDesktop');
    });
    suiteRechargerFiltre();
}
function suiteRechargerFiltre() {
    if (typeof ($('#critereValeurId .filtreCritereValeur').get(0)) != 'undefined') {
        if ($._data($('#critereValeurId .filtreCritereValeur').get(0), "events") == undefined) {
            $('#critereValeurId .filtreCritereValeur').click(function () {
                if ($(this).is(':checked')) {
                    filtrerListesParCritereValeur();
                }
                afficherBlockFiltrerPar(this.id);
            });
        }
    }
    if (typeof ($('.filtreCritereArticleValeur').get(0)) != 'undefined') {
        if ($._data($('.filtreCritereArticleValeur').get(0), "events") == undefined) {
            $('.unFiltreArticle .filtreCritereArticleValeur').click(function () {
                if ($(this).is(':checked')) {
                    filtrerListesParCritereValeur();
                }
                afficherBlockFiltrerPar(this.id);
            });
        }
    }
    if (typeof ($('.filtreTaillePresentation').get(0)) != 'undefined') {
        if ($._data($('.filtreTaillePresentation').get(0), "events") == undefined) {
            $('.unFiltreTaillePresentation .filtreTaillePresentation').click(function () {
                if ($(this).is(':checked')) {
                    filtrerListesParCritereValeur();
                }
                afficherBlockFiltrerPar(this.id);
            });
        }
    }
    //click sur filtre sans bouton
    if (typeof ($('#listeFiltreFamille .filtreFamille').get(0)) != 'undefined') {
        if ($._data($('#listeFiltreFamille .filtreFamille').get(0), "events") == undefined) {
            $('#listeFiltreFamille .filtreFamille').click(function () {
                idFiltreFamilles = $(this).parent().attr('id');

                indiceDUnCatalogue = idFiltreFamilles.substring(19, idFiltreFamilles.length);
                // if (COMMANDE_MONO_CATALOGUE != 'OUI') {
                surFamilleBlock2 = $(this).parent().parent().attr('id');
                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .familleBox').length > $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .familleBox input:checked').length && $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .familleBox input:checked').length != 0) {
                    $('#catalogue' + indiceDUnCatalogue).siblings('.catalogueFiltreFamille').addClass('catalogueFiltreFamilleGriser');
                    $('#catalogue' + indiceDUnCatalogue).attr('checked', 'checked');
                    document.getElementById("catalogue" + indiceDUnCatalogue).checked = true;
                    //            $('#unCatalogue_' + indiceDUnCatalogue).addClass('choixCatalogueCocher');
                    //            $('#unCatalogue_' + indiceDUnCatalogue).removeClass('choixCatalogueNonCocher');
                    $(this).parent().siblings('.surFamilleBox').find('.labelsurFamille').addClass('catalogueFiltreFamilleGriser');
                    $('#' + surFamilleBlock2 + ' .surFamilleBox .surFamille').prop('checked', 'checked');
                } else {
                    $('#catalogue' + indiceDUnCatalogue).siblings('.catalogueFiltreFamille').removeClass('catalogueFiltreFamilleGriser');
                    $(this).parent().siblings('.surFamilleBox').find('.labelsurFamille').removeClass('catalogueFiltreFamilleGriser');
                }

                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .familleBox input:checked').length == 0) {
                    $('#catalogue' + indiceDUnCatalogue).removeAttr('checked');
                    //            $('#unCatalogue_' + indiceDUnCatalogue).toggleClass('choixCatalogueNonCocher');
                    //            $('#unCatalogue_' + indiceDUnCatalogue).toggleClass('choixCatalogueCocher');

                    $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .surFamille').removeAttr('checked');

                }
                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .familleBox').length == $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .familleBox input:checked').length) {
                    if (!$('#catalogue' + indiceDUnCatalogue).is(':checked')) {
                        $('#catalogue' + indiceDUnCatalogue).click();
                    }
                    //            $('#unCatalogue_' + indiceDUnCatalogue).toggleClass('choixCatalogueCocher');
                    //            $('#unCatalogue_' + indiceDUnCatalogue).removeClass('choixCatalogueNonCocher');

                }

                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock2 + ' .familleBox input:checked').length == 0) {
                    $('#' + surFamilleBlock2 + ' .surFamilleBox .labelsurFamille').removeClass('catalogueFiltreFamilleGriser');
                    $('#' + surFamilleBlock2 + ' .surFamilleBox .surFamille').removeAttr('checked');
                }
                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock2 + ' .familleBox input:checked').length == $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock2 + ' .familleBox input').length) {
                    if (!$('#' + surFamilleBlock2 + ' .surFamilleBox .surFamille').is(':checked')) {
                        $('#' + surFamilleBlock2 + ' .surFamilleBox .surFamille').click();
                    }
                    $(this).parent().siblings('.surFamilleBox').find('.labelsurFamille').removeClass('catalogueFiltreFamilleGriser');

                }
                filtrerListesParCritereValeur();
                afficherBlockFiltrerPar(this.id);

            });
        }
    }
    if (typeof ($('.surFamille').get(0)) != 'undefined') {
        if ($._data($('.surFamille').get(0), "events") == undefined) {
            $('.surFamille').change(function () {
                domCatalogue = $(this).parent().parent().parent().attr('id');
                indiceDUnCatalogue = domCatalogue.substring(23, domCatalogue.length);
                surFamilleBlock = $(this).parent().parent().attr('id');
                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .surFamilleBox').length > $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .surFamilleBox input:checked').length && $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .surFamilleBox input:checked').length != 0) {
                    $('#catalogue' + indiceDUnCatalogue).siblings('.catalogueFiltreFamille').addClass('catalogueFiltreFamilleGriser');
                    if (!$('#catalogue' + indiceDUnCatalogue).is(':checked')) {
                        $('#catalogue' + indiceDUnCatalogue).prop('checked', 'checked');
                    }
                    $('#' + surFamilleBlock + ' .surFamilleBox .labelsurFamille').removeClass('catalogueFiltreFamilleGriser');
                } else {
                    $('#catalogue' + indiceDUnCatalogue).siblings('.catalogueFiltreFamille').removeClass('catalogueFiltreFamilleGriser');

                }
                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .surFamilleBox input:checked').length == 0) {
                    $('#catalogue' + indiceDUnCatalogue).removeAttr('checked');
                }
                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .surFamilleBox').length == $('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' .surFamilleBox input:checked').length) {
                    if (!$('#catalogue' + indiceDUnCatalogue).is(':checked')) {
                        $('#catalogue' + indiceDUnCatalogue).click();
                    }
                }

                if ($('#contenuBlock_catalogue_' + indiceDUnCatalogue + ' #' + surFamilleBlock + ' .familleBox input:checked').length == 0) {
                    $('#' + surFamilleBlock + ' .surFamilleBox .labelsurFamille').removeClass('catalogueFiltreFamilleGriser');
                }

                $('#' + surFamilleBlock + ' span .filtreFamille').prop('checked', $(this).prop("checked"));
                filtrerListesParCritereValeur();
                afficherBlockFiltrerPar(this.id);

            });
        }
    }
}
function cocherDecocherTousLesCatalogues(cocherDecocher, decocherOuCocherExterne) {
    if ((cocherDecocher != null && $(cocherDecocher).hasClass('decocherTout')) || typeof decocherOuCocherExterne !== 'undefined') {
        $('.choixCatalogueCocher').each(function () {
            $(this).removeClass('choixCatalogueCocher');
            $(this).toggleClass('choixCatalogueNonCocher');
            $(this).find('.cocherOuNon').addClass('icon-ic-check-vide');
            $(this).find('.cocherOuNon').removeClass('icon-ic-check');
        });
        if (typeof decocherOuCocherExterne !== "undefined") {
            $('.decocherTout').val(COCHER_TOUS_LES_CATALOGUES);
            $('.decocherTout').addClass('cocherTout');
            $('.cocherTout').removeClass('decocherTout');
            catalogueCocher = [];
            catalogueCocherStringify = "[]";
            setTimeout(function () { $((typeCatalogue == 'Type 5' ? '#nomCata_' + decocherOuCocherExterne : '#unCatalogue_' + decocherOuCocherExterne)).trigger('click'); }, 300);

        } else {
            $(cocherDecocher).val(COCHER_TOUS_LES_CATALOGUES);
            $(cocherDecocher).addClass('cocherTout');
            $(cocherDecocher).removeClass('decocherTout');
            catalogueCocher = [];
            catalogueCocherStringify = "[]";
        }

    } else {
        $('.choixCatalogueNonCocher').each(function () {
            $(this).removeClass('choixCatalogueNonCocher');
            $(this).toggleClass('choixCatalogueCocher');
            $(this).find('.cocherOuNon').addClass('icon-ic-check');
            $(this).find('.cocherOuNon').removeClass('icon-ic-check-vide');
            catalogueCocher.push(typeCatalogue != 'Type 5' ? $(this).find('.numeroCatalogue').text() : $(this).val());
            catalogueCocherStringify = JSON.stringify(catalogueCocher);
        });
        $(cocherDecocher).val(DECOCHER_TOUS_LES_CATALOGUES.replace('&#233;', 'é'));
        $(cocherDecocher).addClass('decocherTout');
        $(cocherDecocher).removeClass('cocherTout');
    }
    if (modeDAffichage == VALEUR_LISTE) {
        filtrerProduitDX();
    } else {
        setTimeout(function () { afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT); }, 300);

    }
}

function supprimerToutesSelections() {
    filtresCocher = [];
    listeNomFiltreCritereValeur = [];
    listeIdFiltreCritereValeur = [];
    filtreCritereValeurCocher = [];
    listecodeFamillesSelectionnee = [];
    filtresArticleCritereXXCocher = [];
    filtresTaillePresentationCocher = [];
    listeNomTaillePresentation = [];
    listeNomCritereArticle = [];
    listeNomCritere = [];
    listeNomCatalog = [];
    listeNomFamille = [];
    listeNomSurFamille = [];
    if (listeIdFiltreCritereValeur.length == 0 && listeNomCatalog.length == 0 && listeNomFamille.length == 0 && listeNomSurFamille.length == 0 && listeNomCritereArticle.length == 0 && listeNomTaillePresentation.length == 0) {

        $('.filtreFamille').removeAttr('checked');
        $('.surFamille').removeAttr('checked');
        $('.filtreCritereValeur').removeAttr('checked');
        $('.filtreCritereArticleValeur').removeAttr('checked');
        $('.filtreTaillePresentation').removeAttr('checked');
        $('.checkboxCatalogueType5').each(function () {
            $(this).removeClass('choixCatalogueNonCocher');
            $(this).removeClass('choixCatalogueCocher');
            $(this).removeAttr('checked');
        });

    }
    $('.checkboxCatalogueType5').each(function () {
        numeroCatalogue = $(this).val();
        index = catalogueCocher.indexOf(numeroCatalogue);
        if (index == -1) {
            catalogueCocher.push(numeroCatalogue);
        }
    });
    $('#filtreActifs').hide();
    $('.filtreListeCata').html('');
    $('.filtreListeFam').html('');
    $('.filtreListeCrit').html('');
    $('.filtreListeCritArticle').html('');
    $('.filtreListeTailPres').html('');
    catalogueCocherStringify = JSON.stringify(catalogueCocher);
    filtreCritereValeurCocherStringify = JSON.stringify(filtreCritereValeurCocher);
    filtresArticleCritereXXCocherStringify = JSON.stringify(filtresArticleCritereXXCocher);
    filtresTaillePresentationCocherStringify = JSON.stringify(filtresTaillePresentationCocher);
    filtersStringify = JSON.stringify(filtresCocher);
    if (modeDAffichage == VALEUR_LISTE) {
        filtrerProduitDX();
        //afficherListeProduits();
    } else {
        afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
    }
    rechargerFiltreCriteresWebshop();
    suiteRechargerFiltre();
}
function fermerFenetreAccesMobile() {
    activerLayoutPopup();
    $('#fenetreAccesMobile').fadeOut(200);
    $('#layoutPopup').fadeOut(200);
    $('body').css("overflow-y", "scroll");
}
function fermerFenetreLogin() {
    $('#loginBox').val("");
    $('#motDePasseBox').val("");
    $('#fenetreLogin').fadeOut(200);
    $('#layoutLogin').fadeOut(200);
    $('body').css("overflow-y", "scroll");
}
function fermerFenetreLoginTransition() {
    $('#loginBox').val("");
    $('#motDePasseBox').val("");
    $('#fenetreLogin').fadeOut(200);
    $('#layoutLogin').fadeOut(200);
    $('body').css("overflow-y", "scroll");
}
function desactiverLayoutPopup() {
    $('#layoutPopup').attr('onClick', '');
    $('#layoutPopup').css('cursor', 'default');
}
function activerLayoutPopup() {
    $('#layoutPopup').attr('onClick', 'fermerPopup();');
    $('#layoutPopup').css('cursor', 'pointer');
}

function envoieAccesParEmailOuSms(champ, type) {
    messageErreur = '';
    champ = $('#' + champ).val();
    if (type == 'email' && ($('#accesParEmail').val() == "" || verifierEmail.exec($('#accesParEmail').val().toLowerCase().trim()) == null)) {
        messageErreur += EMAIL_PAS_CORRECTE + '.<br/>';
    }
    if (type == 'sms' && $('#accesParSms').val() == "") {
        messageErreur += VEUILLER_INTRODUIRE_VOTRE_NUMERO_PORTABLE + '.<br/>';
    }
    if (messageErreur == '') {
        afficherChargement();
        $.ajax({
            url: '/webshop/envoieAccesParEmailOuSms',
            async: false,
            data: {
                'champ': champ,
                'url': urlWebshop,
                'numeroSociete': numeroSociete,
                'type': type
            },
            success: function (resultat) {
                if (resultat.indexOf("erreur;") >= 0) {
                    alerte(resultat.split(";")[1], 'erreur');
                } else if (resultat == "emailEnvoye") {
                    alerte(UN_EMAIL_A_ETE_ENVOYE);
                    $('#accesParEmail').val('');
                } else {
                    alerte(UN_SMS_A_ETE_ENVOYE);
                    $('#accesParSms').val('');
                }
                masquerChargement();
            }
        });
    } else {
        alerte(messageErreur, 'erreur');
    }
}


function retourVersListeAccesExterne(idElementDeRetour) {

    if (modeDAffichage == VALEUR_LISTE) {
        //changements syrine
        //                oTable = $('#tableauListeDesProduits').dataTable();
        //                oTable.fnFilter($('#rechercheLignes').val());
        zoneDeRecherche = $('#rechercheLignes').val();
        filtrerProduitDX();
        // afficherListeProduits($('#rechercheLignes').val());
    } else {
        afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT);
    }
    retourALaListeDesProduits(idElementDeRetour);
}
function onChangeSemaineLivraison(e) {
    if ($('#semaineDateLivraison').val() != null && $('#semaineDateLivraison').val() != "") {
        weekNumberOfDateLivraison = $('#semaineDateLivraison').val();
        if ($("#contenuPanier").is(":visible")) {
            confirmationMiseAJourPanierChangementSemaine();
        } else {

            rechargerNouvelleOperation();
        }

    } else {
        //reinitialiser la valeur qui est séléctionné
        $('#semaineDateLivraison').val(weekNumberOfDateLivraison);
        alerte(MERCI_DE_SAISIR_UNE_SEMAINE_DE_LIVRAISON);
    }
}

function changerSemaine(type) {
    var oldWeek = $('#semaineDateLivraison').val();
    var newWeek;
    var lastOptionVal = $("#semaineDateLivraison option:last").val();
    var firstOptionVal = $("#semaineDateLivraison option:first").val();
    if (type == 'down') {
        var currentWeek = getCurrentWeek();
        //Si semaine courante = a la semaine preselectionner, desactiver le bouton previous sinon l'activer'
        //if (currentWeek + 1 == oldWeek) {
        //    console.log("changerSemaine disable btn ")
        //    $("#previousButtonWeek").prop("disabled", true);
        //    return;
        //} else {
        //    $("#previousButtonWeek").prop("disabled", false);
        //}
        //Desactiver le mode circulaire 
        if (oldWeek == firstOptionVal) {
            $("#previousButtonWeek").prop("disabled", true);
            return;
        } else {
            $("#previousButtonWeek").prop("disabled", false);
        }
        newWeek = parseInt(oldWeek) - 1;
        newWeek = newWeek == 0 ? $('#semaineDateLivraison').data("maxnumerosemaine") : newWeek;
        $('#semaineDateLivraison option[value=' + newWeek + ']').prop('selected', true);
        $("#nextButtonWeek").prop("disabled", false);

    } else {
        //Desactiver le mode circulaire 
        if (oldWeek == lastOptionVal) {
            $("#nextButtonWeek").prop("disabled", true);
            return;
        } else {
            $("#nextButtonWeek").prop("disabled", false);
        }
        newWeek = parseInt(oldWeek) + 1;
        newWeek = newWeek > $('#semaineDateLivraison').data("maxnumerosemaine") ? 1 : newWeek;
        //if ($("#semaineDateLivraison option[value=" + newWeek + "]").length < 1) {
        //    newWeek = 1;
        //}
        $('#semaineDateLivraison option[value=' + newWeek + ']').prop('selected', true);
        $("#previousButtonWeek").prop("disabled", false);
    }

    if ($("#contenuPanier").is(":visible")) {
        //En cas de vue de visualiser le panier il faut afficher le message de confirmation de mise a jour du panier
        confirmationMiseAJourPanierChangementSemaine();
    } else {
        rechargerNouvelleOperation();
    }
}
function getCurrentWeek() {
    var currentDateTemp = new Date();
    // Create a copy of this date object  
    var target = new Date(currentDateTemp.valueOf());

    // ISO week date weeks start on monday, so correct the day number  
    var dayNr = (currentDateTemp.getDay() + 6) % 7;

    // Set the target to the thursday of this week so the  
    // target date is in the right year  
    target.setDate(target.getDate() - dayNr + 3);

    // ISO 8601 states that week 1 is the week with january 4th in it  
    var jan4 = new Date(target.getFullYear(), 0, 4);

    // Number of days between target date and january 4th  
    var dayDiff = (target - jan4) / 86400000;

    if (new Date(target.getFullYear(), 0, 1).getDay() < 5) {
        // Calculate week number: Week 1 (january 4th) plus the    
        // number of weeks between target date and january 4th    
        return 1 + Math.ceil(dayDiff / 7);
    }
    else {  // jan 4th is on the next week (so next week is week 1)
        return Math.ceil(dayDiff / 7);
    }
}


function initialisationRenommageColonne(conf, id, configRenommage) {

    conf = conf.filter(function (item) { return item.columRename === true });
    $("#gridRenommageColonnes_" + id).data({ conf: configRenommage });

    gridRenommageColonne = $("#gridRenommageColonnes_" + id).dxDataGrid({
        dataSource: conf,
        editing: {
            mode: "popup",
            allowUpdating: true,
            allowAdding: true,
            popup: {
                title: "Colonne à renommer",
                showTitle: true,
                width: 700,
                height: 300,
                position: {
                    my: "top",
                    at: "top",
                    of: window
                }
            },
        },
        onEditingStart: function (e) {

            e.data.caption = e.data.caption + " ";

        },
        onRowUpdated: function (e) {
            masquerChargement();
        },
        onRowValidating: function (e) {
            e.isValid = true;
        },
        onRowUpdating: function (e) {
            var deferr = new $.Deferred();

            var succes = miseAjourNomColonne(e.newData, e.oldData, id);
            if (succes) {
                deferr.resolve();
            } else {
                deferr.resolve(true);
            }

            e.cancel = deferr.promise();
        },
        columns: [{
            dataField: "caption",
            caption: "nouveauNom",
            selectedFilterOperation: "startswith",
            width: 130
        }, {
            dataField: "originalCaption",
            caption: "ancienNom",
            selectedFilterOperation: "startswith",
            width: 130,
        }
            //    ,

            // {
            //    caption: "estVisible",
            //     dataField: "estVisible",
            //     selectedFilterOperation: "startswith",
            //     width: 130,

            //     calculateCellValue: function (data) {
            //         dataGridInst = $('#tableauListeDesProduitsDX').dxDataGrid("instance");
            //         etat = dataGridInst.state();
            //         var valeur = etat.columns.find(function (item) { if (item.dataField === data.dataField) { return item; } });
            //         console.log(valeur);
            //         if (valeur.visible) {
            //             return "Oui";
            //         } else {
            //             return "Oui";
            //         }
            //     },
            //     calculateFilterExpression: function (filterValue, selectedFilterOperation) {
            //         // Implementation for the "between" comparison operator

            //         var filterExpression = [[this.calculateCellValue, selectedFilterOperation, filterValue]]
            //             ;
            //         return filterExpression;
            //     }


            //}
        ]
    }).dxDataGrid("instance");
}



function miseAjourNomColonne(newData, oldData, id) {
    var succes = false;
    $.ajax({
        url: '/webshop/renommageDesColonnesDX',
        async: false,
        data: {
            'nouveauNomColonne': newData.caption,
            'idTableau': id,
            'dataField': oldData.dataField
        },
        success: function (resultat) {
            masquerChargement();
            if (resultat == "ajout") {

                succes = true;
                alerte(MODIFICATION_PRISE_EN_COMPTE, 'confirmation');

            } else {
                succes = false;
                alerte(resultat, "erreur");

            }

        }
    });

    return succes;
}

function confirmationMiseAJourPanierChangementSemaine() {
    //console.log("confirmationMiseAJourPanierChangementSemaine source");
    activerLesChampsDePanier();
    if (lignesPanierAModifier.length > 0) {
        $("#layoutPopupMiseAJourPanier").height($("#contenuPage").height());
        $('#layoutPopupMiseAJourPanier').fadeIn(200);
        $('#alertePopupMiseAJourPanier').fadeIn(200);
        $('#bouttonNon').show();
        $('#bouttonOUI').show();
        $('#bouttonNon').attr('onclick', "fermerPopupMiseAJourPanier();rechargerNouvelleOperation();");
        $('#bouttonOUI').attr('onclick', 'fermerPopupMiseAJourPanier();modifierPanierGlobal("rechargeNouvelleOperation");');
    } else {
        //if (cataloguesConditionneeParDateLivraison != "cataloguesConditionneeParDateLivraison") {
        //     retourAArriere();
        //}
        rechargerNouvelleOperation();
    }
}
function rafraichirDonneeSemaineLivraison(numeroSemaine, dateDebutSemaine, dateFinSemaine) {
    weekNumberOfDateLivraison = numeroSemaine;
    firstDateOfWeekOperation = dateDebutSemaine;
    endDateOfWeekOperation = dateFinSemaine;
    dateLivraisonEncours = dateDebutSemaine;
    nouvelleDateDeLivraison = dateDebutSemaine;
    $("#labelSemaineLivraison").show();
    $('#semaineDateLivraison').data("datelivraison", dateDebutSemaine);
    $("#labelSemaineLivraison").text(dateDebutSemaine + " - " + dateFinSemaine);

}

function rechargerNouvelleOperation() {
    //console.log("rechargerNouvelleOperation begin")
    if (modeDAffichage == VALEUR_LISTE) {
        annulerLesAppelsEnAttente();
    } else {
        if (typeAnnulation != 1) {
            annulerLesAppelsEnAttente();
        }
    }

    if (typeof $("#semaineDateLivraison").val() == "undefined" || $("#semaineDateLivraison").val() == null || $("#semaineDateLivraison").val() == "") {
        alerte(MERCI_DE_COMMENCER_PAR_SAISIR_UNE_SEMAINE_DE_LIVRAISON, 'temporaire');
        return;
    }
    var numeroSemaine = $("#semaineDateLivraison").val();
    afficherChargement();
    $.ajax({
        url: '/OperationDesktop/RechargerNouvelleOperation',
        data: {
            'numeroSemaineLivraison': numeroSemaine,
        },
        success: function (retourServeur) {
            masquerChargement();
            //console.log("rechargerNouvelleOperation retourServeur", retourServeur)
            messageAffichage = "";
            if (retourServeur.success != true) {
                alerte(retourServeur.message);
            }
            if (typeof saisieEnModeSemaine !== 'undefined' && saisieEnModeSemaine == "True") {
                rafraichirDonneeSemaineLivraison(numeroSemaine, retourServeur.firstDateOfWeekOperation, retourServeur.endDateOfWeekOperation);
            }

            rafraichirCumulsEmballage();

            //if (numeroModeExpeditionParDefaut != "") {
            //    rafraichirAffichageModeExpedition(numeroModeExpeditionParDefaut);
            //}
            if (cataloguesConditionneeParDateLivraison == "cataloguesConditionneeParDateLivraison") {
                rechargerCataloguesWebshop(messageAffichage);
            } else {

                $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(retourServeur.quantiteProduitsDescktop));
                tableauValeursPanier = nombreAvecDesEspaces(nombreAvecDesEspaces(retourServeur.montantTotalProduitsDescktop)).replace(',', '.').split('.');
                $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);

                if ($(".valeurVolumeTotal").length > 0) {
                    $(".valeurVolumeTotal").html(retourServeur.volumeTotal);
                }
                totalPanier = retourServeur.montantTotalProduitsDescktop;
                valeurNombreProduitsAjouter = retourServeur.quantiteProduitsDescktop;
                if (typeof (choixAdresseEffectuer) !== 'undefined') {
                    choixAdresseEffectuer = valeurNon;
                }
                //console.log("rechargerNouvelleOperation modeExpeditionNumero", retourServeur.modeExpeditionNumero)
                //console.log("rechargerNouvelleOperation imposerModeExpeditionBool", imposerModeExpeditionBool)
                if (imposerModeExpeditionBool == 'True' && typeof retourServeur.modeExpeditionNumero !== "undefined" && retourServeur.modeExpeditionNumero != null) {
                    //Récuperer le mode expedtion au cas ou une des operation en cours a changé son mode d'expédition, toutes les operation aura le même mode d'expedition
                    //console.log("rechargerNouvelleOperation mise a jour mode expedition")
                    $('#modeExpeditionSelection').val(retourServeur.modeExpeditionNumero);
                }
                $('#typeOperationSelection').val(retourServeur.operationType);

                if (affichageDeLaSurfaceBool == 'True' && typeof retourServeur.densite !== "undefined" && retourServeur.densite != "") {
                    //tableauValeursDensite = nombreAvecDesEspaces(nombreAvecDesEspaces(retourServeur.densite)).replace(',', '.').split('.');
                    $('.valeurDensite').html(retourServeur.densite + "&nbsp;");
                    //$('.valeurDensiteDecimal').text("." + tableauValeursDensite[1]);
                }
                if ($('#contenuPanier').is(':visible')) {
                    visualiserPanier();
                } else {
                    if (modeDAffichage == VALEUR_LISTE) {
                        afficherListeProduits();
                    } else {
                        catalogueCocherStringify = JSON.stringify(catalogueCocher);
                        afficherListeProduitsMosaique(pageCouranteMozaique, $('#rechercheLignes').val().trim(), valeurTri, $('.nombreProduitsAAfficher').val(), catalogueCocherStringify, filtersStringify, filtreCritereValeurCocherStringify, MAX_MIN_QUANTITE_PAR_DEFAUT, MAX_MIN_QUANTITE_PAR_DEFAUT, true); // true est pour le forçage du scroll trop dans aller vers le haut
                    }
                }
            }
            viderCalculsEnSessionEtMettreAJourDateDeLivraison(nouvelleDateDeLivraison, 'accueil', '', '', false);
            //console.log("rechargerNouvelleOperation end")
        }
    })

}

function formaterDatePourDatePicker(date) {
    var dateArray = date.split('/');
    return new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
}
var AUTORISER_LIGNE_PERIME;
var ALERTE_LIGNE_PERIME;
//Produits
var tableauListeDesProduits = null;
var tableauListeClientsWebshop = null;
var tableauListeCumulsEmballages = null;

//Produits
var tableauDesLargeuresEtIndicesProduits = "";
var titresColonnesProduits = [];
var tableauDesLargeuresEtIndicesChargementProduits = [];

//Panier
var tableauListeDuPanier = null;
var tableauDesLargeuresEtIndicesPanier = "";
var titresColonnesPanier = [];
var tableauDesLargeuresEtIndicesChargementPanier = [];



//ListeClientWebshop
var tableauDesLargeuresEtIndicesClientWebshop = "";
var titresColonnesClientWebshop = [];
var tableauDesLargeuresEtIndicesChargementClientWebshop = [];

//ListeCumulsEmballages
var tableauDesLargeuresEtIndicesCumulsEmballages = "";
var titresColonnesCumulsEmballages = [];
var tableauDesLargeuresEtIndicesChargementCumulsEmballages = [];

//ListeDesAdressesDeLivraisonWebshop
var tableauDesLargeuresEtIndicesAdresseLivraison = "";
var titresColonnesAdresseLivraison = [];
var tableauDesLargeuresEtIndicesChargementAdresseLivraison = [];
var tableauListeDesAdressesDeLivraisonWebshop = null;

//ListeDesOperationsWebshop
var tableauListeDesOperationsWebshop = null;
var tableauDesLargeuresEtIndicesOperationsWebshop = "";
var titresColonnesOperationsWebshop = [];
var tableauDesLargeuresEtIndicesChargementOperationsWebshop = [];

var recherchesParIntervalles = "";
// Factorisation du comportement des appels AJAX
// Entre autre : mise en cache de fichier js et css lors d'appel AJAX sur l'ensemble de site

$.ajaxSetup({
    cache: true,
    type: 'POST',
    error: function (jqXHR, status, erreur) {
        if (jqXHR.status === 408 || jqXHR.status === 0) {
            if (jqXHR.statusText === 'abort') {// cas pour les appels async des grilles tarifaires
               
            } else if (est_fireFox && jqXHR.status === 0) { 
                 masquerChargement();
            } else {
                masquerChargement();
                console.log(ERREUR_RESEAU_VEUILLEZ_RECOMMENCER + " : code XHR " + jqXHR.status);
            }
        } else {
            masquerChargement();
            if (jqXHR.responseText.indexOf('<title>') != -1) {
                exception = jqXHR.responseText.split('<title>')[1].split('</title>')[0];
                if (exception.substring(0, 4) == '1000') {
                    alerte(exception.replace('1000:', ''), 'erreur');
                } else if (exception.substring(0, 4) == '3000') {
                    alerte(exception.replace('3000:', ''), 'confirmationUtilisateur', 'rechargerPage');
                } else if (exception.substring(0, 4) == '4000') {
                    alerte(exception.replace('4000:', ''), 'confirmationUtilisateur', 'validerRechargePageAccueil');
                }
            }
        }
    },
    beforeSend: function (jqXHR, settings) {
        if (bloquerAppelAjax == false) {
            jqXHR.url = settings.url;
            //ATTENTION !!! ne jamais toucher au settings.data en append ni en écrasement car il génère un bug sur upload des fichiers !!!!!! Si paramètre à ajouter le faire sur settings.url 

            if (settings.url.indexOf('?') < 0) {
                settings.url += "?versionCode=" + VERSION_CODE + "&numeroSocieteFournisseurEncours=" + numeroSociete + "&numeroBoutiqueEncours=" + numeroBoutique;
            } else {
                settings.url += "&versionCode=" + VERSION_CODE + "&numeroSocieteFournisseurEncours=" + numeroSociete + "&numeroBoutiqueEncours=" + numeroBoutique;
            }
            if (settings.url.indexOf("/webshop/afficherTarifsQuantitatifs?") <0)
                afficherChargement();
            if ($.cookie('infosCompte') == null) {
                demarrerOuRedemarrerCompteurTimeOut();
            }
        } else {
            return false;
        }
    }
});
function rechargerPage() {
    setTimeout(function () { location.reload(); }, 1000);
}
function initialiserLayoutWebShop() {


    // Si F5 par l'utilisateur alors il faut désactiver la capture d'événement de fermeture navigateur.
    // Car F5 ou fermeture navigateur c'est pareil pour le JS
    $(document).keydown(function (event) {
        if (event.keyCode == 116) {
            window.onbeforeunload = null;
        }
    });

    // Fermeture du navigateur : déclenche la deconnexion (deconnexion = appel AJAX pour décrémenter le nombre total d'utilisateurs connectés)
    window.onbeforeunload = function () {
        if ($('#messageJavaScriptDesactive').length != 0) { // élément de la page d'accueil, 
            // Inutile d'appeler la fct qd l'utilisateur s'est déconnecté puis qu'il ferme le navigateur
            deconnexion();
        }
    }
}

// Gestion timeout, rafrachissement
var compteurRedirectionSiTimeout;
function demarrerOuRedemarrerCompteurTimeOut() {
    tempsEcoule = 1000;
    clearTimeout(compteurRedirectionSiTimeout);
    compteurRedirectionSiTimeout = setTimeout(function () {
        clearTimeout(compteurRedirectionSiTimeout);
        afficherChargement();
        $.ajax({
            url: '/webshop/accueil?numeroSociete=' + numeroSociete,
            success: function (resultat) {
                $('body').html(resultat);
                masquerChargement();
            }
        });
    }, (timeOut * 60000) + 1000);
}

function deconnexion() {
    afficherChargement();
    filtresCocher = [];
    //catalogueCocher = [];
    listeNomFiltreCritereValeur = [];
    listeIdFiltreCritereValeur = [];
    filtreCritereValeurCocher = [];
    filtreCritereValeurCocherStringify = [];
    filtresArticleCritereXXCocher = [];
    filtresTaillePresentationCocher = [];
    listeNomTaillePresentation = [];
    listeNomCritereArticle = [];
    listecodeFamillesSelectionnee = [];
    filtersStringify = [];
    zoneDeRecherche = '';
    zoneDeRecherche = '';
    $('#rechercheLignes').val('');
    $('#listeFiltreFamille input[type="checkbox"]').each(function () {
        $(this).attr('checked', false);
    });
    $('#listeCriteresWebshop input[type="checkbox"]').each(function () {
        $(this).attr('checked', false);
    });
    $('#listeCritresArticles input[type="checkbox"]').each(function () {
        $(this).attr('checked', false);
    });
    $('#listeFiltreTaillePresentation input[type="checkbox"]').each(function () {
        $(this).attr('checked', false);
    });
    $.ajax({
        url: '/webshop/seDeconnecter',
        async: false,
        cache: false,
        data: {
            'appelAJAX': 'seDeconnecter',
            'numeroSociete': numeroSociete
        },
        success: function (resultat) {
            lignesPanier = [];

            clearTimeout(compteurRedirectionSiTimeout);
            masquerChargement();
            $('body').html(resultat);
            if (typeof rechargerPageVar !== 'undefined' && rechargerPageVar == "True") {
                location.reload();
            }
        }
    });
}


function initialiserLesVariablesConfigurationTableaux() {
    
    if (configurationTableaux != null && configurationTableaux != '') {
     
        //listeEtatsTableaux = configurationTableaux.replace(/&quot;/g, '"').split(SEPARATEUR_ETATS_TABLEAUX); PB avec les ', l'instruction suivante résoud :
        listeEtatsTableaux = $('<div>' + configurationTableaux + '</div>').text().split(SEPARATEUR_ETATS_TABLEAUX);
        cpt = 0;
        nombreEtatsTableaux = listeEtatsTableaux.length;
        while (cpt < nombreEtatsTableaux) {
            idPlusEtatTableau = listeEtatsTableaux[cpt].split(SEPARATEUR_ID_VALEUR);
            if (idPlusEtatTableau[0] == 'tableauListeDesProduits' + numeroBoutique) {
                tableauListeDesProduits = idPlusEtatTableau[1];
            } else if (idPlusEtatTableau[0] == 'tableauListePanier' + numeroBoutique) {
                tableauListeDuPanier = idPlusEtatTableau[1];
            } else if (idPlusEtatTableau[0] == 'tableauListeDesOperationsWebshop' + numeroBoutique) {
                tableauListeDesOperationsWebshop = idPlusEtatTableau[1];
            } else if (idPlusEtatTableau[0] == 'tableauListeDesAdressesDeLivraisonWebshop' + numeroBoutique) {
                tableauListeDesAdressesDeLivraisonWebshop = idPlusEtatTableau[1];
            } else if (idPlusEtatTableau[0] == 'tableauListeClientsWebshop' + numeroBoutique) {
                tableauListeClientsWebshop = idPlusEtatTableau[1];
            }
            cpt++;
        }
    }


//    if (configurationTableauxAutresComptes != null && configurationTableauxAutresComptes != '') {
//        listeEtatsTableaux = $('<div>' + configurationTableauxAutresComptes + '</div>').text().split(SEPARATEUR_ETATS_TABLEAUX);
//        nombreEtatsTableaux = listeEtatsTableaux.length;
//        cpt = 0;
//        while (cpt < nombreEtatsTableaux) {
//            idPlusEtatTableau = listeEtatsTableaux[cpt].split(SEPARATEUR_ID_VALEUR);
//            if (idPlusEtatTableau[0] == 'tableauListeClientsWebshop') {
//                tableauListeClientsWebshop = idPlusEtatTableau[1];
//            } 

//            cpt++;
//        }
//    }
}

function visualiserPanier(mode) {

    $.ajax({
        url: '/OperationDesktop/visualiserPanier',
        data: {
            'contexte': 'PANIER',
            'numeroSociete': numeroSociete,
            'mode': typeof mode === 'undefined' ? "CLIENT" : mode
        },
        success: function (retourServeur) {
            $('#contenuPanier').html(retourServeur);
            $('#contenuBlockBas').hide();
            $('#contenuPanier').show();
            masquerChargement();
        }
    });
}
//function gererLesInputDeSaisiDX(input) {
//    //tableauUtiliser = (context == 'panier') ? "tableauListePanier" : "tableauListeDesProduitsDX";

//    $(input).keypress(function (event) {
//        console.log("keypress");
//        charCode = (event.which) ? event.which : event.keyCode;
//        saisiValide = true;
//        if (charCode == 46 || charCode == 44) {
//            if ($(this).val().indexOf(',') == -1 && $(this).val().indexOf('.') == -1 && !$(this).hasClass('chiffreUniquement')) {
//                saisiValide = true;
//            } else {
//                saisiValide = false;
//            }
//        } else if (charCode > 31 && (charCode < 48 || charCode > 57)) {
//            saisiValide = false;
//        } else {
//            saisiValide = true;
//        }
//        return saisiValide;
//    });



//    //    $('#' + tableauUtiliser + ' .commentaireEtiquettes ,#'+ tableauUtiliser +' .quantiteProduit, #'+ tableauUtiliser +' .quantiteCommandee').keydown(function (event) {
//    //        charCode = (event.which) ? event.which : event.keyCode;
//    //        saisiValide = true;
//    //        if (event.ctrlKey == true &&  charCode == '86') {
//    //            saisiValide = false;
//    //        }
//    //        return saisiValide;
//    //    });
//    //    $('#' + tableauUtiliser + ' .commentaireEtiquettes').keypress(function (event) {
//    //        charCode = (event.which) ? event.which : event.keyCode;
//    //        saisiValide = true;
//    //        if ($(this).val().length > 255) {
//    //            saisiValide = false;
//    //        }
//    //        return saisiValide;
//    //    });


//    $(input).on('blur', function (e) {
//        console.log("blur");
//        if (this.value != '') {
//            stockerLignesOperation(this, false, context);
//        } else {
//            viderLignesOperation(this);
//        }

//    });
//    $(input).focus(function () {
//        console.log("focus");
//        $(this).select();
//    });

//    $(input).on('blur', function (e) {
//        console.log("blur 2");
//        if (this.value != 0 && this.value != "") {
//            input = $(this).parent().parent().find(".quantiteProduit");
//            if (context == 'panier') {
//                if (typeof input.val() == 'undefined') {
//                    input = this;
//                    gererLignesOperation(input, context, true);
//                } else {
//                    gererLignesOperation(input, context);
//                }

//            } else {

//                if (typeof input.val() != 'undefined' && input.val() != '') {
//                    gererLignesOperation(input, context);
//                } else {
//                    viderLignesOperation(input);
//                }
//            }
//        }
//    });
//    $('.chiffreUniquement').keyup(function (event) {
//        if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
//            alerte(MERCI_DE_SAISIR_UN_NOMBRE_ENTIER);
//        }
//    });
//}
function gererLesInputDeSaisi(context) {
    tableauUtiliser = (context == 'panier') ? "tableauListePanierDX" : "tableauListeDesProduitsDX";

    $('#'+ tableauUtiliser +' .prixEtiquettes, #'+ tableauUtiliser +' .quantiteProduit, #'+ tableauUtiliser +' .quantiteCommandee').keypress(function (event) {
        
        charCode = (event.which) ? event.which : event.keyCode;
        saisiValide = true;
        if (charCode == 46 || charCode == 44) {
            if ($(this).val().indexOf(',') == -1 && $(this).val().indexOf('.') == -1 && !$(this).hasClass('chiffreUniquement')) {
                saisiValide = true;
            } else {
                saisiValide = false;
            }
        } else if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            saisiValide = false;
        } else {
            saisiValide = true;
        }
        return saisiValide;
    });



    $('#' + tableauUtiliser + ' .quantiteProduit, #' + tableauUtiliser + ' .quantiteCommandee').on('blur', function (e) {
       
        if (this.value != '') {
            stockerLignesOperation(this, false, context);
        } else {
            viderLignesOperation(this);
        }

    });
    $('#' + tableauUtiliser + ' .prixEtiquettes , #' + tableauUtiliser + ' .commentaireEtiquettes , #' + tableauUtiliser + ' .quantiteProduit , #' + tableauUtiliser + ' .codeEAN , #' + tableauUtiliser + ' .codePartenaireInput').on('focus', function (e) {
        
        $(this).select();
    });

    $('#' + tableauUtiliser + ' .prixEtiquettes , #' + tableauUtiliser + ' .commentaireEtiquettes ,#' + tableauUtiliser + ' .codeEAN , #' + tableauUtiliser + ' .codePartenaireInput').on('blur', function (e) {
        
        if (this.value != 0 && this.value != "") {
            
                input = $(this).parent().parent().find(".quantiteProduit");
                if (context == 'panier') {
                    if (typeof input.val() == 'undefined') {
                        input = this;
                        gererLignesOperation(input, context, true);
                    } else {
                        gererLignesOperation(input, context);
                    }

                } else {

                    if (typeof input.val() != 'undefined' && input.val() != '') {
                        gererLignesOperation(input, context);
                    } else {
                        viderLignesOperation(input);
                    }
                }
            }
    });
    $('.chiffreUniquement').keyup(function (event) {
        if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
            alerte(MERCI_DE_SAISIR_UN_NOMBRE_ENTIER);
        }
    });
}
function stockerLignesOperation(input, ajoutAuPanier, context, modifierPanier) {
   
    modifierPanier = typeof modifierPanier !== 'undefined' ? modifierPanier : false;
    vider = true;
    //console.log(input.value);
    //console.log(input);
    //'panier'
    if (input.value == "") {
        //this.value = 0;
        if ($(input).hasClass("quantiteProduit")) {

            inputQuantiteProduit = $(input).parent().parent().find(".quantiteProduit");
            inputPrixEtiquettes = $(input).parent().parent().find(".prixEtiquettes");
        
            if (inputQuantiteProduit.length > 0) {

                if (inputQuantiteProduit.val() != "") {
                    vider = false;
                }
            }
            if (inputPrixEtiquettes.length > 0) {

                if (inputPrixEtiquettes.val() != "") {
                    vider = false;
                }
            }
            if (vider) {
                viderLignesOperation(input);
            }

        }
    } else if ($(input).hasClass("quantiteProduit")) {
        if (input.value == 0) {
            inputQuantiteProduit = $(input).parent().parent().find(".quantiteProduit");
            inputPrixEtiquettes = $(input).parent().parent().find(".prixEtiquettes");
            if (inputQuantiteProduit.length > 0) {
                if (inputQuantiteProduit.val() != "") {
                    vider = false;
                }
            }
            if (inputPrixEtiquettes.length > 0) {
                if (inputPrixEtiquettes.val() != "") {
                    vider = false;
                }
            }
            if (vider) {
                viderLignesOperation(input);
            }
        } else {
            
            gererLignesOperation(input, context);
        }

    }
    if (ajoutAuPanier) {
        ajouterAuPanier();
    }
    if (modifierPanier) {
        modifierPanierGlobal();
    }
    
}

function gererLignesOperation(input, context, typeAssortiment) {
    
    typeAssortiment = typeof typeAssortiment !== 'undefined' ? typeAssortiment : false;
    lignesPanierLocal = (context == 'panier') ? lignesPanierAModifier : lignesPanier;
    nbLignes = lignesPanierLocal.length;
    if (typeAssortiment) {
        numeroExterneCatalogue = $(input).data('numeroexterne');
        numeroCatalogue = $(input).data('numerocatalogue');
        quantite = $('.panierQuantiteLigneOperation' + numeroExterneCatalogue).html();
        prixHt = "A";
    } else {
        numeroExterneCatalogue = $(input).data('numeroexterne');
        numeroCatalogue = $(input).data('numerocatalogue');
        prixHt = $(input).data('prix');
        quantite = (context == 'panier' && typeof $('.panierQuantiteLigneOperation' + numeroExterneCatalogue).val() !== 'undefined') ? $('.panierQuantiteLigneOperation' + numeroExterneCatalogue).val().trim() : $('.quantiteProduit' + numeroExterneCatalogue).val().trim();
        quantite = (quantite == "" || quantite == "0"  ? 1 : quantite);
    }
    expression = "^" + numeroExterneCatalogue + ";";
    reg = new RegExp(expression, 'g');
    trouverLigne = false
    commentaireEtiquettes = (context === 'panier' && typeof $('.panierCommentaire' + numeroExterneCatalogue).val() !== 'undefined') ? ($('.panierCommentaire' + numeroExterneCatalogue).length === 0 ? "" : $('.panierCommentaire' + numeroExterneCatalogue).val().trim()) : ($('.commentaireEtiquettes' + numeroExterneCatalogue).length === 0 ? "" : $('.commentaireEtiquettes' + numeroExterneCatalogue).val().trim());
    prixEtiquettes = (context === 'panier' && typeof $('.panierPrixEtiquette' + numeroExterneCatalogue).val() !== 'undefined') ? ($('.panierPrixEtiquette' + numeroExterneCatalogue).length === 0 || $('.panierPrixEtiquette' + numeroExterneCatalogue).val() === '' ? '' : $('.panierPrixEtiquette' + numeroExterneCatalogue).val().trim()) : ($('.prixEtiquettes' + numeroExterneCatalogue).length === 0 || $('.prixEtiquettes' + numeroExterneCatalogue).val() === '' ? '' : $('.prixEtiquettes' + numeroExterneCatalogue).val().trim());
    codePartenaire = autoriserLaModificationDuCodePartenaire !== "" ? (context === 'panier' && typeof $('.panierCodePartenaire' + numeroExterneCatalogue).val() !== 'undefined') ? ($('.panierCodePartenaire' + numeroExterneCatalogue).length == 0 ? "" : $('.panierCodePartenaire' + numeroExterneCatalogue).val().trim()) : ($('.panierCodePartenaire' + numeroExterneCatalogue).length === 0 ? "" : $('.panierCodePartenaire' + numeroExterneCatalogue).val().trim()) : "-1";
    codeEAN = autoriserLaModificationDuCodeBarreReferencement !== "" ? (context === 'panier' && typeof $('.panierCodeEAN' + numeroExterneCatalogue).val() !== 'undefined') ? ($('.panierCodeEAN' + numeroExterneCatalogue).length === 0 ? "" : $('.panierCodeEAN' + numeroExterneCatalogue).val().trim()) : ($('.panierCodeEAN' + numeroExterneCatalogue).length === 0 ? "" : $('.panierCodeEAN' + numeroExterneCatalogue).val().trim()) : "-1";
    i = 0;
   
    // numeroExterneCatalogueLigne,numeroCatalogue,quantite,prixEtiquettes,commentaireEtiquettes,prixUnitaireHTDansDeviseClient
    while (!trouverLigne && i < nbLignes) {
        if (lignesPanierLocal[i].match(reg)) {
            lignesPanierLocal[i] = numeroExterneCatalogue + ";" + numeroCatalogue + ";" + quantite + ";" + prixEtiquettes + ";" + commentaireEtiquettes + ";" + prixHt + ";" + codePartenaire + ";" + codeEAN;
            trouverLigne = true;
        }
        i++;
    }
    if (!trouverLigne) {
        lignesPanierLocal.push(numeroExterneCatalogue + ";" + numeroCatalogue + ";" + quantite + ";" + prixEtiquettes + ";" + commentaireEtiquettes + ";" + prixHt + ";" + codePartenaire + ";" + codeEAN);
    }
    if (context == 'panier') {
        lignesPanierAModifier = lignesPanierLocal;
    } else {
        lignesPanier = lignesPanierLocal; 
    }
}

function viderLignesOperation(input) {
    nbLignes = lignesPanier.length;
    numeroExterneCatalogue = "^" + $(input).data('numeroexterne') + ";";
    reg = new RegExp(numeroExterneCatalogue, 'g');
    trouverLigne = false
    i = 0;
    while (!trouverLigne && i < nbLignes) {
        if (lignesPanier[i].match(reg)) {
            lignesPanier.splice(i, 1);
            trouverLigne = true;
        }
        i++;
    }
}
function extraireLesNumeroExterneCatalogueLignes(lignesPanier) {
    numeroExterneCatalogues = [];
    nbLignes = lignesPanier.length;
    trouverLigne = false
    i = 0;
    while (i < nbLignes) {
        tableauDesValeurs = lignesPanier[i].split(";");
        numeroExterneCatalogues.push(tableauDesValeurs[0]);
        i++;
    }
    return numeroExterneCatalogues;
}

function extraireLesQuantiteSaisi(lignesPanier) {
    quantiteSaisi = [];
    nbLignes = lignesPanier.length;
    trouverLigne = false
    i = 0;
    while (i < nbLignes) {
        tableauDesValeurs = lignesPanier[i].split(";");
        quantiteSaisi.push(tableauDesValeurs[2]);
        i++;
    }
    return quantiteSaisi;
}



function viderCalculsEnSessionEtMettreAJourDateDeLivraison(date, source, action, affichageControleDate,avecChargement=true) {

    if (typeof (action) === 'undefined') {
        action = "";
    }
    if (typeof (affichageControleDate) === 'undefined') {
        affichageControleDate = "";
    }
    if (validerDateLivraison(affichageControleDate)) {
        if (avecChargement) {
            afficherChargement();
        }
        $.ajax({
            url: '/webshop/viderCalculsEnSessionEtMettreAJourDateDeLivraison',
            data: {
                'dateDeLivraisonChoisie': date,
                'cataloguesConditionneeParDateLivraison': cataloguesConditionneeParDateLivraison,
                'action': action,
            },
            success: function (retours) {
                nouvelleDateDeLivraison = date;
                listeDesNumerosExterneCataloguesNonValides = retours.split("|");
                //            $.ajax({
                //                url: '/OperationDesktop/rafraichirOperation',
                //                data: {
                //                    'dateModifiee': "True"
                //                },
                //                success: function (quantiteEtMontant) {
                //                    tableauValeurs = quantiteEtMontant.split("|");
                //                    if (tableauValeurs.length > 1) {
                //                        quantite = tableauValeurs[0];
                //                        montant = tableauValeurs[1];
                //                        masquerChargement();
                //                        $('.valeurNombreProduitsAjouter').html(quantite);
                //                        $('.valeurMontantTotal').text(montant);
                //                    } else {
                //                        alerte(tableauValeurs, 'erreur');
                //                    }
                //                }
                //            });

                if (retours != "") {
                    if (AUTORISER_LIGNE_PERIME == "" || AUTORISER_LIGNE_PERIME.toLowerCase().ltrim().rtrim() == "non") {
                        alerte(MERCI_DE_SUPPRIMER_LES_LIGNES_DES_CATALOGUES_INDISPONIBLES, 'info');
                    } else if (source != 'panier') {
                        alerte(ALERTE_LIGNE_PERIME, 'info');
                    }
                }
               // materialiserLesLignesInvalidesDansLePanier();
                if (avecChargement) {
                    masquerChargement();
                }
            }
        });
    } else if (date == "") {
        nouvelleDateDeLivraison = date;
    }
    activerLesChampsDePanier();
}
function rafraichirAffichageModeExpedition(numeroModeExpeditionParDefaut) {
    if (typeof ($('#modeExpeditionSelection')) != 'undefined') {
        $('#modeExpeditionSelection').val(numeroModeExpeditionParDefaut);
    }
}


function fermerAlerteReinitialiserRenommageColonne() {
    $('#layoutAlerteReinitialiserRenommageColonne').fadeOut(200);
    $('#alerteReinitialiserRenommageColonne').fadeOut(200);
    $('#reinitialiserRenommageColonne').attr('checked', false);
}
function fermerPopupMiseAJourPanier() {
    $('#layoutPopupMiseAJourPanier').fadeOut(200);
    $('#alertePopupMiseAJourPanier').fadeOut(200);
}

function nombreAvecDesEspaces(nombre) {
    var parties = nombre.toString().split(".");
    parties[0] = parties[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    return parties.join(".");
}
function afficherChargement() {
    $('#layoutChargement').css('height', document.documentElement.scrollHeight);
    $('#layoutChargement').fadeTo(1, 0.5, function () { });
    $('#chargement').show();
}

function masquerChargement() {
    //debugger
    $('#layoutChargement').fadeOut(200);
    $('#chargement').fadeOut(200);
}


// Dans le cas de la touche précédente dans le navigateur, il ne recharge pas la page,
// le div de chargement est donc visible. Ceci permet de le masquer.
/*window.onunload = function () {
    masquerChargement();
}

n'est plus utile car contexte AJAX. On garde en commentaire pour info.
*/

function initialiserDetailProduitWebShop() {
    allerVersLeHaut();
    $('.quantite').keypress(function (event) {
        charCode = (event.which) ? event.which : event.keyCode;
        saisiValide = true;
        if (charCode == 46 || charCode == 44) {
            if ($(this).val().indexOf(',') == -1 && $(this).val().indexOf('.') == -1 && !$(this).hasClass('chiffreUniquement')) {
                saisiValide = true;
            } else {
                saisiValide = false;
            }
        } else if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            saisiValide = false;
        } else {
            saisiValide = true;
        }
        return saisiValide;
    });
    $('.quantiteFocus').focus(function () {
        $(this).select();
    });

    // Validation d'ajout au panier avec touche entré
    $('.quantiteFocus').keyup(function (event) {
        if (event.keyCode == CODE_TOUCHE_ENTREE) {
            $('#ajouterAuPanier').click();
        }
    });
    $('.chiffreUniquement').keyup(function (event) {
        if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
            alerte(MERCI_DE_SAISIR_UN_NOMBRE_ENTIER);
        }
    });
    $("#slideshow-carousel").tinycarousel({ interval: false, axis: 'y', infinite: false });
    
    //Combine jCarousel with Image Display
    $('div#slideshow-carousel li a').click(function () {
	    $('div#slideshow-main li').removeClass('active');
	    $('div#slideshow-main li.' + $(this).attr('rel')).addClass('active');
	    return false;
	});


}
function voirDetailsProduit(numeroLigneCatalogue, typeGestionTarifs, modeEmballageOuUnite, appelExterne, numeroCatalogue, numeroExterneCatalogueLigne, numeroExterneArticle) {
	typeGestionTarifs = typeGestionTarifs != "" ? typeGestionTarifs : 0;
    positionScroll = $(document).scrollTop();
    $.ajax({
        url: '/webshop/detailsProduit', 
        data: {
            'numeroLigneCatalogue': numeroLigneCatalogue,
            'typeGestionTarifs': typeGestionTarifs,
            'modeEmballageOuUnite': modeEmballageOuUnite,
            'numeroSociete': numeroSociete,
            'numeroBoutique': numeroBoutique,
            'appelExterne': appelExterne !== undefined ? appelExterne : "",
            'numeroCatalogue': numeroCatalogue,
            'numeroExterneCatalogueLigne': numeroExterneCatalogueLigne,
            'numeroExterneArticle': numeroExterneArticle
        },
        success: function (template) {
            $('#detailDUnProduit').html(template);
            $('.listeProduitsContenu').hide();
            $('.enteteNavigateur').hide();
            $('#detailDUnProduit').show();
            $('.conteneurEnteteNavigateurZoneFiltre').hide();
            afficherOnlget($('#libelleInformations'), 1);
            allerVersLeHaut(true);
            numeroArticleVisibleEnDetail = numeroLigneCatalogue;
            masquerChargement();
        }
    });
}

function afficherOnlget(libelleOnglet, indiceOnglet) {
    $('.ongletActif').removeClass('ongletActif').addClass('ongletNonActif');
    $(libelleOnglet).removeClass('ongletNonActif').addClass('ongletActif');
    $('.onglet').hide();
    $('.onglet:nth-of-type(' + (indiceOnglet + 1) + ')').show();
}

function retourALaListeDesProduits(idElementDeRetour) {
    $('.listeProduitsContenu').show();
    $('.enteteNavigateur').show();
    $('#detailDUnProduit').hide();
    numeroArticleVisibleEnDetail = -1;
    $('.conteneurEnteteNavigateurZoneFiltre').show();
    var positionDeElement = $('#' + idElementDeRetour);
    if (positionDeElement.length > 0) {
        var offsetPositionDeElement = positionDeElement.offset();
        if (activerAllerVersLeHaut == 'True') {
            $('html, body').scrollTop(offsetPositionDeElement.top - 85);
        } else if (positionScroll != 0) {
            $(document).scrollTop(positionScroll);
            positionScroll = 0;
        }
    }

}

function ajouterAuPanier(numeroExterneCatalogueLigne, mode, prixUnitaireHTDansDeviseClient, numeroCatalogue, confirmation, appelExterne) {

    champsValide = true;
    messageErreur = "";
    if (numeroExterneCatalogueLigne != undefined) {
        if (mode == VALEUR_LISTE && $('.quantiteProduit' + numeroExterneCatalogueLigne).val() != '') {
                viderLignesOperation($('.quantiteProduit' + numeroExterneCatalogueLigne))
        }
        codePartenaire = "-1";
        codeEAN =  "-1";
        // numeroExterneCatalogueLigne,numeroCatalogue,quantite,prixEtiquettes,commentaireEtiquettes,prixUnitaireHTDansDeviseClient
        chaineDesValeurs = numeroExterneCatalogueLigne + ";"
        + numeroCatalogue + ";"
        + (mode !== VALEUR_LISTE ? ($('.quantite').val() !== '' ? $('.quantite').val().trim() : 1) : ($('.quantiteProduit' + numeroExterneCatalogueLigne).val() !== '' ? $('.quantiteProduit' + numeroExterneCatalogueLigne).val().trim() : 1)) + ";"
        + (mode !== VALEUR_LISTE || $('.prixEtiquettes' + numeroExterneCatalogueLigne).length === 0 || $('.prixEtiquettes' + numeroExterneCatalogueLigne).val() === '' ? '' : $('.prixEtiquettes' + numeroExterneCatalogueLigne).val().trim()) + ";"
        + (mode !== VALEUR_LISTE || $('.commentaireEtiquettes' + numeroExterneCatalogueLigne).length === 0 ? "" : $('.commentaireEtiquettes' + numeroExterneCatalogueLigne).val().trim())
            + ";" + prixUnitaireHTDansDeviseClient + ";"
            + (mode === VALEUR_LISTE ? $('.panierCodePartenaire' + numeroExterneCatalogueLigne).length === 0 || $('.panierCodePartenaire' + numeroExterneCatalogueLigne).val() === '' ? codePartenaire : $('.panierCodePartenaire' + numeroExterneCatalogueLigne).val().trim() : codePartenaire) + ";"
            + (mode === VALEUR_LISTE ? $('.anierCodeEAN' + numeroExterneCatalogueLigne).length === 0 || $('.anierCodeEAN' + numeroExterneCatalogueLigne).val() === '' ? codeEAN : $('.anierCodeEAN' + numeroExterneCatalogueLigne).val().trim() : codeEAN);
        if (mode === VALEUR_LISTE) {
            viderLignesOperation($('.quantiteProduit' + numeroExterneCatalogueLigne));
        }
    } else {
        chaineDesValeurs = (lignesPanier.length > 0 ? lignesPanier.join("_") : "");
    }
    if (saisieEnModeSemaine == "True" && $('#semaineDateLivraison').val() == '') {
        messageErreur += MERCI_DE_SAISIR_UNE_SEMAINE_DE_LIVRAISON;
        champsValide = false;
    }
    if (saisieEnModeSemaine == "True" && $('#semaineDateLivraison').val() != '' && firstDateOfWeekOperation != null) {
        dateLivraison = firstDateOfWeekOperation;
    }

    if ($('#dateLivraison').val() == '' && saisieEnModeSemaine!="True") {
        messageErreur += MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON;
        champsValide = false;
    }
    if (!validerDateLivraison() && (typeof saisieEnModeSemaine == 'undefined' || saisieEnModeSemaine != "True")) return;
    modeExpedition = '';
    if (typeof ($('#modeExpeditionSelection')) != 'undefined') {
        modeExpedition = $('#modeExpeditionSelection').val();
    }
    dateDeJour = new Date();
    dateDeJour.setDate(dateDeJour.getDate() - 1);
    dateDeJour.setHours(23);
    dateDeJour.setMinutes(59);
    dateDeJour.setSeconds(59);


    //if (preinitialiserDateLivraison == "False") {
    if ($('#dateLivraison').val() != '' && $('#dateLivraison').datepicker("getDate") <= dateDeJour && saisieEnModeSemaine != "True") {
        messageErreur += MERCI_DE_SAISIR_UNE_DATE_DE_LIVRAISON_SUPEREUR_A_DATE_D_AUJOURDHUI;
        champsValide = false;
    }
    //}
    if (chaineDesValeurs == "") {
        messageErreur += MERCI_DE_SAISIR_AU_MOINS_UN_PRODUIT;
        champsValide = false;
    }
    $('.chiffreUniquement').each(function () {
        if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
            messageErreur += MERCI_DE_SAISIR_UN_NOMBRE_ENTIER;
            champsValide = false;
            return false;
        }
    });

    if (messageErreur == "" && chaineDesValeurs != "") {
        $.ajax({
            url: '/OperationDesktop/ajouterAuPanier',
            data: {
                'chaineDesValeurs': chaineDesValeurs,
                'dateLivraison': saisieEnModeSemaine == "True" ? firstDateOfWeekOperation : ($('#dateLivraison').val() != '' ? $('#dateLivraison').val() : ''),
                'confirmation': confirmation != undefined ? 'oui' : 'non',
                'modeExpedition': modeExpedition
            },
            dataType: "json",
            success: function (retourServeur) {
                tableauQteNumrExterne = retourServeur.TableauQuantiteEtNumeroExterneJ;
                retourServeur = retourServeur.ResultatJ;
                masquerChargement();
                quantiteAfficher = 0;
                montant = 0;
                toRemove = [];
                indiceTableau = [];

                if (retourServeur == 'operationEncoursExistante') {
                    alerte(UNE_OPERATION_EST_DEJA_EN_COURS_DE_SAISIE_VOULEZ_VOUS_AJOUTER_CE_PRODUIT_DANS_L_OPERATION_EN_COURS + ' ?', 'confirmationUtilisateur', 'ajouterAuPanier',
                        numeroExterneCatalogueLigne, '"' + mode + '"', prixUnitaireHTDansDeviseClient, numeroCatalogue, 'oui'
                    );
                } else {
                    if (typeof saisieEnModeSemaine !== "undefined" && saisieEnModeSemaine == "True") {
                       if ($('#semaineDateLivraison').find(":selected").hasClass("selectedSemaineLivraison")==false) {
                            $('#semaineDateLivraison').find(":selected").addClass('selectedSemaineLivraison');
                        }
                    }
                    tableauValeurs = retourServeur.split("|");
                    tableauQteNumrExterne = tableauQteNumrExterne.split(";");
                    if (tableauValeurs.length > 1) {// le cas normal on peut ajouter un produit traitement normal le else de cet if le message d'erreur lorsque on peut pas ajouter produit
                        quantiteAfficher = tableauValeurs[0];
                        montant = tableauValeurs[1];
                        var message = tableauValeurs[2];
                        if (message != "") {
                            alerte(message);
                        } else {
                            if (numeroExterneCatalogueLigne != undefined) {
                                alerte(LE_PRODUIT_A_BIEN_ETE_AJOUTE_AU_PANIER, 'confirmation');
                            } else {
                                if (templatePersonnalise != "" && affichageMsgValidationAjoutArticlePanier!= "") {
                                    afficherPopupRecapAjoutPanier(chaineDesValeurs);
                                } else {
                                    var messageSuccess;
                                    if (lignesPanier.length == 1) {
                                        messageSuccess = LE_PRODUIT_A_BIEN_ETE_AJOUTE_AU_PANIER;
                                    } else if (lignesPanier.length > 1) {
                                        messageSuccess = LES_PRODUITS_ONT_BIEN_ETE_AJOUTES_AU_PANIER;
                                    }
                                    if (templatePersonnalise != "") {
                                        $("#toastContainer").dxToast({
                                            type: "success", // or "info" | "warning" | "error"
                                            message: messageSuccess
                                        });
                                        $("#toastContainer").dxToast("show");
                                    } else {
                                        
                                        alerte(messageSuccess);
                                    }
                                }
                            }
                        }
                        if (appelExterne !== undefined && appelExterne == "EXTERNE") {
                            $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(quantiteAfficher));

                            tableauValeursPanier = nombreAvecDesEspaces(montant).replace(',', '.').split('.');

                            $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                            $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);                            

                            rafraichirCumulsEmballage();
                            if (COMMANDE_MONO_CATALOGUE == 'OUI') {
                                echapperLeChangementDeCatalogue = "OUI";
                                numeroCatalogueSelectionner = catalogueCocher[0];
                            }
                            retourVersListeAccesExterne(numeroExterneCatalogueLigne + "_" + numeroCatalogue);
                        } else if (mode == VALEUR_LISTE || numeroExterneCatalogueLigne === undefined) {

                            if (numeroExterneCatalogueLigne != undefined) {
                                
                                $('.quantiteProduit' + numeroExterneCatalogueLigne).parent().siblings().not('.colonneAjoutPanier').addClass('produitDansLePanier');
                                $('.quantiteProduit' + numeroExterneCatalogueLigne).parent().addClass('produitDansLePanier');
                                $('.quantiteProduit' + numeroExterneCatalogueLigne).parent().parent().find('.prixStyle').addClass('prixStyleBlanc');
                                if (preinitialiserLePrixEtiquetteParValeurDeLaLigneCatalogue != valeurOui) {
                                    $('.prixEtiquettes' + numeroExterneCatalogueLigne).val("");
                                }
                                if (preinitialiserLeCommentaireEtiquetteParValeurDeLaLigneCatalogue != valeurOui) {
                                    $('.commentaireEtiquettes' + numeroExterneCatalogueLigne).val("");
                                }
                                $('.quantiteProduit' + numeroExterneCatalogueLigne).val("");
                            } else {
                                
                                numeroExterneCatalogueLignes = extraireLesNumeroExterneCatalogueLignes(lignesPanier);
                                quantiteSaisi = extraireLesQuantiteSaisi(lignesPanier);
                                nbNumeroExternes = numeroExterneCatalogueLignes.length;
                                if ($('.dx-datagrid').height() > 0) {
                                    for (var i = 0; i < nbNumeroExternes; i++) {
                                        if (tableauQteNumrExterne.toString().indexOf(numeroExterneCatalogueLignes[i]) == -1) {// on traite que les bonnes numeroExterne dons laquelle la quantité est correcte
                                            if ($('.quantiteProduit' + numeroExterneCatalogueLignes[i]).length > 0) {

                                                $('.quantiteProduit' + numeroExterneCatalogueLignes[i]).parent().siblings().not('.colonneAjoutPanier').addClass('produitDansLePanier');
                                                $('.quantiteProduit' + numeroExterneCatalogueLignes[i]).parent().addClass('produitDansLePanier');
                                                $('.quantiteProduit' + numeroExterneCatalogueLignes[i]).parent().parent().find('.prixStyle').addClass('prixStyleBlanc');
                                                if (preinitialiserLePrixEtiquetteParValeurDeLaLigneCatalogue != valeurOui) {
                                                    $('.prixEtiquettes' + numeroExterneCatalogueLignes[i]).val("");
                                                }
                                                if (preinitialiserLeCommentaireEtiquetteParValeurDeLaLigneCatalogue != valeurOui) {
                                                    $('.commentaireEtiquettes' + numeroExterneCatalogueLignes[i]).val("");
                                                }
                                                $('.quantiteProduit' + numeroExterneCatalogueLignes[i]).val("");
                                            }
                                        }
                                    }
                                }
                                if ($('.conteneurBlocProduitEnMosaique').height() != null) {
                                    modifierModeDAffichageWebShop('Miniature');
                                } else {
                                    modifierModeDAffichageWebShop(VALEUR_LISTE);
                                }

                                ////*** Retirer de tableau lignesPanier les numeros externes corrects et on maintien les mauvais ***//////
                                if (tableauQteNumrExterne != "") {
                                    var cpt3 = 0;
                                    while (cpt3 < tableauQteNumrExterne.length) {

                                        if (tableauQteNumrExterne[cpt3] != "") {
                                            messageReservation2 = tableauQteNumrExterne[cpt3].split("#");
                                            toRemove.push(messageReservation2[1]);
                                        }
                                        cpt3++;
                                    }
                                }
                                var cpt4 = 0;
                                while (cpt4 < toRemove.length) {
                                    for (var k = 0; k < lignesPanier.length; k++) {
                                        if (lignesPanier[k].indexOf(toRemove[cpt4]) > -1) {
                                            indiceTableau.push(lignesPanier[k]);
                                            break;
                                        }
                                    }
                                    cpt4++;
                                }
                                lignesPanier = indiceTableau;
                            }
                        } else {
                            retourALaListeDesProduits(numeroExterneCatalogueLigne + '_' + numeroCatalogue);
                            modifierModeDAffichageWebShop("");

                        }
                        $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(quantiteAfficher));

                        tableauValeursPanier = nombreAvecDesEspaces(montant).replace(',', '.').split('.');

                        $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                        $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);
                        if (affichageDeLaSurfaceBool == 'True' && typeof tableauValeurs[3] !== "undefined" && tableauValeurs[3] != "") {
                            $('.valeurDensite').html(tableauValeurs[3] + "&nbsp;");
                         }
                        rafraichirCumulsEmballage();
                        if (COMMANDE_MONO_CATALOGUE == 'OUI') {
                            echapperLeChangementDeCatalogue = "OUI";
                            numeroCatalogueSelectionner = catalogueCocher[0];
                        }
                    } else {

                        if (tableauValeurs[0].indexOf("MESSAGE:") == 0) {// tableauValeurs[0] : retour message avec un mot clé MESSAGE dans la position 0
                            alerte(tableauValeurs[0].substring(8), 'confirmationUtilisateur', 'validerRechargePageAccueil'); //8 le nombre de caractere de mot clé MESSAGE:
                        } else if (tableauValeurs[0].indexOf("MESSAGESANSACTIONS:") == 0) {
                            alerte(tableauValeurs[0].substring(19), 'confirmationUtilisateur'); //19 le nombre de caractere de mot clé MESSAGESANSACTIONS:
                        } else {
                            alerte(tableauValeurs[0], 'erreur');
                        }




                    }
                }
                if (retourServeur.indexOf("MESSAGESANSACTIONS:") < 0) {
                    $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(quantiteAfficher));

                    tableauValeursPanier = nombreAvecDesEspaces(montant).replace(',', '.').split('.');

                    $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                    $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);

                    rafraichirCumulsEmballage();
                }

            }
        });
    } else {
        alerte(messageErreur, 'erreur');
    }
    masquerChargement();
}


$(document).ready(function () {

    


});


//Carousel Tweaking

function mycarousel_initCallback(carousel) {

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function () {
        carousel.stopAuto();
    }, function () {
        carousel.startAuto();
    });
}

function afficherNomDuMedia(nonMedia ,element) {
    var position = $(element).offset();
    $('#tooltipNomMedia').css('top', position.top - $('#tooltipNomMedia').parent().offset().top + element.offsetHeight/2 -10);
    $('#tooltipNomMedia').css('left', position.left - $('#tooltipNomMedia').parent().offset().left + element.offsetWidth + 5);
    $('#tooltipNomMedia').text(nonMedia);
    $('#tooltipNomMedia').show();
}

function afficherPopupRecapAjoutPanier() {
    //console.log("afficherPopupRecapAjoutPanier ", (lignesPanier.length > 0 ? lignesPanier.join("_") : ""))   
    afficherChargement();
    $.ajax({
        url: '/webshop/recapAjoutPanier',
        data: {
            'articleAjoutes': (lignesPanier.length > 0 ? lignesPanier.join("_") : ""),
            'numeroSociete': numeroSociete,
            'numeroBoutique': numeroBoutique},
        success: function (resultat) {
           
            $("#layoutPopupRecapAjoutPanier").height($("#contenuPage").height());
            $('#layoutPopupRecapAjoutPanier').fadeIn(200);
            $('#popupRecapAjoutPanier').html(resultat);
            $('#popupRecapAjoutPanier').fadeIn(200);
            //$('#popupRecapAjoutPanier').draggable({
            //    handle: "div#recapAjoutPanierHeader"
            //});
            masquerChargement();
        }
    });
}
function fermerPopupRecapAjoutPanier() {
    $('#layoutPopupRecapAjoutPanier').fadeOut(200);
    $('#popupRecapAjoutPanier').fadeOut(200);
}
var lignesPanierAModifier = [];
var entetePanierInitialisee = false;
var TYPE_OPERATION_DEVIS = "E";
var rechargerPanier = false;

function initialisationPageListePanierDX(modePanier) {
    allerVersLeHaut();
    // entetePanierInitialisee = false;
    $('.contenuPage').hide();
    //tableauListePanier = tableauListeDuPanier;
    // idTableauHtml = "tableauListePanier";
    lignesPanierAModifier = [];
    // $('#tableauListePanier').hide();
    $.ajax({
        url: '/webshop/colonnesConfigPanier',
        async: false,
        dataType: "json",
        success: function (resultat) {
            conf = resultat;
            $("#tableauListePanierDX").data({ conf: resultat });
            $('#listeLargeursColonnes_tableauListePanierDX').draggable({
            });
            if (typeof ($('#blockRecapitulatifCommande').html()) !== 'undefined' && $('#blockRecapitulatifCommande').html().indexOf("recapCommande") == -1) {
                activerLesChampsDePanier();
            }
            listePanier = $("#tableauListePanierDX").dxDataGrid({
                dataSource: operationsLigneJson,
                paging: {
                    pageSize: nombreLigneOperation
                },
                pager: {
                    visible: false,
                },
                height: "100%",
                filterRow: {
                    visible: false
                },
                columnChooser: {
                    enabled: true,
                    mode: "select"

                },
                remoteOperations: {
                    filtering: $("#tableauListePanierDX").data("enableheader") == "True",
                    sorting: $("#tableauListePanierDX").data("enableheader") == "True"
                },
                allowColumnReordering: $("#tableauListePanierDX").data("enableheader") == "True",
                allowColumnFiltering: $("#tableauListePanierDX").data("enableheader") == "True",
                allowSearch: $("#tableauListePanierDX").data("enableheader") == "True",

                columns: [
                    {
                        dataField: "numeroOperationLigne",
                        caption: "numeroOperationLigne",
                        allowEditing: false,
                        width: 40,
                        alignment: "right"
                    }
                    , {
                        caption: "imageMedia",
                        dataField: "imageMedia",
                        allowEditing: false,
                        width: 135,
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            $(container).addClass("image");

                            if (options.data.urlImageMedia !== "") {
                                $("<img src=\"" + options.data.urlImageMedia + "\" alt=\"\" class=\"masqueRondMedia\" height=\"50px\" />").appendTo(container);
                            } else {
                                $("<img class=\"pasDImage\" src=\"/ressource/image/webshop/img_default.png\" alt=\"\" class=\"masqueRondMedia\" height=\"50px\" />").appendTo(container);
                            }

                        }

                    }
                    , {
                        caption: "imageCatalogue",
                        dataField: "imageCatalogue",
                        width: 135,
                        allowEditing: false,
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            $("<img src=\"" + options.data.imageCatalogue + "\" alt=\"\" height=\"30px\" class=\"imageCatalogue\"/>").appendTo(container);
                        }

                    }
                    , {
                        caption: "genre",
                        dataField: "genre",
                        width: 135,
                        allowEditing: false,
                        alignment: "left",
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            $("<span />").text(options.value).appendTo(container);
                        }

                    },
                    {
                        caption: "espece",
                        dataField: "espece",
                        allowEditing: false,
                        width: 135,
                        alignment: "left",
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            $("<span />").text(options.value).appendTo(container);
                        }

                    },
                    {
                        caption: "variete",
                        dataField: "variete",
                        allowEditing: false,
                        width: 135,
                        alignment: "left",
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            $("<span />").text(options.value).appendTo(container);
                        }

                    },
                    {
                        caption: "presentationMillesime",
                        dataField: "presentationMillesime",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"

                    },
                    {
                        caption: "tailleUniteVente",
                        dataField: "tailleUniteVente",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"
                    },
                    {
                        caption: "designationArticle",
                        dataField: "designationArticle",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "designation",
                        dataField: "designation",
                        width: 135,
                        allowEditing: false,
                        alignment: "left",
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            $("<span />").text(options.value).appendTo(container);
                        }

                    },
                    {
                        caption: "quantiteProduits",
                        dataField: "quantiteProduits",
                        width: 135,
                        allowEditing: true,
                        cellTemplate: function (container, options) {
                            var clone;
                            var stringQuantiteProduit = options.data.quantiteProduit === undefined ? "" : options.data.quantiteProduit;
                            var classQuantitePourAssortiment = options.data.quantitePourAssortiment === undefined ? "" : options.data.quantitePourAssortiment;
                            if (options.data.typeAssortiment !== undefined && (options.data.typeAssortiment === null || options.data.typeAssortiment === "" || options.data.typeAssortiment === "A")) {
                                stringQuantiteProduit = "<input class=\"numeriqueTri quantiteProduit " + classQuantitePourAssortiment + " panierQuantiteLigneOperation" + options.data.numeroExterneCatalogueLigne + "\" data-prix=\"" + options.data.colonnePrix + "\"  data-numeroexterne=\"" + (options.data.numeroExterneCatalogueLigne) + "\" data-typeAssortiment=\"" + options.data.typeAssortiment + "\"  data-numerocatalogue=\"" + options.data.numeroCatalogue + "\" type=\"text\" id=\"quantiteLigneOperation" + options.data.numeroExterneCatalogueLigne + "\" value=\"" + stringQuantiteProduit + "\"  />";
                            } else {
                                stringQuantiteProduit = "<label class=\"numeriqueTri panierQuantiteLigneOperation" + options.data.numeroExterneCatalogueLigne + "\"  data-numeroexterne=\"" + options.data.numeroExterneCatalogueLigne + "\" data-typeAssortiment=\"" + options.data.typeAssortiment + "\"  id=\"quantiteLigneOperation" + options.data.numeroExterneCatalogueLigne + "\" >" + stringQuantiteProduit + "</label>";
                            }
                            $(container).addClass("colonneQuantite");
                            if ($(stringQuantiteProduit).hasClass("quantiteProduit")) {
                                expression = "^" + options.data.numeroExterneProduit + ";";
                                reg = new RegExp(expression, 'g');
                                uneLigne = lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                    undefined;
                                
                                if (typeof uneLigne !== 'undefined') {
                                    valeurs = uneLigne.split(";");
                                    clone = $(stringQuantiteProduit).val(valeurs[2]);
                                } else {
                                    clone = stringQuantiteProduit;
                                }
                            } else {
                                clone = stringQuantiteProduit;
                            }

                            $(container).append(stringQuantiteProduit);
                        },
                        alignment: "right"
                    },
                    {
                        caption: "quantiteLivree",
                        dataField: "quantiteLivree",
                        allowEditing: false,
                        width: 135,
                        alignment: "right",
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            $(container).attr('class', EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? ' colonneQuantite inactif numeriqueTri' : ' colonneQuantite numeriqueTri');
                            $(container).append(options.value);
                        }

                    },
                    {
                        caption: "colonnePrix",
                        dataField: "colonnePrix",
                        width: 135,
                        allowEditing: false,
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            var clone = $(options.data.colonnePrix).clone();
                            $(container).attr('class', 'prixStyle numeriqueTri');
                            if (options.data.prixAvecJustification === true) {
                                $(container).addClass('dx-link').on('dxclick', function (event) {
                                    if (templatePersonnalise == "") {
                                        //desactiver l'affichage de popup si template personnalisé
                                        window.setTimeout(function () { afficherJustification(options.data.numeroOperation, options.data.numeroOperationLigne) }, 0);
                                    }

                                });
                            }


                            $("<label class=\"prixHt\" />").text(options.data.colonnePrix + options.data.symboleDevise).appendTo(container);



                        },
                        alignment: "right"
                    },
                    {
                        caption: "commentaireEtiquettes",
                        dataField: "commentaireEtiquettes",
                        width: 135,
                        allowEditing: true,
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            var clone;

                            //if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                            expression = "^" + options.data.numeroExterneProduit + ";";
                            reg = new RegExp(expression, 'g');
                            uneLigne = lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                undefined;
                            valeurEtiquette = options.data.commentaireEtiquettes === undefined ? "" : options.data.commentaireEtiquettes;
                            if (typeof uneLigne !== 'undefined') {
                                valeurs = uneLigne.split(";");
                                clone = $("<input maxlength=\"255\" class=\"commentaireEtiquettes  autocomplete=\"something-new\" panierCommentaire" + options.data.numeroExterneCatalogueLigne + "\" id=\"commentaire" + options.data.numeroExterneCatalogueLigne + "\" data-numeroexterne =\"" + options.data.numeroExterneCatalogueLigne + "\" data-numerocatalogue =\"" + options.data.numeroCatalogue + "\" type=\"text\"  value=\"" + valeurEtiquette + "\" />").val(valeurs[4]);

                            } else {
                                clone = $("<input maxlength=\"255\" autocomplete=\"something-new\" class=\"commentaireEtiquettes  panierCommentaire" + options.data.numeroExterneCatalogueLigne + "\" id=\"commentaire" + options.data.numeroExterneCatalogueLigne + "\" data-numeroexterne =\"" + options.data.numeroExterneCatalogueLigne + "\" data-numerocatalogue =\"" + options.data.numeroCatalogue + "\" type=\"text\"  value=\"" + valeurEtiquette + "\" />");
                            }
                            //} else {
                            //    clone = options.value;
                            //}


                            $(clone)
                                .appendTo(container);
                        },
                        alignment: "right"
                    },
                    {
                        caption: "prixEtiquettes",
                        dataField: "prixEtiquettes",
                        width: 135,
                        allowEditing: true,
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            var clone;
                            //if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                            expression = "^" + options.data.numeroExterneProduit + ";";
                            var valeurPrixEtiquette = options.data.prixEtiquettes === undefined ? "" : options.data.prixEtiquettes;

                            reg = new RegExp(expression, 'g');
                            uneLigne = lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                undefined;
                            if (typeof uneLigne !== 'undefined') {
                                valeurs = uneLigne.split(";");

                                clone = $("<input class=\"prixEtiquettes panierPrixEtiquette" + (options.data.numeroExterneCatalogueLigne) + "\" id=\"prixEtiquette" + (options.data.numeroExterneCatalogueLigne) + "\" data-numeroexterne =\"" + (options.data.numeroExterneCatalogueLigne) + "\" data-numerocatalogue =\"" + options.data.prixEtiquettes.numeroCatalogue + "\"  type=\"text\" value=\"" + valeurPrixEtiquette + "\" /> ").val(valeurs[3]);

                            } else {
                                clone = $("<input class=\"prixEtiquettes panierPrixEtiquette" + (options.data.numeroExterneCatalogueLigne) + "\" id=\"prixEtiquette" + (options.data.numeroExterneCatalogueLigne) + "\" data-numeroexterne =\"" + (options.data.numeroExterneCatalogueLigne) + "\" data-numerocatalogue =\"" + options.data.prixEtiquettes.numeroCatalogue + "\"  type=\"text\" value=\"" + valeurPrixEtiquette + "\" /> ");
                            }
                            //} else {
                            //    clone = options.value;
                            //}


                            $(clone).appendTo(container);
                        },
                        alignment: "right"
                    },
                    {
                        caption: "codeEAN",
                        dataField: "codeEAN",
                        allowEditing: true,
                        width: 135,
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            var clone;
                            var valeurEan = options.data.codeEAN !== null && options.data.codeEAN !== undefined ? options.data.codeEAN.toString() : "";
                            if (options.data.autoriserLaModificationDuCodeBarreReferencement !== "") {
                                valeurEan = "<input maxlength=\"20\" class=\"codeEAN panierCodeEAN" + options.data.numeroExterneCatalogueLigne + "\" id=\"EANCode" + options.data.numeroExterneCatalogueLigne + "\" data-numeroexterne=\"" + options.data.numeroExterneCatalogueLigne + "\" data-numerocatalogue=\"" + options.data.numeroCatalogue + "\" type=\"text\" value=\"" + valeurEan + "\" />";
                            }
                            //if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                            expression = "^" + options.data.numeroExterneProduit + ";";
                            reg = new RegExp(expression, 'g');
                            uneLigne = lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                undefined;
                            if (typeof uneLigne !== 'undefined') {
                                valeurs = uneLigne.split(";");


                                if ($(valeurEan).hasClass("codeEAN")) {

                                    clone = $(valeurEan).val(valeurs[7]);

                                }

                            } else {
                                clone = valeurEan.replace("(", "").replace(")", "");
                            }
                            //} else {
                            //    clone = options.value.replace("(", "").replace(")", "");
                            //}
                            container.append(clone);
                            //$(clone).appendTo(container);
                        },
                        alignment: "left"

                    },
                    {
                        caption: "codePartenaire",
                        dataField: "codePartenaire",
                        width: 135,
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            var clone;
                            var valeurcodePartenaire = options.data.codePartenaire !== null && options.data.codePartenaire !== undefined ? options.data.codePartenaire.toString() : "";

                            if (options.data.autoriserLaModificationDuCodePartenaire !== "") {
                                valeurcodePartenaire = "<input maxlength=\"60\" class=\"codePartenaireInput panierCodePartenaire" + (options.data.numeroExterneCatalogueLigne) + "\" data-numerocatalogue=\"" + options.data.numeroCatalogue + "\" type=\"text\" data-numeroexterne=\"" + options.data.numeroExterneCatalogueLigne + "\" value=\"" + valeurcodePartenaire + "\" />";
                            }
                            // if ($(options.data.quantiteProduits).hasClass("quantiteProduit")) {
                            expression = "^" + options.data.numeroExterneProduit + ";";
                            reg = new RegExp(expression, 'g');
                            uneLigne = lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } }).length > 0 ? lignesPanierAModifier.filter(function (item) { if (item.match(reg)) { return item } })[0] :
                                undefined;
                            if (typeof uneLigne !== 'undefined') {
                                valeurs = uneLigne.split(";");


                                if ($(valeurcodePartenaire).hasClass("codePartenaireInput")) {

                                    clone = $(valeurcodePartenaire).val(valeurs[6]);

                                }

                            } else {
                                clone = valeurcodePartenaire;
                            }
                            //} else {
                            //    clone = options.value;
                            //}

                            container.append(clone);
                            //$(clone).appendTo(container);
                        },
                        alignment: "left"

                    },
                    {
                        caption: "numeroExterne",
                        dataField: "numeroExterne",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"
                    },
                    {
                        caption: "codeArticle",
                        dataField: "codeArticle",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "pcb",
                        dataField: "pcb",
                        allowEditing: false,
                        width: 100,
                        alignment: "right"
                    },
                    {
                        caption: "quantiteArticleParEmballage",
                        dataField: "quantiteArticleParEmballage",
                        allowEditing: false,
                        width: 135,
                        alignment: "right"
                    },
                    {
                        caption: "codeEmballage3",
                        dataField: "codeEmballage3",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "croisementEmballage2Vers3",
                        dataField: "croisementEmballage2Vers3",
                        allowEditing: false,
                        width: 135,
                        alignment: "right"
                    },
                    {
                        caption: "codeEmballage2",
                        dataField: "codeEmballage2",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "croisementEmballage1Vers2",
                        dataField: "croisementEmballage1Vers2",
                        allowEditing: false,
                        width: 135,
                        alignment: "right"
                    },
                    {
                        caption: "codeEmballage1",
                        dataField: "codeEmballage1",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "codeEmballage4",
                        dataField: "codeEmballage4",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "prix2",
                        dataField: "prix2",
                        width: 135,
                        allowEditing: false,
                        alignment: "right"
                    },
                    {
                        caption: "libelleWebshop1",
                        dataField: "libelleWebshop1",
                        width: 135,
                        allowEditing: false,
                        alignment: "left",
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            $(container).addClass("libellewebshop1");
                            $("<span />").text(options.value).appendTo(container);
                        }
                    },
                    {
                        caption: "libelleWebshop2",
                        dataField: "libelleWebshop2",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "libelleWebshop3",
                        dataField: "libelleWebshop3",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"
                    },
                    {
                        caption: "codeCritere1",
                        dataField: "codeCritere1",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"
                    },
                    {
                        caption: "montantTotal",
                        dataField: "montantTotal",
                        allowEditing: false,
                        width: 135,
                        alignment: "right"
                    },
                    {
                        caption: "inputBoutonSupprimer",
                        dataField: "inputBoutonSupprimer",
                        width: 80,
                        allowEditing: false,
                        showInColumnChooser: false,
                        cssClass: "largeurBoutonAjoutPanier",
                        renderAsync: true,
                        cellTemplate: function (container, options) {
                            var valeurColonne = "";
                            if (options.data.typeAssortiment !== undefined && (options.data.typeAssortiment === null || options.data.typeAssortiment === "" || options.data.typeAssortiment === "A")) {
                                valeurColonne = "<span id=\"supprimerLigneOperation\" class=\"boutonAction\" onclick=\"afficherSupprimerDescktop(" + options.data.numeroExterneCatalogueLigne + "," + options.data.numeroOperationLigne + ");\">" + SUPPRIMER + "</span>";
                            }

                            $(valeurColonne).appendTo(container);
                        }
                    }
                ],
                onSelectionChanged: function (selectedItems) {
                    var idGrid = selectedItems.component.element()[0].id;
                    var data = selectedItems.selectedRowsData[0];

                },
                onInitialized: function (e) {

                    initialized(e);
                    var dataGrid = e.component;



                    if (catalogueSansPrix == valeurOui || (clientGenerique == 'True' && afficherPrixDansLesDemandeDeDevis == valeurNon)) {
                        e.component.columnOption("colonnePrix", "visible", false);
                        e.component.columnOption('montantTotal', "visible", false);
                    }

                    dataGrid.option("columnChooser.enabled", false);

                    e.component.columnOption("inputBoutonSupprimer", "visible", true);

                },
                onContentReady: function (e) {

                    var dataGrid = e.component;


                    if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True') {

                        gererLesInputDeSaisi('panier');
                    }
                    // Validation d'ajout au panier avec touche entrée
                    $('.quantiteProduit').keyup(function (event) {
                        if (event.keyCode == CODE_TOUCHE_ENTREE) {
                            //$(this).parent().parent().find('.ajoutPanier').click();
                            stockerLignesOperation(this, false, 'panier', true);

                        }
                    });
                    if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'False' || EST_CONNECTE == 'False') {
                        $('#tableauListePanierDX>.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar>.dx-toolbar-items-container>.dx-toolbar-before').hide();
                    }
                    if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' && EST_CONNECTE == 'True') {
                        if (!$('#tableauListePanierDX>.dx-datagrid>.dx-datagrid-header-panel').hasClass("fournisseur")) {
                            $('.blockGestionCommande').hide();
                            $('#tableauListePanierDX>.dx-datagrid>.dx-datagrid-header-panel').addClass("fournisseur");
                            $('#retourAArriere').addClass('retourAArriere_fournisseur');
                            $('#tableauListePanierDX>.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar>.dx-toolbar-items-container>.dx-toolbar-before').prepend('<input id="retourAArriere" class="passerCommande retourAArriere_fournisseur" type="button" value="Retour" onclick="retourAArriere();">');

                        }

                    } else {
                        $('#tableauListePanierDX>.dx-datagrid>.dx-datagrid-header-panel>.dx-toolbar').addClass("videClient");

                        dataGrid.option("allowColumnResizing", false);

                    }
                    $('.contenuPage').show();
                    masquerChargement();


                },
                onRowPrepared: function (e) {
                    if (e.rowType == "data") {
                        $(e.rowElement).addClass("prixQuantiteHt" + e.data.numeroExterneCatalogueLigne.toString()).addClass("prixQuantiteHt");
                        $(e.rowElement).data("numeroExterneCatalogue", e.data.operationSupprimable);
                        $(e.rowElement).data("prixQuantiteHt", e.data.totalHTDansDeviseClient);
                        if (jQuery.inArray(e.data.operationSupprimable.toString(), listeDesNumerosExterneCataloguesNonValides) > -1) {
                            $(e.rowElement).addClass('catalogueInvalide');
                            if (AUTORISER_LIGNE_PERIME == "" || AUTORISER_LIGNE_PERIME.toLowerCase().ltrim().rtrim() == "non") {
                                $(e.rowElement).find('input').prop('disabled', true);
                            }

                        }

                    }


                },
                onCellClick: function (e) {
                    //var pager = e.component.getView("pagerView").element().dxPager("instance");
                    //pager.option("lightModeEnabled", true);
                    //setTimeout(function () {
                    //    if ($(".dx-affichage-avant").length == 0) {
                    //        $("#tableauListePanierDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes").prepend("<label class='dx-affichage-avant'>Montrer </label>");
                    //        $("<span class='dx-affichage-apres'> par page</span><span class='dx-affichage-apres2'>Page </span>").insertAfter("#tableauListePanierDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes>.dx-selectbox");
                    //        $("#tableauListePanierDX>.dx-datagrid>.dx-datagrid-header-panel").prepend("<div class='vide' ></div>");
                    //        $("<span id='dxInfo'/>").text("(" + nbElements + " éléments)").appendTo(".dx-pages");
                    //    }

                    //});
                },
                onRowClick: function (selectedItems) {
                    //var dataGrid = selectedItems.component;
                    //var pager = dataGrid.getView("pagerView").element().dxPager("instance");

                    //pager.option("lightModeEnabled", true);
                    ////setTimeout(function () {
                    //if ($(".dx-affichage-avant").length == 0) {
                    //    $("#tableauListePanierDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes").prepend("<label class='dx-affichage-avant'>Montrer </label>");
                    //    $("<span class='dx-affichage-apres'> par page</span><span class='dx-affichage-apres2'>Page </span>").insertAfter("#tableauListePanierDX>.dx-datagrid>.dx-datagrid-pager.dx-light-mode>.dx-page-sizes>.dx-selectbox");
                    //    $("#tableauListePanierDX>.dx-datagrid>.dx-datagrid-header-panel").prepend("<div class='vide' ></div>");
                    //    $("<span id='dxInfo'/>").text("(" + nbElements + " éléments)").appendTo(".dx-pages");
                    //}

                    //});


                },
                onKeyDown: function (e) {
                    var row;
                    var $target = $(e.event.target);
                    if (e.event.keyCode === 37 || e.event.keyCode === 39) {
                        e.event.preventDefault();
                    }
                    var visibleColumns = e.component.getController("columns").getVisibleColumns();
                    if (e.event.keyCode === 9) {

                        columnIndex = $target.is("input") ? $target.parent().index() + 1 : $target.index() + 1;

                        if (!e.event.shiftKey && $target.is("input") && visibleColumns[columnIndex] && !visibleColumns[columnIndex].allowEditing) {
                            nextRow = columnIndex == visibleColumns.length ? true : false;

                            if (nextRow) {
                                nextRow = false;
                                $nextTarget = $target.parent().parent().next().find(".td:first-child");
                            } else {
                                $nextTarget = $target.parent().next();

                            }

                            while ($nextTarget.find("input").length == 0) {

                                $nextTarget = $nextTarget.next();

                            }
                            e.event.target = $nextTarget;
                        }
                    }
                    if (e.event.keyCode === 40) {
                        columnIndex = $target.is("input") ? $target.parent().index() : $target.index();

                        row = $target.parent().parent().next();

                        if (!e.event.shiftKey && $target.is("input") && visibleColumns[columnIndex] && (!visibleColumns[columnIndex].allowEditing || $($(row.get(0)).find("td")[6]).find("input").length == 0)) {// 


                            $nextTarget = $($($target.parent().parent().next().get(0)).find("td")[columnIndex]);


                            while ($nextTarget.length > 0 && $nextTarget.find("input").length == 0) {
                                $nextTarget = $($($nextTarget.parent().next().get(0)).find("td:not('.nonNaviguable')")[columnIndex]);
                            }


                            e.event.target = $nextTarget;
                            setTimeout(function () { $nextTarget.find("input").focus(); }, 100);
                        } else {

                            setTimeout(function () { $($($target.parent().parent().next().get(0)).find("td:not('.nonNaviguable')")[columnIndex]).find("input").focus(); }, 100);
                        }
                    }
                    if (e.event.keyCode === 38) {
                        columnIndex = $target.is("input") ? $target.parent().index() : $target.index();

                        row = $target.parent().parent().prev();

                        if (!e.event.shiftKey && $target.is("input") && visibleColumns[columnIndex] && (!visibleColumns[columnIndex].allowEditing || $($(row.get(0)).find("td")[6]).find("input").length == 0)) {// 


                            $nextTarget = $($($target.parent().parent().prev().get(0)).find("td")[columnIndex]);


                            while ($nextTarget.length > 0 && $nextTarget.find("input").length == 0) {
                                $nextTarget = $($($nextTarget.parent().prev().get(0)).find("td:not('.nonNaviguable')")[columnIndex]);
                            }


                            e.event.target = $nextTarget;
                            setTimeout(function () { $nextTarget.find("input").focus(); }, 100);
                        } else {

                            setTimeout(function () {
                                $($($target.parent().parent().prev().get(0)).find("td:not('.nonNaviguable')")[columnIndex]).find("input").focus();
                            }, 100);
                        }
                    }
                }

            }).dxDataGrid("instance");
            setTimeout(function () { initialisationRenommageColonne(conf, "tableauListePanierDX", configRenommagePanier); }, 0);

            $('.contenuPage').show();
            setTimeout(function () {
                $('body').removeClass("bodyOverflowHidden").addClass("bodyOverflowAuto");
            }, 600);
            var date = $('#dateLivraison').val();
            if (date != "" && (typeof (date) != 'undefined')) {
                viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'panier', 'reevaluerSeulement');
            }
            $("#boutonVoirPanier").addClass("active");
            $("#boutonVoirPanier").addClass("sansClique");
            $("#boutonCatalogue.active").attr("onclick", "confirmationMiseAJourPanier('retourAArriere')");
            $('.chiffreUniquement').keyup(function (event) {
                if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
                    alerte(MERCI_DE_SAISIR_UN_NOMBRE_ENTIER);
                }
            });

        }
    });
    //if (templatePersonnalise != "") {
    //    $("#tableauListePanierDX").ClassyScroll();
    //}
}




function initialisationPageListePanier(modePanier) {
    allerVersLeHaut();
    entetePanierInitialisee = false;
    $('.contenuPage').hide();
    tableauListePanier = tableauListeDuPanier;
    idTableauHtml = "tableauListePanier";
    lignesPanierAModifier = [];
    $('#tableauListePanier').hide();
    $('#listeLargeursColonnes_tableauListePanierDX').draggable({
    });
    if (typeof ($('#blockRecapitulatifCommande').html()) !== 'undefined' && $('#blockRecapitulatifCommande').html().indexOf("recapCommande") == -1) {
        activerLesChampsDePanier();
    }
    listePanier = $('#tableauListePanier').DataTable({
        'order': [],
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'columns': [
            { 'name': '0', 'className': 'width40 numeriqueTri', 'bSortable': false },
            { 'name': '1', 'className': 'width135', 'bSortable': false },
            { 'name': '2', 'className': 'width135', 'bSortable': false },
            { 'name': '3', 'className': 'width135', 'bSortable': false },
            { 'name': '4', 'className': 'width135', 'bSortable': false },

            { 'name': '5', 'className': 'width135', 'bSortable': false },
            { 'name': '6', 'className': 'width135', 'bSortable': false },
            { 'name': '7', 'className': 'width135', 'bSortable': false },
            { 'name': '8', 'className': 'width135', 'bSortable': false },

            { 'name': '9', 'className': 'width135 numeriqueTri', 'bSortable': false },
            { 'name': '10', 'className': 'width135 numeriqueTri', 'bSortable': false },
            { 'name': '11', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135  inactif' : 'width135 '), 'visible': (EST_CONNECTE == 'True' ? true : false), 'bSortable': false },
            { 'name': '12', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135  inactif' : 'width135 '), 'visible': (EST_CONNECTE == 'True' ? true : false), 'bSortable': false },

            { 'name': '13', 'className': 'width135 numeriqueTri', 'bSortable': false },
            { 'name': '14', 'className': 'width135 numeriqueTri', 'bSortable': false },
            { 'name': '15', 'className': 'width135', 'bSortable': false },


            { 'name': '16', 'className': 'width135', 'bSortable': false },
            { 'name': '17', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135 colonneQuantite inactif' : 'width135 colonneQuantite'), 'visible': (EST_CONNECTE == 'True' ? true : false), 'bSortable': false },
            { 'name': '18', 'className': 'width135 prixStyle', 'visible': true, 'bSortable': false },
            { 'name': '19', 'className': 'width135', 'bSortable': false },
            { 'name': '20', 'className': 'width135', 'bSortable': false },
            { 'name': '21', 'className': 'width135', 'bSortable': false },
            { 'name': '22', 'className': 'width135', 'bSortable': false },
            { 'name': '23', 'className': 'width135', 'bSortable': false },
            { 'name': '24', 'className': 'width135', 'bSortable': false },
            { 'name': '25', 'className': 'width135', 'bSortable': false },
            { 'name': '26', 'className': 'width135', 'bSortable': false },
            { 'name': '27', 'className': 'width135', 'visible': true, 'bSortable': false },
            { 'name': '28', 'className': 'width135', 'bSortable': false },
            { 'name': '29', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '30', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '31', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '32', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '33', 'className': 'width200', 'visible': true, 'bSortable': false }
        ],
        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"CltR>rt',
        'pageLength': nombreLigneOperation,
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        /*'paginationType': 'full_numbers',*/

        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        //        // Options sur les filtres
        //        'oColumnFilterWidgets': {
        //            //  'bGroupTerms': true, // pour activer le groupage sur les filtres
        //            'aiExclude': [1] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        //        },
        // Options sur la visibilité des colonnes
        'colVis': {
            'exclude': [33], // spécifier les colonnes qui ne figurent pas dans la visibilité des colonnes
            'buttonText': AFFICHER_MASQUER_COLONNES
            //            ,
            //            //Gestion Des Filtres Par Colonne Et Visibilite
            //            'fnStateChange': function (iColumn, bVisible) {
            //                gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, listePanier.settings()[0]);
            //            }
        },
        'colReorder': {
            'realtime': true
        },

        'initComplete': function (oSettings, oData) {

            fnOrdonnerColonnes('tableauListePanier', tableauListePanier);
            //$(this).css('visibility', 'visible');
            materialiserChampsDeRecherche('tableauListePanier', true);
            initialiserCoVis('tableauListePanier');
            // Ne pas tenir compte des filtres dans la sauvegarde d'état du tableau
            // Je n'ai pas l'explication mais si l'appel à la méthode se fait en dehors d'un setTimeout alors exception JS
            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(listePanier, true, 'tableauListePanier', tableauListePanier); }, 0);

            fnAfficherCacherColonneOrigCol('tableauListePanier', 33, true);
            if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True') {
                $('#tableauListePanier_wrapper').addClass('dataTables_wrapper_fournisseur');
                $('.blockGestionCommande').prependTo($('.dataTables_wrapper_fournisseur').find('.top'));
                $('#retourAArriere').addClass('retourAArriere_fournisseur');
                $('.dataTables_wrapper_fournisseur').find('.top').find('.ColVis').find('.ColVis_Button').attr("id", "colVisButtonFournisseur");
            }
            setTimeout(function () { $('#tableauListePanier').show(); }, 0);
            if (catalogueSansPrix == valeurOui || (clientGenerique == 'True' && afficherPrixDansLesDemandeDeDevis == valeurNon)) {
                fnAfficherCacherColonneOrigCol('tableauListePanier', 18, false);
                fnAfficherCacherColonneOrigCol('tableauListePanier', 32, false);
            }

            // Validation d'ajout au panier avec touche entrée
            $('.quantiteProduit').keyup(function (event) {
                if (event.keyCode == CODE_TOUCHE_ENTREE) {
                    stockerLignesOperation(this, false, 'panier', true);

                }
            });
        },
        'headerCallback': function (thead, data, start, end, display) {

            if (entetePanierInitialisee == false || tableauDesLargeuresEtIndicesPanier == "reinitialisé") {

                entetePanierInitialisee = true;
                titresColonnesSauveguarde = titresColonnesPanier;
                titresColonnesPanier = [];
                largeurParDefaut = 0;
                tableauDesLargeuresEtIndicesChargementPanier = [];
                indiceColonnes = 0;
                $(thead).find('th').each(function () {
                    if (tableauDesLargeuresEtIndicesPanier == "reinitialisé") {

                        largeurParDefaut = titresColonnesSauveguarde[indiceColonnes].split(";")[2];
                        indiceColonnes++;
                    } else {

                        largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                        largeurParDefaut = (largeurParDefaut == null ? 0 : largeurParDefaut[0].replace("width", ""));
                    }
                    largeurActuellementAppliquee = (tableauDesLargeuresEtIndicesPanier == "reinitialisé" ? largeurParDefaut : largeurActuel(idTableauHtml, tableauListePanier, $(this).data("origColHeader"), largeurParDefaut));
                    enteteColonneAPasserEnParametre = $(this).html().ltrim().rtrim();
                    if ($(this).hasClass("ignorerRenommage")) {
                        enteteColonneAPasserEnParametre = "";
                    }
                    titresColonnesPanier.push(enteteColonneAPasserEnParametre + ";" + $(this).data("origColHeader") + ";" + largeurParDefaut + ";" + largeurActuellementAppliquee);


                });

                titresColonnesPanier = colonnesVisiblesOuPas(tableauListePanier, titresColonnesPanier, idTableauHtml);
                indiceCase = 0;
                $(thead).find('th').each(function () {
                    titresColonnesPanier[indiceCase] = titresColonnesPanier[indiceCase] + ";" + ($(this).data("origNameHeader") === undefined ? "" : $(this).data("origNameHeader"));
                    indiceCase++;
                });
                tableau = [];

                for (i = 0; i < titresColonnesPanier.length; i++) {
                    tableau = titresColonnesPanier[i].split(";");
                    tableauDesLargeuresEtIndicesChargementPanier.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesPanier = (tableauDesLargeuresEtIndicesPanier != "reinitialisé" ? tableauDesLargeuresEtIndicesChargementPanier.join('|') : tableauDesLargeuresEtIndicesPanier);

            }

        },
        "rowCallback": function (nRow, aData, iDisplayIndex) {
            if (jQuery.inArray($(nRow).data('numeroExterneCatalogue').toString(), listeDesNumerosExterneCataloguesNonValides) > -1) {
                $(nRow).addClass('catalogueInvalide');
                if (AUTORISER_LIGNE_PERIME == "" || AUTORISER_LIGNE_PERIME.toLowerCase().ltrim().rtrim() == "non") {
                    $(nRow).find('input').prop('disabled', true);
                }

            }


        },
        'drawCallback': function (oSettings) {

            if (tableauListePanier != '""' && tableauListePanier != null && tableauDesLargeuresEtIndicesPanier != "reinitialisé") {
                tableauListePanier = tableauListePanier.split("\\").join("");
                tableauListePanier = tableauListePanier.split("^(").join("");
                tableauListePanier = tableauListePanier.split(")$").join("");
                oState = JSON.parse(tableauListePanier);
                if (oState.hasOwnProperty('ColWidth') && typeof oState.ColWidth !== 'undefined') {
                    if (oState.ColWidth.length > 0) {
                        appliquerLesLargeurs("tableauListePanier", tableauDesLargeuresEtIndicesPanier);
                    }
                }
            } else if (tableauDesLargeuresEtIndicesPanier == "reinitialisé") {

                indiceColonne = 1;
                $('#' + idTableauHtml).find('thead').find('tr:nth-child(1)').find('th').each(function () {
                    largeurParDefaut = "width" + $(this).data("widthHeader");
                    $('#' + idTableauHtml).find('tfoot').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('tbody').find('td:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('thead').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    indiceColonne++;

                });

                tableauDesLargeuresEtIndicesChargementPanier = [];
                for (i = 0; i < titresColonnesPanier.length; i++) {
                    tableau = titresColonnesPanier[i].split(";");
                    tableauDesLargeuresEtIndicesChargementPanier.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesPanier = tableauDesLargeuresEtIndicesChargementPanier.join('|');


            } else {
                appliquerLesLargeurs("tableauListePanier", tableauDesLargeuresEtIndicesPanier);
            }
            settingsDeSauvegardePanier = listePanier.settings();
            tableauOrdonnementParDefaut = [];
            for (var i = 0; i < settingsDeSauvegardePanier[0].aoColumns.length; i++) {
                origColPanier = settingsDeSauvegardePanier[0].aoColumns[i]._ColReorder_iOrigCol;
                tableauOrdonnementParDefaut.push(origColPanier);
            }

            masquerChargement();
        }

    });
    $('.contenuPage').show();
    gererLesInputDeSaisi('panier');
    navigationInputParFlecheDansTableau('tableauListePanier');
    var date = $('#dateLivraison').val();
    if (date != "" && (typeof (date) != 'undefined')) {
        viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'panier', 'reevaluerSeulement');
    }
    $("#boutonVoirPanier").addClass("active");
    $("#boutonVoirPanier").addClass("sansClique");
    $("#boutonCatalogue.active").attr("onclick", "confirmationMiseAJourPanier('retourAArriere')");
    $('.chiffreUniquement').keyup(function (event) {
        if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
            alerte(MERCI_DE_SAISIR_UN_NOMBRE_ENTIER);
        }
    });
}


function confirmationOuAnnulationForcerDateExpedition(statut) {
    //Livraison impossible un %s !
    //Autoriser ce jour dans la commande ?
    alerte(FORCER_LA_DATE_EXPEDITION + ' : <br />', 'confirmationUtilisateur', 'forcerlaDate', statut);
}

function forcerlaDate(statut) {
    expeditionPossible = 2;
    envoyerOuSauvgarderCommande(statut);
}

function afficherConditionGeneralEnvoyerOuSauvgarderCommande(statut, numeroOperation) {

    var erreur = false;
    var messageErreur = '';
    // Verification champs obligatoires
    if (parametreSupprimerLAccesALaPageAdresseLivraison != valeurOui) {
        
        $('#livraison').find('.inputObligatoire').each(function () {
            if ($(this).val().trim() != '') {
                $(this).removeClass('erreurSaisie');
            } else {
                erreur = true;
                $(this).addClass('erreurSaisie');
            }
        });
        if (erreur) {
            messageErreur += CHAMPS_OBLIGATOIRES_NON_RENSEIGNES + '.<br/>';
        }
        if (true && typeof $('#email').val() !== "undefined" && $('#email').val() != '' && verifierEmail.exec($('#email').val().toLowerCase().trim()) == null) { // prq true dans le if
            messageErreur += EMAIL_PAS_CORRECTE + '.<br/>';
        }
        if (typeof $('#emailCorrespondant').val() !== "undefined" && $('#emailCorrespondant').val() != '' && verifierEmail.exec($('#emailCorrespondant').val().toLowerCase().trim()) == null) { // prq true dans le if
            messageErreur += EMAIL_PAS_CORRECTE + '.<br/>';
        }
        if (montantMinimumCommande != '' && parseFloat(totalPanier.replace(',', '.')) < parseFloat(montantMinimumCommande.replace(',', '.'))) {
            messageErreur += VOUS_DEVEZ_AU_MINIMUM_AVOIR_UN_MONTANT_TOTAL_DE + ' ' + montantMinimumCommande + '€.<br/>';
        }
    }
    if (messageErreur == '') {
        if ((AUTORISER_LIGNE_PERIME != "" && AUTORISER_LIGNE_PERIME.toLowerCase().ltrim().rtrim() != "non") && (listeDesNumerosExterneCataloguesNonValides.join("") != "")) {
            confirmationOuAnnulationSuiteALignesPerimees('Commande', numeroOperation, statut);
        } else {
            miseAjourChampSaisieLivraison(numeroOperation, statut);
        }
    } else {
        alerte(messageErreur);
    }
}

function confirmationOuAnnulationSuiteALignesPerimees(source, numeroOperation, statut) {
    //Livraison impossible un %s !
    //Autoriser ce jour dans la commande ?
    alerte(ALERTE_LIGNE_PERIME + ' : <br />', 'confirmationUtilisateur', source == 'Commande' ? 'miseAjourChampSaisieLivraison' : 'miseAjourChampSaisieLivraisonDevis', numeroOperation, statut);
}
function miseAjourChampSaisieLivraison(numeroOperation, statut) {
    mettreAjourChampSaisieLivraison(function () {
        $('#layoutPopupConditionGeneral').fadeIn(200);
        $('#popupConditionGeneral').fadeIn(200);
        $.ajax({
            url: '/webshop/contenuConditionGeneral',
            data: {
                'numeroSociete': numeroSociete
            },
            success: function (retourServeur) {
                $("#layoutPopupConditionGeneral").height($("#contenuPage").height());
                $('#layoutPopupConditionGeneral').fadeIn(200);
                $('#popupConditionGeneral').fadeIn(200);
                $('#bouttonValiderPopup').show();
                $('#bouttonAnnulerPopup').show();
                $('#bouttonFermerPopup').hide();
                $('#lienPdf').show();
                $('#lienPdf').attr('onclick', 'operationEnPDF(' + numeroOperation + ')');
                $('#popupConditionGeneral #messageConditionGeneral').html(retourServeur != '' ? retourServeur : ENVOYER_LA_COMMANDE + ' ?');
                $('#popupConditionGeneral .lienPdf').html(RECAPITULATIF_COMMANDE);
                masquerChargement();
            }
        });
        $('#bouttonValiderPopup').attr('onclick', 'envoyerOuSauvgarderCommande(' + statut + ');');
    });
}
function mettreAjourChampSaisieLivraison(callback) {
    $.ajax({
        url: '/webshop/mettreAjourChampSaisieLivraison',
        data: {
            'nom1': $('#nom1').val(),
            'nom2': $('#nom2').val(),
            'email': $('#email').val(),
            'adresse1': $('#adresse1').val(),
            'adresse2': $('#adresse2').val(),
            'codePostal': $('#codePostal').val(),
            'ville': $('#ville').val(),
            'pays': $('#pays').val(),
            'telephone': $('#telephone').val(),
            'fax': $('#fax').val(),
            'commentaireLivraison': $('#commentaireLivraison').val(),
            'reference': $('#reference').val(),
            'commentaire': $('#commentaire').val(),
            //partie conditionnée par un paramètre
            'nom1Correspondant': (parametreGestionDesCorrespondants == valeurOui ? $("#nom1Correspondant").val() : ''),
            'nom2Correspondant': (parametreGestionDesCorrespondants == valeurOui ? $("#nom2Correspondant").val() : ''),
            'adresse1Correspondant': (parametreGestionDesCorrespondants == valeurOui ? $("#adresse1Correspondant").val() : ''),
            'adresse2Correspondant': (parametreGestionDesCorrespondants == valeurOui ? $("#adresse2Correspondant").val() : ''),
            'codePostalCorrespondant': (parametreGestionDesCorrespondants == valeurOui ? $("#codePostalCorrespondant").val() : ''),
            'villeCorrespondant': (parametreGestionDesCorrespondants == valeurOui ? $("#villeCorrespondant").val() : ''),
            'paysCorrespondant': (parametreGestionDesCorrespondants == valeurOui ? $("#paysCorrespondant").val() : ''),
            'telephoneCorrespondant': (parametreGestionDesCorrespondants == valeurOui ? $("#telephoneCorrespondant").val() : ''),
            'emailCorrespondant': (parametreGestionDesCorrespondants == valeurOui ? $("#emailCorrespondant").val() : ''),
            'portableCorrespondant': (parametreGestionDesCorrespondants == valeurOui ? $("#portableCorrespondant").val() : ''),
            'faxCorrespondant': (parametreGestionDesCorrespondants == valeurOui ? $("#faxCorrespondant").val() : '')
        },
        success: function (retourServeur) {
            masquerChargement();
            if (retourServeur == "") {
                if (callback) {
                    callback();
                }
            } else if (retourServeur.indexOf("MESSAGE:") == 0) {//  retour message avec un mot clé MESSAGE dans la position 0
                alerte(retourServeur.substring(8), 'confirmationUtilisateur', 'validerRechargePageAccueil'); //8 le nombre de caractere de mot clé MESSAGE:
            } else if (retourServeur.indexOf("MESSAGESANSACTIONS:") == 0) {
                alerte(retourServeur.substring(19), 'confirmationUtilisateur'); //19 le nombre de caractere de mot clé MESSAGESANSACTIONS:
            }
            if (envoyerEmailAuClient == valeurOui && retourServeur.indexOf("MESSAGESANSACTIONS:") < 0) {
                if (!destinataireEmailConfirmation.trim().match(";$")) {
                    destinataireEmailConfirmation += ";";
                }
                if (parametreGestionDesCorrespondants == valeurOui) {
                    
                    if (typeof ($('#emailCorrespondant').val()) !== 'undefined' && destinataireEmailConfirmation.indexOf($('#emailCorrespondant').val()) < 0) {
                        destinataireEmailConfirmation +=  $('#emailCorrespondant').val();
                    }
                    if (typeof ($('#email').val()) !== 'undefined' && destinataireEmailConfirmation.indexOf($('#email').val()) < 0) {
                        destinataireEmailConfirmation += $('#email').val();
                    }
                } else {
                    if (typeof ($('#email').val()) !== 'undefined' && destinataireEmailConfirmation.indexOf($('#email').val()) < 0) {
                        destinataireEmailConfirmation +=  $('#email').val();
                    }
                }
            }
        }
    });
}

function priseEnchargeAffichageConditions(statut, numeroOperation) {
    if ($('#typeOperationSelection').val() == COMMANDE) {
        afficherConditionGeneralEnvoyerOuSauvgarderCommande(statut, numeroOperation);
    } else if ($('#typeOperationSelection').val() == DEVIS) {
        afficherConditiondemandeDeDevis(statut, numeroOperation);
    }
}

function afficherConditiondemandeDeDevis(statut, numeroOperation) {
    messageErreur = '';
    erreur = false;
    // Verification champs obligatoires
    if (parametreSupprimerLAccesALaPageAdresseLivraison != valeurOui) {
        erreur = false;
        // Verification champs obligatoires
        $('#livraison').find('.inputObligatoire').each(function () {
            if ($(this).val().trim() != '') {
                $(this).removeClass('erreurSaisie');
            } else {
                erreur = true;
                $(this).addClass('erreurSaisie');
            }
        });
        if (erreur) {
            messageErreur += CHAMPS_OBLIGATOIRES_NON_RENSEIGNES + '.<br/>';
        }


        if (true && $('#email').val() != '' && verifierEmail.exec($('#email').val().toLowerCase().trim()) == null) {
            messageErreur += EMAIL_PAS_CORRECTE + '.<br/>';
        }
    }
    if (messageErreur == '') {
        if (AUTORISER_LIGNE_PERIME != "" && AUTORISER_LIGNE_PERIME.toLowerCase().ltrim().rtrim() != "non" && (listeDesNumerosExterneCataloguesNonValides.join("") != "")) {
            confirmationOuAnnulationSuiteALignesPerimees('Devis', numeroOperation, statut);
        } else {
            miseAjourChampSaisieLivraisonDevis(numeroOperation, statut);
        }

    } else {
        alerte(messageErreur);
    }
}

function miseAjourChampSaisieLivraisonDevis(numeroOperation, statut) {
    mettreAjourChampSaisieLivraison(function () {
        $('#layoutPopupConditionGeneral').fadeIn(200);
        $('#popupConditionGeneral').fadeIn(200);
        $.ajax({
            url: '/webshop/contenuConditionGeneral',
            data: {
                'numeroSociete': numeroSociete
            },
            success: function (retourServeur) {
                $("#layoutPopupConditionGeneral").height($("#contenuPage").height());
                $('#layoutPopupConditionGeneral').fadeIn(200);
                $('#popupConditionGeneral').fadeIn(200);
                $('#bouttonValiderPopup').show();
                $('#bouttonAnnulerPopup').show();
                $('#bouttonFermerPopup').hide();
                $('#lienPdf').show();
                $('#lienPdf').attr('onclick', 'operationEnPDF(' + numeroOperation + ',"' + TYPE_OPERATION_DEVIS + '")');
                $('#popupConditionGeneral #messageConditionGeneral').html(retourServeur != '' ? retourServeur : ENVOYER_MA_DEMANDE_DE_DEVIS + ' ?');
                $('#popupConditionGeneral .lienPdf').html(RECAPITULATIF_DEVIS);
                masquerChargement();
            }
        });
    });
    $('#bouttonValiderPopup').attr('onclick', 'demandeDeDevis();');
}
function fermerPopupConditionGeneral() {
    $('#layoutPopupConditionGeneral').fadeOut(200);
    $('#popupConditionGeneral').fadeOut(200);
}

function envoyerOuSauvgarderCommande(statut) {
    afficherChargement();
    if (parseFloat($('.valeurNombreProduitsAjouter').html().replace(' ', '').replace(',', '.')) > 0) {
        nom1 = $('#nom1').val();
        nom2 = $('#nom2').val();
        email = $('#email').val();
        adresse1 = $('#adresse1').val();
        adresse2 = $('#adresse2').val();
        codePostal = $('#codePostal').val();
        ville = $('#ville').val();
        pays = $('#pays').val();
        telephone = $('#telephone').val();
        fax = $('#fax').val();
        commentaireLivraison = $('#commentaireLivraison').val();
        reference = $('#reference').val();
        commentaire = $('#commentaire').val();
        continuerCommande = true;
        if (expeditionPossible == 0) {
            confirmationOuAnnulationForcerDateExpedition(statut);
        } else {
            if ($('#tableauListePanierDX').find('.catalogueInvalide').length > 0) {
                if (AUTORISER_LIGNE_PERIME == "" || AUTORISER_LIGNE_PERIME.toLowerCase().ltrim().rtrim() == "non") {
                    continuerCommande = false;
                    alerte(MERCI_DE_SUPPRIMER_LES_LIGNES_DES_CATALOGUES_INDISPONIBLES, 'info');
                }
            }
            if (continuerCommande) {
                $.ajax({
                    url: '/OperationDesktop/envoyerOuSauvgarderCommande',
                    data: {
                        'statutCommande': statut,
                        'expeditionPossible': expeditionPossible,
                        'nom1': nom1,
                        'nom2': nom2,
                        'email': email,
                        'adresse1': adresse1,
                        'adresse2': adresse2,
                        'codePostal': codePostal,
                        'ville': ville,
                        'pays': pays,
                        'telephone': telephone,
                        'fax': fax,
                        'commentaireLivraison': commentaireLivraison,
                        'reference': reference,
                        'commentaire': commentaire,
                        'saisieEnModeSemaine': typeof saisieEnModeSemaine !== "undefined" ? saisieEnModeSemaine: false
                    },
                    success: function (retourServeur) {
                        console.log(retourServeur);
                        retours = JSON.parse(retourServeur);
                        console.log(retours);
                        initialiserPanier = true;
                        if (retours.status === 'commandeNonEnvoyer') {
                            initialiserPanier = false;
                            if (retours.message === "") {
                                alerte(VOTRE_PANIER_EST_VIDE);
                            } else {
                                alerte(retours.message);
                            }
                            
                        } else if (retours.status === 'commandeEnvoyer' || (retours.status === 'devisEnvoyer' && !retours.generique)) {
                            if (retours.paybox) {
                                $.ajax({
                                    url: '/OperationDesktop/priseEnChargePaiement',
                                    data: {
                                        'email': email
                                    },
                                    success: function (retourServeur) {
                                        $('#contenuPanier').html(retourServeur);
                                        
                                    }
                                });
                            } else {
                               
                                    var nbSemaines = $("#semaineDateLivraison").length > 0 ? $("#semaineDateLivraison").find(".selectedSemaineLivraison").length : "";
                                    var messageConfirmation = "";
                                    if (typeof saisieEnModeSemaine !== "undefined" && saisieEnModeSemaine == "True")  {
                                        messageConfirmation = retours.status == 'devisEnvoyer' ? OPERATIONS_MARQUEES_COMME_DEVIS.replace(NB_SEMAINES, nbSemaines) : LES_COMMANDES_ONT_BIEN_ETE_ENVOYEES.replace(NB_SEMAINES, nbSemaines);
                                        $("#semaineDateLivraison").find("option").removeClass("selectedSemaineLivraison");
                                    } else {
                                        messageConfirmation =  retours.status == 'devisEnvoyer' ? OPERATION_MARQUEE_COMME_DEVIS : LA_COMMANDE_A_BIEN_ETE_ENVOYEE;
                                    }
                                         
                                    if (retours.emailEnvoye === "envoieMailAuClient") {
                                        messageConfirmation = messageConfirmation + ' .</br>';
                                        if (destinataireEmailConfirmation.replace(";", "").trim().length > 0) {
                                            messageConfirmation = messageConfirmation + CONFIRMATION_ENVOYEE_A + '</br>' + destinataireEmailConfirmation.replace(";", "</br>");
                                        }

                                    }
                                    if (COMMANDE_MONO_CATALOGUE == 'OUI') {
                                        echapperLeChangementDeCatalogue = 'NON';
                                    }
                                    if (typeof saisieEnModeSemaine !== "undefined" && saisieEnModeSemaine == "True") {
                                        $('#semaineDateLivraison').data("datelivraison", retours.dateDeLivraison);
                                    } else {
                                        $('#dateLivraison').val(retours.dateDeLivraison);
                                    }

                                    if (numeroModeExpeditionParDefaut != "") {
                                        rafraichirAffichageModeExpedition(numeroModeExpeditionParDefaut);
                                    }
                                    if (cataloguesConditionneeParDateLivraison == "cataloguesConditionneeParDateLivraison") {
                                        rechargerCataloguesWebshop(messageConfirmation);
                                    } else {
                                        alerte(messageConfirmation + ' .</br>', 'confirmation');
                                        $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(retours.quantiteProduitsDescktop));

                                        tableauValeursPanier = nombreAvecDesEspaces(nombreAvecDesEspaces(retours.montantTotalProduitsDescktop)).replace(',', '.').split('.');

                                        $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                                        $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);

                                        if ($(".valeurVolumeTotal").length > 0) {
                                            $(".valeurVolumeTotal").html(retours.volumeTotal);
                                        }
                                        if (affichageDeLaSurfaceBool == 'True' && typeof retours.densite !== "undefined" && retours.densite != "") {
                                            $('.valeurDensite').html(retours.densite+ "&nbsp;");
                                        }
                                            
                                        if (obligatoireInitialiserDate != "False" && (typeof saisieEnModeSemaine == "undefined" || saisieEnModeSemaine !== "True")) {
                                            jQuery('#dateLivraison').datepicker("show");
                                            activerModeModal();
                                            //modal
                                        }
                                    }
                                    if (typeof saisieEnModeSemaine !== "undefined" && saisieEnModeSemaine == "True") {
                                        viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#semaineDateLivraison').data("datelivraison"), 'accueil', '', false);
                                    } else {
                                        //modif Syrine et Léo le 14/04/2017
                                        $('#dateLivraison').data("prev", $('#dateLivraison').val());
                                        viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'accueil', '', false);
                                    }

                                    
                                    
                              

                            }


                        } else if (retours.status === 'devisEnvoyer' && retours.generique) {
                                messageAffichage="";
                                if (retours.emailEnvoye === "envoieMailAuClient" && destinataireEmailConfirmation.replace(";", "").trim().length > 0) {
                                    messageAffichage = OPERATION_MARQUEE_COMME_DEVIS + ' .</br>' + CONFIRMATION_ENVOYEE_A + '</br>' + destinataireEmailConfirmation.replace(";", "</br>");

                                } else {
                                    messageAffichage = OPERATION_MARQUEE_COMME_DEVIS + ' .</br>';

                                }
                                if (COMMANDE_MONO_CATALOGUE == 'OUI') {
                                    echapperLeChangementDeCatalogue = 'NON';
                                }
                                $('#dateLivraison').val(retours.dateDeLivraison);

                                if (numeroModeExpeditionParDefaut != "") {
                                    rafraichirAffichageModeExpedition(numeroModeExpeditionParDefaut);
                                }
                                if (cataloguesConditionneeParDateLivraison == "cataloguesConditionneeParDateLivraison") {
                                    rechargerCataloguesWebshop(messageAffichage);
                                } else {
                                    alerte(messageAffichage, 'confirmation');
                                    $('.valeurNombreProduitsAjouter').html(retours.quantiteProduitsDescktop);

                                    tableauValeursPanier = nombreAvecDesEspaces(nombreAvecDesEspaces(retours.montantTotalProduitsDescktop)).replace(',', '.').split('.');

                                    $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                                    $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);

                                    if ($(".valeurVolumeTotal").length > 0) {
                                        $(".valeurVolumeTotal").html(retours.volumeTotal);
                                    }
                                }

                                //modif Syrine et Léo le 14/04/2017
                                viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'accueil', '', false);

                                   
                                
                        } else if (retours.status === 'commandeSauvegarder') {
                            //if (COMMANDE_MONO_CATALOGUE == 'OUI') {
                            //    echapperLeChangementDeCatalogue = 'NON';
                            //}
                            //// il faut vérifier avec Emmanuel lorsque la commande sauvgarder on vide la date de livraison et on le enabled ou non?
                            //$('#dateLivraison').datepicker('enable');
                            //$('#dateLivraison').val(retours[4]);
                            //$('.spanTrsaparentPourClick').remove();
                            //if (numeroModeExpeditionParDefaut != "") {
                            //    rafraichirAffichageModeExpedition(numeroModeExpeditionParDefaut);
                            //}
                            //if (cataloguesConditionneeParDateLivraison == "cataloguesConditionneeParDateLivraison") {
                            //    rechargerCataloguesWebshop(LA_COMMANDE_A_BIEN_ETE_SAUVEGARDEE);
                            //} else {
                            //    alerte(LA_COMMANDE_A_BIEN_ETE_SAUVEGARDEE, 'confirmation');
                            //    $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(retours[1]));
                            //    tableauValeursPanier = nombreAvecDesEspaces(nombreAvecDesEspaces(retours[2])).replace(',', '.').split('.');

                            //    $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                            //    $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);

                            //    if ($(".valeurVolumeTotal").length > 0) {
                            //        $(".valeurVolumeTotal").html(retours[3]);
                            //    }
                            //}
                            ////modif Syrine et Léo le 14/04/2017
                            //viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'accueil', false);

                           
                        } else if (retours.status==="MESSAGE") {
                            alerte(retours.message, 'confirmationUtilisateur', 'validerRechargePageAccueil'); 
                        } else if (retours.status ==="MESSAGESANSACTIONS") {
                            alerte(retours.message, 'confirmationUtilisateur'); 
                        }

                        if (retours.status !== "MESSAGESANSACTIONS" && initialiserPanier && !retours.paybox) {
                            rafraichirCumulsEmballage();

                            retourAArriere();
                        }

                    }
                });
            }

        }
    } else {
       
        alerte(VOTRE_PANIER_EST_VIDE);
    }
    masquerChargement();
    fermerPopupConditionGeneral();
    
}

function demandeDeDevis() {

    afficherChargement();

    if (parseFloat($('.valeurNombreProduitsAjouter').html().replace(' ', '').replace(',', '.')) > 0) {
        messageErreur = '';
        erreur = false;
        // Verification champs obligatoires
        if (parametreSupprimerLAccesALaPageAdresseLivraison != valeurOui) {
            $('#livraison').find('.inputObligatoire').each(function () {
                if ($(this).val().trim() == '' && messageErreur == '') {
                    messageErreur += CHAMPS_OBLIGATOIRES_NON_RENSEIGNES + '.<br/>';
                }
            });


            if (true && $('#email').val() != '' && verifierEmail.exec($('#email').val().toLowerCase().trim()) == null) {
                messageErreur += EMAIL_PAS_CORRECTE + '.<br/>';
            }
        }
        if (messageErreur == '') {
            $.ajax({
                url: '/webshop/demandeDeDevis',
                success: function (retourServeur) {
                    if (retourServeur != null && retourServeur != "" && retourServeur == "ok") {
                        envoyerOuSauvgarderCommande(1);
                    } else {
                        alerte(IMPOSSIBLE_DE_MARQUER_CETTE_OPERATION_COMME_DEVIS, 'confirmation');
                    }

                    masquerChargement();
                }
            });
        } else {
            masquerChargement();
            alerte(messageErreur);
        }
    } else {
        masquerChargement();
        alerte(VOTRE_PANIER_EST_VIDE);
    }



}

function afficherSupprimerCommande() {
    $("#layoutSupprimerWebshop").height($("#layoutSupprimerWebshop").parent().height());
    $('#layoutSupprimerWebshop').fadeIn(200);
    $('#fenetreSupprimerWebshop').fadeIn(200);
    $('#fenetreSupprimerWebshop .phrasePopup').text(VOULEZ_VOUS_SUPPRIMER_VOTRE_COMMANDE_EN_COURS);
    $('.validationOuAnnulerPopup #boutonSupprimer').attr('onclick', 'supprimerCommande();');
}

function supprimerCommande() {
    afficherChargement();
    $.ajax({
        url: '/OperationDesktop/supprimerCommande',
        success: function (retourServeur) {
            retourSupprimerCommande = retourServeur.split("|");
            masquerChargement();
            fermerLayoutSupprimer();
            messageAffichage = "";
            if (retourServeur == 'commandeNonSupprimer') {
                messageAffichage = VOTRE_PANIER_EST_VIDE;
            } else if (retourServeur.indexOf('commandeNonSupprimerCarUtilisee') >= 0) {
                messageAffichage = retourServeur.split("|")[1];
            } else {
                messageAffichage = LA_COMMANDE_A_BIEN_ETE_SUPPRIMER;
                if (COMMANDE_MONO_CATALOGUE == 'OUI') {
                    echapperLeChangementDeCatalogue = 'NON';
                }
                if (typeof saisieEnModeSemaine == 'undefined' || saisieEnModeSemaine != "True") {
                    if (preinitialiserDateLivraison == "True") {
                        $('#dateLivraison').datepicker('setDate', dateDeLivraisonPreinitialisee);
                    } else {
                        $('#dateLivraison').val(retourSupprimerCommande[4]);
                    }
                    //modif Syrine et Léo le 14/04/2017
                    $('#dateLivraison').data("prev", $('#dateLivraison').val());
                    viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'accueil');
                } else {
                    //console.log("supprimerCommande saisieEnModeSemaine retour serveur ", retourSupprimerCommande)
                    //Si en mode Semaine Livraison  mettre à jour le select et le label des dates debut et fin'
                    //Supprimer la colorisation du numéro de semaine 
                    if (retourSupprimerCommande[4] != "") {
                        $('#semaineDateLivraison').data("datelivraison", retourSupprimerCommande[4]);
                        $('#semaineDateLivraison option[value=' + retourSupprimerCommande[5] + ']').prop('selected', true);
                        $('#semaineDateLivraison option[value= ' + weekNumberOfDateLivraison + ']').removeClass('selectedSemaineLivraison');
                        //$("#labelSemaineLivraison").text(retourSupprimerCommande[6] + " - " + retourSupprimerCommande[7]);
                        rafraichirDonneeSemaineLivraison(retourSupprimerCommande[5], retourSupprimerCommande[6], retourSupprimerCommande[7])
                    } 
                    viderCalculsEnSessionEtMettreAJourDateDeLivraison(retourSupprimerCommande[4], 'accueil');

                }
            }
            rafraichirCumulsEmballage();

            if (numeroModeExpeditionParDefaut != "") {
                rafraichirAffichageModeExpedition(numeroModeExpeditionParDefaut);
            }
            if (cataloguesConditionneeParDateLivraison == "cataloguesConditionneeParDateLivraison") {
                rechargerCataloguesWebshop(messageAffichage);

            } else {
                alerte(messageAffichage, 'confirmation');
                $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(retourSupprimerCommande[1]));
                tableauValeursPanier = nombreAvecDesEspaces(nombreAvecDesEspaces(retourSupprimerCommande[2])).replace(',', '.').split('.');

                $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);

                if ($(".valeurVolumeTotal").length > 0) {
                    $(".valeurVolumeTotal").html(retourSupprimerCommande[3]);
                }

                if (obligatoireInitialiserDate != "False" && (typeof saisieEnModeSemaine == "undefined" || saisieEnModeSemaine !== "True")) {
                    jQuery('#dateLivraison').datepicker("show");
                    activerModeModal();
                    //modal
                }
            }

            totalPanier = retourSupprimerCommande[2];
            valeurNombreProduitsAjouter = retourSupprimerCommande[1];
            if (typeof (choixAdresseEffectuer) !== 'undefined') {
                choixAdresseEffectuer = valeurNon;
            }
            masquerChargement();
            retourAArriere();


        }
    });
}

function modifierPanierGlobal(source) {
    messageErreur = '';
    if (lignesPanierAModifier.length > 0) {
        var champsValide = true;
        var cpt = 0;
        var nombreLignesPanierAModifier = lignesPanierAModifier.length;
        while (cpt < nombreLignesPanierAModifier) {
            var numeroExterneCatalogueLigne = lignesPanierAModifier[cpt].split(';')[0];
            var typeAssortiment = $('.panierQuantiteLigneOperation' + numeroExterneCatalogueLigne).data('typeassortiment');
            cpt++;
        }
        $('.chiffreUniquement').each(function () {
            if ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) {
                messageErreur += MERCI_DE_SAISIR_UN_NOMBRE_ENTIER;
                champsValide = false;
                return false;
            }
        });
        var chaineDesValeurs = (lignesPanierAModifier.length > 0 ? lignesPanierAModifier.join("_") : "");
        if (champsValide) {
            afficherChargement();
            $.ajax({
                url: '/OperationDesktop/modifierLigneOperation',
                data: {
                    'chaineDesValeurs': chaineDesValeurs
                },
                dataType: "json",
                success: function (messageRetour) {
                    var totalPanier = messageRetour.totalPanier;
                    var message = messageRetour.message;
                    if (message != "") {
                        if (message.indexOf("MESSAGE:") == 0) {// retour message avec un mot clé MESSAGE dans la position 0
                            alerte(message.substring(8), 'confirmationUtilisateur', 'validerRechargePageAccueil'); //8 le nombre de caractere de mot clé MESSAGE:
                        } else if (message.indexOf("MESSAGESANSACTIONS:") == 0) {
                            alerte(message.substring(19), 'confirmationUtilisateur'); //19 le nombre de caractere de mot clé MESSAGESANSACTIONS:
                        } else {
                            alerte(message);
                        }
                    } else {
                        tableauValeursPanier = nombreAvecDesEspaces(nombreAvecDesEspaces(parseFloat(totalPanier.replace(',', '.').toString()).toFixed(2))).split('.');

                        $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                        $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);

                        $('.valeurNombreProduitsAjouter').text(nombreAvecDesEspaces(messageRetour.quantiteDescktop));
                        rafraichirCumulsEmballage();
                        if ($(".valeurVolumeTotal").length > 0) {
                            var volumeTotal = messageRetour.volumeTotal;
                            $(".valeurVolumeTotal").html(volumeTotal);
                        }
                        if (affichageDeLaSurfaceBool == 'True' && typeof messageRetour.densite !== "undefined" && messageRetour.densite != "") {
                            var densite = messageRetour.densite;
                            $('.valeurDensite').html(densite + "&nbsp;");
                        }
                        alerte(LES_MODIFICATIONS_ONT_BIEN_ETE_PRISES_EN_COMPTE, 'confirmation');
                        lignesPanierAModifier = [];

                        if (typeof source !== 'undefined') {
                            if (source == 'retourAArriere') {
                                retourAArriere();
                            } else if (source == "rechargeNouvelleOperation") {
                                //retourAArriere();
                                rechargerNouvelleOperation();
                            } else if (source == 'afficherLivraisonWebShop') {
                                afficherLivraisonWebShop();
                            } else if (source == 'afficherRecapCommande') {
                                afficherRecapitulatifCommande(true);
                            }
                        } else {
                            visualiserPanier();
                        }
                    }
                    masquerChargement();

                }
            });
        } else {
            alerte(messageErreur);
        }

    } else {
        alerte(AUCUNE_MODIFICATION_EFFECTUEE);
    }
}

function envoyerMailRecapitulatifCommandeSurWebShop(numeroCompte) {

    $.ajax({
        url: '/webshop/envoyerMailRecapitulatifCommandeSurWebShop',
        async: true,
        data: {
            'numeroCompte': numeroCompte
        },
        success: function (retourServeur) {
            retoursEnvoyerMailRecapitulatifCommandeSurWebShop = retourServeur.split("|");
            if (retourServeur != null && retourServeur != "" && retoursEnvoyerMailRecapitulatifCommandeSurWebShop[0] == "envoieMailAuClient" && destinataireEmailConfirmation.replace(";", "").trim().length > 0) {

                alerte(CONFIRMATION_ENVOYEE_A + '</br>' + destinataireEmailConfirmation.replace(";", "</br>"), 'confirmation');

            } else {
                alerte(AUCUN_EMAIL_ENVOYE, 'confirmation');
            }
            masquerChargement();

        }
    });

}

function afficherSupprimerDescktop(numeroCatalogueLigneS, numeroOperationLigne) {
    $("#layoutSupprimerWebshop").height($("#layoutSupprimerWebshop").parent().height());
    $('#layoutSupprimerWebshop').fadeIn(200);
    $('#fenetreSupprimerWebshop').fadeIn(200);
    $('#fenetreSupprimerWebshop .phrasePopup').text(SUPPRIMER_CET_ELEMENT);
    $('.validationOuAnnulerPopup #boutonSupprimer').attr('onclick', 'supprimerLigneOperation("' + numeroCatalogueLigneS + '", "' + numeroOperationLigne + '");');
}

function supprimerLigneOperation(numeroCatalogueLigneS, numeroOperationLigne) {
    commandeSeraVide = false;
    if ($('#supprimerLigneOperation .boutonAction').length == 1) {
        commandeSeraVide = true;
    }

    $.ajax({
        url: '/OperationDesktop/supprimerLigneOperation',
        data: {
            'numeroLigneCatalogue': numeroCatalogueLigneS,
            'contexte': "PANIER",
            'numeroSociete': numeroSociete,
            'numeroOperationLigne': numeroOperationLigne,
            'numeroBoutique': numeroBoutique
        },
        success: function (retour) {
            masquerChargement();
            if (retour.indexOf("MESSAGESANSACTIONS") >= 0) {
                alerte(retour.substring(19), 'confirmationUtilisateur'); //19 le nombre de caractere de mot clé MESSAGESANSACTIONS:
            } else {

                valeurs = retour.split("|");
                $('*[data-numero-externe-catalogue="' + numeroCatalogueLigneS + '"]').remove();

                //$('#contenuPanier').html(retourServeur);
                valeurNombreProduitsAjouter = valeurs[0];
                $('.valeurNombreProduitsAjouter').html(nombreAvecDesEspaces(valeurNombreProduitsAjouter));
                totalPanier = valeurs[1];
                tableauValeursPanier = nombreAvecDesEspaces(nombreAvecDesEspaces(parseFloat(totalPanier.replace(',', '.').toString()).toFixed(2))).split('.');

                $('.valeurMontantTotal').text(tableauValeursPanier[0]);
                $('.valeurMontantTotalDecimale').text("." + tableauValeursPanier[1] + SYMBOLE_DEVISE);
                rafraichirCumulsEmballage();
                $('.sommeLigneOperation').html(parseFloat(totalPanier.replace(',', '.').toString()).toFixed(2) + SYMBOLE_DEVISE);


                if ($(".valeurVolumeTotal").length > 0) {
                    volumeTotal = valeurs[2];
                    $(".valeurVolumeTotal").html(volumeTotal);
                }

                fermerLayoutSupprimer();
                //commentaire sur ligne qui a été réactivée par SYRINE car elle bloquait le passage à l'envoi du panier après suppression des lignes perimées
                viderCalculsEnSessionEtMettreAJourDateDeLivraison($('#dateLivraison').val(), 'panier', 'reevaluerSeulement');
                window.setTimeout(function () { retourCatalogue(); visualiserPanier(); }, 0);

            }

        }
    });
}

function confirmationMiseAJourPanier(source) {
    activerLesChampsDePanier();
    if (lignesPanierAModifier.length > 0) {
        $("#layoutPopupMiseAJourPanier").height($("#contenuPage").height());
        $('#layoutPopupMiseAJourPanier').fadeIn(200);
        $('#alertePopupMiseAJourPanier').fadeIn(200);
        $('#bouttonNon').show();
        $('#bouttonOUI').show();
        var actionbtnNon = "";
        switch (source) {
            case "retourAArriereModifDateLivraison":
                actionbtnNon = "fermerPopupMiseAJourPanier(); retourAArriere();";
                if (cataloguesConditionneeParDateLivraison == 'cataloguesConditionneeParDateLivraison' || $('#dateLivraison').data("prev") == '') {
                    actionbtnNon += " rechargerCataloguesWebshop();";
                }
                break;
            case "retourAArriere":
                actionbtnNon = "fermerPopupMiseAJourPanier(); retourAArriere();";
                break;
            case "afficherRecapCommande":
                actionbtnNon = "fermerPopupMiseAJourPanier();afficherRecapitulatifCommande(true);";
                break;
            default:
                actionbtnNon = "rechargerPanier = true; fermerPopupMiseAJourPanier();afficherLivraisonWebShop();";
                break;

        }
        //$('#bouttonNon').attr('onclick', source == 'retourAArriere' ?
        //                                        "fermerPopupMiseAJourPanier();retourAArriere();" :
        //                                        (source == 'afficherRecapCommande' ?
        //                                        "fermerPopupMiseAJourPanier();afficherRecapitulatifCommande(true);" :
        //                                        "rechargerPanier = true; fermerPopupMiseAJourPanier();afficherLivraisonWebShop();"));
        //console.log("confirmationMiseAJourPanier source actionbtnNon", source, actionbtnNon);
        $('#bouttonNon').attr('onclick', actionbtnNon);
        source = source == "retourAArriereModifDateLivraison" ? "retourAArriere" : source;
        $('#bouttonOUI').attr('onclick', 'fermerPopupMiseAJourPanier();modifierPanierGlobal("' + source + '");');
    } else {
        if (source == 'retourAArriere' || source == "retourAArriereModifDateLivraison") {
            if (source == "retourAArriereModifDateLivraison" && cataloguesConditionneeParDateLivraison == 'cataloguesConditionneeParDateLivraison') {
                rechargerCataloguesWebshop();
            } else {
                if ($("#boutonEtapeLivraison").hasClass('active') && $("#boutonEtapeLivraison").hasClass('sansClique')) {
                    mettreAjourChampSaisieLivraison();
                }
                retourAArriere();
            }
        } else if (source == 'afficherRecapCommande') {
            if (!$("#boutonVoirPanier").hasClass("active")) {
                $("#boutonVoirPanier").addClass('active');
                $("#boutonVoirPanier").removeClass('sansClique');
                $("#boutonVoirPanier").attr('onclick', 'retourAArriereVersCommande();');
            }
            if (!$("#boutonEtapeLivraison").hasClass("active")) {
                $("#boutonEtapeLivraison").addClass('active');
                $("#boutonEtapeLivraison").removeClass('sansClique');
                $("#boutonEtapeLivraison").attr('onclick', 'afficherLivraisonWebShop();');
            }
            afficherRecapitulatifCommande(true);// true: pour paramètre sansLivraison
        } else {
            if (parseFloat($('.valeurNombreProduitsAjouter').html().replace(' ', '').replace(',', '.')) > 0) {
                $("#boutonVoirPanier").addClass('active');
                $("#boutonVoirPanier").removeClass('sansClique');
                $("#boutonVoirPanier").attr('onclick', 'retourAArriereVersCommande();');
                if (!$("#boutonEtapeLivraison").hasClass("active")) {
                    $("#boutonEtapeLivraison").addClass('active');
                    $("#boutonEtapeLivraison").addClass('sansClique');
                    $("#boutonEtapeLivraison").attr('onclick', '');
                }
            }
            afficherLivraisonWebShop();
        }
    }

}
function retourAArriere() {
    $('#contenuPanier').hide();
    $('#contenuBlockBas').show();
    if ($("#tableauListeDesProduits").length > 0 || $("#tableauListeDesProduitsDX").length > 0) {
        modifierModeDAffichageWebShop(VALEUR_LISTE);
    } else {
        modifierModeDAffichageWebShop("");
    }
}
function retourAArriereVersCommande() {
    if ($('#titrePanier').length > 0) {
        $('#titrePanier').text(PANIER);
    }
    $("#boutonVoirPanier").addClass('sansClique');
    $("#boutonVoirPanier").attr('onclick', '');
    if (typeof ($("#boutonVoirPanier").val()) !== "undefined") {
        $("#boutonEtapeLivraison").removeClass('active');
        $("#boutonEtapeLivraison").attr('onclick', '');
    }
    if ($("#boutonRecap").hasClass('active')) {
        $("#boutonRecap").removeClass('active');
        $("#boutonRecap").removeClass('sansClique');
    }
    activerLesChampsDePanier();
    if (rechargerPanier) {
        rechargerPanier = false;
        visualiserPanier();
        mettreAjourChampSaisieLivraison();
    } else {
        mettreAjourChampSaisieLivraison();
        $('.blockBoutonLivraison').hide();
        $('.blockBoutonRecapCommande').hide();
        $('#blockLivraison').hide();
        $('#blockRecapitulatifCommande').html('');
        $('#blockRecapitulatifCommande').hide();
        $('.blockBoutonCommande').show();
        $('#lignesOperationsId').show();

        setTimeout(function () {
            $('body').removeClass("bodyOverflowHidden").addClass("bodyOverflowAuto");
        }, 600);
    }
}
function fermerLayoutSupprimer() {
    $('#layoutSupprimerWebshop').fadeOut(200);
    $('#fenetreSupprimerWebshop').fadeOut(200);
}

function afficherLivraisonWebShop() {
    
    if (parseFloat($('.valeurNombreProduitsAjouter').html().replace(' ', '').replace(',', '.')) > 0) {
        if ($("#boutonVoirPanier").hasClass("sansClique")) {
            $("#boutonVoirPanier").removeClass('sansClique');
            $("#boutonVoirPanier").attr('onclick', 'retourAArriereVersCommande();');
        }
        if (!$("#boutonEtapeLivraison").hasClass("active")) {
            $("#boutonEtapeLivraison").addClass('active');
            $("#boutonEtapeLivraison").addClass('sansClique');
            $("#boutonEtapeLivraison").attr('onclick', '');
        }
        if (validerDateLivraison()) {
            if ($('#tableauListePanierDX').find('tbody').find('.catalogueInvalide').length > 0) {
                if (AUTORISER_LIGNE_PERIME != "" && AUTORISER_LIGNE_PERIME.toLowerCase().ltrim().rtrim() != "non") {
                    $('.blockBoutonCommande').hide();
                    $('#lignesOperationsId').hide();
                    setTimeout(function () { $('body').removeClass("bodyOverflowAuto").addClass("bodyOverflowHidden"); }, 600);
                    $('.blockBoutonRecapCommande').hide();
                    $('#blockRecapitulatifCommande').html('');
                    $('#blockRecapitulatifCommande').hide();
                    $('.blockBoutonLivraison').show();
                    if ($('#titrePanier').length > 0) {
                        $('#titrePanier').text(INFORMATIONS_LIVRAISON);
                    }
                    $('#blockLivraison').show();
                    if (typeof saisieEnModeSemaine !== "undefined" && saisieEnModeSemaine == "True") {
                        //si Mode Saisie en Semaine Livraison , desactiver les champs paniers
                        desActiverLesChampsDePanier();
                    }
                } else {
                    alerte(MERCI_DE_SUPPRIMER_LES_LIGNES_DES_CATALOGUES_INDISPONIBLES, 'info');
                }

            } else {
                $('.blockBoutonCommande').hide();
                $('#lignesOperationsId').hide();
                setTimeout(function () { $('body').removeClass("bodyOverflowAuto").addClass("bodyOverflowHidden"); }, 600);
                $('.blockBoutonLivraison').show();
                if ($('#titrePanier').length > 0) {
                    $('#titrePanier').text(INFORMATIONS_LIVRAISON);
                }
                $('#blockLivraison').show();
                if (typeof saisieEnModeSemaine !== 'undefined' && saisieEnModeSemaine == "True") {
                    //si Mode Saisie en Semaine Livraison , desactiver les champs paniers
                    desActiverLesChampsDePanier();
                }
            }
        }
        if (parametreForcerChoixAdresseLivraison != valeurOui) {
            $('#tableauChoixAdressLivraison_wrapper').hide();
        }
    } else {
        alerte(VOTRE_PANIER_EST_VIDE);
        if (typeof (choixAdresseEffectuer) !== 'undefined') {
            choixAdresseEffectuer = valeurNon;
        }
    }
}

function afficherRecapitulatifCommande(sansLivraison) {
    if ($("#boutonVoirPanier").hasClass("sansClique")) {
        $("#boutonVoirPanier").removeClass('sansClique');
        $("#boutonVoirPanier").attr('onclick', 'retourAArriereVersCommande();');
    }
    $('#lignesOperationsId').hide();
    setTimeout(function () { $('body').removeClass("bodyOverflowAuto").addClass("bodyOverflowHidden"); }, 600);
    messageErreur = '';
    if (!sansLivraison) {
        erreur = false;
        // Verification champs obligatoires
        $('#livraison').find('.inputObligatoire').each(function () {
            if ($(this).val().trim() != '') {
                $(this).removeClass('erreurSaisie');
            } else {
                erreur = true;
                $(this).addClass('erreurSaisie');
            }
        });
        if (erreur) {
            messageErreur += CHAMPS_OBLIGATOIRES_NON_RENSEIGNES + '.<br/>';
        }
        if (true && typeof $('#email').val() !== "undefined" && $('#email').val() != '' && verifierEmail.exec($('#email').val().toLowerCase().trim()) == null) { // prq true dans le if
            messageErreur += EMAIL_PAS_CORRECTE + '.<br/>';
        }
        if (typeof $('#emailCorrespondant').val() !== "undefined" && $('#emailCorrespondant').val() != '' && verifierEmail.exec($('#emailCorrespondant').val().toLowerCase().trim()) == null) { // prq true dans le if
            messageErreur += EMAIL_CORRESPONDANT_PAS_CORRECTE + '.<br/>';
        }
    }
    if (messageErreur == '') {
        if (!sansLivraison) {
            mettreAjourChampSaisieLivraison();
            $("#boutonEtapeLivraison").addClass('active');
            $("#boutonEtapeLivraison").removeClass('sansClique');
            $("#boutonEtapeLivraison").attr('onclick', 'retourAdresseLivraison();');
        }
        $.ajax({
            url: '/webshop/afficherRecapitulatifCommandeNEW',
            success: function (retourServeur) {
                if (!sansLivraison) {
                    $('.blockBoutonLivraison').hide();
                    $('#blockLivraison').hide();
                } else {
                    $('.blockBoutonCommande').hide();
                }
                if ($('#titrePanier').length > 0) {
                    $('#titrePanier').text(RECAPITULATIF_COMMANDE);
                }
                $('.blockBoutonRecapCommande').show();
                $('#passerCommande').show();
                $('#blockRecapitulatifCommande').html(retourServeur);
                $('#blockRecapitulatifCommande').show();
                $("#boutonRecap").addClass('active');
                $("#boutonRecap").addClass('sansClique');
                masquerChargement();

            }
        });
    } else {
        alerte(messageErreur);
    }


}

var champPanierActive = true;
function desActiverLesChampsDePanier() {
    champPanierActive = false;
    $('#panier').find('input').prop('disabled', true);
    $('#panier').find('select').prop('disabled', true);
    if (typeof saisieEnModeSemaine !== "undefined" && saisieEnModeSemaine !== "True") {
        $("#dateLivraison").datepicker("option", "disabled", true);
        $('.ui-datepicker-trigger').attr('src', '/ressource/image/webshop' + templatePersonnalise +'/calendrier.png');
    }
}
function activerLesChampsDePanier() {
    if (!champPanierActive) {
        $('#panier').find('input').prop('disabled', false);
        $('#panier').find('select').prop('disabled', false);
        if (typeof saisieEnModeSemaine !== "undefined" && saisieEnModeSemaine !== "True") {
            $("#dateLivraison").datepicker("option", "disabled", false);
            $('.ui-datepicker-trigger').attr('src', '/ressource/image/webshop' + templatePersonnalise +'/calendrier.png');
        }
        champPanierActive = true;
    }
}



//function initialiserPageLivraison() {   
//    tableauListeDesAdressesLivraison = $('#tableauChoixAdressLivraison').DataTable({
//        // Options sur les colonnes
//        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
//        'order': [[12, "asc"]],
//        'columns': [
//            { 'className': 'width40', 'visible': true }, //0
//            {'className': 'width140', 'visible': tableauChoixAdressLivraisonColVis.indexOf(1) != -1 }, //1
//            {'className': 'width140', 'visible': tableauChoixAdressLivraisonColVis.indexOf(2) != -1 }, //2
//            {'className': 'width135', 'visible': tableauChoixAdressLivraisonColVis.indexOf(3) != -1 }, //3
//            {'className': 'width135', 'visible': tableauChoixAdressLivraisonColVis.indexOf(4) != -1 }, //4
//            {'className': 'width100', 'visible': tableauChoixAdressLivraisonColVis.indexOf(5) != -1 }, //5
//            {'className': 'width135', 'visible': tableauChoixAdressLivraisonColVis.indexOf(6) != -1 }, //6
//            {'className': 'width140', 'visible': tableauChoixAdressLivraisonColVis.indexOf(7) != -1 }, //7
//            {'className': 'width140', 'visible': tableauChoixAdressLivraisonColVis.indexOf(8) != -1 }, //8
//            {'className': 'width140', 'visible': tableauChoixAdressLivraisonColVis.indexOf(9) != -1 }, //9
//            {'className': 'width140', 'visible': tableauChoixAdressLivraisonColVis.indexOf(10) != -1 }, //10
//            {'className': 'width140', 'visible': tableauChoixAdressLivraisonColVis.indexOf(11) != -1 }, //11
//            {'className': 'width40', 'visible': true }, //12
//            {'className': 'width59', 'visible': true} //13

//        ],
//        // W<"clear"> pour activer les filtres
//        // T          pour activer l'export
//        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
//        // f          pour activer le champ de recherche textuelle
//        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
//        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
//        // p          pour activer la pagination
//        // R          pour activer le déplacement des colonnes
//        // w<"clear"> pour activer le choix de visibilité des colonnes
//        // C          pour activer la visibilité des colonnes
//        'dom': '<"top"ftipR>rt',
//        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
//        'paginationType': 'full_numbers',
//        // Spécifier le fichier de langue pour dataTables
//        'language': { 'url': fichierLangue },
//        'colVis': {
//            column: tableauChoixAdressLivraisonColVis
//        },

//        'colReorder': {
//            'realtime': true,
//            'order': [13, 1, 2, 3, 4, 5, 7, 6, 9, 8, 10, 11, 12, 0]
//        },

//        'initComplete': function (oSettings, oData) {
//            $(this).css('visibility', 'visible');
//            materialiserChampsDeRecherche('tableauChoixAdressLivraison');
//            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(tableauListeDesAdressesLivraison, true, 'tableauChoixAdressLivraison', tableauListeDesAdressesDeLivraisonWebshop); }, 0);

//        },
//        "rowCallback": function (nRow, aData, iDisplayIndex) {
//            $(nRow).click(function () {
//                selectionnerAdresseLivraison(aData);
//                $("#tableauChoixAdressLivraison .active").removeClass("active");
//                $(nRow).addClass("active");
//            });
//        }
//    });
   
//    visible = false;
//    $('#choixAdressLivraison button').click(function () {
//        if (visible) {
//            $('#tableauChoixAdressLivraison_wrapper').hide("slow");
//            visible = false;
//        } else {
//            $('#tableauChoixAdressLivraison_wrapper').show("slow");
//            visible = true;
//        }
//    });

//    // suivant le parametreForcerChoixAdresseLivraison l'affichage de la page va varier
//    if (parametreForcerChoixAdresseLivraison == valeurOui) {
//        $('#tableauChoixAdressLivraison_wrapper').show();
//        $('#butonChoixAdresseLivraison').hide();
//        $('.blockBoutonRetourNoir').hide();
//        $('#passerCommande').hide();
//        $('#afficherRecap').hide();
//        $('#formulaireLivraison').hide();
//        if (parametreGestionDesCorrespondants == valeurOui) {
//            $('#blockCorrespondant').hide();
//        }
//        $('#titreLivraison').html(MES_ADRESSES_LIVRAISONS);
//    } else {
//        $('.blockBoutonLivraisonAvecEtape').hide();
//    }
//    if (choixAdresseEffectuer == valeurOui) {
//        $('#validerChoixAdresse').hide();
//        $('#afficherRecap').show();
//        $('#choixAdressLivraison').hide();
//        $('#formulaireLivraison').show();
//        if (parametreGestionDesCorrespondants == valeurOui) {
//            $('#blockCorrespondant').show();
//        }
//        $('#titreLivraison').html(ADRESSE_DE_LIVRAISON);
//        $('#retourAArriere').hide();
//        $('#passerCommande').hide();
//        $('.blockBoutonRetourNoir').show();
//    }
//}

function initialiserGridLivraison() {

    allerVersLeHaut();
    // entetePanierInitialisee = false;
    $('.contenuPage').hide();
    $("#tableauChoixAdressLivraisonDX").data({ conf: configAdressesLivraisonDUneSocieteJson });
    setTimeout(function () { initialiserPageLivraisonNew(); }, 0);
  
   
}

function initialiserPageLivraisonNew() {
    tableauListeDesAdressesLivraison = $("#tableauChoixAdressLivraisonDX").dxDataGrid({
        dataSource: ligneAdressesLivraisonDUneSocieteJson,
        searchPanel: {
            visible: true,
            width: 240,
            placeholder: RECHERCHER
        },
        filterRow: {
            visible: false
        },
        columnChooser: {
            enabled: false
        },
        columns: [{
            caption: "adresseParDefaut",
            dataField: "adresseParDefaut",
            width: 59,
            cellTemplate: function (container, options) {
                if (typeof templatePersonnalise !== "undefined" && templatePersonnalise != "") {
                    $("<img  src=\"/ressource/image/webshop/templatePersonnalise/" + (options.data.adresseParDefaut == true ? "star_check.png" : "star_uncheck.png") + "\" width=\"19.2px\" height=\"18.26px\"/>").appendTo(container);
                } else {
                    if (options.data.adresseParDefaut) {
                        $("<img  src=\"/ressource/image/commun/accepter.png\"/>").appendTo(container);
                    }
                }
            }
        },{
            dataField: "adresse.adresseComplement.nom1",
            caption: "adresse.adresseComplement.nom1",
            selectedFilterOperation: "startswith",
            width: 140
        }, {
            caption: "adresse.adresseComplement.nom2",
            dataField: "adresse.adresseComplement.nom2",
            selectedFilterOperation: "startswith",
            visible:tableauChoixAdressLivraisonColVis.indexOf(1) !== -1 ,
            width: 140

        }, {
            caption: "adresse.adresse1",
            dataField: "adresse.adresse1",
            visible:tableauChoixAdressLivraisonColVis.indexOf(2) !== -1 ,
            width: 140
            
            }, {
                caption: "adresse.adresse2",
                dataField: "adresse.adresse2",
                visible:tableauChoixAdressLivraisonColVis.indexOf(3) !== -1 ,
                width: 140

            }, {
                caption: "adresse.codePostal",
                dataField: "adresse.codePostal",
                visible: tableauChoixAdressLivraisonColVis.indexOf(4) !== -1,
                width: 135

            }, {
                caption: "adresse.pays.libelleFrancais",
                dataField: "adresse.pays.libelleFrancais",
                visible: tableauChoixAdressLivraisonColVis.indexOf(5) !== -1,
                width: 135

            }, {
                caption: "adresse.ville",
                dataField: "adresse.ville",
                visible: tableauChoixAdressLivraisonColVis.indexOf(6) !== -1,
                width: 100

            }, {
                caption: "adresse.adresseComplement.email",
                dataField: "adresse.adresseComplement.email",
                visible: tableauChoixAdressLivraisonColVis.indexOf(7) !== -1,
                width: 135

            }, {
                caption: "adresse.adresseComplement.telephone",
                dataField: "adresse.adresseComplement.telephone",
                visible: tableauChoixAdressLivraisonColVis.indexOf(8) !== -1,
                width: 140

            }, {
                caption: "adresse.adresseComplement.fax",
                dataField: "adresse.adresseComplement.fax",
                visible: tableauChoixAdressLivraisonColVis.indexOf(9) !== -1,
                width: 140

            }, {
                caption: "adresse.adresseComplement.commentaire",
                dataField: "adresse.adresseComplement.commentaire",
                visible: tableauChoixAdressLivraisonColVis.indexOf(10) !== -1,
                width: 140

            }, {
                caption: "ordre",
                dataField: "ordre",
                width: 50,
                sortOrder: "asc"

            }, {
                dataField: "adresse.numeroAdresse",
                caption: "adresse.numeroAdresse",
                width: 140
            }]
        , onRowClick: function (e) {
            var adata=[];
            adata.push(e.data.adresse.numeroAdresse);
            adata.push(e.data.adresse.pays.libelleFrancais);
            selectionnerAdresseLivraison(adata);
            $("#tableauChoixAdressLivraisonDX .active").removeClass("active");
            e.rowElement.addClass("active");
            
        }

    }).dxDataGrid("instance");
    
    visible = false;
    $('#choixAdressLivraison button').click(function () {
        if (visible) {
            $('#tableauChoixAdressLivraison_wrapper').hide("slow");
            visible = false;
        } else {
            $('#tableauChoixAdressLivraison_wrapper').show("slow");
            visible = true;
        }
    });

    // suivant le parametreForcerChoixAdresseLivraison l'affichage de la page va varier
    if (parametreForcerChoixAdresseLivraison == valeurOui) {
        $('#tableauChoixAdressLivraison_wrapper').show();
        $('#butonChoixAdresseLivraison').hide();
        $('.blockBoutonRetourNoir').hide();
        $('#passerCommande').hide();
        $('#afficherRecap').hide();
        $('#formulaireLivraison').hide();
        if (parametreGestionDesCorrespondants == valeurOui) {
            $('#blockCorrespondant').hide();
        }
        $('#titreLivraison').html(MES_ADRESSES_LIVRAISONS);
    } else {
        $('.blockBoutonLivraisonAvecEtape').hide();
    }
    if (choixAdresseEffectuer == valeurOui) {
        $('#validerChoixAdresse').hide();
        $('#afficherRecap').show();
        $('#choixAdressLivraison').hide();
        $('#formulaireLivraison').show();
        if (parametreGestionDesCorrespondants == valeurOui) {
            $('#blockCorrespondant').show();
        }
        $('#titreLivraison').html(ADRESSE_DE_LIVRAISON);
        $('#retourAArriere').hide();
        $('#passerCommande').hide();
        $('.blockBoutonRetourNoir').show();
        if ($("#validerChoixAdresse").hasClass('desactive')) {
            $("#validerChoixAdresse.desactive").removeClass("desactive");
        }
    }
}


function selectionnerAdresseLivraison(aData) {
    choixAdresseEffectuer = valeurOui;
    afficherChargement();
    $.ajax({
        url: '/OperationDesktop/choisirAdresseOperation',
        data: {
            'idAdresseSociete': aData[0]
        },
        success: function (operationEncours) {
            $("#nom1").val(operationEncours.nom1);
            $("#nom2").val(operationEncours.nom2);
            $("#adresse1").val(operationEncours.adresse1);
            $("#adresse2").val(operationEncours.adresse2);
            $("#codePostal").val(operationEncours.codePostal);
            $("#ville").val(operationEncours.ville);
            $("#pays").val($('#pays option').filter(function () { return $(this).html().trim() == aData[1].trim(); }).val());
            $("#telephone").val(operationEncours.telephone);
            $("#email").val(operationEncours.email);
            $("#fax").val(operationEncours.fax);
            $("#commentaireLivraison").val(operationEncours.commentaireLivraison);
            autoriserJoursFeries = (operationEncours.recevoirLivraisonJoursFeries == 1) ? "True" : "False";
            initialiserCalendrier('webshop');
            if (parametreGestionDesCorrespondants == valeurOui) {
                $("#nom1Correspondant").val(($("#nom1Correspondant").hasClass('inputPreinitialise') ? operationEncours.nom1 : $("#nom1Correspondant").val()));
                $("#nom2Correspondant").val(($("#nom2Correspondant").hasClass('inputPreinitialise') ? operationEncours.nom2 : $("#nom2Correspondant").val()));
                $("#adresse1Correspondant").val(($("#adresse1Correspondant").hasClass('inputPreinitialise') ? operationEncours.adresse1 : $("#adresse1Correspondant").val()));
                $("#adresse2Correspondant").val(($("#adresse2Correspondant").hasClass('inputPreinitialise') ? operationEncours.adresse2 : $("#adresse2Correspondant").val()));
                $("#codePostalCorrespondant").val(($("#codePostalCorrespondant").hasClass('inputPreinitialise') ? operationEncours.codePostal : $("#codePostalCorrespondant").val()));
                $("#villeCorrespondant").val(($("#villeCorrespondant").hasClass('inputPreinitialise') ? operationEncours.ville : $("#villeCorrespondant").val()));
                $("#paysCorrespondant").val(($("#paysCorrespondant").hasClass('inputPreinitialise') ? $('#paysCorrespondant option').filter(function () { return $(this).html().trim() == aData[1].trim(); }).val() : $("#paysCorrespondant").val()));
                $("#telephoneCorrespondant").val(($("#telephoneCorrespondant").hasClass('inputPreinitialise') ? operationEncours.telephone : $("#telephoneCorrespondant").val()));
                $("#emailCorrespondant").val(($("#emailCorrespondant").hasClass('inputPreinitialise') ? operationEncours.email : $("#emailCorrespondant").val()));
                $("#portableCorrespondant").val(($("#portableCorrespondant").hasClass('inputPreinitialise') ? operationEncours.portable : $("#portableCorrespondant").val()));
                $("#faxCorrespondant").val(($("#faxCorrespondant").hasClass('inputPreinitialise') ? operationEncours.fax : $("#faxCorrespondant").val()));
            }
            if ($("#validerChoixAdresse").hasClass('desactive')) {
                $("#validerChoixAdresse.desactive").removeClass("desactive");
            }
            masquerChargement();
        }
    });
}
function validerChoixAdresseLivraison() {
    if (choixAdresseEffectuer == valeurOui) {
        $('#validerChoixAdresse').hide();
        $('#afficherRecap').show();
        $('#choixAdressLivraison').hide();
        $('#formulaireLivraison').show();
        if (parametreGestionDesCorrespondants == valeurOui) {
            $('#blockCorrespondant').show();
        }
        $('#titreLivraison').html(ADRESSE_DE_LIVRAISON);
        if ($('#titrePanier').length > 0) {
            $('#titrePanier').text(INFORMATIONS_LIVRAISON);
        }
        $('#retourAArriere').hide();
        $('#passerCommande').hide();
        $('.blockBoutonRetourNoir').show();
    } else {
        alerte(VEUILLEZ_CHOISIR_UNE_ADRESSE_DE_LIVRAISON_AVANT_DE_CONTINUER);
    }
}
function retourChoixAdresse() {
    $('#titreLivraison').html(MES_ADRESSES_LIVRAISONS);
    if ($('#titrePanier').length > 0) {
        $('#titrePanier').text(MES_ADRESSES_LIVRAISONS);
    }    $('#retourAArriere').show();
    $('#afficherRecap').hide();
    $('#validerChoixAdresse').show();
    $('#choixAdressLivraison').show();
    $('#tableauChoixAdressLivraison_wrapper').show();
    $('#butonChoixAdresseLivraison').hide();
    $('.blockBoutonRetourNoir').hide();
    $('#formulaireLivraison').hide();
    if (parametreGestionDesCorrespondants == valeurOui) {
        $('#blockCorrespondant').hide();
    }
}

var enteteListeClientsWebshopInitialisee = false;
function initialiserListeClientsWebshopDX() {
    $('.boutonChoixLangue').click(function () {
        $('.dropdown-Langue').toggle();
    });
    $('.boutonMenuCompte').click(function () {
        $('.blockMenuConnection').toggle();
    });
    $("#tableauListeClientsWebshop").data({ conf: conf });
      $(function () {
    
          var clientStore = new DevExpress.data.CustomStore({
            load: function (loadOptions) {
                var deferred = $.Deferred(),
                    filter = [];
                filterHeader = [];
                chargerFiltres(myTable, loadOptions, filter, filterHeader);
                $.ajax({
                    url: '/administration/peuplementListeDesClientsDX?filtreEtatTableau=tableauListeClientsWebshop&filtrerCodeRepresentant=1',

                    dataType: "json",
                    data: {
                        filter: JSON.stringify(filter),
                        filterHeader: JSON.stringify(filterHeader),
                        sort: JSON.stringify(loadOptions.sort == null ? [] : loadOptions.sort),
                        skip: loadOptions.skip || 0,
                        take: loadOptions.take || -1
                    },
                    success: function (result) {
                        deferred.resolve(result.items, { totalCount: result.totalCount });
                        masquerChargement();
                    },
                    error: function (xhr, error, thrown) {
                        //console.log("xhr", xhr)
                        //deferred.reject("Data Loading Error");
                        if (xhr.responseText.indexOf('<title>') != -1) {
                            exception = xhr.responseText.split('<title>')[1].split('</title>')[0];
                            if (exception.substring(0, 4) == '1000') {
                                alerte(exception.replace('1000:', ''), 'erreur');
                            } else if (exception.substring(0, 4) == '3000') {
                                alerte(exception.replace('3000:', ''), 'confirmationUtilisateur', 'rechargerPage');
                            }
                        }
                    }
                });

                return deferred.promise();
            }
        });


          myTable = $("#tableauListeClientsWebshop").dxDataGrid({
            dataSource: clientStore,
            paging: {
                pageSize: (configurationTableauxDx !== null && configurationTableauxDx.some(function (item) { if (item.idGrid === "tableauListeClientsWebshop") { return item; } })) ? configurationTableauxDx.find(function (item) { if (item.idGrid === "tableauListeClientsWebshop") { return item; } }).structuredEtatDatagrid.pageSize : 20
            },           
            columns: [
                {
                    dataField: "numeroSociete",
                    caption: "numeroSociete",
                    width: 100,
                    alignment: "center",
                    renderAsync: true,
                    visible: false
                },
                {
                    dataField: "numeroExterne",
                    caption: "numeroExterne",
                    width: 90,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['numeroExterne']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                         {
                    dataField: "nom1",
                    caption: "nom1",
                    width: 160,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['nom1']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "nom2",
                    caption: "nom2",
                    width: 160,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['nom2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "adresse1",
                    caption: "adresse1",
                    width: 170,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['adresse1']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "adresse2",
                    caption: "adresse2",
                    width: 170,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['adresse2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "adresse3",
                    caption: "adresse3",
                    width: 100,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['adresse3']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codePostal",
                    caption: "codePostal",
                    width: 100,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codePostal']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },

                {
                    dataField: "ville",
                    caption: "ville",
                    width: 125,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['ville']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "pays",
                    caption: "pays",
                    width: 70,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['pays']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "raisonSociale",
                    caption: "raisonSociale",
                    width: 130,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['raisonSociale']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "telephone1",
                    caption: "telephone1",
                    width: 115,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['telephone1']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },

                {
                    dataField: "telephone2",
                    caption: "telephone2",
                    width: 115,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['telephone2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },

                {
                    dataField: "mobile",
                    caption: "mobile",
                    width: 115,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['mobile']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "fax",
                    caption: "fax",
                    width: 115,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['fax']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },


                {
                    dataField: "email",
                    caption: "email",
                    width: 200,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['email']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCategorie",
                    caption: "codeCategorie",
                    width: 140,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCategorie']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeRepresentant1",
                    caption: "codeRepresentant1",
                    width: 170,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeRepresentant1']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeRepresentant2",
                    caption: "codeRepresentant2",
                    width: 170,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeRepresentant2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeRepresentant3",
                    caption: "codeRepresentant3",
                    width: 170,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeRepresentant3']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeRepresentant4",
                    caption: "codeRepresentant4",
                    width: 170,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeRepresentant4']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeRepresentant5",
                    caption: "codeRepresentant5",
                    width: 170,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeRepresentant5']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeRepresentant6",
                    caption: "codeRepresentant6",
                    width: 170,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeRepresentant6']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "dateDernierEnvoiIdentifiants",
                    caption: "dateDernierEnvoiIdentifiants",
                    width: 275,
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]];

                        return filterExpression;
                    },
                    visible: false
                },

                {
                    dataField: "codeCivilite",
                    caption: "codeCivilite",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCivilite']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere1",
                    caption: "codeCritere1",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere1']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere2",
                    caption: "codeCritere2",
                    width: 70,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere3",
                    caption: "codeCritere3",
                    width: 70,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere3']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere4",
                    caption: "codeCritere4",
                    width: 70,
                    dataType: "string",
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere4']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere5",
                    caption: "codeCritere5",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere5']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere6",
                    caption: "codeCritere6",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere6']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere7",
                    caption: "codeCritere7",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere7']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere8",
                    caption: "codeCritere8",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere8']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere9",
                    caption: "codeCritere9",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere9']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere10",
                    caption: "codeCritere10",
                    width: 70
                    , renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere10']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere11",
                    caption: "codeCritere11",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere11']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere12",
                    caption: "codeCritere12",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere12']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere13",
                    caption: "codeCritere13",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere13']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere14",
                    caption: "codeCritere14",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere14']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere15",
                    caption: "codeCritere15",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere15']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere16",
                    caption: "codeCritere16",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere16']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere17",
                    caption: "codeCritere17",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere17']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere18",
                    caption: "codeCritere18",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere18']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeDevise",
                    caption: "codeDevise",
                    width: 70,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeDevise']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "siteInternet",
                    caption: "siteInternet",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['siteInternet']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "siteInternet2",
                    caption: "siteInternet2",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['siteInternet2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "siret",
                    caption: "siret",
                    width: 70,
                     visible: false,renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['siret']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "numeroTVAIntracommunautaire",
                    caption: "numeroTVAIntracommunautaire",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['numeroTVAIntracommunautaire']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "twitter",
                    caption: "twitter",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['twitter']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "facebook",
                    caption: "facebook",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['facebook']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "notes",
                    caption: "notes",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['notes']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "heuresJoursOuverture",
                    caption: "heuresJoursOuverture",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['heuresJoursOuverture']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "heuresJoursReceptionMarchandises",
                    caption: "heuresJoursReceptionMarchandises",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['heuresJoursReceptionMarchandises']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "autresMentionsUtiles",
                    caption: "autresMentionsUtiles",
                    width: 70,
                     visible: false,renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['autresMentionsUtiles']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },

                {
                    caption: "dateCreation",
                    dataField: "dateCreation",
                    width: 135,
                    alignment: "left",
                    dataType: "datetime",
                     visible: false,renderAsync: true,
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]];

                        return filterExpression;
                    }
                },
                {
                    caption: "dateModification",
                    dataField: "dateModification",
                    width: 135,
                    alignment: "left",
                    dataType: "datetime",
                     visible: false,renderAsync: true,
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]];

                        return filterExpression;
                    }
                },

                {
                    dataField: "numeroSocieteHortiPass",
                    caption: "numeroSocieteHortiPass",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                },
                {
                    dataField: "numeroCompteHortiPass",
                    caption: "numeroCompteHortiPass",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "numeroTarif",
                    caption: "numeroTarif",
                    width: 70,
                     visible: false,renderAsync: true,

                },
                {
                    dataField: "societeAuxiliaire",
                    caption: "societeAuxiliaire",
                    width: 70,
                     visible: false,renderAsync: true,

                },
                {
                    dataField: "codeRegroupementFacture",
                    caption: "codeRegroupementFacture",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeRegroupementFacture']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "regleEtiquette",
                    caption: "regleEtiquette",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['regleEtiquette']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codePaysProvenanceOuDestination",
                    caption: "codePaysProvenanceOuDestination",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codePaysProvenanceOuDestination']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeConditionnement",
                    caption: "codeConditionnement",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeConditionnement']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "paysOrigine",
                    caption: "paysOrigine",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['paysOrigine']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeClasse",
                    caption: "codeClasse",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeClasse']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "numeroReferencement",
                    caption: "numeroReferencement",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "numeroModeleEtiquette",
                    caption: "numeroModeleEtiquette",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "codeChoixDePort",
                    caption: "codeChoixDePort",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeChoixDePort']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeModeReglement",
                    caption: "codeModeReglement",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeModeReglement']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "tauxRemiseLigne",
                    caption: "tauxRemiseLigne",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "tauxRemisePied",
                    caption: "tauxRemisePied",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "compteTiers",
                    caption: "compteTiers",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['compteTiers']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },


                {
                    caption: "dateCreationExterne",
                    dataField: "dateCreationExterne",
                    width: 135,
                    visible: false,
                    renderAsync: true,
                    alignment: "left",
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]];

                        return filterExpression;
                    }
                },
                {
                    caption: "dateModificationExterne",
                    dataField: "dateModificationExterne",
                    width: 135,
                    alignment: "left",
                    visible: false,
                    renderAsync: true,
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]];

                        return filterExpression;
                    }
                },
                {
                    dataField: "chiffreDAffaireAnneeEnCours",
                    caption: "chiffreDAffaireAnneeEnCours",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "chiffreDAffaireAnnee1",
                    caption: "chiffreDAffaireAnnee1",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "chiffreDAffaireAnnee2",
                    caption: "chiffreDAffaireAnnee2",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },

                {
                    dataField: "chiffreDAffairesANouveau",
                    caption: "chiffreDAffairesANouveau",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "chiffreDAffairesDAvoirAnneeEnCours",
                    caption: "chiffreDAffairesDAvoirAnneeEnCours",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "tauxAvoir",
                    caption: "tauxAvoir",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    caption: "dateDerniereCommande",
                    dataField: "dateDerniereCommande",
                    width: 135,
                    visible: false,
                    renderAsync: true,
                    alignment: "left",
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]];

                        return filterExpression;
                    }
                },
                {
                    dataField: "codeIdentificationTva",
                    caption: "codeIdentificationTva",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeIdentificationTva']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "assurance",
                    caption: "assurance",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['assurance']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "numeroExterneAfacturer",
                    caption: "numeroExterneAfacturer",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "plafond",
                    caption: "plafond",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    caption: "dateModificationPlafond",
                    dataField: "dateModificationPlafond",
                    width: 135,
                    alignment: "left",
                    visible: false,
                    renderAsync: true,
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]];

                        return filterExpression;
                    }
                },
                {
                    dataField: "objectifChiffreDAffaire",
                    caption: "objectifChiffreDAffaire",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "nombreFactures",
                    caption: "nombreFactures",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "codeCNUF",
                    caption: "codeCNUF",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "numeroAccise",
                    caption: "numeroAccise",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['numeroAccise']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "numeroCVI",
                    caption: "numeroCVI",
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    width: 70,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['numeroCVI']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "invisible",
                    caption: "invisible",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "tauxDEscompte",
                    caption: "tauxDEscompte",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "paysCodeBarre",
                    caption: "paysCodeBarre",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "typeClientFiscal",
                    caption: "typeClientFiscal",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },

                {
                    dataField: "numeroExterneOrigine",
                    caption: "numeroExterneOrigine",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['numeroExterneOrigine']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCentrale",
                    caption: "codeCentrale",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCentrale']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeEmballageFinal",
                    caption: "codeEmballageFinal",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeEmballageFinal']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeTypeTitre",
                    caption: "codeTypeTitre",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeTypeTitre']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCommissionRepresentant1",
                    caption: "codeCommissionRepresentant1",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCommissionRepresentant1']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCommissionRepresentant2",
                    caption: "codeCommissionRepresentant2",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCommissionRepresentant2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCommissionRepresentant3",
                    caption: "codeCommissionRepresentant3",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCommissionRepresentant3']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCommissionRepresentant4",
                    caption: "codeCommissionRepresentant4",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCommissionRepresentant4']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCommissionRepresentant5",
                    caption: "codeCommissionRepresentant5",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCommissionRepresentant5']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCommissionRepresentant6",
                    caption: "codeCommissionRepresentant6",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCommissionRepresentant6']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "tauxPrixAchat",
                    caption: "tauxPrixAchat",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "codeBaremePort",
                    caption: "codeBaremePort",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeBaremePort']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },

                {
                    dataField: "commentaire",
                    caption: "commentaire",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['commentaire']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "commentaire2",
                    caption: "commentaire2",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['commentaire2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "commentaire3",
                    caption: "commentaire3",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['commentaire3']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "commentaire4",
                    caption: "commentaire4",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['commentaire4']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },

                {
                    dataField: "codeCritere1Operation",
                    caption: "codeCritere1Operation",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere1Operation']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCritere2Operation",
                    caption: "codeCritere2Operation",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere2Operation']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCritere3Operation",
                    caption: "codeCritere3Operation",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere3Operation']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "tauxAcompte",
                    caption: "tauxAcompte",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "coefficientReventeEtiquette",
                    caption: "coefficientReventeEtiquette",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "mouvementerLesStocks",
                    caption: "mouvementerLesStocks",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "valoriserLesConsignes",
                    caption: "valoriserLesConsignes",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "appliquerFraisFacturation",
                    caption: "appliquerFraisFacturation",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "autoriserEmballagesHeterogenes",
                    caption: "autoriserEmballagesHeterogenes",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "clientEstFacturable",
                    caption: "clientEstFacturable",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "francoValeur",
                    caption: "francoValeur",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "francoType",
                    caption: "francoType",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },


                {
                    dataField: "codeBaseTransport",
                    caption: "codeBaseTransport",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeBaseTransport']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeLieuFonction",
                    caption: "codeLieuFonction",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeLieuFonction']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeDepot",
                    caption: "codeDepot",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeDepot']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "paiementEstSurReleve",
                    caption: "paiementEstSurReleve",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "delaiExpedition",
                    caption: "delaiExpedition",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "decalageEntreDateExpeditionPrevuEtLivraison",
                    caption: "decalageEntreDateExpeditionPrevuEtLivraison",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "complementPourComptabilite",
                    caption: "complementPourComptabilite",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['complementPourComptabilite']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "activerTransfertDepotADepot",
                    caption: "activerTransfertDepotADepot",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "codeDepotDestination",
                    caption: "codeDepotDestination",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeDepotDestination']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeNatureFacturation",
                    caption: "codeNatureFacturation",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "nombrePointFidelite",
                    caption: "nombrePointFidelite",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "groupesDestinataires",
                    caption: "groupesDestinataires",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['groupesDestinataires']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "activerCarteFidelite",
                    caption: "activerCarteFidelite",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "dateCreationCarteFidelite",
                    caption: "dateCreationCarteFidelite",
                    width: 70,
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    visible: false,
                    renderAsync: true,
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]];

                        return filterExpression;
                    }
                },
                {
                    dataField: "critereNumerique01",
                    caption: "critereNumerique01",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "mouvementerLesConsignes",
                    caption: "mouvementerLesConsignes",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "codeStatutDeRelance",
                    caption: "codeStatutDeRelance",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeStatutDeRelance']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeStatutDeRelancePrecedent",
                    caption: "codeStatutDeRelancePrecedent",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeStatutDeRelancePrecedent']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "consignesEnCompte",
                    caption: "consignesEnCompte",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "codeHortitrace",
                    caption: "codeHortitrace",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeHortitrace']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "ancienNumeroExterne",
                    caption: "ancienNumeroExterne",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "genererFactureEdi",
                    caption: "genererFactureEdi",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "bloquerRemisePersonnalisee",
                    caption: "bloquerRemisePersonnalisee",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "bloquerRemiseTarifsEvolues",
                    caption: "bloquerRemiseTarifsEvolues",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "bloquerRemisePrixDeRevient",
                    caption: "bloquerRemisePrixDeRevient",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "regleEclatementCommande",
                    caption: "regleEclatementCommande",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "codeTelevendeur",
                    caption: "codeTelevendeur",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeTelevendeur']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "televenteHeureDAppel",
                    caption: "televenteHeureDAppel",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['televenteHeureDAppel']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "televenteAppelerLundi",
                    caption: "televenteAppelerLundi",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "televenteAppelerMardi",
                    caption: "televenteAppelerMardi",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "televenteAppelerMercredi",
                    caption: "televenteAppelerMercredi",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "televenteAppelerJeudi",
                    caption: "televenteAppelerJeudi",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "televenteAppelerVendredi",
                    caption: "televenteAppelerVendredi",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "televenteAppelerSamedi",
                    caption: "televenteAppelerSamedi",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "televenteAppelerDimanche",
                    caption: "televenteAppelerDimanche",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "lierAuNumeroExterne",
                    caption: "lierAuNumeroExterne",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "centreComptableEdi",
                    caption: "centreComptableEdi",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['centreComptableEdi']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeEnseigne",
                    caption: "codeEnseigne",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeEnseigne']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codePeriodiciteReleve",
                    caption: "codePeriodiciteReleve",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codePeriodiciteReleve']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "codeCritereArticleFiltrage",
                    caption: "codeCritereArticleFiltrage",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereArticleFiltrage']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "coefficientArrondiEtiquette",
                    caption: "coefficientArrondiEtiquette",
                    width: 70,
                    visible: false,
                    renderAsync: true,
                    dataType: "string",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['coefficientArrondiEtiquette']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    }
                },
                {
                    dataField: "escompteEstPrecompte",
                    caption: "escompteEstPrecompte",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "typeClient",
                    caption: "typeClient",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },
                {
                    dataField: "envoyerTotauxEmballagesSurHortitrace",
                    caption: "envoyerTotauxEmballagesSurHortitrace",
                    width: 70,
                    visible: false,
                    renderAsync: true,

                },


            ],
            onRowClick: function (selectedItems) {
               
                if (typeDeCompte == "compteSecondaire") {
                   
                        nomPrenomDeCompteSollicite = "";
                        telephone1DeCompteSollicite = "";
                        mobileDeCompteSollicite = "";
                        numeroSocieteDeCompteSollicite = selectedItems.data.numeroSocieteSelection;
                        // afficherChargement(); // 15/05/2024 : WAZ : suppression de l'affichage du chargement pour qu'il reste affiché lors d'un choix de client en mode collectivité (compte secondaire fournisseur)
                        $.ajax({
                            url: '/societeEtCompte/recupererCompteAdministrateurJson',
                            async: false,
                            data: {
                                'numeroSocieteDeCompteSollicite': numeroSocieteDeCompteSollicite
                            },
                            success: function (compteAdmin) {
                                // masquerChargement(); // 15/05/2024 : WAZ : suppression du masquage du chargement pour qu'il reste affiché lors d'un choix de client en mode collectivité (compte secondaire fournisseur)
                                numeroCompteSollicite = compteAdmin.numeroCompte;
                                nomPrenomDeCompteSollicite = (compteAdmin.nom1 == null ? "" : compteAdmin.nom1) + " " + (compteAdmin.nom2 == null ? "" : compteAdmin.nom2);
                                selectionnerClientSurLequelPasserCommande(numeroCompteSollicite, '');
                            }
                        });

                    
                }

            }
     

        }).dxDataGrid("instance");
          
    });
   }
function initialiserListeClientsWebshop() {
    enteteListeClientsWebshopInitialisee = false;
    pageSelectionnees = new Array();
    $('.contenuPage').hide();
    tableauindice = retournerIndiceTableau('tableauListeClientsWebshop');
    idTableauHtml = 'tableauListeClientsWebshop';
    etatTableau = tableauListeClientsWebshop;
    pageSelectionnee = retournerdebutPage(tableauindice);
    tableauClientsWebshop = $('#tableauListeClientsWebshop').DataTable({
        'serverSide': true,
        'ajax': {
            'url': '/administration/peuplementListeDesClients?filtreEtatTableau=tableauListeClientsWebshop&filtrerCodeRepresentant=1' + "&versionCode=" + VERSION_CODE + "&numeroSocieteFournisseurEncours=" + numeroSociete + "&numeroBoutiqueEncours=" + numeroBoutique,
            'type': 'POST',
             error: function (xhr, error, thrown) {
                if (xhr.responseText.indexOf('<title>') != -1) {
                    exception = xhr.responseText.split('<title>')[1].split('</title>')[0];
                    if (exception.substring(0, 4) == '1000') {
                        alerte(exception.replace('1000:', ''), 'erreur');
                    } else if (exception.substring(0, 4) == '3000') {
                        alerte(exception.replace('3000:', ''), 'confirmationUtilisateur', 'rechargerPage');
                    }
                }
            },
            'beforeSend': function (request) {
                afficherChargement();
            },
            'data': function (d) {
                return $.extend({}, d, {
                    'attacherGroupe': "",
                    'modeGroupe': "",
                    'modeWebShop': "webshop",
                    '#pageAccueilEspaceClient': $('#pageAccueilEspaceClientInput').val()
                });
            }
        },
        'order': [],
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'columns': [
            { 'name': '0', 'className': 'width40' },
            { 'name': '1', 'type': 'num-html', 'className': 'width100' },
            { 'name': '2', 'type': 'num-html', 'className': 'width100' },
            { 'name': '3', 'className': 'width135' },
            { 'name': '4', 'className': 'width135' },

            { 'name': '5', 'className': 'width135' },
            { 'name': '6', 'className': 'width135' },
            { 'name': '7', 'className': 'width135' },
            { 'name': '8', 'className': 'width135' },

            { 'name': '9', 'className': 'width150' },
        //            { 'name': '10', 'className': 'width135' },
        //            { 'name': '11', 'className': 'width135' },
            {'name': '10', 'className': 'width140' },
            { 'name': '11', 'className': 'forcerSur1Ligne width135' },

            { 'name': '12', 'className': 'forcerSur1Ligne width135' },
            { 'name': '13', 'className': 'forcerSur1Ligne width135' },
            { 'name': '14', 'className': 'width135' },
            { 'name': '15', 'className': 'width135' },
            { 'name': '16', 'searchable': false, 'visible': true, 'className': 'width135' },
            { 'name': '17', 'searchable': false, 'visible': true, 'className': 'width135' },
            { 'name': '18', 'orderable': false, 'visible': false, 'className': 'width10' },
            { 'name': '19', 'searchable': false, 'orderable': false, 'visible': false, 'className': 'width10' },
            { 'name': '20', 'searchable': false, 'orderable': false, 'visible': false, 'className': 'width10' }, //'sName': 'activerOuDesactiver',
            {'name': '21', 'searchable': false, 'orderable': false, 'visible': false, 'className': 'width10' },
            { 'name': '22', 'className': 'width100' }, // code postal
            {'name': '23', 'className': 'width135' }, // ville 
            {'name': '24', 'className': 'width135' }, // pays
            {'name': '25', 'className': 'width100' }, // N° tarif
            {'name': '26', 'className': 'width100' },
            { 'name': '27', 'className': 'width100' },
            { 'name': '28', 'className': 'width100' },
            { 'name': '29', 'className': 'width100' },
            { 'name': '30', 'className': 'width100' },
            { 'name': '31', 'className': 'width100' },
            { 'name': '32', 'className': 'width100' },
            { 'name': '33', 'className': 'width100' },
            { 'name': '34', 'className': 'width100' },
            { 'name': '35', 'className': 'width100' },
            { 'name': '36', 'className': 'width100' },
            { 'name': '37', 'className': 'width100' },
            { 'name': '38', 'className': 'width100' },
            { 'name': '39', 'className': 'width100' },
            { 'name': '40', 'className': 'width100' },
            { 'name': '41', 'className': 'width100' },
            { 'name': '42', 'className': 'width100' },
            { 'name': '43', 'className': 'width100' },
            { 'name': '44', 'className': 'width100' },
            { 'name': '45', 'visible': false }, //, 'sName': 'numeroSocieteDeCompteSollicite' 
            { 'name': '46', 'orderable': false, 'className': 'width30 colonneCochage', 'visible': false },
            { 'name': '47', 'visible': false }, //, 'sName': 'numeroSocieteDeCompteSollicite' 
            {'name': '48', 'visible': false }, //, 'sName': 'denominationSocieteDeCompteSollicite'
            {'name': '49', 'visible': false, 'className': 'width10' }

        //            {'name': '31', 'searchable': false, 'orderable': false, 'visible': false },
        //            { 'name': '32', 'visible': true, 'className': 'width30' }, //'sName': 'attacherOuDetacher'
        //            {'name': '33', 'visible': false }, //, 'sName': 'numeroSocieteDeCompteSollicite'
        //            {'name': '34', 'visible': false}//, 'sName': 'denominationSocieteDeCompteSollicite' 

        ],
        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // w<"clear"> pour activer le choix de visibilité des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"CltfipR>rt',
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        'paginationType': 'full_numbers',

        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        // Spécifier la première page d'affichage
        'displayStart': parseInt(pageSelectionnee),
        // Options sur les filtres
        'oColumnFilterWidgets': {
            //  'bGroupTerms': true, // pour activer le groupage sur les filtres
            'aiExclude': [1] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        },
        'colVis': {
            'exclude': [18, 19, 20, 21, 45, 46, 47, 48, 49], // spécifier les colonnes qui ne figurent pas dans la visibilité des colonnes
            'buttonText': AFFICHER_MASQUER_COLONNES,
            //Gestion Des Filtres Par Colonne Et Visibilite
            'fnStateChange': function (iColumn, bVisible) {

                gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, tableauClientsWebshop.settings()[0]);
            }
        },

        'headerCallback': function (thead, data, start, end, display) {
            if (enteteListeClientsWebshopInitialisee == false || tableauDesLargeuresEtIndicesClientWebshop == "reinitialisé") {
                enteteListeClientsWebshopInitialisee = true;
                titresColonnesSauveguarde = titresColonnesClientWebshop;
                titresColonnesClientWebshop = [];
                largeurParDefaut = 0;
                tableauDesLargeuresEtIndicesChargementClientWebshop = [];
                indiceColonnes = 0;
                colonneCheckBox = "";
                //alert(titresColonnesSauveguarde.join('|'));
                j = 0;
                $(thead).find('th').each(function () {
                    if (tableauDesLargeuresEtIndicesClientWebshop == "reinitialisé") {
                        //alert(titresColonnesSauveguarde[indiceColonnes]);
                        largeurParDefaut = titresColonnesSauveguarde[indiceColonnes].split(";")[2];
                        indiceColonnes++;
                    } else {
                        largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                        largeurParDefaut = (largeurParDefaut == null ? 0 : largeurParDefaut[0].replace("width", ""));
                    }

                    largeurActuellementAppliquee = (tableauDesLargeuresEtIndicesClientWebshop == "reinitialisé" ? largeurParDefaut : largeurActuel(idTableauHtml, etatTableau, $(this).data("origColHeader"), largeurParDefaut));
                    titresColonnesClientWebshop.push($(this).text().ltrim().rtrim() + ";" + $(this).data("origColHeader") + ";" + largeurParDefaut + ";" + largeurActuellementAppliquee);
                    j++;
                });

                titresColonnesClientWebshop = colonnesVisiblesOuPas(etatTableau, titresColonnesClientWebshop, idTableauHtml);
                tableau = [];
                for (i = 0; i < titresColonnesClientWebshop.length; i++) {
                    tableau = titresColonnesClientWebshop[i].split(";");
                    tableauDesLargeuresEtIndicesChargementClientWebshop.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesClientWebshop = (tableauDesLargeuresEtIndicesClientWebshop != "reinitialisé" ? tableauDesLargeuresEtIndicesChargementClientWebshop.join('|') : tableauDesLargeuresEtIndicesClientWebshop);
            }
        },
        'initComplete': function (oSettings, oData) {
            fnOrdonnerColonnes(idTableauHtml, etatTableau);

            // $(this).css('visibility', 'visible');
            materialiserChampsDeRecherche(idTableauHtml, true);
            //remplirLesFiltres('/administration/listeFiltresMesCliens', idTableauHtml, "", etatTableau);
            initialiserCoVis(idTableauHtml);
            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(tableauClientsWebshop, true, idTableauHtml, etatTableau, "", (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? false : true)); }, 0);
            tableauClientsWebshop.ajax.url('/administration/peuplementListeDesClients?filtrerCodeRepresentant=1'+ "&versionCode=" + VERSION_CODE + "&numeroSocieteFournisseurEncours=" + numeroSociete + "&numeroBoutiqueEncours=" + numeroBoutique);
            if (typeDeCompte == "compteSecondaire") {
                $("#tableauListeClientsWebshop tbody tr").css('cursor', 'pointer');
            }

        },
        'colReorder': {
            'realtime': true

        },
        'drawCallback': function (oSettings) {
            //cette fonction prend en charge de masquer le loader de chargement et affiche la table après sa création
            forcerCablagePagination(idTableauHtml);
            if (etatTableau != '""' && etatTableau != null && tableauDesLargeuresEtIndicesClientWebshop != "reinitialisé") {
                etatTableau = etatTableau.split("\\").join("");
                etatTableau = etatTableau.split("^(").join("");
                etatTableau = etatTableau.split(")$").join("");
                oState = JSON.parse(etatTableau);
                if (oState.hasOwnProperty('ColWidth') && typeof oState.ColWidth !== 'undefined') {
                    if (oState.ColWidth.length > 0) {
                        appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesClientWebshop);

                    }
                }
            } else if (tableauDesLargeuresEtIndicesClientWebshop == "reinitialisé") {
                indiceColonne = 1;
                $('#' + idTableauHtml).find('tbody').find('tr:nth-child(1)').find('td').each(function () {
                    largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                    largeurParDefaut = largeurParDefaut[0];
                    $('#' + idTableauHtml).find('tfoot').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('thead').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);

                    indiceColonne++;

                });

                tableauDesLargeuresEtIndicesChargementClientWebshop = [];
                for (i = 0; i < titresColonnesClientWebshop.length; i++) {
                    tableau = titresColonnesClientWebshop[i].split(";");
                    tableauDesLargeuresEtIndicesChargementClientWebshop.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesClientWebshop = tableauDesLargeuresEtIndicesChargementClientWebshop.join('|');


            } else {
                appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesClientWebshop);
            }
            masquerChargement();
        }
    });
    if (typeDeCompte == "compteSecondaire") {
        $('#tableauListeClientsWebshop').on("click", "tbody tr", function () {
            // Récuperer les paramètres nécessaires
            nomPrenomDeCompteSollicite = "";
            telephone1DeCompteSollicite = "";
            mobileDeCompteSollicite = "";
            iPos = tableauClientsWebshop.row(this).index();
            aData = tableauClientsWebshop.row(iPos).data();
            numeroSocieteDeCompteSollicite = aData[tableauClientsWebshop.column('47:name').index()];
            //denominationSocieteDeCompteSollicite = aData[tableauClientsWebshop.column('24:name').index()]; //33
            // selectionnerClientSurLequelPasserCommande(numeroSocieteDeCompteSollicite, denominationSocieteDeCompteSollicite);
            afficherChargement();
            $.ajax({
                url: '/societeEtCompte/recupererCompteAdministrateurJson',
                async: false,
                data: {
                    'numeroSocieteDeCompteSollicite': numeroSocieteDeCompteSollicite
                },
                success: function (compteAdmin) {
                    masquerChargement();
                    numeroCompteSollicite = compteAdmin.numeroCompte;
                    nomPrenomDeCompteSollicite = (compteAdmin.nom1 == null ? "" : compteAdmin.nom1) + " " + (compteAdmin.nom2 == null ? "" : compteAdmin.nom2);
                    selectionnerClientSurLequelPasserCommande(numeroCompteSollicite, nomPrenomDeCompteSollicite);
                    // masquerChargement();
                }
            });

        });
    }
}

function selectionnerClientSurLequelPasserCommande(numeroCompte, numeroOperation) {
    afficherChargement();
    $.ajax({
        url: '/webshop/selectionnerComptePourPasserCommandeWebshop?numeroSociete=' + numeroSociete,
        data: {
            'numeroCompte': numeroCompte,
            'numeroOperation': numeroOperation
        },
        success: function (template) {
            $('body').html(template);
            masquerChargement();
           // alerte(LE_COMPTE_A_ETE_SELECTIONNE + ' (' + nomCompte + ')', 'confirmation');
        }
    });
}

function reprendreLeCompteSecondaire() {
    if ($('#dateLivraison').length> 0) {
        jQuery('#dateLivraison').datepicker("hide");
        desactiverModeModal();
    }
    
    //vider les inputs de saisie si renseigner
    lignesPanierAModifier = [];
    lignesPanier = [];
        $.ajax({
            url: '/webshop/reprendreLeCompteSecondaire?numeroSociete=' + numeroSociete,
            success: function (template) {
                $('body').html(template);
                masquerChargement();
               // alerte(LE_COMPTE_SUPER_ADMINISTRATEUR_A_ETE_RECUPERE, 'confirmation');
            }
        });
    
}
var verifierChampsPourModifierCompte = '';
function initialisationMonCompteClient() {
    if (typeof ($('#blockRecapitulatifCommande').html()) !== 'undefined' && $('#blockRecapitulatifCommande').html().indexOf("recapCommande") > -1) {
        activerLesChampsDePanier();
    }
    $('.passwordActuel').blur(function () {
        //afficherChargement();
        $.ajax({
            url: '/webshop/verifierAncienMotDePasse',
            data: {
                'motDePasseActuel': $('.passwordActuel').val()
            },
            success: function (resultat) {
                $('.ancienMP').show();
                if (resultat == 'OK') {
                    if (parmetreTemplateSite != "") {
                        $('.passwordActuel').removeClass("errorInputInfoCompte").addClass("validInputInfoCompte")
                    } else {
                        $('.ancienMP').attr('src', '/ressource/image/webshop/ic_valide.png');
                    }                    
                } else {
                    if (parmetreTemplateSite != "") {
                        $('.passwordActuel').removeClass("validInputInfoCompte").addClass("errorInputInfoCompte")
                    } else {
                        $('.ancienMP').attr('src', '/ressource/image/webshop/ic_error.png');
                    } 
                }
                masquerChargement();
            }
        });
    });

    $('.identifiantActuel').blur(function () {
        //afficherChargement();
        $.ajax({
            url: '/webshop/verifierUniciteIdentifiant',
            data: {
                'identifiant': $('.identifiantActuel').val()
            },
            success: function (resultat) {
                $('.ancienIdentifiant').show();
                if (resultat == 'unique') {
                    if (parmetreTemplateSite != "") {
                        $('.identifiantActuel').removeClass("errorInputInfoCompte").addClass("validInputInfoCompte")
                    } else {
                        $('.ancienIdentifiant').attr('src', '/ressource/image/webshop/ic_valide.png');
                    }
                    verifierChampsPourModifierCompte = ''
                } else {
                    if (parmetreTemplateSite != "") {
                        $('.identifiantActuel').removeClass("validInputInfoCompte").addClass("errorInputInfoCompte")
                    } else {
                        $('.ancienIdentifiant').attr('src', '/ressource/image/webshop/ic_error.png');
                    }
                    verifierChampsPourModifierCompte = 'nonUnique';
                }
                masquerChargement();
            }
        });
    });
 

    $('.nouveauPassword').blur(function () {
        $('.nouveauMP').show();
        if ($('.nouveauPassword').val().trim().length < 6 // Au moins 6 caractères
            || regMajuscule.exec($('.nouveauPassword').val()) == null  // Au moins une majuscule
            || regMinuscule.exec($('.nouveauPassword').val()) == null // Au moins une minuscule
            || regChiffre.exec($('.nouveauPassword').val()) == null // Au moins un chiffre
        ) {
            if (parmetreTemplateSite != "") {
                $('.nouveauPassword').removeClass("validInputInfoCompte").addClass("errorInputInfoCompte")
            } else {
                $('.nouveauMP').attr('src', '/ressource/image/webshop/ic_error.png');
            }
        } else {
            if (parmetreTemplateSite != "") {
                $('.nouveauPassword').removeClass("errorInputInfoCompte").addClass("validInputInfoCompte")
            } else {
                $('.nouveauMP').attr('src', '/ressource/image/webshop/ic_valide.png');
            }
        }
    });
    $('.confirmerPassword').blur(function () {
        $('.confirmerMP').show();
        if ($('.confirmerPassword').val().trim().length < 6 // Au moins 6 caractères
            || regMajuscule.exec($('.confirmerPassword').val()) == null // Au moins une majuscule
            || regMinuscule.exec($('.confirmerPassword').val()) == null // Au moins une minuscule
            || regChiffre.exec($('.confirmerPassword').val()) == null // Au moins un chiffre
            || $('.nouveauPassword').val() != $('.confirmerPassword').val()
        ) {
            if (parmetreTemplateSite != "") {
                $('.confirmerPassword').removeClass("validInputInfoCompte").addClass("errorInputInfoCompte")
            } else {
                $('.confirmerMP').attr('src', '/ressource/image/webshop/ic_error.png');
            }
        } else {
            if (parmetreTemplateSite != "") {
                $('.confirmerPassword').removeClass("errorInputInfoCompte").addClass("validInputInfoCompte")
            } else {
                $('.confirmerMP').attr('src', '/ressource/image/webshop/ic_valide.png');
            }
        }
    });

    // Paramètres compte
    $('.parametreAvecValeur').each(function () {
        $(this).css('visibility', 'visible');
    });
    
}

function afficherMonCompte() {
    desactiverModeModal();
    $('#contenuPanier').hide();
    $('#contenuBlockBas').hide();
    $('#blockMonCompteAccueil').show();
    fermerBlockMenuConnection();
    afficherChargement();
    $.ajax({
        url: '/webshop/afficherMonCompte',
        success: function (resultat) {
            $('#catalogues').hide();
            $('#listeProduits').hide();
            $('#affichagePageDesCommandes').hide();
	        $('#tableauListeClientsWebshop').hide();
	        $('#labelListeDesClients').hide();
            $('#blockMonCompteAccueil').html(resultat);
            masquerChargement();
        }
    });
}
function envoyerPasswordWebshop(numeroSociete) {
    messageErreur = '';
    erreur = false;
    if ($('.passwordActuel').val() != "" || $('.nouveauPassword').val() != "" || $('.confirmerPassword').val() != "") {
        $('.inputCompte').each(function () {
            if ($(this).val() == '') {
                erreur = true;
            }
        });
        if (erreur == true) {
            messageErreur += TOUS_LES_CHAMPS_DOIVENT_ETRE_REMPLIS + '.</br>';
        }

        if ($('.nouveauPassword').val() != $('.confirmerPassword').val()) {
            messageErreur += MOT_PASSE_ET_SA_CONFIRMATION_NE_SONT_PAS_IDENTIQUES + '.</br>'; ;
            $('.confirmerPassword').addClass('erreurSaisie');
        } else if (
            $('.nouveauPassword').val().trim().length < 6 || $('.confirmerPassword').val().trim().length < 6 // Au moins 6 caractères
                || regMajuscule.exec($('.nouveauPassword').val()) == null || regMajuscule.exec($('.confirmerPassword').val()) == null // Au moins une majuscule
                || regMinuscule.exec($('.nouveauPassword').val()) == null || regMinuscule.exec($('.confirmerPassword').val()) == null // Au moins une minuscule
                || regChiffre.exec($('.nouveauPassword').val()) == null || regChiffre.exec($('.confirmerPassword').val()) == null // Au moins un chiffre
            ) {
            messageErreur += MOT_DE_PASSE_DOIT_AVOIR_AU_MOINS_6_CARACTERES_1_MAJUSCULE_1_MINUSCULE_1_CHIFFRE + '.<br/>';
            $('.nouveauPassword').addClass('erreurSaisie');
            $('.confirmerPassword').addClass('erreurSaisie');
        }
        if (verifierChampsPourModifierCompte == 'nonUnique') {
            messageErreur += IDENTIFIANT_EXISTE + '.<br/>';
            $('.identifiantActuel').addClass('erreurSaisie');
        }
        // Paramètres compte
        //SeparateurSaisi = 'SeparateurSaisi';
        listeDesIdParametres = '';
        listeDesNombreDesValeursSelectionnable = '';
        listeDesIdValeursParametres = '';
        listeDesValeursLibres = '';
        listeDesValeursLibres2 = '';
        if (messageErreur == '') {
            $('select[id*="parametre-"] option:selected').each(function () {
                if ($(this).hasClass('modeCodeRepresentant')) {
                    listeDesIdParametres += $(this).parent().attr('id').split('-')[2] + SEPARATEUR_SAISI;
                    listeDesNombreDesValeursSelectionnable += $(this).parent().attr('id').split('-')[1];
                    listeDesIdValeursParametres += -1 + SEPARATEUR_SAISI;
                    listeDesValeursLibres += $(this).val() + SEPARATEUR_SAISI;
                    listeDesValeursLibres2 += '' + SEPARATEUR_SAISI;
                } else if ($(this).val() != PREMIERE_VALEUR_COMBOBOX && !$(this).hasClass('aUnValeurParDefaut')) {
                    listeDesIdParametres += $(this).parent().attr('id').split('-')[2] + SEPARATEUR_SAISI;
                    listeDesNombreDesValeursSelectionnable += $(this).parent().attr('id').split('-')[1];
                    listeDesIdValeursParametres += $(this).val() + SEPARATEUR_SAISI;
                    listeDesValeursLibres += '' + SEPARATEUR_SAISI;
                    listeDesValeursLibres2 += '' + SEPARATEUR_SAISI;
                }
                if ($(this).val() == PREMIERE_VALEUR_COMBOBOX && $(this).hasClass('aUnValeurParDefaut')) {
                    variableGlobale_listeDesIdParametresSupprimes += $(this).parent().attr('id').split('-')[2] + SEPARATEUR_SAISI;
                }

            });



            // Critere textarea & inputext
            $('input[id*="parametre-"]').each(function () {
                if (($(this).attr('id').split('-')[1] == VALEUR_DE_TYPE_COULEUR && variableGlobale_listeDesIdParametresCouleur.indexOf($(this).attr('id').split('-')[2] + SEPARATEUR_SAISI) != -1)
            || ($(this).attr('id').split('-')[1] != VALEUR_DE_TYPE_COULEUR && $(this).val() != '') || ($(this).attr('id').split('-')[1] == VALEUR_DE_TYPE_EMAIL && $(this).val() != '')
        ) {
                    listeDesIdParametres += $(this).attr('id').split('-')[2] + SEPARATEUR_SAISI;
                    listeDesNombreDesValeursSelectionnable += $(this).attr('id').split('-')[1];
                    listeDesIdValeursParametres += -1 + SEPARATEUR_SAISI;
                    listeDesValeursLibres += $(this).val() + SEPARATEUR_SAISI;
                }
            });

            //Checkbox liste valeurs selectionnables
            $('input[id*="valeur-"]:checked').each(function () {
                listeDesIdParametres += $(this).closest('div').attr('id').split('-')[2] + SEPARATEUR_SAISI;
                listeDesNombreDesValeursSelectionnable += $(this).closest('div').attr('id').split('-')[1];
                listeDesIdValeursParametres += $(this).attr('id').split('-')[2] + SEPARATEUR_SAISI;
                listeDesValeursLibres += '' + SEPARATEUR_SAISI;
                listeDesValeursLibres2 += '' + SEPARATEUR_SAISI;

            });
        }
        if (messageErreur == '') {
            $.ajax({
                url: '/webshop/changerMonMotDePasse',
                data: {
                    'motDePasseActuel': $('.passwordActuel').val(),
                    'nouveauMotDePasse': $('.nouveauPassword').val(),
                    'confirmerMotDePasse': $('.confirmerPassword').val(),
                    'identifiantActuel': $('.identifiantActuel').val(),
                    // Paramètres compte
                    'listeDesIdParametres': listeDesIdParametres,
                    'listeDesIdValeursParametres': listeDesIdValeursParametres,
                    'listeDesValeursLibres': listeDesValeursLibres,
                    'listeDesNombreDesValeursSelectionnable': listeDesNombreDesValeursSelectionnable,
                    'listeDesIdParametresSupprimes': variableGlobale_listeDesIdParametresSupprimes,
                    'listeDesValeursLibres2': listeDesValeursLibres2
                },
                success: function (message) {
                    if (message == 'OK') {
                        retourCatalogueAvecRaffraichissementParametresSession(numeroSociete)
                    } else {
                        $(':password').each(function () {
                            $(this).val('');
                        });
                        alerte(message, 'erreur');

                    }
                    masquerChargement();
                }
            });
        } else {
            alerte(messageErreur, 'erreur');
        }

    } else {
        envoyerParametreWebshop(numeroSociete);
    }

   

}
function envoyerParametreWebshop(numeroSociete) {
    // Paramètres compte
    //SeparateurSaisi = 'SeparateurSaisi';
    listeDesIdParametres = '';
    listeDesNombreDesValeursSelectionnable = '';
    listeDesIdValeursParametres = '';
    listeDesValeursLibres = '';
    listeDesValeursLibres2 = '';
    $('select[id*="parametre-"] option:selected').each(function () {
        if ($(this).hasClass('modeCodeRepresentant')) {
            listeDesIdParametres += $(this).parent().attr('id').split('-')[2] + SEPARATEUR_SAISI;
            listeDesNombreDesValeursSelectionnable += $(this).parent().attr('id').split('-')[1];
            listeDesIdValeursParametres += -1 + SEPARATEUR_SAISI;
            listeDesValeursLibres += $(this).val() + SEPARATEUR_SAISI;
            listeDesValeursLibres2 += '' + SEPARATEUR_SAISI;
        } else if ($(this).val() != PREMIERE_VALEUR_COMBOBOX && !$(this).hasClass('aUnValeurParDefaut')) {
            listeDesIdParametres += $(this).parent().attr('id').split('-')[2] + SEPARATEUR_SAISI;
            listeDesNombreDesValeursSelectionnable += $(this).parent().attr('id').split('-')[1];
            listeDesIdValeursParametres += $(this).val() + SEPARATEUR_SAISI;
            listeDesValeursLibres += '' + SEPARATEUR_SAISI;
            listeDesValeursLibres2 += '' + SEPARATEUR_SAISI;
        }
        if ($(this).val() == PREMIERE_VALEUR_COMBOBOX && $(this).hasClass('aUnValeurParDefaut')) {
            variableGlobale_listeDesIdParametresSupprimes += $(this).parent().attr('id').split('-')[2] + SEPARATEUR_SAISI;
        }

    });



    // Critere textarea & inputext
    $('input[id*="parametre-"]').each(function () {
        if (($(this).attr('id').split('-')[1] == VALEUR_DE_TYPE_COULEUR && variableGlobale_listeDesIdParametresCouleur.indexOf($(this).attr('id').split('-')[2] + SEPARATEUR_SAISI) != -1)
        || ($(this).attr('id').split('-')[1] != VALEUR_DE_TYPE_COULEUR && $(this).val() != '') || ($(this).attr('id').split('-')[1] == VALEUR_DE_TYPE_EMAIL && $(this).val() != '')
    ) {
            listeDesIdParametres += $(this).attr('id').split('-')[2] + SEPARATEUR_SAISI;
            listeDesNombreDesValeursSelectionnable += $(this).attr('id').split('-')[1];
            listeDesIdValeursParametres += -1 + SEPARATEUR_SAISI;
            listeDesValeursLibres += $(this).val() + SEPARATEUR_SAISI;
        }
    });

    //Checkbox liste valeurs selectionnables
    $('input[id*="valeur-"]:checked').each(function () {
        listeDesIdParametres += $(this).closest('div').attr('id').split('-')[2] + SEPARATEUR_SAISI;
        listeDesNombreDesValeursSelectionnable += $(this).closest('div').attr('id').split('-')[1];
        listeDesIdValeursParametres += $(this).attr('id').split('-')[2] + SEPARATEUR_SAISI;
        listeDesValeursLibres += '' + SEPARATEUR_SAISI;
        listeDesValeursLibres2 += '' + SEPARATEUR_SAISI;

    });

    $.ajax({
        url: '/webshop/changerMesParametresClient',
        data: {
            // Paramètres compte
            'listeDesIdParametres': listeDesIdParametres,
            'listeDesIdValeursParametres': listeDesIdValeursParametres,
            'listeDesValeursLibres': listeDesValeursLibres,
            'listeDesNombreDesValeursSelectionnable': listeDesNombreDesValeursSelectionnable,
            'listeDesIdParametresSupprimes': variableGlobale_listeDesIdParametresSupprimes,
            'listeDesValeursLibres2': listeDesValeursLibres2
        },
        success: function (message) {
            if (message == 'OK') {
                retourCatalogueAvecRaffraichissementParametresSession(numeroSociete)
            } 
            masquerChargement();
        }
    });
    
}
function retourCatalogueAvecRaffraichissementParametresSession(numeroSociete) {

    afficherChargement();
    $.ajax({
        url: '/webshop/accueil?numeroSociete=' + numeroSociete,
        success: function (resultat) {
            $('body').html(resultat);
            masquerChargement();
            alerte(LES_MODIFICATIONS_ONT_BIEN_ETE_PRISES_EN_COMPTE);
        }
    });
}
function retourCatalogue() {
    $('#blockMonCompteAccueil').hide();
    $('#contenuBlockBas').show();
    $('#catalogues').show();
    $('#listeProduits').show();
    if (typeof saisieEnModeSemaine == "undefined" || saisieEnModeSemaine !== "True") {
        if (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR != 'True' && EST_CONNECTE == 'True' && $('#dateLivraison').val() == '' && changementDateDeLivraison == "False") {
            if (preinitialiserDateLivraison == "False") {
                if (sourceChargement == "") {
                    if (obligatoireInitialiserDate != "False") {
                        jQuery('#dateLivraison').datepicker("show");
                        activerModeModal();
                    }
                }
            }
        }
    }
}


var enteteModesExpeditionsInitialisee = false;
var listeModeExpeditionWebshopAAjouter = new Array();
function initialisationPageListeModesExpeditions() {
    enteteModesExpeditionsInitialisee = false; 

    // Cabler la librairie dataTables sur le tableau
    $('.contenuPage').hide();
    etatDuTableau = tableauListeModesExpeditions;

    tableauindice = retournerIndiceTableau(idTableauHtml);

    pageSelectionnee = retournerdebutPage(tableauindice);

    tableauModesExpeditions = $('#' + idTableauHtml).DataTable({
        'order': [],
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'columns': [
            { 'className': 'width40 numeriqueTri' },
            { 'className': 'width40' },
            { 'className': 'width135 colonneAvecLargeurSpecifique' }
    ],

        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // w<"clear"> pour activer le choix de visibilité des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"CW<"clear">TlftipR>rt',
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        'paginationType': 'full_numbers',
        // Spécifier la première page d'affichage
        'displayStart': parseInt(pageSelectionnee),
        // Export de Datatable sous plusieurs format
        'tableTools': {
            // Attribuer les évènements aux bouttons d'export (csv, pdf, Excel)
            'sSwfPath': '/ressource/js/librairie/DataTables-1.10.0/extras/TableTools-2.2.1/swf/copy_csv_xls_pdf.swf',
            'aButtons': [
            // Definir les colonnes qu'on souhaite exporter
            {'sExtends': 'copy', 'sButtonText': '', 'mColumns': [0, 1, 2], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
            { 'sExtends': 'csv', 'sButtonText': '', 'sFileName': LISTE_DES_MODES_EXPEDITIONS + '.csv', 'sTitle': LISTE_DES_MODES_EXPEDITIONS, 'mColumns': [0, 1, 2], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
            { 'sExtends': 'xls', 'sButtonText': '', 'sFileName': LISTE_DES_MODES_EXPEDITIONS + '.xls', 'sTitle': LISTE_DES_MODES_EXPEDITIONS, 'mColumns': [0, 1, 2], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
            { 'sExtends': 'pdf', 'sButtonText': '', 'sFileName': LISTE_DES_MODES_EXPEDITIONS + '.pdf', 'sTitle': LISTE_DES_MODES_EXPEDITIONS, 'mColumns': [0, 1, 2], 'oSelectorOpts': { filter: 'applied', order: 'current'} }
        ]
        },
        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        // Options sur les filtres
        'oColumnFilterWidgets': {
            //  'bGroupTerms': true, // pour activer le groupage sur les filtres
            //'aiExclude': [] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        },
        // Options sur la visibilité des colonnes
        'colVis': {
            //'exclude': [], // spécifier les colonnes qui ne figurent pas dans la visibilité des colonnes
            'buttonText': AFFICHER_MASQUER_COLONNES,
            //Gestion Des Filtres Par Colonne Et Visibilite
            'fnStateChange': function (iColumn, bVisible) {
                gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, tableauModesExpeditions.settings()[0]);
            }
        },
        'colReorder': {
            'realtime': true
        },
        'headerCallback': function (thead, data, start, end, display) {
            if (enteteModesExpeditionsInitialisee == false || tableauDesLargeuresEtIndicesModesExpeditions == "reinitialisé") {
                enteteModesExpeditionsInitialisee = true;
                titresColonnesSauveguarde = titresColonnesModesExpeditions;
                titresColonnesModesExpeditions = [];
                largeurParDefaut = 0;
                tableauDesLargeuresEtIndicesChargementModesExpeditions = [];
                indiceColonnes = 0;
                $(thead).find('th').each(function () {
                    if (tableauDesLargeuresEtIndicesModesExpeditions == "reinitialisé") {
                        largeurParDefaut = titresColonnesSauveguarde[indiceColonnes].split(";")[2];
                        indiceColonnes++;
                    } else {
                        largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                        largeurParDefaut = (largeurParDefaut == null ? 0 : largeurParDefaut[0].replace("width", ""));
                    }
                    largeurActuellementAppliquee = (tableauDesLargeuresEtIndicesModesExpeditions == "reinitialisé" ? largeurParDefaut : largeurActuel(idTableauHtml, etatDuTableau, $(this).data("origColHeader"), largeurParDefaut));
                    titresColonnesModesExpeditions.push($(this).html().ltrim().rtrim() + ";" + $(this).data("origColHeader") + ";" + largeurParDefaut + ";" + largeurActuellementAppliquee);
                });
                titresColonnesModesExpeditions = colonnesVisiblesOuPas(etatDuTableau, titresColonnesModesExpeditions, idTableauHtml);
                tableau = [];
                for (i = 0; i < titresColonnesModesExpeditions.length; i++) {
                    tableau = titresColonnesModesExpeditions[i].split(";");
                    tableauDesLargeuresEtIndicesChargementModesExpeditions.push(tableau[1] + ";" + tableau[3]);
                }
                tableauDesLargeuresEtIndicesModesExpeditions = (tableauDesLargeuresEtIndicesModesExpeditions != "reinitialisé" ? tableauDesLargeuresEtIndicesChargementModesExpeditions.join('|') : tableauDesLargeuresEtIndicesModesExpeditions);
            }
        },
        'initComplete': function (oSettings, oData) {
            fnOrdonnerColonnes(idTableauHtml, etatDuTableau);
            $(this).css('visibility', 'visible');
            materialiserChampsDeRecherche(idTableauHtml);
            initialiserCoVis(idTableauHtml);
            // Ne pas tenir compte des filtres dans la sauvegarde d'état du tableau
            // Je n'ai pas l'explication mais si l'appel à la méthode se fait en dehors d'un setTimeout alors exception JS
            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(tableauModesExpeditions, true, idTableauHtml, etatDuTableau); }, 0);

        },
        'drawCallback': function (oSettings) {
            forcerCablagePagination(idTableauHtml);

            if (etatDuTableau != '""' && etatDuTableau != null && tableauDesLargeuresEtIndicesModesExpeditions != "reinitialisé") {
                etatDuTableau = etatDuTableau.split("\\").join("");
                etatDuTableau = etatDuTableau.split("^(").join("");
                etatDuTableau = etatDuTableau.split(")$").join("");
                oState = JSON.parse(etatDuTableau);
                if (oState.hasOwnProperty('ColWidth') && typeof oState.ColWidth !== 'undefined') {
                    if (oState.ColWidth.length > 0) {
                        appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesModesExpeditions);

                    }
                }
            } else if (tableauDesLargeuresEtIndicesModesExpeditions == "reinitialisé") {

                indiceColonne = 1;
                $('#' + idTableauHtml).find('thead').find('tr:nth-child(1)').find('th').each(function () {
                    largeurParDefaut = "width" + $(this).data("widthHeader");
                    $('#' + idTableauHtml).find('tfoot').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('tbody').find('td:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('thead').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    indiceColonne++;

                });

                tableauDesLargeuresEtIndicesChargementModesExpeditions = [];
                for (i = 0; i < titresColonnesModesExpeditions.length; i++) {
                    tableau = titresColonnesModesExpeditions[i].split(";");
                    tableauDesLargeuresEtIndicesChargementModesExpeditions.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesModesExpeditions = tableauDesLargeuresEtIndicesChargementModesExpeditions.join('|');


            } else {
                appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesModesExpeditions);
            }

        }
    });

    $('.enTeteColonneCliquable').attr('title', CLIQUER_POUR_TRIER_SUR_LA_COLONNE_OU_MAINTENIR_POUR_DEPLACER_LA_COLONNE);

}

function afficherModesExpeditionsWebshop() {
    afficherChargement();
    $('#listeModesExpeditionsWebshop #divDetails').html('');
    $.ajax({
        url: '/webshop/listeDesModesExpeditions',
        async: false,
        success: function (resultat) {
            $('#listeModesExpeditionsWebshop #divDetails').html(resultat);
            masquerChargement();
        }
    });
}
function selectionnerModeExpeditionPourWebshop(numeroModeExpedition) {
    if ($('.modeExpedition').get(0)) {
        listeId = new Array();
        $('#listeDesModesExpeditionsWebshop .modeExpedition').each(function () {
            listeId.push(parseInt($(this).attr('id')));
        });
        index = listeId.indexOf(parseInt(numeroModeExpedition));

        if (index > -1) {
            alerte(CE_MODE_D_EXPEDITION_EST_DEJA_AFFICHE);
        } else {
        $.ajax({
            url: '/webshop/recupererModeExpedition',
            data: {
                'numeroModeExpedition': numeroModeExpedition
            },
            success: function (resultat) {
                masquerChargement();
                unModeExpeditionWebshop = "<span id=" + numeroModeExpedition + " class=\"modeExpedition\">" + resultat +
                                " <input value=\"" + numeroModeExpedition + "\" type=\"radio\" name=\"modeExpeditionParDefaut\" />" +
                                " <img class=\"cursorPointer boutonSupprimerParametre\"  src=\"/ressource/image/commun/supprimer.png\" alt=\"\" " +
                                " onclick=\"afficherSupprimerModeExpeditionWebshop(" + numeroModeExpedition + ");\" /></span><br/>";
                $('#listeDesModesExpeditionsWebshop').append(unModeExpeditionWebshop);
                $('.modeExpedition .boutonSupprimerParametre').css('visibility', 'visible');

            }
        });
            listeModeExpeditionWebshopAAjouter.push(numeroModeExpedition);

        }

    } else {
        $.ajax({
            url: '/webshop/recupererModeExpedition',
            data: {
                'numeroModeExpedition': numeroModeExpedition
            },
            success: function (resultat) {
                masquerChargement();
                unModeExpeditionWebshop = "<span id=" + numeroModeExpedition + " class=\"modeExpedition\">" + resultat +
                                " <input value=\"" + numeroModeExpedition + "\" type=\"radio\" name=\"modeExpeditionParDefaut\" checked=\"checked\" />" +
                                " <img class=\"cursorPointer boutonSupprimerParametre\"  src=\"/ressource/image/commun/supprimer.png\" alt=\"\" " +
                                " onclick=\"afficherSupprimerModeExpeditionWebshop(" + numeroModeExpedition + ");\" /></span><br/>";
                $('#listeDesModesExpeditionsWebshop').append(unModeExpeditionWebshop);
                $('.modeExpedition .boutonSupprimerParametre').css('visibility', 'visible');
            }
        });
        listeModeExpeditionWebshopAAjouter.push(numeroModeExpedition);

    }
    fermerPopup();
    masquerChargement();
}
var enteteCumulsEmballagesInitialisee = false;
function initialisationPageListeCumulsEmballages() {
    enteteCumulsEmballagesInitialisee = false;

    // Cabler la librairie dataTables sur le tableau
    $('.contenuPage').hide();
    etatDuTableau = tableauListeCumulsEmballages;

    tableauindice = retournerIndiceTableau(idTableauHtml);

    pageSelectionnee = retournerdebutPage(tableauindice);

    tableauCumulsEmballages = $('#' + idTableauHtml).DataTable({
        'order': [],
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'columns': [
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width135 numeriqueTri' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width150 colonneAvecLargeurSpecifique' }
    ],

        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // w<"clear"> pour activer le choix de visibilité des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"CW<"clear">TlftipR>rt',
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        'paginationType': 'full_numbers',
        // Spécifier la première page d'affichage
        'displayStart': parseInt(pageSelectionnee),
        // Export de Datatable sous plusieurs format
        'tableTools': {
            // Attribuer les évènements aux bouttons d'export (csv, pdf, Excel)
            'sSwfPath': '/ressource/js/librairie/DataTables-1.10.0/extras/TableTools-2.2.1/swf/copy_csv_xls_pdf.swf',
            'aButtons': [
            // Definir les colonnes qu'on souhaite exporter
            {'sExtends': 'copy', 'sButtonText': '', 'mColumns': [0, 1, 2, 3, 4], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
            { 'sExtends': 'csv', 'sButtonText': '', 'sFileName': LISTE_DES_CUMULS_EMBALLAGES + '.csv', 'sTitle': LISTE_DES_CUMULS_EMBALLAGES, 'mColumns': [0, 1, 2, 3, 4], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
            { 'sExtends': 'xls', 'sButtonText': '', 'sFileName': LISTE_DES_CUMULS_EMBALLAGES + '.xls', 'sTitle': LISTE_DES_CUMULS_EMBALLAGES, 'mColumns': [0, 1, 2, 3, 4], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
            { 'sExtends': 'pdf', 'sButtonText': '', 'sFileName': LISTE_DES_CUMULS_EMBALLAGES + '.pdf', 'sTitle': LISTE_DES_CUMULS_EMBALLAGES, 'mColumns': [0, 1, 2, 3, 4], 'oSelectorOpts': { filter: 'applied', order: 'current'} }
        ]
        },
        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        // Options sur les filtres
        'oColumnFilterWidgets': {
            //  'bGroupTerms': true, // pour activer le groupage sur les filtres
            'aiExclude': [5] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        },
        // Options sur la visibilité des colonnes
        'colVis': {
            'exclude': [], // spécifier les colonnes qui ne figurent pas dans la visibilité des colonnes
            'buttonText': AFFICHER_MASQUER_COLONNES,
            //Gestion Des Filtres Par Colonne Et Visibilite
            'fnStateChange': function (iColumn, bVisible) {
                gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, tableauCumulsEmballages.settings()[0]);
            }
        },
        'colReorder': {
            'realtime': true
        },
        'headerCallback': function (thead, data, start, end, display) {
            if (enteteCumulsEmballagesInitialisee == false || tableauDesLargeuresEtIndicesCumulsEmballages == "reinitialisé") {
                enteteCumulsEmballagesInitialisee = true;
                titresColonnesSauveguarde = titresColonnesCumulsEmballages;
                titresColonnesCumulsEmballages = [];
                largeurParDefaut = 0;
                tableauDesLargeuresEtIndicesChargementCumulsEmballages = [];
                indiceColonnes = 0;
                $(thead).find('th').each(function () {
                    if (tableauDesLargeuresEtIndicesCumulsEmballages == "reinitialisé") {
                        largeurParDefaut = titresColonnesSauveguarde[indiceColonnes].split(";")[2];
                        indiceColonnes++;
                    } else {
                        largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                        largeurParDefaut = (largeurParDefaut == null ? 0 : largeurParDefaut[0].replace("width", ""));
                    }
                    largeurActuellementAppliquee = (tableauDesLargeuresEtIndicesCumulsEmballages == "reinitialisé" ? largeurParDefaut : largeurActuel(idTableauHtml, etatDuTableau, $(this).data("origColHeader"), largeurParDefaut));
                    titresColonnesCumulsEmballages.push($(this).html().ltrim().rtrim() + ";" + $(this).data("origColHeader") + ";" + largeurParDefaut + ";" + largeurActuellementAppliquee);
                });
                titresColonnesCumulsEmballages = colonnesVisiblesOuPas(etatDuTableau, titresColonnesCumulsEmballages, idTableauHtml);
                tableau = [];
                for (i = 0; i < titresColonnesCumulsEmballages.length; i++) {
                    tableau = titresColonnesCumulsEmballages[i].split(";");
                    tableauDesLargeuresEtIndicesChargementCumulsEmballages.push(tableau[1] + ";" + tableau[3]);
                }
                tableauDesLargeuresEtIndicesCumulsEmballages = (tableauDesLargeuresEtIndicesCumulsEmballages != "reinitialisé" ? tableauDesLargeuresEtIndicesChargementCumulsEmballages.join('|') : tableauDesLargeuresEtIndicesCumulsEmballages);
            }
        },
        'initComplete': function (oSettings, oData) {
            fnOrdonnerColonnes(idTableauHtml, etatDuTableau);
            $(this).css('visibility', 'visible');
            materialiserChampsDeRecherche(idTableauHtml);
            initialiserCoVis(idTableauHtml);
            // Ne pas tenir compte des filtres dans la sauvegarde d'état du tableau
            // Je n'ai pas l'explication mais si l'appel à la méthode se fait en dehors d'un setTimeout alors exception JS
            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(tableauCumulsEmballages, true, idTableauHtml, etatDuTableau); }, 0);

        },
        'drawCallback': function (oSettings) {
            forcerCablagePagination(idTableauHtml);

            if (etatDuTableau != '""' && etatDuTableau != null && tableauDesLargeuresEtIndicesCumulsEmballages != "reinitialisé") {
                etatDuTableau = etatDuTableau.split("\\").join("");
                etatDuTableau = etatDuTableau.split("^(").join("");
                etatDuTableau = etatDuTableau.split(")$").join("");
                oState = JSON.parse(etatDuTableau);
                if (oState.hasOwnProperty('ColWidth') && typeof oState.ColWidth !== 'undefined') {
                    if (oState.ColWidth.length > 0) {
                        appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesCumulsEmballages);

                    }
                }
            } else if (tableauDesLargeuresEtIndicesCumulsEmballages == "reinitialisé") {

                indiceColonne = 1;
                $('#' + idTableauHtml).find('thead').find('tr:nth-child(1)').find('th').each(function () {
                    largeurParDefaut = "width" + $(this).data("widthHeader");
                    $('#' + idTableauHtml).find('tfoot').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('tbody').find('td:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('thead').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    indiceColonne++;

                });

                tableauDesLargeuresEtIndicesChargementCumulsEmballages = [];
                for (i = 0; i < titresColonnesCumulsEmballages.length; i++) {
                    tableau = titresColonnesCumulsEmballages[i].split(";");
                    tableauDesLargeuresEtIndicesChargementCumulsEmballages.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesCumulsEmballages = tableauDesLargeuresEtIndicesChargementCumulsEmballages.join('|');


            } else {
                appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesCumulsEmballages);
            }

        }
    });

    $('.enTeteColonneCliquable').attr('title', CLIQUER_POUR_TRIER_SUR_LA_COLONNE_OU_MAINTENIR_POUR_DEPLACER_LA_COLONNE);

}

function initialisationPageCumulsEmballages() {
    //setTimeout(function () { $('.picto').css('display', 'inline-block'); }, 10)
}
var enteteOperationsWebshopInitialisee = false;
function initialisationPageListeDesOperationsWebshop() {
    if (typeof ($('#blockRecapitulatifCommande').html()) !== 'undefined' && $('#blockRecapitulatifCommande').html().indexOf("recapCommande") > -1) {
        activerLesChampsDePanier();
    }
    enteteOperationsWebshopInitialisee = false;
    $('.contenuPage').hide();
    tableauindice = retournerIndiceTableau('tableauListeDesOperationsWebshop');
    etatDuTableau = tableauListeDesOperationsWebshop;
    idTableauHtml = "tableauListeDesOperationsWebshop";
    pageSelectionnee = retournerdebutPage(tableauindice);

    listeDesOperationsWebshop = $('#tableauListeDesOperationsWebshop').DataTable({
        'order': [],
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'columns': [
            { 'className': 'width40 numeriqueTri' },
            { 'className': 'width100' },
            { 'className': 'width135' },
            { 'type': 'date-euro', 'className': 'width135' },
            { 'type': 'date-euro', 'className': 'width135' },
            { 'type': 'date-euro', 'className': 'width135 dateTri' },
            { 'type': 'date-euro', 'className': 'width135 dateTri' },
            { 'type': 'date-euro', 'className': 'width135 dateTri' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'orderable': false, 'className': 'width10 colonneAvecLargeurSpecifique' }


        ],
        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // w<"clear"> pour activer le choix de visibilité des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"CTltpR>rt',
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        'paginationType': 'full_numbers',
        // Export de Datatable sous plusieurs format
        'oTableTools': {
            // Attribuer les évènements aux bouttons d'export (csv, pdf, Excel)
            'sSwfPath': '/ressource/js/librairie/DataTables-1.10.0/extras/TableTools-2.2.1/swf/copy_csv_xls_pdf.swf',
            'aButtons': [
            // Definir les colonnes qu'on souhaite exporter
                {'sExtends': 'copy', 'sButtonText': '', 'mColumns': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'csv', 'sButtonText': '', 'sFileName': MA_LISTE_D_OPERATIONS + '.csv', 'sTitle': MA_LISTE_D_OPERATIONS, 'mColumns': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,16], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'xls', 'sButtonText': '', 'sFileName': MA_LISTE_D_OPERATIONS + '.xls', 'sTitle': MA_LISTE_D_OPERATIONS, 'mColumns': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'pdf', 'sButtonText': '', 'sFileName': MA_LISTE_D_OPERATIONS + '.pdf', 'sTitle': MA_LISTE_D_OPERATIONS, 'mColumns': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 'oSelectorOpts': { filter: 'applied', order: 'current'} }
            ]
        },
        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        // Spécifier la première page d'affichage
        'displayStart': parseInt(pageSelectionnee),
        // Options sur les filtres
        //        'oColumnFilterWidgets': {
        //            //'bGroupTerms': true, // pour activer le groupage sur les filtres
        //            'aiExclude': [7] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        //        },
        // Options sur la visibilité des colonnes
        'colVis': {
            //'exclude', // spécifier les colonnes qui ne figurent pas dans la visibilité des colonnes
            'buttonText': AFFICHER_MASQUER_COLONNES,
            //Gestion Des Filtres Par Colonne Et Visibilite
            'fnStateChange': function (iColumn, bVisible) {
                gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, listeDesOperationsWebshop.settings()[0]);
            }
        },
        'oColumnFilterWidgets': {
            //'bGroupTerms': true, // pour activer le groupage sur les filtres
            //'aiExclude': [] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        },
        'colReorder': {
            'realtime': true
        },
        'headerCallback': function (thead, data, start, end, display) {
            if (enteteOperationsWebshopInitialisee == false || tableauDesLargeuresEtIndicesOperationsWebshop == "reinitialisé") {
                enteteOperationsWebshopInitialisee = true;
                titresColonnesSauveguarde = titresColonnesOperationsWebshop;
                titresColonnesOperationsWebshop = [];
                largeurParDefaut = 0;
                tableauDesLargeuresEtIndicesChargementOperationsWebshop = [];
                indiceColonnes = 0;
                $(thead).find('th').each(function () {
                    if (tableauDesLargeuresEtIndicesOperationsWebshop == "reinitialisé") {
                        largeurParDefaut = titresColonnesSauveguarde[indiceColonnes].split(";")[2];
                        indiceColonnes++;
                    } else {
                        largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                        largeurParDefaut = (largeurParDefaut == null ? 0 : largeurParDefaut[0].replace("width", ""));
                    }
                    largeurActuellementAppliquee = (tableauDesLargeuresEtIndicesOperationsWebshop == "reinitialisé" ? largeurParDefaut : largeurActuel(idTableauHtml, etatDuTableau, $(this).data("origColHeader"), largeurParDefaut));
                    titresColonnesOperationsWebshop.push($(this).html().ltrim().rtrim() + ";" + $(this).data("origColHeader") + ";" + largeurParDefaut + ";" + largeurActuellementAppliquee);

                });
                titresColonnesOperationsWebshop = colonnesVisiblesOuPas(etatDuTableau, titresColonnesOperationsWebshop, idTableauHtml);
                tableau = [];
                for (i = 0; i < titresColonnesOperationsWebshop.length; i++) {
                    tableau = titresColonnesOperationsWebshop[i].split(";");
                    tableauDesLargeuresEtIndicesChargementOperationsWebshop.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesOperationsWebshop = (tableauDesLargeuresEtIndicesOperationsWebshop != "reinitialisé" ? tableauDesLargeuresEtIndicesChargementOperationsWebshop.join('|') : tableauDesLargeuresEtIndicesOperationsWebshop);
            }
        },
        'initComplete': function (oSettings, oData) {
            fnOrdonnerColonnes('tableauListeDesOperationsWebshop', tableauListeDesOperationsWebshop);
            //$(this).css('visibility', 'visible');
            materialiserChampsDeRecherche('tableauListeDesOperationsWebshop', false);
            initialiserCoVis('tableauListeDesOperationsWebshop');
            // Ne pas tenir compte des filtres dans la sauvegarde d'état du tableau
            // Je n'ai pas l'explication mais si l'appel à la méthode se fait en dehors d'un setTimeout alors exception JS
            if ($('#tableauListeDesOperationsWebshop').find('.iconeInitialiserTableau').hasClass('iconesMasquees')) {
                $('#tableauListeDesOperationsWebshop').find('.iconeParametrage').hide();
            }
            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(listeDesOperationsWebshop, true, 'tableauListeDesOperationsWebshop', tableauListeDesOperationsWebshop); }, 0);
            
        },
        'drawCallback': function (oSettings) {
            //cette fonction prend en charge de masquer le loader de chargement et affiche la table après sa création

            //$('.contenuCaption').css('width', $('.dataTables_wrapper').width() - 20);
            forcerCablagePagination('tableauListeDesOperationsWebshop');

            if (etatDuTableau != '""' && etatDuTableau != null && tableauDesLargeuresEtIndicesOperationsWebshop != "reinitialisé") {
                etatDuTableau = etatDuTableau.split("\\").join("");
                etatDuTableau = etatDuTableau.split("^(").join("");
                etatDuTableau = etatDuTableau.split(")$").join("");
                oState = JSON.parse(etatDuTableau);
                if (oState.hasOwnProperty('ColWidth') && typeof oState.ColWidth !== 'undefined') {
                    if (oState.ColWidth.length > 0) {
                        appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesOperationsWebshop);

                    }
                }
            } else if (tableauDesLargeuresEtIndicesOperationsWebshop == "reinitialisé") {

                indiceColonne = 1;
                $('#' + idTableauHtml).find('thead').find('tr:nth-child(1)').find('th').each(function () {
                    largeurParDefaut = "width" + $(this).data("widthHeader");
                    $('#' + idTableauHtml).find('tfoot').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('tbody').find('td:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('thead').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    indiceColonne++;

                });

                tableauDesLargeuresEtIndicesChargementOperationsWebshop = [];
                for (i = 0; i < titresColonnesOperationsWebshop.length; i++) {
                    tableau = titresColonnesOperationsWebshop[i].split(";");
                    tableauDesLargeuresEtIndicesChargementOperationsWebshop.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesOperationsWebshop = tableauDesLargeuresEtIndicesChargementOperationsWebshop.join('|');


            } else {
                appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesOperationsWebshop);
            }
        }

    });
}
var enteteAdresseLivraisonInitialisee = false;
function initialiserListeAdresseLivraison() {
    enteteAdresseLivraisonInitialisee = false;
    tableauindice = retournerIndiceTableau(idTableauHtml);
    etatTableau = (idTableauHtml == 'tableauListeDesAdressesDeLivraison') ? tableauListeDesAdressesDeLivraison : tableauListeDesAdressesDeLivraisonWebshop;

    pageSelectionnee = retournerdebutPage(tableauindice);
    // Cabler la librairie dataTables sur le tableau
    tableauListeDesAdressesLivraison = $('#' + idTableauHtml).DataTable({
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'order': [],
        'columns': [
            { 'className': 'width40 numeriqueTri' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width135' },
            { 'className': 'width100' },
            { 'className': 'width140' },
            { 'className': 'width140' },
            { 'className': 'width140' },
            { 'className': 'width140' },
            { 'orderable': false, 'className': 'width10 colonneAvecLargeurSpecifique', 'visible': (idTableauHtml == 'tableauListeDesAdressesDeLivraison') ? true : false }
        ],
        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // w<"clear"> pour activer le choix de visibilité des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"CW<"clear">TlftipR>rt',
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        'paginationType': 'full_numbers',
        // Spécifier la première page d'affichage
        'displayStart': parseInt(pageSelectionnee),
        // Export de Datatable sous plusieurs format
        'oTableTools': {
            // Attribuer les évènements aux bouttons d'export (csv, pdf, Excel)
            'sSwfPath': '/ressource/js/librairie/DataTables-1.10.0/extras/TableTools-2.2.1/swf/copy_csv_xls_pdf.swf',
            'aButtons': [
            // Definir les colonnes qu'on souhaite exporter
                {'sExtends': 'copy', 'sButtonText': '', 'mColumns': [0, 1, 2, 3, 4, 5, 7, 8], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'csv', 'sButtonText': '', 'sFileName': MES_ADRESSES_LIVRAISONS + '.csv', 'sTitle': MES_ADRESSES_LIVRAISONS, 'mColumns': [0, 1, 2, 3, 4, 5, 7, 8], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'xls', 'sButtonText': '', 'sFileName': MES_ADRESSES_LIVRAISONS + '.xls', 'sTitle': MES_ADRESSES_LIVRAISONS, 'mColumns': [0, 1, 2, 3, 4, 5, 7, 8], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'pdf', 'sButtonText': '', 'sFileName': MES_ADRESSES_LIVRAISONS + '.pdf', 'sTitle': MES_ADRESSES_LIVRAISONS, 'mColumns': [0, 1, 2, 3, 4, 5, 7, 8], 'oSelectorOpts': { filter: 'applied', order: 'current'} }
            ]
        },
        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        // Options sur les filtres
        'oColumnFilterWidgets': {
            // 'bGroupTerms': true, // pour activer le groupage sur les filtres
            'aiExclude': [9] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        },
        // Options sur la visibilité des colonnes
        'colVis': {
            'exclude': [9], // spécifier les colonnes qui ne figurent pas dans la visibilité des colonnes
            'buttonText': AFFICHER_MASQUER_COLONNES,
            //Gestion Des Filtres Par Colonne Et Visibilite
            'fnStateChange': function (iColumn, bVisible) {
                gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, tableauListeDesAdressesLivraison.settings()[0]);
            }
        },
        'initComplete': function (oSettings, oData) {
            fnOrdonnerColonnes(idTableauHtml, etatTableau);
            $(this).css('visibility', 'visible');
            if (idTableauHtml == 'tableauListeDesAdressesDeLivraisonWebshop') {
                materialiserChampsDeRecherche(idTableauHtml, false);
            } else {
                materialiserChampsDeRecherche(idTableauHtml);
            }
            
            initialiserCoVis(idTableauHtml);
            // Ne pas tenir compte des filtres dans la sauvegarde d'état du tableau
            // Je n'ai pas l'explication mais si l'appel à la méthode se fait en dehors d'un setTimeout alors exception JS
            if (idTableauHtml == 'tableauListeDesAdressesDeLivraisonWebshop' && $('#tableauListeDesAdressesDeLivraisonWebshop').find('.iconeInitialiserTableau').hasClass('iconesMasquees')) {
                $('#tableauListeDesAdressesDeLivraisonWebshop').find('.iconeParametrage').hide();
            }
            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(tableauListeDesAdressesLivraison, true, idTableauHtml, etatTableau); }, 0);

            
        },
        'colReorder': {
            'realtime': true
        },
        'headerCallback': function (thead, data, start, end, display) {
            if (enteteAdresseLivraisonInitialisee == false || tableauDesLargeuresEtIndicesAdresseLivraison == "reinitialisé") {
                enteteAdresseLivraisonInitialisee = true;
                titresColonnesSauveguarde = titresColonnesAdresseLivraison;
                titresColonnesAdresseLivraison = [];
                largeurParDefaut = 0;
                tableauDesLargeuresEtIndicesChargementAdresseLivraison = [];
                indiceColonnes = 0;
                $(thead).find('th').each(function () {
                    if (tableauDesLargeuresEtIndicesAdresseLivraison == "reinitialisé") {
                        largeurParDefaut = titresColonnesSauveguarde[indiceColonnes].split(";")[2];
                        indiceColonnes++;
                    } else {
                        largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                        largeurParDefaut = (largeurParDefaut == null ? 0 : largeurParDefaut[0].replace("width", ""));
                    }
                    largeurActuellementAppliquee = (tableauDesLargeuresEtIndicesAdresseLivraison == "reinitialisé" ? largeurParDefaut : largeurActuel(idTableauHtml, etatTableau, $(this).data("origColHeader"), largeurParDefaut));
                    titresColonnesAdresseLivraison.push($(this).html().ltrim().rtrim() + ";" + $(this).data("origColHeader") + ";" + largeurParDefaut + ";" + largeurActuellementAppliquee);

                });
                titresColonnesAdresseLivraison = colonnesVisiblesOuPas(etatTableau, titresColonnesAdresseLivraison, idTableauHtml);
                tableau = [];
                for (i = 0; i < titresColonnesAdresseLivraison.length; i++) {
                    tableau = titresColonnesAdresseLivraison[i].split(";");
                    tableauDesLargeuresEtIndicesChargementAdresseLivraison.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesAdresseLivraison = (tableauDesLargeuresEtIndicesAdresseLivraison != "reinitialisé" ? tableauDesLargeuresEtIndicesChargementAdresseLivraison.join('|') : tableauDesLargeuresEtIndicesAdresseLivraison);
            }
        },
        'drawCallback': function (oSettings) {
            //cette fonction prend en charge de masquer le loader de chargement et affiche la table après sa création

            //$('.contenuCaption').css('width', $('.dataTables_wrapper').width() - 20);
            forcerCablagePagination(idTableauHtml);
            if (etatTableau != '""' && etatTableau != null && tableauDesLargeuresEtIndicesAdresseLivraison != "reinitialisé") {
                etatTableau = etatTableau.split("\\").join("");
                etatTableau = etatTableau.split("^(").join("");
                etatTableau = etatTableau.split(")$").join("");
                oState = JSON.parse(etatTableau);
                if (oState.hasOwnProperty('ColWidth') && typeof oState.ColWidth !== 'undefined') {
                    if (oState.ColWidth.length > 0) {
                        appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesAdresseLivraison);

                    }
                }
            } else if (tableauDesLargeuresEtIndicesAdresseLivraison == "reinitialisé") {

                indiceColonne = 1;
                $('#' + idTableauHtml).find('thead').find('tr:nth-child(1)').find('th').each(function () {
                    largeurParDefaut = "width" + $(this).data("widthHeader");
                    $('#' + idTableauHtml).find('tfoot').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('tbody').find('td:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('thead').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    indiceColonne++;

                });

                tableauDesLargeuresEtIndicesChargementAdresseLivraison = [];
                for (i = 0; i < titresColonnesAdresseLivraison.length; i++) {
                    tableau = titresColonnesAdresseLivraison[i].split(";");
                    tableauDesLargeuresEtIndicesChargementAdresseLivraison.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesAdresseLivraison = tableauDesLargeuresEtIndicesChargementAdresseLivraison.join('|');


            } else {
                appliquerLesLargeurs(idTableauHtml, tableauDesLargeuresEtIndicesAdresseLivraison);
            }
        }
    });

    $('.enTeteColonneCliquable').attr('title', CLIQUER_POUR_TRIER_SUR_LA_COLONNE_OU_MAINTENIR_POUR_DEPLACER_LA_COLONNE);

}

function visualiserAdresseLivraison(numeroAdresse) {
    afficherChargement();
    $.ajax({
        url: '/administration/uneAdresseLivraison',
        data: {
            'numeroAdresse': numeroAdresse
        },
        success: function (resultat) {
            $('#page').html(resultat);
            masquerChargement();
        }
    });
} 

function initialiserListeAdresseLivraisonNew() {
    $('#' + idTableauHtml).data({ conf: conf });
    var isHeaderTableauAdresseEnabled = $('#' + idTableauHtml).data("enableheader") == "True";
    //console.log("initialiserListeAdresseLivraisonNew idTableauHtml isHeaderTableauAdresseEnabled", idTableauHtml, isHeaderTableauAdresseEnabled); 
       
    var   gridAdresseLivraison = $('#' + idTableauHtml).dxDataGrid({
        dataSource: adressesJson, 
        pager: {
            visible: false,
        },
        paging: {
            pageSize: nombreAdresse
        },
        filterRow: {
            visible: isHeaderTableauAdresseEnabled
        },
        columnChooser: {
            enabled: isHeaderTableauAdresseEnabled,
        },
        remoteOperations: {
            filtering: isHeaderTableauAdresseEnabled,
            sorting: isHeaderTableauAdresseEnabled
        },
        allowColumnReordering: isHeaderTableauAdresseEnabled,
        allowColumnFiltering: isHeaderTableauAdresseEnabled,
        allowSearch: isHeaderTableauAdresseEnabled,
        allowColumnResizing: isHeaderTableauAdresseEnabled,
        onRowClick: function (selectedItems) {
            if (modePageAdresseLivraison == "hol") {
                visualiserAdresseLivraison(selectedItems.data.numeroAdresse);
            }
        },
        columns: [
            {
                dataField: "numeroAdresse",
                caption: "numeroAdresse",
                width: 90,
                alignment: "left",
                dataType: "number",
                selectedFilterOperation: '='
            },
            {
                dataField: "adresse1",
                caption: "adresse1",
                width: 200,
                alignment: "left",
                dataType: "string",
            },
            {
                dataField: "adresse2",
                caption: "adresse2",
                width: 200,
                alignment: "left",
                dataType: "string",
            },
            {
                dataField: "adresse3",
                caption: "adresse3",
                width: 150,
                alignment: "left"
            },
            {
                dataField: "codePostal",
                caption: "codePostal",
                width: 100,
                alignment: "right",
                dataType: "number",
                selectedFilterOperation: '='
            },
            {
                dataField: "pays",
                caption: "pays",
                width: 135,
                alignment: "left",
                dataType: "string",
            },
            {
                dataField: "ville",
                caption: "ville",
                width: 135,
                alignment: "left",
                dataType: "string",
            },
            {
                dataField: "ordre",
                caption: "ordre",
                width: 140,
                alignment: "right",
                dataType: "number",
                selectedFilterOperation: '='
            },
            {
                dataField: "adresseParDefaut",
                caption: "adresseParDefaut",
                width: 160,
                alignment: "center",
                dataType: "boolean",
                cellTemplate: function (container, options) {
                    if (parmetreTemplateSite != "") {
                        $("<img  src=\"/ressource/image/webshop/templatePersonnalise/" + (options.data.adresseParDefaut == true ? "star_check.png" : "star_uncheck.png") + "\" width=\"19.2px\" height=\"18.26px\"/>").appendTo(container);
                    } else {
                        $("<img  src=\"/ressource/image/commun/videe.png\"" + (options.data.adresseParDefaut == true ? " class=\"defaultAdresse\"":"")+"/>").appendTo(container);
                    }
                },
                calculateCellValue: function (rowData) {
                    return rowData["adresseParDefaut"] == 1;
                },
                calculateFilterExpression: function (filterValue, selectedFilterOperation) {                  
                    return [this.calculateCellValue, selectedFilterOperation || '=', filterValue];
                }
            },
            {
                dataField: "voirAdresse",
                caption: "voirAdresse",
                width: 50,
                renderAsync: true,
                fixed: false,
                alignment: "center",
                showInColumnChooser: false,
                cellTemplate: function (container, options) {
                    $("<img alt=\"\" src=\"/ressource/image/commun/loupe.png\"/>").appendTo(container);                   
                }
            },]


    }).dxDataGrid("instance");

    $("#" + gridAdresseLivraison.element()[0].id).data("extendedParams", '&&numeroSocieteClient=' + numeroSocieteClient) + '&template';
    $("#" + gridAdresseLivraison.element()[0].id).data("template", "&&template=~/views/administration/listeAExporterDX.cshtml");
    $("#" + gridAdresseLivraison.element()[0].id).data("controller", "/administration/exporterListeEnCSV?");
   
}
var entetePanierRecapInitialisee = false;
function initialisationPageListeRecapPanier() {
    desActiverLesChampsDePanier();
    entetePanierRecapInitialisee = false;
    $('.contenuPage').hide();
    tableauListePanierRecap = tableauListeDuPanier;
    idTableauHtml = "tableauListeRecapPanier";


    listePanierRecap = $('#tableauListeRecapPanier').DataTable({
        'order': [],
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'columns': [
            { 'name': '0', 'className': 'width40 numeriqueTri', 'bSortable': false },
            { 'name': '1', 'className': 'width135', 'bSortable': false },
            { 'name': '2', 'className': 'width135', 'bSortable': false },
            { 'name': '3', 'className': 'width135', 'bSortable': false },
            { 'name': '4', 'className': 'width135', 'bSortable': false },

            { 'name': '5', 'className': 'width135', 'bSortable': false },
            { 'name': '6', 'className': 'width135', 'bSortable': false },
            { 'name': '7', 'className': 'width135', 'bSortable': false },
            { 'name': '8', 'className': 'width135', 'bSortable': false },

            { 'name': '9', 'className': 'width135 numeriqueTri', 'bSortable': false },
            { 'name': '10', 'className': 'width135 numeriqueTri', 'bSortable': false },
            { 'name': '11', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135  inactif' : 'width135 '), 'visible': (EST_CONNECTE == 'True' ? true : false), 'bSortable': false },
            { 'name': '12', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135  inactif' : 'width135 '), 'visible': (EST_CONNECTE == 'True' ? true : false), 'bSortable': false },

            { 'name': '13', 'className': 'width135 numeriqueTri', 'bSortable': false },
            { 'name': '14', 'className': 'width135 numeriqueTri', 'bSortable': false },
            { 'name': '15', 'className': 'width135', 'bSortable': false },


            { 'name': '16', 'className': 'width135', 'bSortable': false },
            { 'name': '17', 'className': (EST_ADMINISTRATEUR_SOCIETE_FOURNISSEUR == 'True' ? 'width135 colonneQuantite inactif' : 'width135 colonneQuantite'), 'visible': (EST_CONNECTE == 'True' ? true : false), 'bSortable': false },
            { 'name': '18', 'className': 'width135 prixStyle', 'visible': true, 'bSortable': false },
            { 'name': '19', 'className': 'width135', 'bSortable': false },
            { 'name': '20', 'className': 'width135', 'bSortable': false },
            { 'name': '21', 'className': 'width135', 'bSortable': false },
            { 'name': '22', 'className': 'width135', 'bSortable': false },
            { 'name': '23', 'className': 'width135', 'bSortable': false },
            { 'name': '24', 'className': 'width135', 'bSortable': false },
            { 'name': '25', 'className': 'width135', 'bSortable': false },
            { 'name': '26', 'className': 'width135', 'bSortable': false },
            { 'name': '27', 'className': 'width135', 'visible': true, 'bSortable': false },
            { 'name': '28', 'className': 'width135', 'bSortable': false },
            { 'name': '29', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '30', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '31', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '32', 'className': 'width135', 'visible': true, 'bSortable': true },
            { 'name': '33', 'className': 'width200', 'visible': true, 'bSortable': false }
        ],
        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"CltR>rt',
        'pageLength': nombreLigneOperation,
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        /*'paginationType': 'full_numbers',*/

        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        //        // Options sur les filtres
        //        'oColumnFilterWidgets': {
        //            //  'bGroupTerms': true, // pour activer le groupage sur les filtres
        //            'aiExclude': [1] // spécifier les colonnes pour lesquelles il n'y aura pas de filtre
        //        },
        // Options sur la visibilité des colonnes
        'colVis': {
            'exclude': [33], // spécifier les colonnes qui ne figurent pas dans la visibilité des colonnes
            'buttonText': AFFICHER_MASQUER_COLONNES
            //            ,
            //            //Gestion Des Filtres Par Colonne Et Visibilite
            //            'fnStateChange': function (iColumn, bVisible) {
            //                gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, listePanier.settings()[0]);
            //            }
        },
        'colReorder': {
            'realtime': true
        },
        'initComplete': function (oSettings, oData) {
            fnOrdonnerColonnes('tableauListeRecapPanier', tableauListePanierRecap);
            //$(this).css('visibility', 'visible');
            materialiserChampsDeRecherche('tableauListeRecapPanier', true);
            initialiserCoVis('tableauListeRecapPanier');
            // Ne pas tenir compte des filtres dans la sauvegarde d'état du tableau
            // Je n'ai pas l'explication mais si l'appel à la méthode se fait en dehors d'un setTimeout alors exception JS
            //setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(listePanierRecap, true, 'tableauListeRecapPanier', tableauListePanierRecap); }, 0);

            fnAfficherCacherColonneOrigCol('tableauListeRecapPanier', 33, false);

            setTimeout(function () { $('#tableauListeRecapPanier').show(); }, 0);
            if (catalogueSansPrix == valeurOui || (clientGenerique == 'True' && afficherPrixDansLesDemandeDeDevis == valeurNon)) {
                fnAfficherCacherColonneOrigCol('tableauListeRecapPanier', 18, false);
                fnAfficherCacherColonneOrigCol('tableauListeRecapPanier', 32, false);
            }
        },
        'headerCallback': function (thead, data, start, end, display) {

            if (entetePanierRecapInitialisee == false || tableauDesLargeuresEtIndicesPanier == "reinitialisé") {

                entetePanierRecapInitialisee = true;
                titresColonnesSauveguarde = titresColonnesPanier;
                titresColonnesPanier = [];
                largeurParDefaut = 0;
                tableauDesLargeuresEtIndicesChargementPanier = [];
                indiceColonnes = 0;
                $(thead).find('th').each(function () {
                    if (tableauDesLargeuresEtIndicesPanier == "reinitialisé") {

                        largeurParDefaut = titresColonnesSauveguarde[indiceColonnes].split(";")[2];
                        indiceColonnes++;
                    } else {

                        largeurParDefaut = $(this).attr("class").match(/width[\w-]*\b/);
                        largeurParDefaut = (largeurParDefaut == null ? 0 : largeurParDefaut[0].replace("width", ""));
                    }
                    largeurActuellementAppliquee = (tableauDesLargeuresEtIndicesPanier == "reinitialisé" ? largeurParDefaut : largeurActuel(idTableauHtml, tableauListePanierRecap, $(this).data("origColHeader"), largeurParDefaut));
                    enteteColonneAPasserEnParametre = $(this).html().ltrim().rtrim();
                    if ($(this).hasClass("ignorerRenommage")) {
                        enteteColonneAPasserEnParametre = "";
                    }
                    titresColonnesPanier.push(enteteColonneAPasserEnParametre + ";" + $(this).data("origColHeader") + ";" + largeurParDefaut + ";" + largeurActuellementAppliquee);


                });

                titresColonnesPanier = colonnesVisiblesOuPas(tableauListePanierRecap, titresColonnesPanier, idTableauHtml);
                indiceCase = 0;
                $(thead).find('th').each(function () {
                    titresColonnesPanier[indiceCase] = titresColonnesPanier[indiceCase] + ";" + ($(this).data("origNameHeader") === undefined ? "" : $(this).data("origNameHeader"));
                    indiceCase++;
                });
                tableau = [];

                for (i = 0; i < titresColonnesPanier.length; i++) {
                    tableau = titresColonnesPanier[i].split(";");
                    tableauDesLargeuresEtIndicesChargementPanier.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesPanier = (tableauDesLargeuresEtIndicesPanier != "reinitialisé" ? tableauDesLargeuresEtIndicesChargementPanier.join('|') : tableauDesLargeuresEtIndicesPanier);

            }

        },
        'drawCallback': function (oSettings) {

            if (tableauListePanierRecap != '""' && tableauListePanierRecap != null && tableauDesLargeuresEtIndicesPanier != "reinitialisé") {
                tableauListePanierRecap = tableauListePanierRecap.split("\\").join("");
                tableauListePanierRecap = tableauListePanierRecap.split("^(").join("");
                tableauListePanierRecap = tableauListePanierRecap.split(")$").join("");
                oState = JSON.parse(tableauListePanierRecap);
                if (oState.hasOwnProperty('ColWidth') && typeof oState.ColWidth !== 'undefined') {
                    if (oState.ColWidth.length > 0) {
                        appliquerLesLargeurs("tableauListeRecapPanier", tableauDesLargeuresEtIndicesPanier);
                    }
                }
            } else if (tableauDesLargeuresEtIndicesPanier == "reinitialisé") {

                indiceColonne = 1;
                $('#' + idTableauHtml).find('thead').find('tr:nth-child(1)').find('th').each(function () {
                    largeurParDefaut = "width" + $(this).data("widthHeader");
                    $('#' + idTableauHtml).find('tfoot').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('tbody').find('td:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    $('#' + idTableauHtml).find('thead').find('th:nth-child(' + (indiceColonne) + ')').addClass(largeurParDefaut);
                    indiceColonne++;

                });

                tableauDesLargeuresEtIndicesChargementPanier = [];
                for (i = 0; i < titresColonnesPanier.length; i++) {
                    tableau = titresColonnesPanier[i].split(";");
                    tableauDesLargeuresEtIndicesChargementPanier.push(tableau[1] + ";" + tableau[3]);

                }

                tableauDesLargeuresEtIndicesPanier = tableauDesLargeuresEtIndicesChargementPanier.join('|');


            } else {
                appliquerLesLargeurs("tableauListeRecapPanier", tableauDesLargeuresEtIndicesPanier);
            }
            settingsDeSauvegardePanier = listePanierRecap.settings();
            tableauOrdonnementParDefaut = [];
            for (var i = 0; i < settingsDeSauvegardePanier[0].aoColumns.length; i++) {
                origColPanier = settingsDeSauvegardePanier[0].aoColumns[i]._ColReorder_iOrigCol;
                tableauOrdonnementParDefaut.push(origColPanier);
            }
            masquerChargement();
        }

    });
    $('.contenuPage').show();
}
function retourAdresseLivraison() {
    if ($('#titrePanier').length > 0) {
        $('#titrePanier').text(ADRESSE_DE_LIVRAISON);
    }
    
    if (typeof saisieEnModeSemaine !== "undefined" && saisieEnModeSemaine == "True") {
        desActiverLesChampsDePanier();
    } else {
        activerLesChampsDePanier();
    }
    $('html, body').animate({
        scrollTop: $('#enteteBasGauche').height()
    }, "fast");
    $('.blockBoutonRecapCommande').hide();
    $('#blockRecapitulatifCommande').hide();
    $('.blockBoutonLivraison').show();
    $('#blockLivraison').show();
    if ($("#boutonEtapeLivraison").hasClass('active')) {
        $("#boutonEtapeLivraison").addClass('sansClique');
        $("#boutonEtapeLivraison").attr('onclick', '');
    }
    if ($("#boutonRecap").hasClass('active')) {
        $("#boutonRecap").removeClass('active');
        $("#boutonRecap").removeClass('sansClique');
    }
}

function initialisationPageListeRecapPanierDX() {
    desActiverLesChampsDePanier();
    $('.contenuPage').hide();
    $.ajax({
        url: '/webshop/colonnesConfigPanier',
        async: false,
        dataType: "json",
        success: function (resultat) {
            conf = resultat;
            $("#tableauListeRecapPanierDx").data({ conf: resultat });
            if (typeof ($('#blockRecapitulatifCommande').html()) !== 'undefined' && $('#blockRecapitulatifCommande').html().indexOf("recapCommande") == -1) {
                activerLesChampsDePanier();
            }
            $("#tableauListeRecapPanierDx").dxDataGrid({
                dataSource: operationsLignePourRecapJson,
                paging: {
                    pageSize: nombreLigneOperation
                },
                pager: {
                    showPageSizeSelector: false,
                    visible: false
                },
                onToolbarPreparing: function (e) {
                    e.toolbarOptions.visible = false;
                },
                allowSearch: false,
                allowColumnResizing: true,
                allowColumnReordering: false,
                allowColumnFiltering: false,
                filterRow: {
                    visible: false
                },
                columns: [
                    {
                        dataField: "numeroOperationLigne",
                        caption: "numeroOperationLigne",
                        allowEditing: false,
                        width: 40,
                        alignment: "right"
                    }
                    , {
                        caption: "imageMedia",
                        dataField: "imageMedia",
                        allowEditing: false,
                        width: 135,
                        cellTemplate: function (container, options) {
                            $(container).addClass("image");

                            if (options.data.urlImageMedia !== "") {
                                $("<img src=\"" + options.data.urlImageMedia + "\" alt=\"\" height=\"50px\" />").appendTo(container);
                            } else {
                                $("<img class=\"pasDImage\" src=\"/ressource/image/webshop/img_default.png\" alt=\"\" height=\"50px\" />").appendTo(container);
                            }

                        }

                    }
                    , {
                        caption: "imageCatalogue",
                        dataField: "imageCatalogue",
                        width: 135,
                        allowEditing: false,
                        cellTemplate: function (container, options) {
                            $("<img src=\"" + options.data.imageCatalogue + "\" alt=\"\" height=\"30px\" />").appendTo(container);
                        }

                    }
                    , {
                        caption: "genre",
                        dataField: "genre",
                        width: 135,
                        allowEditing: false,
                        alignment: "left",
                        cellTemplate: function (container, options) {
                            $("<span />").text(options.value).appendTo(container);
                        }

                    },
                    {
                        caption: "espece",
                        dataField: "espece",
                        allowEditing: false,
                        width: 135,
                        alignment: "left",
                        cellTemplate: function (container, options) {
                            $("<span />").text(options.value).appendTo(container);
                        }

                    },
                    {
                        caption: "variete",
                        dataField: "variete",
                        allowEditing: false,
                        width: 135,
                        alignment: "left",
                        cellTemplate: function (container, options) {
                            $("<span />").text(options.value).appendTo(container);
                        }

                    },
                    {
                        caption: "presentationMillesime",
                        dataField: "presentationMillesime",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"

                    },
                    {
                        caption: "tailleUniteVente",
                        dataField: "tailleUniteVente",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"
                    },
                    {
                        caption: "designationArticle",
                        dataField: "designationArticle",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "designation",
                        dataField: "designation",
                        width: 135,
                        allowEditing: false,
                        alignment: "left",
                        cellTemplate: function (container, options) {
                            $("<span />").text(options.value).appendTo(container);
                        }

                    },
                    {
                        caption: "quantiteProduits",
                        dataField: "quantiteProduits",
                        width: 135,
                        allowEditing: false,
                        cellTemplate: function (container, options) {
                            var stringQuantiteProduit = options.data.quantiteProduit === undefined ? "" : options.data.quantiteProduit;
                            stringQuantiteProduit = "<label class=\"numeriqueTri \" >" + stringQuantiteProduit + "</label>";
                            $(stringQuantiteProduit).appendTo(container);
                        },
                        alignment: "right"
                    },
                    {
                        caption: "quantiteLivree",
                        dataField: "quantiteLivree",
                        allowEditing: false,
                        width: 135,
                        cellTemplate: function (container, options) {
                            var stringQuantiteLivree = options.data.quantiteLivree === undefined ? "" : options.data.quantiteLivree;
                            stringQuantiteLivree = "<label class=\"numeriqueTri \" >" + stringQuantiteLivree + "</label>";
                            $(stringQuantiteLivree).appendTo(container);
                        },
                        alignment: "right"

                    },
                    {
                        caption: "colonnePrix",
                        dataField: "colonnePrix",
                        width: 135,
                        allowEditing: false,
                        cellTemplate: function (container, options) {
                            var clone = $(options.data.colonnePrix).clone();
                            $(container).attr('class', 'prixStyle numeriqueTri');
                            $("<label class=\"prixHt\" />").text(options.data.colonnePrix + options.data.symboleDevise).appendTo(container);
                        },
                        alignment: "right"
                    },
                    {
                        caption: "commentaireEtiquettes",
                        dataField: "commentaireEtiquettes",
                        width: 135,
                        allowEditing: false,
                        alignment: "right"
                    },
                    {
                        caption: "prixEtiquettes",
                        dataField: "prixEtiquettes",
                        width: 135,
                        allowEditing: false,
                        alignment: "right"
                    },
                    {
                        caption: "codeEAN",
                        dataField: "codeEAN",
                        allowEditing: true,
                        width: 135,
                        alignment: "left"

                    },
                    {
                        caption: "codePartenaire",
                        dataField: "codePartenaire",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"

                    },
                    {
                        caption: "numeroExterne",
                        dataField: "numeroExterne",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"
                    },
                    {
                        caption: "codeArticle",
                        dataField: "codeArticle",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "pcb",
                        dataField: "pcb",
                        allowEditing: false,
                        width: 100,
                        alignment: "right"
                    },
                    {
                        caption: "quantiteArticleParEmballage",
                        dataField: "quantiteArticleParEmballage",
                        allowEditing: false,
                        width: 135,
                        alignment: "right"
                    },
                    {
                        caption: "codeEmballage3",
                        dataField: "codeEmballage3",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "croisementEmballage2Vers3",
                        dataField: "croisementEmballage2Vers3",
                        allowEditing: false,
                        width: 135,
                        alignment: "right"
                    },
                    {
                        caption: "codeEmballage2",
                        dataField: "codeEmballage2",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "croisementEmballage1Vers2",
                        dataField: "croisementEmballage1Vers2",
                        allowEditing: false,
                        width: 135,
                        alignment: "right"
                    },
                    {
                        caption: "codeEmballage1",
                        dataField: "codeEmballage1",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "codeEmballage4",
                        dataField: "codeEmballage4",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "prix2",
                        dataField: "prix2",
                        width: 135,
                        allowEditing: false,
                        alignment: "right"
                    },
                    {
                        caption: "libelleWebshop1",
                        dataField: "libelleWebshop1",
                        width: 135,
                        allowEditing: false,
                        alignment: "left",
                    },
                    {
                        caption: "libelleWebshop2",
                        dataField: "libelleWebshop2",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"

                    },
                    {
                        caption: "libelleWebshop3",
                        dataField: "libelleWebshop3",
                        width: 135,
                        allowEditing: false,
                        alignment: "left"
                    },
                    {
                        caption: "codeCritere1",
                        dataField: "codeCritere1",
                        allowEditing: false,
                        width: 135,
                        alignment: "left"
                    },
                    {
                        caption: "montantTotal",
                        dataField: "montantTotal",
                        allowEditing: false,
                        width: 135,
                        alignment: "right"
                    },
                    {
                        caption: "inputBoutonSupprimer",
                        dataField: "inputBoutonSupprimer",
                        width: 80,
                        allowEditing: false,
                        alignment: "left"
                    }
                    ,
                    {
                        caption: "semaineLivraison",
                        dataField: "semaineLivraison",
                        width: 80,
                        allowEditing: false,
                        alignment: "left",
                        sortOrder: saisieEnModeSemaine !== "False" ? 'asc' : undefined,
                        sortIndex: saisieEnModeSemaine !== "False" ? 1 : undefined,
                        visible: saisieEnModeSemaine !== "False",
                        groupIndex: saisieEnModeSemaine === "False" ? undefined : 1
						/*calculateGroupValue: function(rowData) {
							return rowData.anneeLivraison+';'+ rowData.semaineLivraison;
						},
						groupCellTemplate: function(element, options) {
                          console.log(options);
                          element.text("Année: "+options.key[0].split(";")[0]+" - "+ options.column.caption + ": " + options.key[0].split(";")[1]);
                        }*/

                    },
                    {
                        caption: "anneeLivraison",
                        dataField: "anneeLivraison",
                        width: 80,
                        allowEditing: false,
                        alignment: "left",
                        visible: saisieEnModeSemaine !== "False",
                        groupIndex: saisieEnModeSemaine === "False" ? undefined : 0,
                        sortOrder: saisieEnModeSemaine !== "False" ? 'asc' : undefined,
                        sortIndex: saisieEnModeSemaine !== "False" ? 0 : undefined

                    }

                ],
                scrolling: {
                    mode: "virtual"
                },
                grouping: {
                    autoExpandAll: true,
                    allowCollapsing: false
                },
                onInitialized: function (e) {

                    initialized(e);
                    var dataGrid = e.component;
                    e.component.columnOption("inputBoutonSupprimer", "visible", false);
                    if (catalogueSansPrix == valeurOui || (clientGenerique == 'True' && afficherPrixDansLesDemandeDeDevis == valeurNon)) {
                        e.component.columnOption("colonnePrix", "visible", false);
                        e.component.columnOption('montantTotal', "visible", false);
                    }
                    dataGrid.option("columnChooser.enabled", false);
                },
                onContentReady: function (e) {
                    e.component.columnOption("inputBoutonSupprimer", "visible", false);
                }

            });
            $('.contenuPage').show();
        }
    });

}
function initialisationPageListeDesOperationsWebshopNew() {
    //initialiserCalendrier();

    $("#" + idDxGridHtml).data({ conf: conf });
    $(function () {
        var filterOperation = [];
        var statuses = [{ text: OPERATIONS_EN_COURS, valeur: OPERATION_ENCOURS }, { text: OPERATIONS_EN_ATTENTE_DE_VALIDATION, valeur: OPERATION_ATTENTE_VALIDATION }, { text: OPERATIONS_VALIDEES, valeur: OPERATION_ENVOYER }];
       // var filterOperation = [];
        radioGroupTypeOperation = $("#selectStatus").dxRadioGroup({
            dataSource: statuses,
            displayExpr: "text",
            valueExpr: "valeur",
            value: OPERATION_ATTENTE_VALIDATION,
            layout: "horizontal",
            onValueChanged: function (data) {
                filterOperation = { "dataField": "statutCommande", "selectedFilterOperation": "=", "filterValueRange": "", "filterValue": data.value };
                
                
                if (typeof (estValideur) != 'undefined' && estValideur == "True" && data.value == OPERATION_ATTENTE_VALIDATION) {
                    myTable.option("selection.mode", "multiple");
                    $("#validerOperations").show();
                }
                else {
                    myTable.option("selection.mode", "single");
                    $("#validerOperations").hide();
                }
                    
                    

                myTable.refresh();
            }
        }).dxRadioGroup("instance");
        var operationStore = new DevExpress.data.CustomStore({
            load: function (loadOptions) {
                var deferred = $.Deferred();
                var filter =  [];
                filterHeader = [];
                chargerFiltres(myTable, loadOptions, filter, filterHeader);
                if (typeDeCompte == "compteSecondaire") {
                    if (filterOperation.length != 0) {
                        filter.push(filterOperation);
                    } else {
                        filter.push({ "dataField": "statutCommande", "selectedFilterOperation": "=", "filterValueRange": "", "filterValue": OPERATION_ATTENTE_VALIDATION });
                    }
                        
                }
                //paramètres d'exports spécifiques !! évitez les espaces !!
                $("#" + myTable.element()[0].id).data("extendedParams", '&&numeroBoutique=' + numeroBoutique ) + '&template';
                $("#" + myTable.element()[0].id).data("template", "&&template=~/views/administration/listeAExporterDX.cshtml");
                $("#" + myTable.element()[0].id).data("controller", "/administration/exporterListeEnCSV?");
                $.ajax({
                    url: '/administration/peuplementListeDesOperationsWebshopDX?numeroBoutique=' + numeroBoutique ,
                    dataType: "json",
                    data: {
                        filter: JSON.stringify(filter),
                        filterHeader: JSON.stringify(filterHeader),
                        sort: JSON.stringify(loadOptions.sort == null ? [] : loadOptions.sort),
                        skip: loadOptions.skip || 0,
                        take: loadOptions.take || -1
                    },
                    success: function (result) {
                        deferred.resolve(result.items, { totalCount: result.totalCount });
                        masquerChargement();
                    },
                    error: function () {
                        deferred.reject("Data Loading Error");
                    }
                });

                return deferred.promise();
            }
        });
        myTable = $("#" + idDxGridHtml).dxDataGrid({
            dataSource: {
                store: operationStore,
                key: "numeroOperation"
            },
            paging: {
                pageSize: (configurationTableauxDx !== null && configurationTableauxDx.some(function (item) { if (item.idGrid === idDxGridHtml) { return item; } })) ? configurationTableauxDx.find(function (item) { if (item.idGrid === idDxGridHtml) { return item; } }).structuredEtatDatagrid.pageSize : (typeof (typeDeCompte) != 'undefined' && typeDeCompte == "compteSecondaire") ? 20 : 5
            },
            columnChooser: {
                enabled: true,
                mode: "select"

            },
            selection: {
                mode: (typeof (estValideur) != 'undefined' && estValideur == "True") ? "multiple" : "single",
                selectAllMode: "allPages",
                allowSelectAll: true,
                showCheckBoxesMode: "always",
            },
            columns: [
               
              {
                    caption: "pdfFicheOperation",
                    dataField: "pdfFicheOperation",
                    width: 100,
                    cellTemplate: function (container, options) {
                        $('<img />').attr('src', urlPdf).on('click', function (event) { operationEnPDFListe(options.value); }).appendTo(container);
                    }
                },
                {
                    dataField: "numeroOperation",
                    caption: "numeroOperation",
                    width: 100,
                    alignment: "center",
                    dataType: "number"
                },
                {
                    caption: "etatOperation",
                    dataField: "etatOperation",
                    width: 170,
                    alignment: "left",
                    dataType: "string"
                },
                {
                    dataField: "numeroExterneCompteClient",
                    caption: "numeroExterneCompteClient",
                    width: 130,
                    alignment: "center",
                    dataType: "string"
                },
                {
                    dataField: "nom1_Client",
                    caption: "nom1_Client",
                    width: 120,
                    alignment: "left",
                    dataType: "string",
                },
                {
                    dataField: "nom2_Client",
                    caption: "nom2_Client",
                    width: 120,
                    alignment: "left",
                    dataType: "string",
                },
                {
                    dataField: "codeCritereClient1",
                    caption: "codeCritereClient1",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient1']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient2",
                    caption: "codeCritereClient2",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient3",
                    caption: "codeCritereClient3",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient3']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient4",
                    caption: "codeCritereClient4",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient4']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient5",
                    caption: "codeCritereClient5",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient5']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient6",
                    caption: "codeCritereClient6",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient6']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient7",
                    caption: "codeCritereClient7",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient7']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient8",
                    caption: "codeCritereClient8",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient8']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient9",
                    caption: "codeCritereClient9",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient9']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient10",
                    caption: "codeCritereClient10",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient10']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient11",
                    caption: "codeCritereClient11",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient11']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient12",
                    caption: "codeCritereClient12",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient12']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient13",
                    caption: "codeCritereClient13",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient13']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient14",
                    caption: "codeCritereClient14",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient14']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient15",
                    caption: "codeCritereClient15",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient15']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient16",
                    caption: "codeCritereClient16",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient16']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient17",
                    caption: "codeCritereClient17",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient17']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritereClient18",
                    caption: "codeCritereClient18",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritereClient18']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "raisonSocialeClient",
                    caption: "raisonSocialeClient",
                    width: 70,
                    renderAsync: true,
                    visible: false
                },
                {
                    dataField: "codeCritere1",
                    caption: "codeCritere1",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere1']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere2",
                    caption: "codeCritere2",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere2']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "codeCritere3",
                    caption: "codeCritere3",
                    width: 70,
                    renderAsync: true,

                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        var valeurData = function (data) {
                            return enleverAccents(data['codeCritere3']);
                        };
                        filterValue = enleverAccents(filterValue);
                        var filterExpression = [[valeurData, selectedFilterOperation, filterValue]];
                        return filterExpression;
                    },
                    visible: false
                },
                {
                    dataField: "type",
                    caption: "type",
                    width: 120,
                    alignment: "left",
                    dataType: "string",
                    visible: false
                },
                {
                    caption: "dateCreation",
                    dataField: "dateCreation",
                    width: 170,
                    alignment: "left",
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]]
                            ;
                        return filterExpression;
                    }
                },
                {
                    caption: "dateModification",
                    dataField: "dateModification",
                    width: 170,
                    alignment: "left",
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]]
                            ;
                        return filterExpression;
                    }
                },
                {
                    caption: "dateEnvoi",
                    dataField: "dateEnvoi",
                    width: 135,
                    alignment: "left",
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]]
                            ;
                        return filterExpression;
                    }
                },
                {
                    caption: "dateExpeditionPrevue",
                    dataField: "dateExpeditionPrevue",
                    width: 230,
                    alignment: "left",
                    dataType: "date"
                },

                {
                    caption: "dateExpeditionEffective",
                    dataField: "dateExpeditionEffective",
                    width: 230,
                    alignment: "left",
                    dataType: "date"
                },
                {
                    caption: "designation",
                    dataField: "designation",
                    width: 210,
                    alignment: "left",
                    dataType: "string"              
                },
                {
                    caption: "estRecuperee",
                    dataField: "estRecuperee",
                    width: 200,
                    alignment: "left",
                    dataType: "datetime",
                    format: "dd/MM/yyyy HH:mm:ss",
                    calculateFilterExpression: function (filterValue, selectedFilterOperation) {
                        // Implementation for the "between" comparison operator
                        var filterExpression = [[this.calculateCellValue, "<>", filterValue]]
                            ;
                        return filterExpression;
                    }
                },
                {
                    dataField: "statutGescomS",
                    caption: "statutGescomS",
                    width: 170,
                    alignment: "left",
                    dataType: "string",
                    cellTemplate: function (container, options) {
                        //options.data
                        //var parmetreStatusGestComSaisi = '@parmetreStatusGestComSaisi';
                        //var parmetreStatusValidee = '@parmetreStatusValidee';
                        //var parmetreStatusPretAExpedier = '@parmetreStatusPretAExpedier';
                        //var parmetreStatusLivree = '@parmetreStatusLivree';
                        //var parmetreStatusExpediee = '@parmetreStatusExpediee';
                        //var parmetreStatusEnPreparation = '@parmetreStatusEnPreparation';
                        var avecClass = false;
                        var span = $("<span />");
                        if (options.data.statutGescom !== null) {
                            switch (options.data.statutGescom) {
                                case valeurStatusValidee:
                                    if (parmetreStatusValidee !== "") {
                                        span.attr('style', 'background-color:' + parmetreStatusValidee + '50');
                                        span.css('color', parmetreStatusValidee);
                                        avecClass = true;
                                    }
                                    break;
                                case valeurStatusPretAExpedier:
                                    if (parmetreStatusPretAExpedier !== "") {
                                        span.attr('style', 'background-color:' + parmetreStatusPretAExpedier + '50');
                                        span.css('color', parmetreStatusPretAExpedier);
                                        avecClass = true;
                                    }
                                    break;
                                case valeurStatusLivree:
                                    if (parmetreStatusLivree !== "") {
                                        span.attr('style', 'background-color:' + parmetreStatusLivree + '50' );
                                        span.css('color', parmetreStatusLivree);
                                        avecClass = true;
                                    }
                                    break;
                                case valeurStatusExpediee:
                                    if (parmetreStatusExpediee !== "") {
                                        span.attr('style', 'background-color:' + parmetreStatusExpediee + '50');
                                        span.css('color', parmetreStatusExpediee);
                                        avecClass = true;
                                    }
                                    break;
                                case valeurStatusEnPreparation:
                                    if (parmetreStatusEnPreparation !== "") {
                                        span.attr('style', 'background-color:' + parmetreStatusEnPreparation + '50');
                                        span.css('color', parmetreStatusEnPreparation);
                                        avecClass = true;
                                    }
                                    break;
                                default:
                                // code block
                            }
                        } else {
                            if (parmetreStatusGestComSaisi !== "") {
                                span.attr('style', 'background-color:' + parmetreStatusGestComSaisi+'50');
                                span.css('color', parmetreStatusGestComSaisi);
                                avecClass = true;
                                
                            }
                        }
                        if (avecClass) {
                            span.addClass("etiquetteGestcom");
                        }
                
                        span.text(options.value).appendTo(container);
                    }
                },
                {
                    caption: "totalHTDeviseBaseS",
                    dataField: "totalHTDeviseBaseS",
                    alignment: "right",
                    width: 230,
                    dataType: "string"
                },
                {
                    caption: "totalTVADeviseBaseS",
                    dataField: "totalTVADeviseBaseS",
                    alignment: "right",
                    width: 200,
                    dataType: "string"
                },
                {
                    caption: "totalTTCDeviseBaseS",
                    dataField: "totalTTCDeviseBaseS",
                    alignment: "right",
                    width: 230,
                    dataType: "string"
                },
                {
                    caption: "adresseComplement_codeTransporteur",
                    dataField: "adresseComplement_codeTransporteur",
                    width: 230,
                    alignment: "left",
                    dataType: "string"

                },
                {
                    caption: "designationTransporteur",
                    dataField: "designationTransporteur",
                    width: 200,
                    alignment: "left",
                    dataType: "string"

                },
                {
                    dataField: "densite",
                    caption: "densite",
                    width: 150,
                    alignment: "right",
                    dataType: "number",
                    selectedFilterOperation: '=',
                    renderAsync: true,
                    format: "#0.00"
                },
                {
                    dataField: "surface",
                    caption: "surface",
                    width: 150,
                    alignment: "right",
                    dataType: "number",
                    selectedFilterOperation: '=',
                    renderAsync: true,
                    format: "#0.00"
                }
           

            ],
            onCellPrepared: function (e) {
                cellPrepared(e);
                //if (typeof (typeDeCompte) != 'undefined' && typeDeCompte == "compteSecondaire" && e.rowType === "data" && e.column.command === 'select' && e.data.statutCommande != 9) {
                //    var instance = e.cellElement.find('.dx-select-checkbox').dxCheckBox("instance");
                //    instance.option("disabled", true);
                //    e.cellElement.off();
                //} 
            },
            onEditorPrepared: function (e) {
            },
            onRowClick: function (selectedItems) {
                if (typeof (typeDeCompte) != 'undefined' && typeDeCompte == "compteSecondaire") {
                    if (selectedItems.data.statutCommande == 2 || (selectedItems.data.statutCommande == 9 && estValideur == 'True')) {
                        selectionnerClientSurLequelPasserCommande(selectedItems.data.numeroCompteClient, selectedItems.data.numeroOperation);
                    } else {
                        operationEnPDFListe(selectedItems.data.numeroOperation);
                    }
                }
            },
            onCellClick: function (e) {
                if (e.column.dataField == "pdfFicheOperation") {
                    e.event.stopPropagation();
                }
            } ,
            onSelectionChanged: function (selectedItems) {
                //if (typeof (typeDeCompte) != 'undefined' && typeDeCompte == "compteSecondaire") {
                //    console.log(selectedItems);
                //    var disabledKeys = selectedItems.currentSelectedRowKeys.filter(i => i.statutCommande != 9);
                //    if (disabledKeys.length > 0)
                //        selectedItems.component.deselectRows(disabledKeys);  
                    
                //    console.log('1 ' + LISTE_DES_OPERATION_A_VALIDERS_Modif);
                    
                //    var unselectedRows = selectedItems.currentDeselectedRowKeys.map(function (obj) {
                //        return obj.numeroOperation
                //    });

                //    LISTE_DES_OPERATION_A_VALIDERS_Modif = LISTE_DES_OPERATION_A_VALIDERS_Modif.filter(function (el) {
                //        return !unselectedRows.includes(el);
                //    });
                //    console.log('2 ' + LISTE_DES_OPERATION_A_VALIDERS_Modif);
                   
                    
                //}

                //var idGrid = selectedItems.component.element()[0].id;
                //if (etatIntermediaires != null && etatIntermediaires.some(function (item) { if (item.id == idGrid) { return item; } })) {
                //    etatIntermediaires.find(function (item) { if (item.id == idGrid) { return item; } }).state = JSON.stringify(this.state());
                //} else {
                //    etatIntermediaire = new Object();
                //    etatIntermediaire.state = JSON.stringify(this.state());
                //    etatIntermediaire.id = idGrid;
                //    etatIntermediaires.push(etatIntermediaire);
                //}
            },
            onOptionChanged: function (e) {
                //if (e.fullName.endsWith("selectedFilterOperation")) {
                //    columnIndex = e.fullName.replace("].selectedFilterOperation", "").replace("columns[", "");
                //    if (e.component.columnOption(parseInt(columnIndex)).filterValue !== null && e.component.columnOption(parseInt(columnIndex)).filterValue !== "") {
                //        e.component.refresh();
                //    }
                //}

            }       

        }).dxDataGrid("instance");

    });
}
function remplirKeyOperation() {

    var grid = $('#' + idDxGridHtml).dxDataGrid("instance");
    var keys = grid.getSelectedRowKeys();
    var keysdata = grid.getSelectedRowsData();


    if (keys.length != 0)
        return extraireColonne(keys, "numeroOperation").join("|") + "|";
    else
        return null;
}
function extraireColonne(input, field) {
    var output = [];
    for (var i = 0; i < input.length; ++i)
        output.push(input[i][field]);
    return output;
}
function confirmationValidationListeDesOperations() {
    listeDesOperationAvaliders = remplirKeyOperation();
    if (listeDesOperationAvaliders != null) {
        alerte(MESSAGE_CONFIRMATION_VALIDATION_OPERATIONS, 'confirmationUtilisateur', 'validerListeDesOperations');
    } else {
        alerte(VEUILLEZ_CHOISIR_UNE_OU_PLUSIEURS_OPERATIONS_A_VALIDER, 'erreur');
    }
}
function validerListeDesOperations() {
        afficherChargement();
        $.ajax({
            url: '/OperationDesktop/validerOperationEnMasse',
            data: {
                'listeDesOperationAvaliders': listeDesOperationAvaliders
            },
            success: function () {
                masquerChargement();
                alerte(OPERATIONS_ENVOYER_AVEC_SUCCES, 'confirmation');
                var gridOperation = $('#' + idDxGridHtml).dxDataGrid("instance");
                gridOperation.refresh();  
            }
        });
}
/*! DataTables 1.10.0
 * ©2008-2014 SpryMedia Ltd - datatables.net/license
 */

/**
 * @summary     DataTables
 * @description Paginate, search and order HTML tables
 * @version     1.10.0
 * @file        jquery.dataTables.js
 * @author      SpryMedia Ltd (www.sprymedia.co.uk)
 * @contact     www.sprymedia.co.uk/contact
 * @copyright   Copyright 2008-2014 SpryMedia Ltd.
 *
 * This source file is free software, available under the following license:
 *   MIT license - http://datatables.net/license
 *
 * This source file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
 *
 * For details please refer to: http://www.datatables.net
 */

/*jslint evil: true, undef: true, browser: true */
/*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidateRow,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnScrollBarWidth,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/

(/** @lends <global> */function (window, document, undefined) {

    (function (factory) {
        "use strict";

        if (typeof define === 'function' && define.amd) {
            // Define as an AMD module if possible
            define('datatables', ['jquery'], factory);
        }
        else if (typeof exports === 'object') {
            // Node/CommonJS
            factory(require('jquery'));
        }
        else if (jQuery && !jQuery.fn.dataTable) {
            // Define using browser globals otherwise
            // Prevent multiple instantiations if the script is loaded twice
            factory(jQuery);
        }
    }
(/** @lends <global> */function ($) {
    "use strict";

    /**
    * DataTables is a plug-in for the jQuery Javascript library. It is a highly
    * flexible tool, based upon the foundations of progressive enhancement,
    * which will add advanced interaction controls to any HTML table. For a
    * full list of features please refer to
    * [DataTables.net](href="http://datatables.net).
    *
    * Note that the `DataTable` object is not a global variable but is aliased
    * to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may
    * be  accessed.
    *
    *  @class
    *  @param {object} [init={}] Configuration object for DataTables. Options
    *    are defined by {@link DataTable.defaults}
    *  @requires jQuery 1.7+
    *
    *  @example
    *    // Basic initialisation
    *    $(document).ready( function {
    *      $('#example').dataTable();
    *    } );
    *
    *  @example
    *    // Initialisation with configuration options - in this case, disable
    *    // pagination and sorting.
    *    $(document).ready( function {
    *      $('#example').dataTable( {
    *        "paginate": false,
    *        "sort": false
    *      } );
    *    } );
    */
    var DataTable;


    /*
    * It is useful to have variables which are scoped locally so only the
    * DataTables functions can access them and they don't leak into global space.
    * At the same time these functions are often useful over multiple files in the
    * core and API, so we list, or at least document, all variables which are used
    * by DataTables as private variables here. This also ensures that there is no
    * clashing of variable names and that they can easily referenced for reuse.
    */


    // Defined else where
    //  _selector_run
    //  _selector_opts
    //  _selector_first
    //  _selector_row_indexes

    var _ext; // DataTable.ext
    var _Api; // DataTable.Api
    var _api_register; // DataTable.Api.register
    var _api_registerPlural; // DataTable.Api.registerPlural

    var _re_dic = {};
    var _re_new_lines = /[\r\n]/g;
    var _re_html = /<.*?>/g;
    var _re_date_start = /^[\d\+\-a-zA-Z]/;

    // Escape regular expression special characters
    var _re_escape_regex = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-'].join('|\\') + ')', 'g');

    // U+2009 is thin space and U+202F is narrow no-break space, both used in many
    // standards as thousands separators
    var _re_formatted_numeric = /[',$£€¥%\u2009\u202F]/g;


    var _empty = function (d) {
        return !d || d === '-' ? true : false;
    };


    var _intVal = function (s) {
        var integer = parseInt(s, 10);
        return !isNaN(integer) && isFinite(s) ? integer : null;
    };

    // Convert from a formatted number with characters other than `.` as the
    // decimal place, to a Javascript number
    var _numToDecimal = function (num, decimalPoint) {
        // Cache created regular expressions for speed as this function is called often
        if (!_re_dic[decimalPoint]) {
            _re_dic[decimalPoint] = new RegExp(_fnEscapeRegex(decimalPoint), 'g');
        }
        return typeof num === 'string' ?
			num.replace(/\./g, '').replace(_re_dic[decimalPoint], '.') :
			num;
    };


    var _isNumber = function (d, decimalPoint, formatted) {
        var strType = typeof d === 'string';

        if (decimalPoint && strType) {
            d = _numToDecimal(d, decimalPoint);
        }

        if (formatted && strType) {
            d = d.replace(_re_formatted_numeric, '');
        }

        return !d || d === '-' || (!isNaN(parseFloat(d)) && isFinite(d));
    };


    // A string without HTML in it can be considered to be HTML still
    var _isHtml = function (d) {
        return !d || typeof d === 'string';
    };


    var _htmlNumeric = function (d, decimalPoint, formatted) {
        if (_empty(d)) {
            return true;
        }

        var html = _isHtml(d);
        return !html ?
			null :
			_isNumber(_stripHtml(d), decimalPoint, formatted) ?
				true :
				null;
    };


    var _pluck = function (a, prop, prop2) {
        var out = [];
        var i = 0, ien = a.length;

        // Could have the test in the loop for slightly smaller code, but speed
        // is essential here
        if (prop2 !== undefined) {
            for (; i < ien; i++) {
                if (a[i] && a[i][prop]) {
                    out.push(a[i][prop][prop2]);
                }
            }
        }
        else {
            for (; i < ien; i++) {
                if (a[i]) {
                    out.push(a[i][prop]);
                }
            }
        }

        return out;
    };


    // Basically the same as _pluck, but rather than looping over `a` we use `order`
    // as the indexes to pick from `a`
    var _pluck_order = function (a, order, prop, prop2) {
        var out = [];
        var i = 0, ien = order.length;

        // Could have the test in the loop for slightly smaller code, but speed
        // is essential here
        if (prop2 !== undefined) {
            for (; i < ien; i++) {
                out.push(a[order[i]][prop][prop2]);
            }
        }
        else {
            for (; i < ien; i++) {
                out.push(a[order[i]][prop]);
            }
        }

        return out;
    };


    var _range = function (len, start) {
        var out = [];
        var end;

        if (start === undefined) {
            start = 0;
            end = len;
        }
        else {
            end = start;
            start = len;
        }

        for (var i = start; i < end; i++) {
            out.push(i);
        }

        return out;
    };


    var _stripHtml = function (d) {
        return d.replace(_re_html, '');
    };


    /**
    * Find the unique elements in a source array.
    *
    * @param  {array} src Source array
    * @return {array} Array of unique items
    * @ignore
    */
    var _unique = function (src) {
        // A faster unique method is to use object keys to identify used values,
        // but this doesn't work with arrays or objects, which we must also
        // consider. See jsperf.com/compare-array-unique-versions/4 for more
        // information.
        var 
			out = [],
			val,
			i, ien = src.length,
			j, k = 0;

        again: for (i = 0; i < ien; i++) {
            val = src[i];

            for (j = 0; j < k; j++) {
                if (out[j] === val) {
                    continue again;
                }
            }

            out.push(val);
            k++;
        }

        return out;
    };



    /**
    * Create a mapping object that allows camel case parameters to be looked up
    * for their Hungarian counterparts. The mapping is stored in a private
    * parameter called `_hungarianMap` which can be accessed on the source object.
    *  @param {object} o
    *  @memberof DataTable#oApi
    */
    function _fnHungarianMap(o) {
        var 
			hungarian = 'a aa ai ao as b fn i m o s ',
			match,
			newKey,
			map = {};

        $.each(o, function (key, val) {
            match = key.match(/^([^A-Z]+?)([A-Z])/);

            if (match && hungarian.indexOf(match[1] + ' ') !== -1) {
                newKey = key.replace(match[0], match[2].toLowerCase());
                map[newKey] = key;

                ////console.log( key, match );
                if (match[1] === 'o') {
                    _fnHungarianMap(o[key]);
                }
            }
        });

        o._hungarianMap = map;
    }


    /**
    * Convert from camel case parameters to Hungarian, based on a Hungarian map
    * created by _fnHungarianMap.
    *  @param {object} src The model object which holds all parameters that can be
    *    mapped.
    *  @param {object} user The object to convert from camel case to Hungarian.
    *  @param {boolean} force When set to `true`, properties which already have a
    *    Hungarian value in the `user` object will be overwritten. Otherwise they
    *    won't be.
    *  @memberof DataTable#oApi
    */
    function _fnCamelToHungarian(src, user, force) {
        if (!src._hungarianMap) {
            _fnHungarianMap(src);
        }

        var hungarianKey;

        $.each(user, function (key, val) {
            hungarianKey = src._hungarianMap[key];

            if (hungarianKey !== undefined && (force || user[hungarianKey] === undefined)) {
                // For objects, we need to buzz down into the object to copy parameters
                if (hungarianKey.charAt(0) === 'o') {
                    // Copy the camelCase options over to the hungarian
                    if (!user[hungarianKey]) {
                        user[hungarianKey] = {};
                    }
                    $.extend(true, user[hungarianKey], user[key]);

                    _fnCamelToHungarian(src[hungarianKey], user[hungarianKey], force);
                }
                else {
                    user[hungarianKey] = user[key];
                }
            }
        });
    }


    /**
    * Language compatibility - when certain options are given, and others aren't, we
    * need to duplicate the values over, in order to provide backwards compatibility
    * with older language files.
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnLanguageCompat(lang) {
        var defaults = DataTable.defaults.oLanguage;
        var zeroRecords = lang.sZeroRecords;

        /* Backwards compatibility - if there is no sEmptyTable given, then use the same as
        * sZeroRecords - assuming that is given.
        */
        if (!lang.sEmptyTable && zeroRecords &&
			defaults.sEmptyTable === "No data available in table") {
            _fnMap(lang, lang, 'sZeroRecords', 'sEmptyTable');
        }

        /* Likewise with loading records */
        if (!lang.sLoadingRecords && zeroRecords &&
			defaults.sLoadingRecords === "Loading...") {
            _fnMap(lang, lang, 'sZeroRecords', 'sLoadingRecords');
        }

        // Old parameter name of the thousands separator mapped onto the new
        if (lang.sInfoThousands) {
            lang.sThousands = lang.sInfoThousands;
        }

        var decimal = lang.sDecimal;
        if (decimal) {
            _addNumericSort(decimal);
        }
    }


    /**
    * Map one parameter onto another
    *  @param {object} o Object to map
    *  @param {*} knew The new parameter name
    *  @param {*} old The old parameter name
    */
    var _fnCompatMap = function (o, knew, old) {
        if (o[knew] !== undefined) {
            o[old] = o[knew];
        }
    };


    /**
    * Provide backwards compatibility for the main DT options. Note that the new
    * options are mapped onto the old parameters, so this is an external interface
    * change only.
    *  @param {object} init Object to map
    */
    function _fnCompatOpts(init) {
        _fnCompatMap(init, 'ordering', 'bSort');
        _fnCompatMap(init, 'orderMulti', 'bSortMulti');
        _fnCompatMap(init, 'orderClasses', 'bSortClasses');
        _fnCompatMap(init, 'orderCellsTop', 'bSortCellsTop');
        _fnCompatMap(init, 'order', 'aaSorting');
        _fnCompatMap(init, 'orderFixed', 'aaSortingFixed');
        _fnCompatMap(init, 'paging', 'bPaginate');
        _fnCompatMap(init, 'pagingType', 'sPaginationType');
        _fnCompatMap(init, 'pageLength', 'iDisplayLength');
        _fnCompatMap(init, 'searching', 'bFilter');
    }


    /**
    * Provide backwards compatibility for column options. Note that the new options
    * are mapped onto the old parameters, so this is an external interface change
    * only.
    *  @param {object} init Object to map
    */
    function _fnCompatCols(init) {
        _fnCompatMap(init, 'orderable', 'bSortable');
        _fnCompatMap(init, 'orderData', 'aDataSort');
        _fnCompatMap(init, 'orderSequence', 'asSorting');
        _fnCompatMap(init, 'orderDataType', 'sortDataType');
    }


    /**
    * Browser feature detection for capabilities, quirks
    *  @param {object} settings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnBrowserDetect(settings) {
        var browser = settings.oBrowser;

        // Scrolling feature / quirks detection
        var n = $('<div/>')
			.css({
			    position: 'absolute',
			    top: 0,
			    left: 0,
			    height: 1,
			    width: 1,
			    overflow: 'hidden'
			})
			.append(
				$('<div/>')
					.css({
					    position: 'absolute',
					    top: 1,
					    left: 1,
					    width: 100,
					    overflow: 'scroll'
					})
					.append(
						$('<div class="test"/>')
							.css({
							    width: '100%',
							    height: 10
							})
					)
			)
			.appendTo('body');

        var test = n.find('.test');

        // IE6/7 will oversize a width 100% element inside a scrolling element, to
        // include the width of the scrollbar, while other browsers ensure the inner
        // element is contained without forcing scrolling
        browser.bScrollOversize = test[0].offsetWidth === 100;

        // In rtl text layout, some browsers (most, but not all) will place the
        // scrollbar on the left, rather than the right.
        browser.bScrollbarLeft = test.offset().left !== 1;

        n.remove();
    }


    /**
    * Array.prototype reduce[Right] method, used for browsers which don't support
    * JS 1.6. Done this way to reduce code size, since we iterate either way
    *  @param {object} settings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnReduce(that, fn, init, start, end, inc) {
        var 
			i = start,
			value,
			isSet = false;

        if (init !== undefined) {
            value = init;
            isSet = true;
        }

        while (i !== end) {
            if (!that.hasOwnProperty(i)) {
                continue;
            }

            value = isSet ?
				fn(value, that[i], i, that) :
				that[i];

            isSet = true;
            i += inc;
        }

        return value;
    }

    /**
    * Add a column to the list used for the table with default values
    *  @param {object} oSettings dataTables settings object
    *  @param {node} nTh The th element for this column
    *  @memberof DataTable#oApi
    */
    function _fnAddColumn(oSettings, nTh) {
        // Add column to aoColumns array
        var oDefaults = DataTable.defaults.column;
        var iCol = oSettings.aoColumns.length;
        var oCol = $.extend({}, DataTable.models.oColumn, oDefaults, {
            "nTh": nTh ? nTh : document.createElement('th'),
            "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '',
            "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
            "mData": oDefaults.mData ? oDefaults.mData : iCol,
            idx: iCol
        });
        oSettings.aoColumns.push(oCol);

        // Add search object for column specific search. Note that the `searchCols[ iCol ]`
        // passed into extend can be undefined. This allows the user to give a default
        // with only some of the parameters defined, and also not give a default
        var searchCols = oSettings.aoPreSearchCols;
        searchCols[iCol] = $.extend({}, DataTable.models.oSearch, searchCols[iCol]);

        // Use the default column options function to initialise classes etc
        _fnColumnOptions(oSettings, iCol, null);
    }


    /**
    * Apply options for a column
    *  @param {object} oSettings dataTables settings object
    *  @param {int} iCol column index to consider
    *  @param {object} oOptions object with sType, bVisible and bSearchable etc
    *  @memberof DataTable#oApi
    */
    function _fnColumnOptions(oSettings, iCol, oOptions) {
        var oCol = oSettings.aoColumns[iCol];
        var oClasses = oSettings.oClasses;
        var th = $(oCol.nTh);

        // Try to get width information from the DOM. We can't get it from CSS
        // as we'd need to parse the CSS stylesheet. `width` option can override
        if (!oCol.sWidthOrig) {
            // Width attribute
            oCol.sWidthOrig = th.attr('width') || null;

            // Style attribute
            var t = (th.attr('style') || '').match(/width:\s*(\d+[pxem%])/);
            if (t) {
                oCol.sWidthOrig = t[1];
            }
        }

        /* User specified column options */
        if (oOptions !== undefined && oOptions !== null) {
            // Backwards compatibility
            _fnCompatCols(oOptions);

            // Map camel case parameters to their Hungarian counterparts
            _fnCamelToHungarian(DataTable.defaults.column, oOptions);

            /* Backwards compatibility for mDataProp */
            if (oOptions.mDataProp !== undefined && !oOptions.mData) {
                oOptions.mData = oOptions.mDataProp;
            }

            if (oOptions.sType) {
                oCol._sManualType = oOptions.sType;
            }

            // `class` is a reserved word in Javascript, so we need to provide
            // the ability to use a valid name for the camel case input
            if (oOptions.className && !oOptions.sClass) {
                oOptions.sClass = oOptions.className;
            }

            $.extend(oCol, oOptions);
            _fnMap(oCol, oOptions, "sWidth", "sWidthOrig");

            /* iDataSort to be applied (backwards compatibility), but aDataSort will take
            * priority if defined
            */
            if (typeof oOptions.iDataSort === 'number') {
                oCol.aDataSort = [oOptions.iDataSort];
            }
            _fnMap(oCol, oOptions, "aDataSort");
        }

        /* Cache the data get and set functions for speed */
        var mDataSrc = oCol.mData;
        var mData = _fnGetObjectDataFn(mDataSrc);
        var mRender = oCol.mRender ? _fnGetObjectDataFn(oCol.mRender) : null;

        var attrTest = function (src) {
            return typeof src === 'string' && src.indexOf('@') !== -1;
        };
        oCol._bAttrSrc = $.isPlainObject(mDataSrc) && (
			attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter)
		);

        oCol.fnGetData = function (oData, sSpecific) {
            var innerData = mData(oData, sSpecific);

            if (oCol.mRender && (sSpecific && sSpecific !== '')) {
                return mRender(innerData, sSpecific, oData);
            }
            return innerData;
        };
        oCol.fnSetData = _fnSetObjectDataFn(mDataSrc);

        /* Feature sorting overrides column specific when off */
        if (!oSettings.oFeatures.bSort) {
            oCol.bSortable = false;
            th.addClass(oClasses.sSortableNone); // Have to add class here as order event isn't called
        }

        /* Check that the class assignment is correct for sorting */
        var bAsc = $.inArray('asc', oCol.asSorting) !== -1;
        var bDesc = $.inArray('desc', oCol.asSorting) !== -1;
        if (!oCol.bSortable || (!bAsc && !bDesc)) {
            oCol.sSortingClass = oClasses.sSortableNone;
            oCol.sSortingClassJUI = "";
        }
        else if (bAsc && !bDesc) {
            oCol.sSortingClass = oClasses.sSortableAsc;
            oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed;
        }
        else if (!bAsc && bDesc) {
            oCol.sSortingClass = oClasses.sSortableDesc;
            oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed;
        }
        else {
            oCol.sSortingClass = oClasses.sSortable;
            oCol.sSortingClassJUI = oClasses.sSortJUI;
        }
    }


    /**
    * Adjust the table column widths for new data. Note: you would probably want to
    * do a redraw after calling this function!
    *  @param {object} settings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnAdjustColumnSizing(settings) {
        /* Not interested in doing column width calculation if auto-width is disabled */
        if (settings.oFeatures.bAutoWidth !== false) {
            var columns = settings.aoColumns;

            _fnCalculateColumnWidths(settings);
            for (var i = 0, iLen = columns.length; i < iLen; i++) {
                columns[i].nTh.style.width = columns[i].sWidth;
            }
        }

        var scroll = settings.oScroll;
        if (scroll.sY !== '' || scroll.sX !== '') {
            _fnScrollDraw(settings);
        }

        _fnCallbackFire(settings, null, 'column-sizing', [settings]);
    }


    /**
    * Covert the index of a visible column to the index in the data array (take account
    * of hidden columns)
    *  @param {object} oSettings dataTables settings object
    *  @param {int} iMatch Visible column index to lookup
    *  @returns {int} i the data index
    *  @memberof DataTable#oApi
    */
    function _fnVisibleToColumnIndex(oSettings, iMatch) {
        var aiVis = _fnGetColumns(oSettings, 'bVisible');

        return typeof aiVis[iMatch] === 'number' ?
			aiVis[iMatch] :
			null;
    }


    /**
    * Covert the index of an index in the data array and convert it to the visible
    *   column index (take account of hidden columns)
    *  @param {int} iMatch Column index to lookup
    *  @param {object} oSettings dataTables settings object
    *  @returns {int} i the data index
    *  @memberof DataTable#oApi
    */
    function _fnColumnIndexToVisible(oSettings, iMatch) {
        var aiVis = _fnGetColumns(oSettings, 'bVisible');
        var iPos = $.inArray(iMatch, aiVis);

        return iPos !== -1 ? iPos : null;
    }


    /**
    * Get the number of visible columns
    *  @param {object} oSettings dataTables settings object
    *  @returns {int} i the number of visible columns
    *  @memberof DataTable#oApi
    */
    function _fnVisbleColumns(oSettings) {
        return _fnGetColumns(oSettings, 'bVisible').length;
    }


    /**
    * Get an array of column indexes that match a given property
    *  @param {object} oSettings dataTables settings object
    *  @param {string} sParam Parameter in aoColumns to look for - typically
    *    bVisible or bSearchable
    *  @returns {array} Array of indexes with matched properties
    *  @memberof DataTable#oApi
    */
    function _fnGetColumns(oSettings, sParam) {
        var a = [];

        $.map(oSettings.aoColumns, function (val, i) {
            if (val[sParam]) {
                a.push(i);
            }
        });

        return a;
    }


    /**
    * Calculate the 'type' of a column
    *  @param {object} settings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnColumnTypes(settings) {
        var columns = settings.aoColumns;
        var data = settings.aoData;
        var types = DataTable.ext.type.detect;
        var i, ien, j, jen, k, ken;
        var col, cell, detectedType, cache;

        // For each column, spin over the 
        for (i = 0, ien = columns.length; i < ien; i++) {
            col = columns[i];
            cache = [];

            if (!col.sType && col._sManualType) {
                col.sType = col._sManualType;
            }
            else if (!col.sType) {
                for (j = 0, jen = types.length; j < jen; j++) {
                    for (k = 0, ken = data.length; k < ken; k++) {
                        // Use a cache array so we only need to get the type data
                        // from the formatter once (when using multiple detectors)
                        if (cache[k] === undefined) {
                            ////console.log("10!");
                            cache[k] = _fnGetCellData(settings, k, i, 'type');
                        }

                        detectedType = types[j](cache[k], settings);

                        // Doesn't match, so break early, since this type can't
                        // apply to this column. Also, HTML is a special case since
                        // it is so similar to `string`. Just a single match is
                        // needed for a column to be html type
                        if (!detectedType || detectedType === 'html') {
                            break;
                        }
                    }

                    // Type is valid for all data points in the column - use this
                    // type
                    if (detectedType) {
                        col.sType = detectedType;
                        break;
                    }
                }

                // Fall back - if no type was detected, always use string
                if (!col.sType) {
                    col.sType = 'string';
                }
            }
        }
    }


    /**
    * Take the column definitions and static columns arrays and calculate how
    * they relate to column indexes. The callback function will then apply the
    * definition found for a column to a suitable configuration object.
    *  @param {object} oSettings dataTables settings object
    *  @param {array} aoColDefs The aoColumnDefs array that is to be applied
    *  @param {array} aoCols The aoColumns array that defines columns individually
    *  @param {function} fn Callback function - takes two parameters, the calculated
    *    column index and the definition for that column.
    *  @memberof DataTable#oApi
    */
    function _fnApplyColumnDefs(oSettings, aoColDefs, aoCols, fn) {
        var i, iLen, j, jLen, k, kLen, def;
        var columns = oSettings.aoColumns;

        // Column definitions with aTargets
        if (aoColDefs) {
            /* Loop over the definitions array - loop in reverse so first instance has priority */
            for (i = aoColDefs.length - 1; i >= 0; i--) {
                def = aoColDefs[i];

                /* Each definition can target multiple columns, as it is an array */
                var aTargets = def.targets !== undefined ?
					def.targets :
					def.aTargets;

                if (!$.isArray(aTargets)) {
                    aTargets = [aTargets];
                }

                for (j = 0, jLen = aTargets.length; j < jLen; j++) {
                    if (typeof aTargets[j] === 'number' && aTargets[j] >= 0) {
                        /* Add columns that we don't yet know about */
                        while (columns.length <= aTargets[j]) {
                            _fnAddColumn(oSettings);
                        }

                        /* Integer, basic index */
                        fn(aTargets[j], def);
                    }
                    else if (typeof aTargets[j] === 'number' && aTargets[j] < 0) {
                        /* Negative integer, right to left column counting */
                        fn(columns.length + aTargets[j], def);
                    }
                    else if (typeof aTargets[j] === 'string') {
                        /* Class name matching on TH element */
                        for (k = 0, kLen = columns.length; k < kLen; k++) {
                            if (aTargets[j] == "_all" ||
							     $(columns[k].nTh).hasClass(aTargets[j])) {
                                fn(k, def);
                            }
                        }
                    }
                }
            }
        }

        // Statically defined columns array
        if (aoCols) {
            for (i = 0, iLen = aoCols.length; i < iLen; i++) {
                fn(i, aoCols[i]);
            }
        }
    }

    /**
    * Add a data array to the table, creating DOM node etc. This is the parallel to
    * _fnGatherData, but for adding rows from a Javascript source, rather than a
    * DOM source.
    *  @param {object} oSettings dataTables settings object
    *  @param {array} aData data array to be added
    *  @param {node} [nTr] TR element to add to the table - optional. If not given,
    *    DataTables will create a row automatically
    *  @param {array} [anTds] Array of TD|TH elements for the row - must be given
    *    if nTr is.
    *  @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
    *  @memberof DataTable#oApi
    */
    function _fnAddData(oSettings, aDataIn, nTr, anTds) {
        /* Create the object for storing information about this new row */
        var iRow = oSettings.aoData.length;
        var oData = $.extend(true, {}, DataTable.models.oRow, {
            src: nTr ? 'dom' : 'data'
        });
        ////console.log("start");

        oData._aData = aDataIn;
        oSettings.aoData.push(oData);

        /* Create the cells */
        var nTd, sThisType;
        var columns = oSettings.aoColumns;
        for (var i = 0, iLen = columns.length; i < iLen; i++) {

            /*BEGIN - HERE IS MAIN CHANGE FOR SHOWING GOOD DATA IN COLREORDER*/
            //            var reorder = i;
            //            if (oSettings.aoColumns[i]._ColReorder_iOrigCol != undefined) {
            //                reorder = oSettings.aoColumns[i]._ColReorder_iOrigCol;
            //                
            //            }
            /*END - HERE IS MAIN CHANGE FOR SHOWING GOOD DATA IN COLREORDER*/

            // When working with a row, the data source object must be populated. In
            // all other cases, the data source object is already populated, so we
            // don't overwrite it, which might break bindings etc
            if (nTr) {
                ////console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
                _fnSetCellData(oSettings, iRow, i, _fnGetCellData(oSettings, iRow, i));

            }
            columns[i].sType = null;
        }

        /* Add to the display array */
        oSettings.aiDisplayMaster.push(iRow);

        /* Create the DOM information */
        if (!oSettings.oFeatures.bDeferRender) {
            _fnCreateTr(oSettings, iRow, nTr, anTds);
        }

        return iRow;
    }


    /**
    * Add one or more TR elements to the table. Generally we'd expect to
    * use this for reading data from a DOM sourced table, but it could be
    * used for an TR element. Note that if a TR is given, it is used (i.e.
    * it is not cloned).
    *  @param {object} settings dataTables settings object
    *  @param {array|node|jQuery} trs The TR element(s) to add to the table
    *  @returns {array} Array of indexes for the added rows
    *  @memberof DataTable#oApi
    */
    function _fnAddTr(settings, trs) {
        var row;

        // Allow an individual node to be passed in
        if (!(trs instanceof $)) {
            trs = $(trs);
        }

        return trs.map(function (i, el) {
            row = _fnGetRowElements(settings, el);
            ////console.log("p1");
            return _fnAddData(settings, row.data, el, row.cells);
        });
    }


    /**
    * Take a TR element and convert it to an index in aoData
    *  @param {object} oSettings dataTables settings object
    *  @param {node} n the TR element to find
    *  @returns {int} index if the node is found, null if not
    *  @memberof DataTable#oApi
    */
    function _fnNodeToDataIndex(oSettings, n) {
        return (n._DT_RowIndex !== undefined) ? n._DT_RowIndex : null;
    }


    /**
    * Take a TD element and convert it into a column data index (not the visible index)
    *  @param {object} oSettings dataTables settings object
    *  @param {int} iRow The row number the TD/TH can be found in
    *  @param {node} n The TD/TH element to find
    *  @returns {int} index if the node is found, -1 if not
    *  @memberof DataTable#oApi
    */
    function _fnNodeToColumnIndex(oSettings, iRow, n) {
        return $.inArray(n, oSettings.aoData[iRow].anCells);
    }


    /**
    * Get the data for a given cell from the internal cache, taking into account data mapping
    *  @param {object} oSettings dataTables settings object
    *  @param {int} iRow aoData row id
    *  @param {int} iCol Column index
    *  @param {string} sSpecific data get type ('display', 'type' 'filter' 'sort')
    *  @returns {*} Cell data
    *  @memberof DataTable#oApi
    */
    function _fnGetCellData(oSettings, iRow, iCol, sSpecific) {
        //console.log("!!!!");
        var oCol = oSettings.aoColumns[iCol];

        var oData = oSettings.aoData[iRow]._aData;
        //console.log("*" + iRow + " => " + oData);
        //console.log("**" + iCol + " => " + oCol);

        var sData = oCol.fnGetData(oData, sSpecific);
        //console.log("*" + iCol + " => " + sData);
        if (sData === undefined) {
            if (oSettings.iDrawError != oSettings.iDraw && oCol.sDefaultContent === null) {
                _fnLog(oSettings, 0, "Requested unknown parameter " +
					(typeof oCol.mData == 'function' ? '{function}' : "'" + oCol.mData + "'") +
					" for row " + iRow, 4);
                oSettings.iDrawError = oSettings.iDraw;
            }
            return oCol.sDefaultContent;
        }

        /* When the data source is null, we can use default column data */
        if ((sData === oData || sData === null) && oCol.sDefaultContent !== null) {
            sData = oCol.sDefaultContent;
        }
        else if (typeof sData === 'function') {
            // If the data source is a function, then we run it and use the return
            return sData();
        }

        if (sData === null && sSpecific == 'display') {
            return '';
        }
        // //console.log(iCol + ":" + sData);
        return sData;
    }


    /**
    * Set the value for a specific cell, into the internal data cache
    *  @param {object} oSettings dataTables settings object
    *  @param {int} iRow aoData row id
    *  @param {int} iCol Column index
    *  @param {*} val Value to set
    *  @memberof DataTable#oApi
    */
    function _fnSetCellData(oSettings, iRow, iCol, val) {
        var oCol = oSettings.aoColumns[iCol];
        var oData = oSettings.aoData[iRow]._aData;

        oCol.fnSetData(oData, val);
    }


    // Private variable that is used to match action syntax in the data property object
    var __reArray = /\[.*?\]$/;
    var __reFn = /\(\)$/;

    /**
    * Split string on periods, taking into account escaped periods
    * @param  {string} str String to split
    * @return {array} Split string
    */
    function _fnSplitObjNotation(str) {
        return $.map(str.match(/(\\.|[^\.])+/g), function (s) {
            return s.replace('\\.', '.');
        });
    }


    /**
    * Return a function that can be used to get data from a source object, taking
    * into account the ability to use nested objects as a source
    *  @param {string|int|function} mSource The data source for the object
    *  @returns {function} Data get function
    *  @memberof DataTable#oApi
    */
    function _fnGetObjectDataFn(mSource) {
        if ($.isPlainObject(mSource)) {
            /* Build an object of get functions, and wrap them in a single call */
            var o = {};
            $.each(mSource, function (key, val) {
                if (val) {
                    o[key] = _fnGetObjectDataFn(val);
                }
            });

            return function (data, type, extra) {
                var t = o[type] || o._;
                return t !== undefined ?
					t(data, type, extra) :
					data;
            };
        }
        else if (mSource === null) {
            /* Give an empty string for rendering / sorting etc */
            return function (data, type) {
                return data;
            };
        }
        else if (typeof mSource === 'function') {
            return function (data, type, extra) {
                return mSource(data, type, extra);
            };
        }
        else if (typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
			      mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1)) {
            /* If there is a . in the source string then the data source is in a
            * nested object so we loop over the data for each level to get the next
            * level down. On each loop we test for undefined, and if found immediately
            * return. This allows entire objects to be missing and sDefaultContent to
            * be used if defined, rather than throwing an error
            */
            var fetchData = function (data, type, src) {
                var arrayNotation, funcNotation, out, innerSrc;

                if (src !== "") {
                    var a = _fnSplitObjNotation(src);

                    for (var i = 0, iLen = a.length; i < iLen; i++) {
                        // Check if we are dealing with special notation
                        arrayNotation = a[i].match(__reArray);
                        funcNotation = a[i].match(__reFn);

                        if (arrayNotation) {
                            // Array notation
                            a[i] = a[i].replace(__reArray, '');

                            // Condition allows simply [] to be passed in
                            if (a[i] !== "") {
                                data = data[a[i]];
                            }
                            out = [];

                            // Get the remainder of the nested object to get
                            a.splice(0, i + 1);
                            innerSrc = a.join('.');

                            // Traverse each entry in the array getting the properties requested
                            for (var j = 0, jLen = data.length; j < jLen; j++) {
                                out.push(fetchData(data[j], type, innerSrc));
                            }

                            // If a string is given in between the array notation indicators, that
                            // is used to join the strings together, otherwise an array is returned
                            var join = arrayNotation[0].substring(1, arrayNotation[0].length - 1);
                            data = (join === "") ? out : out.join(join);

                            // The inner call to fetchData has already traversed through the remainder
                            // of the source requested, so we exit from the loop
                            break;
                        }
                        else if (funcNotation) {
                            // Function call
                            a[i] = a[i].replace(__reFn, '');
                            data = data[a[i]]();
                            continue;
                        }

                        if (data === null || data[a[i]] === undefined) {
                            return undefined;
                        }
                        data = data[a[i]];
                    }
                }

                return data;
            };

            return function (data, type) {
                return fetchData(data, type, mSource);
            };
        }
        else {
            /* Array or flat object mapping */
            return function (data, type) {
                return data[mSource];
            };
        }
    }


    /**
    * Return a function that can be used to set data from a source object, taking
    * into account the ability to use nested objects as a source
    *  @param {string|int|function} mSource The data source for the object
    *  @returns {function} Data set function
    *  @memberof DataTable#oApi
    */
    function _fnSetObjectDataFn(mSource) {
        if ($.isPlainObject(mSource)) {
            /* Unlike get, only the underscore (global) option is used for for
            * setting data since we don't know the type here. This is why an object
            * option is not documented for `mData` (which is read/write), but it is
            * for `mRender` which is read only.
            */
            return _fnSetObjectDataFn(mSource._);
        }
        else if (mSource === null) {
            /* Nothing to do when the data source is null */
            return function (data, val) { };
        }
        else if (typeof mSource === 'function') {
            return function (data, val) {
                mSource(data, 'set', val);
            };
        }
        else if (typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
			      mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1)) {
            /* Like the get, we need to get data from a nested object */
            var setData = function (data, val, src) {
                var a = _fnSplitObjNotation(src), b;
                var aLast = a[a.length - 1];
                var arrayNotation, funcNotation, o, innerSrc;

                for (var i = 0, iLen = a.length - 1; i < iLen; i++) {
                    // Check if we are dealing with an array notation request
                    arrayNotation = a[i].match(__reArray);
                    funcNotation = a[i].match(__reFn);

                    if (arrayNotation) {
                        a[i] = a[i].replace(__reArray, '');
                        data[a[i]] = [];

                        // Get the remainder of the nested object to set so we can recurse
                        b = a.slice();
                        b.splice(0, i + 1);
                        innerSrc = b.join('.');

                        // Traverse each entry in the array setting the properties requested
                        for (var j = 0, jLen = val.length; j < jLen; j++) {
                            o = {};
                            setData(o, val[j], innerSrc);
                            data[a[i]].push(o);
                        }

                        // The inner call to setData has already traversed through the remainder
                        // of the source and has set the data, thus we can exit here
                        return;
                    }
                    else if (funcNotation) {
                        // Function call
                        a[i] = a[i].replace(__reFn, '');
                        data = data[a[i]](val);
                    }

                    // If the nested object doesn't currently exist - since we are
                    // trying to set the value - create it
                    if (data[a[i]] === null || data[a[i]] === undefined) {
                        data[a[i]] = {};
                    }
                    data = data[a[i]];
                }

                // Last item in the input - i.e, the actual set
                if (aLast.match(__reFn)) {
                    // Function call
                    data = data[aLast.replace(__reFn, '')](val);
                }
                else {
                    // If array notation is used, we just want to strip it and use the property name
                    // and assign the value. If it isn't used, then we get the result we want anyway
                    data[aLast.replace(__reArray, '')] = val;
                }
            };

            return function (data, val) {
                return setData(data, val, mSource);
            };
        }
        else {
            /* Array or flat object mapping */
            return function (data, val) {
                data[mSource] = val;
            };
        }
    }


    /**
    * Return an array with the full table data
    *  @param {object} oSettings dataTables settings object
    *  @returns array {array} aData Master data array
    *  @memberof DataTable#oApi
    */
    function _fnGetDataMaster(settings) {
        return _pluck(settings.aoData, '_aData');
    }


    /**
    * Nuke the table
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnClearTable(settings) {
        settings.aoData.length = 0;
        settings.aiDisplayMaster.length = 0;
        settings.aiDisplay.length = 0;
    }


    /**
    * Take an array of integers (index array) and remove a target integer (value - not
    * the key!)
    *  @param {array} a Index array to target
    *  @param {int} iTarget value to find
    *  @memberof DataTable#oApi
    */
    function _fnDeleteIndex(a, iTarget, splice) {
        var iTargetIndex = -1;

        for (var i = 0, iLen = a.length; i < iLen; i++) {
            if (a[i] == iTarget) {
                iTargetIndex = i;
            }
            else if (a[i] > iTarget) {
                a[i]--;
            }
        }

        if (iTargetIndex != -1 && splice === undefined) {
            a.splice(iTargetIndex, 1);
        }
    }


    /**
    * Mark cached data as invalid such that a re-read of the data will occur when
    * the cached data is next requested. Also update from the data source object.
    *
    * @param {object} settings DataTables settings object
    * @param  {int}    rowIdx   Row index to invalidate
    * @memberof DataTable#oApi
    *
    * @todo For the modularisation of v1.11 this will need to become a callback, so
    *   the sort and filter methods can subscribe to it. That will required
    *   initialisation options for sorting, which is why it is not already baked in
    */
    function _fnInvalidateRow(settings, rowIdx, src, column) {
        var row = settings.aoData[rowIdx];
        var i, ien;

        // Are we reading last data from DOM or the data object?
        if (src === 'dom' || ((!src || src === 'auto') && row.src === 'dom')) {
            // Read the data from the DOM
            row._aData = _fnGetRowElements(settings, row).data;
        }
        else {
            // Reading from data object, update the DOM
            var cells = row.anCells;

            if (cells) {
                //console.log("1!");
                for (i = 0, ien = cells.length; i < ien; i++) {
                    cells[i].innerHTML = _fnGetCellData(settings, rowIdx, i, 'display');
                }
            }
        }

        row._aSortData = null;
        row._aFilterData = null;

        // Invalidate the type for a specific column (if given) or all columns since
        // the data might have changed
        var cols = settings.aoColumns;
        if (column !== undefined) {
            cols[column].sType = null;
        }
        else {
            for (i = 0, ien = cols.length; i < ien; i++) {
                cols[i].sType = null;
            }
        }

        // Update DataTables special `DT_*` attributes for the row
        _fnRowAttributes(row);
    }


    /**
    * Build a data source object from an HTML row, reading the contents of the
    * cells that are in the row.
    *
    * @param {object} settings DataTables settings object
    * @param {node|object} TR element from which to read data or existing row
    *   object from which to re-read the data from the cells
    * @returns {object} Object with two parameters: `data` the data read, in
    *   document order, and `cells` and array of nodes (they can be useful to the
    *   caller, so rather than needing a second traversal to get them, just return
    *   them from here).
    * @memberof DataTable#oApi
    */
    function _fnGetRowElements(settings, row) {
        var 
			d = [],
			tds = [],
			td = row.firstChild,
			name, col, o, i = 0, contents,
			columns = settings.aoColumns;

        var attr = function (str, data, td) {
            if (typeof str === 'string') {
                var idx = str.indexOf('@');

                if (idx !== -1) {
                    var src = str.substring(idx + 1);
                    o['@' + src] = td.getAttribute(src);
                }
            }
        };

        var cellProcess = function (cell) {
            col = columns[i];
            contents = $.trim(cell.innerHTML);

            if (col && col._bAttrSrc) {
                o = {
                    display: contents
                };

                attr(col.mData.sort, o, cell);
                attr(col.mData.type, o, cell);
                attr(col.mData.filter, o, cell);

                d.push(o);
            }
            else {
                d.push(contents);
            }

            tds.push(cell);
            i++;
        };

        if (td) {
            // `tr` element passed in
            while (td) {
                name = td.nodeName.toUpperCase();

                if (name == "TD" || name == "TH") {
                    cellProcess(td);
                }

                td = td.nextSibling;
            }
        }
        else {
            // Existing row object passed in
            tds = row.anCells;

            for (var j = 0, jen = tds.length; j < jen; j++) {
                cellProcess(tds[j]);
            }
        }

        return {
            data: d,
            cells: tds
        };
    }
    /**
    * Create a new TR element (and it's TD children) for a row
    *  @param {object} oSettings dataTables settings object
    *  @param {int} iRow Row to consider
    *  @param {node} [nTrIn] TR element to add to the table - optional. If not given,
    *    DataTables will create a row automatically
    *  @param {array} [anTds] Array of TD|TH elements for the row - must be given
    *    if nTr is.
    *  @memberof DataTable#oApi
    */
    function _fnCreateTr(oSettings, iRow, nTrIn, anTds) {
        var 
			row = oSettings.aoData[iRow],
			rowData = row._aData,
			cells = [],
			nTr, nTd, oCol,
			i, iLen;

        if (row.nTr === null) {
            nTr = nTrIn || document.createElement('tr');

            row.nTr = nTr;
            row.anCells = cells;

            /* Use a private property on the node to allow reserve mapping from the node
            * to the aoData array for fast look up
            */
            nTr._DT_RowIndex = iRow;

            /* Special parameters can be given by the data source to be used on the row */
            _fnRowAttributes(row);

            /* Process each column */
            for (i = 0, iLen = oSettings.aoColumns.length; i < iLen; i++) {
                oCol = oSettings.aoColumns[i];

                nTd = nTrIn ? anTds[i] : document.createElement(oCol.sCellType);
                cells.push(nTd);

                // Need to create the HTML if new, or if a rendering function is defined
                if (!nTrIn || oCol.mRender || oCol.mData !== i) {
                    ////console.log("2!");
                    var colonneOriginale = (oSettings.sDom.indexOf('R') >= 0 ? oSettings.aoColumns[i]._ColReorder_iOrigCol : i);
                    nTd.innerHTML = _fnGetCellData(oSettings, iRow, colonneOriginale, 'display');
                }

                /* Add user defined class */
                if (oCol.sClass) {
                    nTd.className += ' ' + oCol.sClass;
                }

                // Visibility - add or remove as required
                if (oCol.bVisible && !nTrIn) {
                    nTr.appendChild(nTd);
                }
                else if (!oCol.bVisible && nTrIn) {
                    nTd.parentNode.removeChild(nTd);
                }

                if (oCol.fnCreatedCell) {
                    ////console.log("3!");
                    oCol.fnCreatedCell.call(oSettings.oInstance,
						nTd, _fnGetCellData(oSettings, iRow, i, 'display'), rowData, iRow, i
					);
                }
            }

            _fnCallbackFire(oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow]);
        }

        // Remove once webkit bug 131819 and Chromium bug 365619 have been resolved
        // and deployed
        row.nTr.setAttribute('role', 'row');
    }


    /**
    * Add attributes to a row based on the special `DT_*` parameters in a data
    * source object.
    *  @param {object} DataTables row object for the row to be modified
    *  @memberof DataTable#oApi
    */
    function _fnRowAttributes(row) {
        var tr = row.nTr;
        var data = row._aData;

        if (tr) {
            if (data.DT_RowId) {
                tr.id = data.DT_RowId;
            }

            if (data.DT_RowClass) {
                // Remove any classes added by DT_RowClass before
                var a = data.DT_RowClass.split(' ');
                row.__rowc = row.__rowc ?
					_unique(row.__rowc.concat(a)) :
					a;

                $(tr)
					.removeClass(row.__rowc.join(' '))
					.addClass(data.DT_RowClass);
            }

            if (data.DT_RowData) {
                $(tr).data(data.DT_RowData);
            }
        }
    }


    /**
    * Create the HTML header for the table
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnBuildHead(oSettings) {
        var i, ien, cell, row, column;
        var thead = oSettings.nTHead;
        var tfoot = oSettings.nTFoot;
        var createHeader = $('th, td', thead).length === 0;
        var classes = oSettings.oClasses;
        var columns = oSettings.aoColumns;

        if (createHeader) {
            row = $('<tr/>').appendTo(thead);
        }

        for (i = 0, ien = columns.length; i < ien; i++) {
            column = columns[i];
            cell = $(column.nTh).addClass(column.sClass);

            if (createHeader) {
                cell.appendTo(row);
            }

            // 1.11 move into sorting
            if (oSettings.oFeatures.bSort) {
                cell.addClass(column.sSortingClass);

                if (column.bSortable !== false) {
                    cell
						.attr('tabindex', oSettings.iTabIndex)
						.attr('aria-controls', oSettings.sTableId);

                    _fnSortAttachListener(oSettings, column.nTh, i);
                }
            }

            if (column.sTitle != cell.html()) {
                cell.html(column.sTitle);
            }

            _fnRenderer(oSettings, 'header')(
				oSettings, cell, column, classes
			);
        }

        if (createHeader) {
            _fnDetectHeader(oSettings.aoHeader, thead);
        }

        /* ARIA role for the rows */
        $(thead).find('>tr').attr('role', 'row');

        /* Deal with the footer - add classes if required */
        $(thead).find('>tr>th, >tr>td').addClass(classes.sHeaderTH);
        $(tfoot).find('>tr>th, >tr>td').addClass(classes.sFooterTH);

        // Cache the footer cells. Note that we only take the cells from the first
        // row in the footer. If there is more than one row the user wants to
        // interact with, they need to use the table().foot() method. Note also this
        // allows cells to be used for multiple columns using colspan
        if (tfoot !== null) {
            var cells = oSettings.aoFooter[0];

            for (i = 0, ien = cells.length; i < ien; i++) {
                column = columns[i];
                column.nTf = cells[i].cell;

                if (column.sClass) {
                    $(column.nTf).addClass(column.sClass);
                }
            }
        }
    }


    /**
    * Draw the header (or footer) element based on the column visibility states. The
    * methodology here is to use the layout array from _fnDetectHeader, modified for
    * the instantaneous column visibility, to construct the new layout. The grid is
    * traversed over cell at a time in a rows x columns grid fashion, although each
    * cell insert can cover multiple elements in the grid - which is tracks using the
    * aApplied array. Cell inserts in the grid will only occur where there isn't
    * already a cell in that position.
    *  @param {object} oSettings dataTables settings object
    *  @param array {objects} aoSource Layout array from _fnDetectHeader
    *  @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
    *  @memberof DataTable#oApi
    */
    function _fnDrawHead(oSettings, aoSource, bIncludeHidden) {
        var i, iLen, j, jLen, k, kLen, n, nLocalTr;
        var aoLocal = [];
        var aApplied = [];
        var iColumns = oSettings.aoColumns.length;
        var iRowspan, iColspan;

        if (!aoSource) {
            return;
        }

        if (bIncludeHidden === undefined) {
            bIncludeHidden = false;
        }

        /* Make a copy of the master layout array, but without the visible columns in it */
        for (i = 0, iLen = aoSource.length; i < iLen; i++) {
            aoLocal[i] = aoSource[i].slice();
            aoLocal[i].nTr = aoSource[i].nTr;

            /* Remove any columns which are currently hidden */
            for (j = iColumns - 1; j >= 0; j--) {
                if (!oSettings.aoColumns[j].bVisible && !bIncludeHidden) {
                    aoLocal[i].splice(j, 1);
                }
            }

            /* Prep the applied array - it needs an element for each row */
            aApplied.push([]);
        }

        for (i = 0, iLen = aoLocal.length; i < iLen; i++) {
            nLocalTr = aoLocal[i].nTr;

            /* All cells are going to be replaced, so empty out the row */
            if (nLocalTr) {
                while ((n = nLocalTr.firstChild)) {
                    nLocalTr.removeChild(n);
                }
            }

            for (j = 0, jLen = aoLocal[i].length; j < jLen; j++) {
                iRowspan = 1;
                iColspan = 1;

                /* Check to see if there is already a cell (row/colspan) covering our target
                * insert point. If there is, then there is nothing to do.
                */
                if (aApplied[i][j] === undefined) {
                    nLocalTr.appendChild(aoLocal[i][j].cell);
                    aApplied[i][j] = 1;

                    /* Expand the cell to cover as many rows as needed */
                    while (aoLocal[i + iRowspan] !== undefined &&
					        aoLocal[i][j].cell == aoLocal[i + iRowspan][j].cell) {
                        aApplied[i + iRowspan][j] = 1;
                        iRowspan++;
                    }

                    /* Expand the cell to cover as many columns as needed */
                    while (aoLocal[i][j + iColspan] !== undefined &&
					        aoLocal[i][j].cell == aoLocal[i][j + iColspan].cell) {
                        /* Must update the applied array over the rows for the columns */
                        for (k = 0; k < iRowspan; k++) {
                            aApplied[i + k][j + iColspan] = 1;
                        }
                        iColspan++;
                    }

                    /* Do the actual expansion in the DOM */
                    $(aoLocal[i][j].cell)
						.attr('rowspan', iRowspan)
						.attr('colspan', iColspan);
                }
            }
        }
    }


    /**
    * Insert the required TR nodes into the table for display
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnDraw(oSettings) {
       // console.log("istart !" + oSettings._iDisplayStart);
        if ((etatTest == true && oSettings.oFeatures.bServerSide) || oSettings.oFeatures.bServerSide == false) {
            /* Provide a pre-callback function which can be used to cancel the draw is false is returned */
            var aPreDraw = _fnCallbackFire(oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings]);
            
            if ($.inArray(false, aPreDraw) !== -1) {
                _fnProcessingDisplay(oSettings, false);
                return;
            }

            var i, iLen, n;
            var anRows = [];
            var iRowCount = 0;
            var asStripeClasses = oSettings.asStripeClasses;
            var iStripes = asStripeClasses.length;
            var iOpenRows = oSettings.aoOpenRows.length;
            var oLang = oSettings.oLanguage;
            var iInitDisplayStart = oSettings.iInitDisplayStart;
            var bServerSide = _fnDataSource(oSettings) == 'ssp';
            var aiDisplay = oSettings.aiDisplay;

            oSettings.bDrawing = true;

            /* Check and see if we have an initial draw position from state saving */
            if (iInitDisplayStart !== undefined && iInitDisplayStart !== -1) {
                oSettings._iDisplayStart = bServerSide ?
				    iInitDisplayStart :
				    iInitDisplayStart >= oSettings.fnRecordsDisplay() ?
					    0 :
					    iInitDisplayStart;

                oSettings.iInitDisplayStart = -1;
            }

            var iDisplayStart = oSettings._iDisplayStart;
            var iDisplayEnd = oSettings.fnDisplayEnd();
            //console.log("iDisplayStart !" + iDisplayStart);
            //console.log("iDisplayEnd !" + iDisplayEnd);
            /* Server-side processing draw intercept */
            if (oSettings.bDeferLoading) {
                oSettings.bDeferLoading = false;
                oSettings.iDraw++;
                _fnProcessingDisplay(oSettings, false);
            }
            else if (!bServerSide) {
                oSettings.iDraw++;
            }
            else if (!oSettings.bDestroying && !_fnAjaxUpdate(oSettings)) {
                return;
            }

            if (aiDisplay.length !== 0) {
                var iStart = bServerSide ? 0 : iDisplayStart;
                var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd;

                for (var j = iStart; j < iEnd; j++) {
                    var iDataIndex = aiDisplay[j];
                    var aoData = oSettings.aoData[iDataIndex];
                    if (aoData.nTr === null) {
                        _fnCreateTr(oSettings, iDataIndex);
                    }

                    var nRow = aoData.nTr;

                    /* Remove the old striping classes and then add the new one */
                    if (iStripes !== 0) {
                        var sStripe = asStripeClasses[iRowCount % iStripes];
                        if (aoData._sRowStripe != sStripe) {
                            $(nRow).removeClass(aoData._sRowStripe).addClass(sStripe);
                            aoData._sRowStripe = sStripe;
                        }
                    }

                    /* Row callback functions - might want to manipulate the row */
                    _fnCallbackFire(oSettings, 'aoRowCallback', null,
					    [nRow, aoData._aData, iRowCount, j]);

                    anRows.push(nRow);
                    iRowCount++;
                }
                $('#' + oSettings.sInstance + ' tbody').css('display', 'inline-block');
            }
            else {
                /* Table is empty - create a row with an empty message in it */
                var sZero = oLang.sZeroRecords;
                if (oSettings.iDraw == 1 && _fnDataSource(oSettings) == 'ajax') {
                    sZero = oLang.sLoadingRecords;
                }
                else if (oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0) {
                    sZero = oLang.sEmptyTable;
                }

                anRows[0] = $('<tr/>', { 'class': iStripes ? asStripeClasses[0] : '' })
				    .append($('<td />', {
				        'valign': 'top',
				        'colSpan': _fnVisbleColumns(oSettings),
				        'class': oSettings.oClasses.sRowEmpty
				    }).html(sZero))[0];
                $('#' + oSettings.sInstance + ' tbody').css('display', 'table-row-group');
            }

            /* Header and footer callbacks */
            _fnCallbackFire(oSettings, 'aoHeaderCallback', 'header', [$(oSettings.nTHead).children('tr')[0],
			    _fnGetDataMaster(oSettings), iDisplayStart, iDisplayEnd, aiDisplay]);

            _fnCallbackFire(oSettings, 'aoFooterCallback', 'footer', [$(oSettings.nTFoot).children('tr')[0],
			    _fnGetDataMaster(oSettings), iDisplayStart, iDisplayEnd, aiDisplay]);

            var body = $(oSettings.nTBody);

            body.children().detach();
            body.append($(anRows));

            /* Call all required callback functions for the end of a draw */
            _fnCallbackFire(oSettings, 'aoDrawCallback', 'draw', [oSettings]);

            /* Draw is complete, sorting and filtering must be as well */
            oSettings.bSorted = false;
            oSettings.bFiltered = false;
            oSettings.bDrawing = false;
        }
       // console.log("end !");
    }


    /**
    * Redraw the table - taking account of the various features which are enabled
    *  @param {object} oSettings dataTables settings object
    *  @param {boolean} [holdPosition] Keep the current paging position. By default
    *    the paging is reset to the first page
    *  @memberof DataTable#oApi
    */
    function _fnReDraw(settings, holdPosition) {
        var 
			features = settings.oFeatures,
			sort = features.bSort,
			filter = features.bFilter;

        if (sort) {
            _fnSort(settings);
        }

        if (filter) {
            _fnFilterComplete(settings, settings.oPreviousSearch);
        }
        else {
            // No filtering, so we want to just use the display master
            settings.aiDisplay = settings.aiDisplayMaster.slice();
        }

        //paginate for template/server-side Nerium avec retour à la page 1 si action après initialisation
        //alert(settings.iDraw);
        //var nbpages = Math.floor(settings.aiDisplay.length / settings._iDisplayLength) + 1
        if (holdPosition !== true &&
        ((!settings.oFeatures.bServerSide && settings.iDraw > 1)
        || (settings.oFeatures.bServerSide && settings.iDraw > 0)) || settings._iDisplayStart > settings.aiDisplay.length) {

            settings._iDisplayStart = 0;
        }

        _fnDraw(settings);
    }


    /**
    * Add the options to the page HTML for the table
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnAddOptionsHtml(oSettings) {
        var classes = oSettings.oClasses;
        var table = $(oSettings.nTable);
        var holding = $('<div/>').insertBefore(table); // Holding element for speed
        var features = oSettings.oFeatures;

        // All DataTables are wrapped in a div
        var insert = $('<div/>', {
            id: oSettings.sTableId + '_wrapper',
            'class': classes.sWrapper + (oSettings.nTFoot ? '' : ' ' + classes.sNoFooter)
        });

        oSettings.nHolding = holding[0];
        oSettings.nTableWrapper = insert[0];
        oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;

        /* Loop over the user set positioning and place the elements as needed */
        var aDom = oSettings.sDom.split('');
        var featureNode, cOption, nNewNode, cNext, sAttr, j;
        for (var i = 0; i < aDom.length; i++) {
            featureNode = null;
            cOption = aDom[i];

            if (cOption == '<') {
                /* New container div */
                nNewNode = $('<div/>')[0];

                /* Check to see if we should append an id and/or a class name to the container */
                cNext = aDom[i + 1];
                if (cNext == "'" || cNext == '"') {
                    sAttr = "";
                    j = 2;
                    while (aDom[i + j] != cNext) {
                        sAttr += aDom[i + j];
                        j++;
                    }

                    /* Replace jQuery UI constants @todo depreciated */
                    if (sAttr == "H") {
                        sAttr = classes.sJUIHeader;
                    }
                    else if (sAttr == "F") {
                        sAttr = classes.sJUIFooter;
                    }

                    /* The attribute can be in the format of "#id.class", "#id" or "class" This logic
                    * breaks the string into parts and applies them as needed
                    */
                    if (sAttr.indexOf('.') != -1) {
                        var aSplit = sAttr.split('.');
                        nNewNode.id = aSplit[0].substr(1, aSplit[0].length - 1);
                        nNewNode.className = aSplit[1];
                    }
                    else if (sAttr.charAt(0) == "#") {
                        nNewNode.id = sAttr.substr(1, sAttr.length - 1);
                    }
                    else {
                        nNewNode.className = sAttr;
                    }

                    i += j; /* Move along the position array */
                }

                insert.append(nNewNode);
                insert = $(nNewNode);
            }
            else if (cOption == '>') {
                /* End container div */
                insert = insert.parent();
            }
            // @todo Move options into their own plugins?
            else if (cOption == 'l' && features.bPaginate && features.bLengthChange) {
                /* Length */
                featureNode = _fnFeatureHtmlLength(oSettings);
            }
            else if (cOption == 'f' && features.bFilter) {
                /* Filter */
                featureNode = _fnFeatureHtmlFilter(oSettings);
            }
            else if (cOption == 'r' && features.bProcessing) {
                /* pRocessing */
                featureNode = _fnFeatureHtmlProcessing(oSettings);
            }
            else if (cOption == 't') {
                /* Table */
                featureNode = _fnFeatureHtmlTable(oSettings);
            }
            else if (cOption == 'i' && features.bInfo) {
                /* Info */
                featureNode = _fnFeatureHtmlInfo(oSettings);
            }
            else if (cOption == 'p' && features.bPaginate) {
                /* Pagination */
                featureNode = _fnFeatureHtmlPaginate(oSettings);
            }
            else if (DataTable.ext.feature.length !== 0) {
                /* Plug-in features */
                var aoFeatures = DataTable.ext.feature;
                for (var k = 0, kLen = aoFeatures.length; k < kLen; k++) {
                    if (cOption == aoFeatures[k].cFeature) {
                        featureNode = aoFeatures[k].fnInit(oSettings);
                        break;
                    }
                }
            }

            /* Add to the 2D features array */
            if (featureNode) {
                var aanFeatures = oSettings.aanFeatures;

                if (!aanFeatures[cOption]) {
                    aanFeatures[cOption] = [];
                }

                aanFeatures[cOption].push(featureNode);
                insert.append(featureNode);
            }
        }

        /* Built our DOM structure - replace the holding div with what we want */
        holding.replaceWith(insert);
    }


    /**
    * Use the DOM source to create up an array of header cells. The idea here is to
    * create a layout grid (array) of rows x columns, which contains a reference
    * to the cell that that point in the grid (regardless of col/rowspan), such that
    * any column / row could be removed and the new grid constructed
    *  @param array {object} aLayout Array to store the calculated layout in
    *  @param {node} nThead The header/footer element for the table
    *  @memberof DataTable#oApi
    */
    function _fnDetectHeader(aLayout, nThead) {
        var nTrs = $(nThead).children('tr');
        var nTr, nCell;
        var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
        var bUnique;
        var fnShiftCol = function (a, i, j) {
            var k = a[i];
            while (k[j]) {
                j++;
            }
            return j;
        };

        aLayout.splice(0, aLayout.length);

        /* We know how many rows there are in the layout - so prep it */
        for (i = 0, iLen = nTrs.length; i < iLen; i++) {
            aLayout.push([]);
        }

        /* Calculate a layout array */
        for (i = 0, iLen = nTrs.length; i < iLen; i++) {
            nTr = nTrs[i];
            iColumn = 0;

            /* For every cell in the row... */
            nCell = nTr.firstChild;
            while (nCell) {
                if (nCell.nodeName.toUpperCase() == "TD" ||
				     nCell.nodeName.toUpperCase() == "TH") {
                    /* Get the col and rowspan attributes from the DOM and sanitise them */
                    iColspan = nCell.getAttribute('colspan') * 1;
                    iRowspan = nCell.getAttribute('rowspan') * 1;
                    iColspan = (!iColspan || iColspan === 0 || iColspan === 1) ? 1 : iColspan;
                    iRowspan = (!iRowspan || iRowspan === 0 || iRowspan === 1) ? 1 : iRowspan;

                    /* There might be colspan cells already in this row, so shift our target
                    * accordingly
                    */
                    iColShifted = fnShiftCol(aLayout, i, iColumn);

                    /* Cache calculation for unique columns */
                    bUnique = iColspan === 1 ? true : false;

                    /* If there is col / rowspan, copy the information into the layout grid */
                    for (l = 0; l < iColspan; l++) {
                        for (k = 0; k < iRowspan; k++) {
                            aLayout[i + k][iColShifted + l] = {
                                "cell": nCell,
                                "unique": bUnique
                            };
                            aLayout[i + k].nTr = nTr;
                        }
                    }
                }
                nCell = nCell.nextSibling;
            }
        }
    }


    /**
    * Get an array of unique th elements, one for each column
    *  @param {object} oSettings dataTables settings object
    *  @param {node} nHeader automatically detect the layout from this node - optional
    *  @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
    *  @returns array {node} aReturn list of unique th's
    *  @memberof DataTable#oApi
    */
    function _fnGetUniqueThs(oSettings, nHeader, aLayout) {
        var aReturn = [];
        if (!aLayout) {
            aLayout = oSettings.aoHeader;
            if (nHeader) {
                aLayout = [];
                _fnDetectHeader(aLayout, nHeader);
            }
        }

        for (var i = 0, iLen = aLayout.length; i < iLen; i++) {
            for (var j = 0, jLen = aLayout[i].length; j < jLen; j++) {
                if (aLayout[i][j].unique &&
					 (!aReturn[j] || !oSettings.bSortCellsTop)) {
                    aReturn[j] = aLayout[i][j].cell;
                }
            }
        }

        return aReturn;
    }



    /**
    * Create an Ajax call based on the table's settings, taking into account that
    * parameters can have multiple forms, and backwards compatibility.
    *
    * @param {object} oSettings dataTables settings object
    * @param {array} data Data to send to the server, required by
    *     DataTables - may be augmented by developer callbacks
    * @param {function} fn Callback function to run when data is obtained
    */
    function _fnBuildAjax(oSettings, data, fn) {
        // Compatibility with 1.9-, allow fnServerData and event to manipulate
        _fnCallbackFire(oSettings, 'aoServerParams', 'serverParams', [data]);

        // Convert to object based for 1.10+ if using the old array scheme which can
        // come from server-side processing or serverParams
        if (data && $.isArray(data)) {
            var tmp = {};
            var rbracket = /(.*?)\[\]$/;

            $.each(data, function (key, val) {
                var match = val.name.match(rbracket);

                if (match) {
                    // Support for arrays
                    var name = match[0];

                    if (!tmp[name]) {
                        tmp[name] = [];
                    }
                    tmp[name].push(val.value);
                }
                else {
                    tmp[val.name] = val.value;
                }
            });
            data = tmp;
        }

        var ajaxData;
        var ajax = oSettings.ajax;
        var instance = oSettings.oInstance;

        if ($.isPlainObject(ajax) && ajax.data) {
            ajaxData = ajax.data;

            var newData = $.isFunction(ajaxData) ?
				ajaxData(data) :  // fn can manipulate data or return an object
				ajaxData;           // object or array to merge

            // If the function returned an object, use that alone
            data = $.isFunction(ajaxData) && newData ?
				newData :
				$.extend(true, data, newData);

            // Remove the data property as we've resolved it already and don't want
            // jQuery to do it again (it is restored at the end of the function)
            delete ajax.data;
        }

        var baseAjax = {
            "data": data,
            "success": function (json) {
                var error = json.error || json.sError;
                if (error) {
                    oSettings.oApi._fnLog(oSettings, 0, error);
                }

                oSettings.json = json;
                _fnCallbackFire(oSettings, null, 'xhr', [oSettings, json]);
                fn(json);
            },
            "dataType": "json",
            "cache": false,
            "type": oSettings.sServerMethod,
            "error": function (xhr, error, thrown) {
                var log = oSettings.oApi._fnLog;

                if (error == "parsererror") {
                    log(oSettings, 0, 'Invalid JSON response', 1);
                }
                else if (xhr.readyState === 4) {
                    log(oSettings, 0, 'Ajax error', 7);
                }

                _fnProcessingDisplay(oSettings, false);
            }
        };

        // Store the data submitted for the API
        oSettings.oAjaxData = data;

        // Allow plug-ins and external processes to modify the data
        _fnCallbackFire(oSettings, null, 'preXhr', [oSettings, data]);

        if (oSettings.fnServerData) {
            // DataTables 1.9- compatibility
            oSettings.fnServerData.call(instance,
				oSettings.sAjaxSource,
				$.map(data, function (val, key) { // Need to convert back to 1.9 trad format
				    return { name: key, value: val };
				}),
				fn,
				oSettings
			);
        }
        else if (oSettings.sAjaxSource || typeof ajax === 'string') {
            // DataTables 1.9- compatibility
            oSettings.jqXHR = $.ajax($.extend(baseAjax, {
                url: ajax || oSettings.sAjaxSource
            }));
        }
        else if ($.isFunction(ajax)) {
            // Is a function - let the caller define what needs to be done
            oSettings.jqXHR = ajax.call(instance, data, fn, oSettings);
        }
        else {
            // Object to extend the base settings
            oSettings.jqXHR = $.ajax($.extend(baseAjax, ajax));

            // Restore for next time around
            ajax.data = ajaxData;
        }
    }


    /**
    * Update the table using an Ajax call
    *  @param {object} oSettings dataTables settings object
    *  @returns {boolean} Block the table drawing or not
    *  @memberof DataTable#oApi
    */
    function _fnAjaxUpdate(oSettings) {
        if (oSettings.bAjaxDataGet) {
            oSettings.iDraw++;
            _fnProcessingDisplay(oSettings, true);
            var iColumns = oSettings.aoColumns.length;
            var aoData = _fnAjaxParameters(oSettings);

            _fnBuildAjax(oSettings, aoData, function (json) {
                _fnAjaxUpdateDraw(oSettings, json);
            }, oSettings);

            return false;
        }
        return true;
    }


    /**
    * Build up the parameters in an object needed for a server-side processing
    * request. Note that this is basically done twice, is different ways - a modern
    * method which is used by default in DataTables 1.10 which uses objects and
    * arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if
    * the sAjaxSource option is used in the initialisation, or the legacyAjax
    * option is set.
    *  @param {object} oSettings dataTables settings object
    *  @returns {bool} block the table drawing or not
    *  @memberof DataTable#oApi
    */
    function _fnAjaxParameters(settings) {
        var 
			columns = settings.aoColumns,
			columnCount = columns.length,
			features = settings.oFeatures,
			preSearch = settings.oPreviousSearch,
			preColSearch = settings.aoPreSearchCols,
			i, data = [], dataProp, column, columnSearch,
			sort = _fnSortFlatten(settings),
			displayStart = settings._iDisplayStart,
			displayLength = features.bPaginate !== false ?
				settings._iDisplayLength :
				-1;

        var param = function (name, value) {
            data.push({ 'name': name, 'value': value });
        };

        // DataTables 1.9- compatible method
        param('sEcho', settings.iDraw);
        param('iColumns', columnCount);
        param('sColumns', _pluck(columns, 'sName').join(','));
        param('iDisplayStart', displayStart);
        param('iDisplayLength', displayLength);

        // DataTables 1.10+ method
        var d = {
            draw: settings.iDraw,
            columns: [],
            order: [],
            start: displayStart,
            length: displayLength,
            search: {
                value: preSearch.sSearch,
                regex: preSearch.bRegex
            }
        };

        for (i = 0; i < columnCount; i++) {
            column = columns[i];
            columnSearch = preColSearch[i];
            dataProp = typeof column.mData == "function" ? 'function' : column.mData;

            d.columns.push({
                data: dataProp,
                name: column.sName,
                searchable: column.bSearchable,
                orderable: column.bSortable,
                search: {
                    value: columnSearch.sSearch,
                    regex: columnSearch.bRegex
                }
            });

            param("mDataProp_" + i, dataProp);

            if (features.bFilter) {
                param('sSearch_' + i, columnSearch.sSearch);
                param('bRegex_' + i, columnSearch.bRegex);
                param('bSearchable_' + i, column.bSearchable);
            }

            if (features.bSort) {
                param('bSortable_' + i, column.bSortable);
            }
        }

        if (features.bFilter) {
            param('sSearch', preSearch.sSearch);
            param('bRegex', preSearch.bRegex);
        }

        if (features.bSort) {
            $.each(sort, function (i, val) {
                d.order.push({ column: val.col, dir: val.dir });

                param('iSortCol_' + i, val.col);
                param('sSortDir_' + i, val.dir);
            });

            param('iSortingCols', sort.length);
        }

        // If the legacy.ajax parameter is null, then we automatically decide which
        // form to use, based on sAjaxSource
        var legacy = DataTable.ext.legacy.ajax;
        if (legacy === null) {
            return settings.sAjaxSource ? data : d;
        }

        // Otherwise, if legacy has been specified then we use that to decide on the
        // form
        return legacy ? data : d;
    }


    /**
    * Data the data from the server (nuking the old) and redraw the table
    *  @param {object} oSettings dataTables settings object
    *  @param {object} json json data return from the server.
    *  @param {string} json.sEcho Tracking flag for DataTables to match requests
    *  @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
    *  @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
    *  @param {array} json.aaData The data to display on this page
    *  @param {string} [json.sColumns] Column ordering (sName, comma separated)
    *  @memberof DataTable#oApi
    */
    function _fnAjaxUpdateDraw(settings, json) {
        // v1.10 uses camelCase variables, while 1.9 uses Hungarian notation.
        // Support both
        var compat = function (old, modern) {
            return json[old] !== undefined ? json[old] : json[modern];
        };

        var draw = compat('sEcho', 'draw');
        var recordsTotal = compat('iTotalRecords', 'recordsTotal');
        var rocordsFiltered = compat('iTotalDisplayRecords', 'recordsFiltered');

        if (draw) {
            // Protect against out of sequence returns
            if (draw * 1 < settings.iDraw) {
                return;
            }
            settings.iDraw = draw * 1;
        }

        _fnClearTable(settings);
        settings._iRecordsTotal = parseInt(recordsTotal, 10);
        settings._iRecordsDisplay = parseInt(rocordsFiltered, 10);

        var data = _fnAjaxDataSrc(settings, json);
        ////console.log("p2");
        for (var i = 0, ien = data.length; i < ien; i++) {
            _fnAddData(settings, data[i]);
        }
        settings.aiDisplay = settings.aiDisplayMaster.slice();

        settings.bAjaxDataGet = false;
        _fnDraw(settings);

        if (!settings._bInitComplete) {
            _fnInitComplete(settings, json);
        }

        settings.bAjaxDataGet = true;
        _fnProcessingDisplay(settings, false);
    }


    /**
    * Get the data from the JSON data source to use for drawing a table. Using
    * `_fnGetObjectDataFn` allows the data to be sourced from a property of the
    * source object, or from a processing function.
    *  @param {object} oSettings dataTables settings object
    *  @param  {object} json Data source object / array from the server
    *  @return {array} Array of data to use
    */
    function _fnAjaxDataSrc(oSettings, json) {
        var dataSrc = $.isPlainObject(oSettings.ajax) && oSettings.ajax.dataSrc !== undefined ?
			oSettings.ajax.dataSrc :
			oSettings.sAjaxDataProp; // Compatibility with 1.9-.

        // Compatibility with 1.9-. In order to read from aaData, check if the
        // default has been changed, if not, check for aaData
        if (dataSrc === 'data') {
            return json.aaData || json[dataSrc];
        }

        return dataSrc !== "" ?
			_fnGetObjectDataFn(dataSrc)(json) :
			json;
    }


    /**
    * Generate the node required for filtering text
    *  @returns {node} Filter control element
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnFeatureHtmlFilter(settings) {
        var classes = settings.oClasses;
        var tableId = settings.sTableId;
        var previousSearch = settings.oPreviousSearch;
        var features = settings.aanFeatures;
        var input = '<input type="search" class="' + classes.sFilterInput + '"/>';

        var str = settings.oLanguage.sSearch;
        str = str.match(/_INPUT_/) ?
			str.replace('_INPUT_', input) :
			str + input;

        var filter = $('<div/>', {
            'id': !features.f ? tableId + '_filter' : null,
            'class': classes.sFilter
        })
			.append($('<label/>').append(str));

        var searchFn = function () {
            /* Update all other filter input elements for the new display */
            var n = features.f;
            var val = !this.value ? "" : this.value; // mental IE8 fix :-(

            /* Now do the filter */
            if (val != previousSearch.sSearch) {
                //enlever les accents
                // val = enleverAccents(val);
                _fnFilterComplete(settings, {
                    "sSearch": val,
                    "bRegex": previousSearch.bRegex,
                    "bSmart": previousSearch.bSmart,
                    "bCaseInsensitive": previousSearch.bCaseInsensitive
                });

                // Need to redraw, without resorting
                settings._iDisplayStart = 0;
                _fnDraw(settings);
            }
        };
        var jqFilter = $('input', filter)
			.val(previousSearch.sSearch.replace('"', '&quot;'))
			.bind(
				'keyup.DT search.DT input.DT paste.DT cut.DT',
				_fnDataSource(settings) === 'ssp' ?
					_fnThrottle(searchFn, 400) :
					searchFn
			)
			.bind('keypress.DT', function (e) {
			    /* Prevent form submission */
			    if (e.keyCode == 13) {
			        return false;
			    }
			})
			.attr('aria-controls', tableId);

        // Update the input elements whenever the table is filtered
        $(settings.nTable).on('filter.DT', function () {
            // IE9 throws an 'unknown error' if document.activeElement is used
            // inside an iframe or frame...
            try {
                if (jqFilter[0] !== document.activeElement) {
                    jqFilter.val(previousSearch.sSearch);
                }
            }
            catch (e) { }
        });

        return filter[0];
    }


    /**
    * Filter the table using both the global filter and column based filtering
    *  @param {object} oSettings dataTables settings object
    *  @param {object} oSearch search information
    *  @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
    *  @memberof DataTable#oApi
    */
    function _fnFilterComplete(oSettings, oInput, iForce) {
        var oPrevSearch = oSettings.oPreviousSearch;
        var aoPrevSearch = oSettings.aoPreSearchCols;
        var fnSaveFilter = function (oFilter) {
            /* Save the filtering values */
            oPrevSearch.sSearch = oFilter.sSearch;
            oPrevSearch.bRegex = oFilter.bRegex;
            oPrevSearch.bSmart = oFilter.bSmart;
            oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
        };
        var fnRegex = function (o) {
            // Backwards compatibility with the bEscapeRegex option
            return o.bEscapeRegex !== undefined ? !o.bEscapeRegex : o.bRegex;
        };

        // Resolve any column types that are unknown due to addition or invalidation
        // @todo As per sort - can this be moved into an event handler?
        _fnColumnTypes(oSettings);

        /* In server-side processing all filtering is done by the server, so no point hanging around here */
        if (_fnDataSource(oSettings) != 'ssp') {
            /* Global filter */
            _fnFilter(oSettings, oInput.sSearch, iForce, fnRegex(oInput), oInput.bSmart, oInput.bCaseInsensitive);
            fnSaveFilter(oInput);

            /* Now do the individual column filter */
            for (var i = 0; i < aoPrevSearch.length; i++) {

                _fnFilterColumn(oSettings, aoPrevSearch[i].sSearch, i, fnRegex(aoPrevSearch[i]),
					aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive);
            }

            /* Custom filtering */
            _fnFilterCustom(oSettings);
        }
        else {
            fnSaveFilter(oInput);
        }

        /* Tell the draw function we have been filtering */
        oSettings.bFiltered = true;
        _fnCallbackFire(oSettings, null, 'search', [oSettings]);
    }


    /**
    * Apply custom filtering functions
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnFilterCustom(settings) {
        var filters = DataTable.ext.search;
        var displayRows = settings.aiDisplay;
        var row, rowIdx;

        for (var i = 0, iLen = filters.length; i < iLen; i++) {
            for (var j = displayRows.length - 1; j >= 0; j--) {
                rowIdx = displayRows[j];
                row = settings.aoData[rowIdx];

                if (!filters[i](settings, row._aFilterData, rowIdx, row._aData)) {
                    displayRows.splice(j, 1);
                }
            }
        }
    }


    /**
    * Filter the table on a per-column basis
    *  @param {object} oSettings dataTables settings object
    *  @param {string} sInput string to filter on
    *  @param {int} iColumn column to filter
    *  @param {bool} bRegex treat search string as a regular expression or not
    *  @param {bool} bSmart use smart filtering or not
    *  @param {bool} bCaseInsensitive Do case insenstive matching or not
    *  @memberof DataTable#oApi
    */
    function _fnFilterColumn(settings, searchStr, colIdx, regex, smart, caseInsensitive) {
        if (searchStr === '') {
            return;
        }

        var data;
        var display = settings.aiDisplay;

        var colCustomSearch = "";
        if (searchStr.indexOf('[') >= 0 && searchStr.indexOf(']') >= 0) {
            colCustomSearch = searchStr.substring(searchStr.indexOf('['), searchStr.indexOf(']') + 1);
            searchStr = enleverAccents(searchStr.replace(colCustomSearch, ""));
            //            alert(colCustomSearch);
            //            alert(search);
            if (searchStr == "" && enleverAccents(colCustomSearch.replace("[", "").replace("]", "")) != "") {
                searchStr = enleverAccents(colCustomSearch.replace("[", "").replace("]", ""));
                colCustomSearch = "";
            }

        }
        if (colCustomSearch != "") {
            colCustomSearch = enleverAccents(colCustomSearch.replace("[", "|").replace("]", ""));
        }

        searchStr = enleverAccents(searchStr + colCustomSearch);
        var rpSearch = _fnFilterCreateSearch(searchStr, regex, smart, caseInsensitive);
        for (var i = display.length - 1; i >= 0; i--) {
            data = settings.aoData[display[i]]._aFilterData[colIdx];
            //ajout nerium recherche sur valeur vide en mode template
            data = (data.trim() == "" ? "(Vide)" : data);
            if (!rpSearch.test(data)) {
                display.splice(i, 1);
            }
        }
    }


    /**
    * Filter the data table based on user input and draw the table
    *  @param {object} settings dataTables settings object
    *  @param {string} input string to filter on
    *  @param {int} force optional - force a research of the master array (1) or not (undefined or 0)
    *  @param {bool} regex treat as a regular expression or not
    *  @param {bool} smart perform smart filtering or not
    *  @param {bool} caseInsensitive Do case insenstive matching or not
    *  @memberof DataTable#oApi
    */
    function _fnFilter(settings, input, force, regex, smart, caseInsensitive) {
        //enleverAccents
        input = enleverAccents(input);
        var rpSearch = _fnFilterCreateSearch(input, regex, smart, caseInsensitive);
        var prevSearch = settings.oPreviousSearch.sSearch;
        var displayMaster = settings.aiDisplayMaster;
        var display, invalidated, i;

        // Need to take account of custom filtering functions - always filter
        if (DataTable.ext.search.length !== 0) {
            force = true;
        }

        // Check if any of the rows were invalidated
        invalidated = _fnFilterData(settings);

        // If the input is blank - we just want the full data set
        if (input.length <= 0) {
            settings.aiDisplay = displayMaster.slice();
        }
        else {
            // New search - start from the master array
            if (invalidated ||
				 force ||
				 prevSearch.length > input.length ||
				 input.indexOf(prevSearch) !== 0 ||
				 settings.bSorted // On resort, the display master needs to be
            // re-filtered since indexes will have changed
			) {
                settings.aiDisplay = displayMaster.slice();
            }

            // Search the display array
            display = settings.aiDisplay;

            for (i = display.length - 1; i >= 0; i--) {
                if (!rpSearch.test(settings.aoData[display[i]]._sFilterRow)) {
                    display.splice(i, 1);
                }
            }
        }
    }


    /**
    * Build a regular expression object suitable for searching a table
    *  @param {string} sSearch string to search for
    *  @param {bool} bRegex treat as a regular expression or not
    *  @param {bool} bSmart perform smart filtering or not
    *  @param {bool} bCaseInsensitive Do case insensitive matching or not
    *  @returns {RegExp} constructed object
    *  @memberof DataTable#oApi
    */
    function _fnFilterCreateSearch(search, regex, smart, caseInsensitive) {
        search = regex ?
			search :
			_fnEscapeRegex(search);
        if (smart) {
            /* For smart filtering we want to allow the search to work regardless of
            * word order. We also want double quoted text to be preserved, so word
            * order is important - a la google. So this is what we want to
            * generate:
            * 
            * ^(?=.*?\bone\b)(?=.*?\btwo three\b)(?=.*?\bfour\b).*$
            */
            var a = $.map(search.match(/"[^"]+"|[^ ]+/g) || '', function (word) {
                return word.charAt(0) === '"' ?
					word.match(/^"(.*)"$/)[1] :
					word;
            });

            search = '^(?=.*?' + a.join(')(?=.*?') + ').*$';

        }

        return new RegExp(search, caseInsensitive ? 'i' : '');
    }


    /**
    * scape a string such that it can be used in a regular expression
    *  @param {string} sVal string to escape
    *  @returns {string} escaped string
    *  @memberof DataTable#oApi
    */
    function _fnEscapeRegex(sVal) {
        return sVal.replace(_re_escape_regex, '\\$1');
    }



    var __filter_div = $('<div>')[0];
    var __filter_div_textContent = __filter_div.textContent !== undefined;

    // Update the filtering data for each row if needed (by invalidation or first run)
    function _fnFilterData(settings) {
        var columns = settings.aoColumns;
        var column;
        var i, j, ien, jen, filterData, cellData, row;
        var fomatters = DataTable.ext.type.search;
        var wasInvalidated = false;

        for (i = 0, ien = settings.aoData.length; i < ien; i++) {
            row = settings.aoData[i];

            if (!row._aFilterData) {
                filterData = [];

                for (j = 0, jen = columns.length; j < jen; j++) {
                    column = columns[j];

                    if (column.bSearchable) {
                        // //console.log("4!");
                        cellData = _fnGetCellData(settings, i, j, 'filter');

                        cellData = fomatters[column.sType] ?
							fomatters[column.sType](cellData) :
							cellData !== null ?
								cellData :
								'';
                    }
                    else {
                        cellData = '';
                    }

                    // If it looks like there is an HTML entity in the string,
                    // attempt to decode it so sorting works as expected. Note that
                    // we could use a single line of jQuery to do this, but the DOM
                    // method used here is much faster http://jsperf.com/html-decode
                    if (cellData.indexOf && cellData.indexOf('&') !== -1) {
                        __filter_div.innerHTML = cellData;
                        cellData = __filter_div_textContent ?
							__filter_div.textContent :
							__filter_div.innerText;
                    }

                    if (cellData.replace) {
                        cellData = cellData.replace(/[\r\n]/g, '');
                    }

                    filterData.push(cellData);
                }

                row._aFilterData = filterData;
                row._sFilterRow = filterData.join('  ');
                wasInvalidated = true;
            }
        }

        return wasInvalidated;
    }

    /**
    * Generate the node required for the info display
    *  @param {object} oSettings dataTables settings object
    *  @returns {node} Information element
    *  @memberof DataTable#oApi
    */
    function _fnFeatureHtmlInfo(settings) {
        var 
			tid = settings.sTableId,
			nodes = settings.aanFeatures.i,
			n = $('<div/>', {
			    'class': settings.oClasses.sInfo,
			    'id': !nodes ? tid + '_info' : null
			});

        if (!nodes) {
            // Update display on each draw
            settings.aoDrawCallback.push({
                "fn": _fnUpdateInfo,
                "sName": "information"
            });

            n
				.attr('role', 'status')
				.attr('aria-live', 'polite');

            // Table is described by our info div
            $(settings.nTable).attr('aria-describedby', tid + '_info');
        }

        return n[0];
    }


    /**
    * Update the information elements in the display
    *  @param {object} settings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnUpdateInfo(settings) {
        /* Show information about the table */
        var nodes = settings.aanFeatures.i;
        if (nodes.length === 0) {
            return;
        }

        var 
			lang = settings.oLanguage,
			start = settings._iDisplayStart + 1,
			end = settings.fnDisplayEnd(),
			max = settings.fnRecordsTotal(),
			total = settings.fnRecordsDisplay(),
			out = total ?
				lang.sInfo :
				lang.sInfoEmpty;

        if (total !== max) {
            /* Record set after filtering */
            out += ' ' + lang.sInfoFiltered;
        }

        // Convert the macros
        out += lang.sInfoPostFix;
        out = _fnInfoMacros(settings, out);

        var callback = lang.fnInfoCallback;
        if (callback !== null) {
            out = callback.call(settings.oInstance,
				settings, start, end, max, total, out
			);
        }

        $(nodes).html(out);
    }


    function _fnInfoMacros(settings, str) {
        // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
        // internally
        var 
			formatter = settings.fnFormatNumber,
			start = settings._iDisplayStart + 1,
			len = settings._iDisplayLength,
			vis = settings.fnRecordsDisplay(),
			all = len === -1;

        return str.
			replace(/_START_/g, formatter.call(settings, start)).
			replace(/_END_/g, formatter.call(settings, settings.fnDisplayEnd())).
			replace(/_MAX_/g, formatter.call(settings, settings.fnRecordsTotal())).
			replace(/_TOTAL_/g, formatter.call(settings, vis)).
			replace(/_PAGE_/g, formatter.call(settings, all ? 1 : Math.ceil(start / len))).
			replace(/_PAGES_/g, formatter.call(settings, all ? 1 : Math.ceil(vis / len)));
    }



    /**
    * Draw the table for the first time, adding all required features
    *  @param {object} settings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnInitialise(settings) {
        var i, iLen, iAjaxStart = settings.iInitDisplayStart;
        var columns = settings.aoColumns, column;
        var features = settings.oFeatures;

        /* Ensure that the table data is fully initialised */
        if (!settings.bInitialised) {
            setTimeout(function () { _fnInitialise(settings); }, 200);
            return;
        }

        /* Show the display HTML options */
        _fnAddOptionsHtml(settings);

        /* Build and draw the header / footer for the table */
        _fnBuildHead(settings);
        _fnDrawHead(settings, settings.aoHeader);
        _fnDrawHead(settings, settings.aoFooter);

        /* Okay to show that something is going on now */
        _fnProcessingDisplay(settings, true);

        /* Calculate sizes for columns */
        if (features.bAutoWidth) {
            _fnCalculateColumnWidths(settings);
        }

        for (i = 0, iLen = columns.length; i < iLen; i++) {
            column = columns[i];

            if (column.sWidth) {
                column.nTh.style.width = _fnStringToCss(column.sWidth);
            }
        }

        // If there is default sorting required - let's do it. The sort function
        // will do the drawing for us. Otherwise we draw the table regardless of the
        // Ajax source - this allows the table to look initialised for Ajax sourcing
        // data (show 'loading' message possibly)
        _fnReDraw(settings);

        // Server-side processing init complete is done by _fnAjaxUpdateDraw
        var dataSrc = _fnDataSource(settings);
        if (dataSrc != 'ssp') {
            // if there is an ajax source load the data
            if (dataSrc == 'ajax') {
                _fnBuildAjax(settings, [], function (json) {
                    var aData = _fnAjaxDataSrc(settings, json);

                    // Got the data - add it to the table
                    ////console.log("p3");
                    for (i = 0; i < aData.length; i++) {
                        _fnAddData(settings, aData[i]);
                    }

                    // Reset the init display for cookie saving. We've already done
                    // a filter, and therefore cleared it before. So we need to make
                    // it appear 'fresh'
                    settings.iInitDisplayStart = iAjaxStart;

                    _fnReDraw(settings);

                    _fnProcessingDisplay(settings, false);
                    _fnInitComplete(settings, json);
                }, settings);
            }
            else {
                _fnProcessingDisplay(settings, false);
                _fnInitComplete(settings);
            }
        }
    }


    /**
    * Draw the table for the first time, adding all required features
    *  @param {object} oSettings dataTables settings object
    *  @param {object} [json] JSON from the server that completed the table, if using Ajax source
    *    with client-side processing (optional)
    *  @memberof DataTable#oApi
    */
    function _fnInitComplete(settings, json) {
        settings._bInitComplete = true;

        // On an Ajax load we now have data and therefore want to apply the column
        // sizing
        if (json) {
            _fnAdjustColumnSizing(settings);
        }

        _fnCallbackFire(settings, 'aoInitComplete', 'init', [settings, json]);
    }


    function _fnLengthChange(settings, val) {
        var len = parseInt(val, 10);
        settings._iDisplayLength = len;

        _fnLengthOverflow(settings);

        // Fire length change event
        _fnCallbackFire(settings, null, 'length', [settings, len]);
    }


    /**
    * Generate the node required for user display length changing
    *  @param {object} settings dataTables settings object
    *  @returns {node} Display length feature node
    *  @memberof DataTable#oApi
    */
    function _fnFeatureHtmlLength(settings) {
        var 
			classes = settings.oClasses,
			tableId = settings.sTableId,
			menu = settings.aLengthMenu,
			d2 = $.isArray(menu[0]),
			lengths = d2 ? menu[0] : menu,
			language = d2 ? menu[1] : menu;

        var select = $('<select/>', {
            'name': tableId + '_length',
            'aria-controls': tableId,
            'class': classes.sLengthSelect
        });

        for (var i = 0, ien = lengths.length; i < ien; i++) {
            select[0][i] = new Option(language[i], lengths[i]);
        }

        var div = $('<div><label/></div>').addClass(classes.sLength);
        if (!settings.aanFeatures.l) {
            div[0].id = tableId + '_length';
        }

        var a = settings.oLanguage.sLengthMenu.split(/(_MENU_)/);
        div.children().append(a.length > 1 ?
			[a[0], select, a[2]] :
			a[0]
		);

        // Can't use `select` variable, as user might provide their own select menu
        $('select', div)
			.val(settings._iDisplayLength)
			.bind('change.DT', function (e) {
			    _fnLengthChange(settings, $(this).val());
			    _fnDraw(settings);
			});

        // Update node value whenever anything changes the table's length
        $(settings.nTable).bind('length.dt.DT', function (e, s, len) {
            $('select', div).val(len);
        });

        return div[0];
    }



    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    * Note that most of the paging logic is done in
    * DataTable.ext.pager
    */

    /**
    * Generate the node required for default pagination
    *  @param {object} oSettings dataTables settings object
    *  @returns {node} Pagination feature node
    *  @memberof DataTable#oApi
    */
    function _fnFeatureHtmlPaginate(settings) {
        var 
			type = settings.sPaginationType,
			plugin = DataTable.ext.pager[type],
			modern = typeof plugin === 'function',
			redraw = function (settings) {
			    _fnDraw(settings);
			},
			node = $('<div/>').addClass(settings.oClasses.sPaging + type)[0],
			features = settings.aanFeatures;

        if (!modern) {
            plugin.fnInit(settings, node, redraw);
        }

        /* Add a draw callback for the pagination on first instance, to update the paging display */
        if (!features.p) {
            node.id = settings.sTableId + '_paginate';

            settings.aoDrawCallback.push({
                "fn": function (settings) {
                    if (modern) {
                        var 
							start = settings._iDisplayStart,
							len = settings._iDisplayLength,
							visRecords = settings.fnRecordsDisplay(),
							all = len === -1,
							page = all ? 0 : Math.ceil(start / len),
							pages = all ? 1 : Math.ceil(visRecords / len),
							buttons = plugin(page, pages),
							i, ien;

                        for (i = 0, ien = features.p.length; i < ien; i++) {
                            _fnRenderer(settings, 'pageButton')(
								settings, features.p[i], i, buttons, page, pages
							);
                        }
                    }
                    else {
                        plugin.fnUpdate(settings, redraw);
                    }
                },
                "sName": "pagination"
            });
        }

        return node;
    }


    /**
    * Alter the display settings to change the page
    *  @param {object} settings DataTables settings object
    *  @param {string|int} action Paging action to take: "first", "previous",
    *    "next" or "last" or page number to jump to (integer)
    *  @param [bool] redraw Automatically draw the update or not
    *  @returns {bool} true page has changed, false - no change
    *  @memberof DataTable#oApi
    */
    function _fnPageChange(settings, action, redraw) {
        var 
			start = settings._iDisplayStart,
			len = settings._iDisplayLength,
			records = settings.fnRecordsDisplay();

        if (records === 0 || len === -1) {
            start = 0;
        }
        else if (typeof action === "number") {
            start = action * len;

            if (start > records) {
                start = 0;
            }
        }
        else if (action == "first") {
            start = 0;
        }
        else if (action == "previous") {
            start = len >= 0 ?
				start - len :
				0;

            if (start < 0) {
                start = 0;
            }
        }
        else if (action == "next") {
            if (start + len < records) {
                start += len;
            }
        }
        else if (action == "last") {
            start = Math.floor((records - 1) / len) * len;
        }
        else {
            _fnLog(settings, 0, "Unknown paging action: " + action, 5);
        }

        var changed = settings._iDisplayStart !== start;
        settings._iDisplayStart = start;

        if (changed) {
            _fnCallbackFire(settings, null, 'page', [settings]);

            if (redraw) {
                _fnDraw(settings);
            }
        }

        return changed;
    }



    /**
    * Generate the node required for the processing node
    *  @param {object} settings dataTables settings object
    *  @returns {node} Processing element
    *  @memberof DataTable#oApi
    */
    function _fnFeatureHtmlProcessing(settings) {
        return $('<div/>', {
            'id': !settings.aanFeatures.r ? settings.sTableId + '_processing' : null,
            'class': settings.oClasses.sProcessing
        })
			.html(settings.oLanguage.sProcessing)
			.insertBefore(settings.nTable)[0];
    }


    /**
    * Display or hide the processing indicator
    *  @param {object} settings dataTables settings object
    *  @param {bool} show Show the processing indicator (true) or not (false)
    *  @memberof DataTable#oApi
    */
    function _fnProcessingDisplay(settings, show) {
        if (settings.oFeatures.bProcessing) {
            $(settings.aanFeatures.r).css('display', show ? 'block' : 'none');
        }

        _fnCallbackFire(settings, null, 'processing', [settings, show]);
    }

    /**
    * Add any control elements for the table - specifically scrolling
    *  @param {object} settings dataTables settings object
    *  @returns {node} Node to add to the DOM
    *  @memberof DataTable#oApi
    */
    function _fnFeatureHtmlTable(settings) {
        var table = $(settings.nTable);

        // Add the ARIA grid role to the table
        table.attr('role', 'grid');

        // Scrolling from here on in
        var scroll = settings.oScroll;

        if (scroll.sX === '' && scroll.sY === '') {
            return settings.nTable;
        }

        var scrollX = scroll.sX;
        var scrollY = scroll.sY;
        var classes = settings.oClasses;
        var caption = table.children('caption');
        var captionSide = caption.length ? caption[0]._captionSide : null;
        var headerClone = $(table[0].cloneNode(false));
        var footerClone = $(table[0].cloneNode(false));
        var footer = table.children('tfoot');
        var _div = '<div/>';
        var size = function (s) {
            return !s ? null : _fnStringToCss(s);
        };

        // This is fairly messy, but with x scrolling enabled, if the table has a
        // width attribute, regardless of any width applied using the column width
        // options, the browser will shrink or grow the table as needed to fit into
        // that 100%. That would make the width options useless. So we remove it.
        // This is okay, under the assumption that width:100% is applied to the
        // table in CSS (it is in the default stylesheet) which will set the table
        // width as appropriate (the attribute and css behave differently...)
        if (scroll.sX && table.attr('width') === '100%') {
            table.removeAttr('width');
        }

        if (!footer.length) {
            footer = null;
        }

        /*
        * The HTML structure that we want to generate in this function is:
        *  div - scroller
        *    div - scroll head
        *      div - scroll head inner
        *        table - scroll head table
        *          thead - thead
        *    div - scroll body
        *      table - table (master table)
        *        thead - thead clone for sizing
        *        tbody - tbody
        *    div - scroll foot
        *      div - scroll foot inner
        *        table - scroll foot table
        *          tfoot - tfoot
        */
        var scroller = $(_div, { 'class': classes.sScrollWrapper })
			.append(
				$(_div, { 'class': classes.sScrollHead })
					.css({
					    overflow: 'hidden',
					    position: 'relative',
					    border: 0,
					    width: scrollX ? size(scrollX) : '100%'
					})
					.append(
						$(_div, { 'class': classes.sScrollHeadInner })
							.css({
							    'box-sizing': 'content-box',
							    width: scroll.sXInner || '100%'
							})
							.append(
								headerClone
									.removeAttr('id')
									.css('margin-left', 0)
									.append(
										table.children('thead')
									)
							)
					)
					.append(captionSide === 'top' ? caption : null)
			)
			.append(
				$(_div, { 'class': classes.sScrollBody })
					.css({
					    overflow: 'auto',
					    height: size(scrollY),
					    width: size(scrollX)
					})
					.append(table)
			);

        if (footer) {
            scroller.append(
				$(_div, { 'class': classes.sScrollFoot })
					.css({
					    overflow: 'hidden',
					    border: 0,
					    width: scrollX ? size(scrollX) : '100%'
					})
					.append(
						$(_div, { 'class': classes.sScrollFootInner })
							.append(
								footerClone
									.removeAttr('id')
									.css('margin-left', 0)
									.append(
										table.children('tfoot')
									)
							)
					)
					.append(captionSide === 'bottom' ? caption : null)
			);
        }

        var children = scroller.children();
        var scrollHead = children[0];
        var scrollBody = children[1];
        var scrollFoot = footer ? children[2] : null;

        // When the body is scrolled, then we also want to scroll the headers
        if (scrollX) {
            $(scrollBody).scroll(function (e) {
                var scrollLeft = this.scrollLeft;

                scrollHead.scrollLeft = scrollLeft;

                if (footer) {
                    scrollFoot.scrollLeft = scrollLeft;
                }
            });
        }

        settings.nScrollHead = scrollHead;
        settings.nScrollBody = scrollBody;
        settings.nScrollFoot = scrollFoot;

        // On redraw - align columns
        settings.aoDrawCallback.push({
            "fn": _fnScrollDraw,
            "sName": "scrolling"
        });

        return scroller[0];
    }



    /**
    * Update the header, footer and body tables for resizing - i.e. column
    * alignment.
    *
    * Welcome to the most horrible function DataTables. The process that this
    * function follows is basically:
    *   1. Re-create the table inside the scrolling div
    *   2. Take live measurements from the DOM
    *   3. Apply the measurements to align the columns
    *   4. Clean up
    *
    *  @param {object} settings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnScrollDraw(settings) {
        // Given that this is such a monster function, a lot of variables are use
        // to try and keep the minimised size as small as possible
        var 
			scroll = settings.oScroll,
			scrollX = scroll.sX,
			scrollXInner = scroll.sXInner,
			scrollY = scroll.sY,
			barWidth = scroll.iBarWidth,
			divHeader = $(settings.nScrollHead),
			divHeaderStyle = divHeader[0].style,
			divHeaderInner = divHeader.children('div'),
			divHeaderInnerStyle = divHeaderInner[0].style,
			divHeaderTable = divHeaderInner.children('table'),
			divBodyEl = settings.nScrollBody,
			divBody = $(divBodyEl),
			divBodyStyle = divBodyEl.style,
			divFooter = $(settings.nScrollFoot),
			divFooterInner = divFooter.children('div'),
			divFooterTable = divFooterInner.children('table'),
			header = $(settings.nTHead),
			table = $(settings.nTable),
			tableEl = table[0],
			tableStyle = tableEl.style,
			footer = settings.nTFoot ? $(settings.nTFoot) : null,
			browser = settings.oBrowser,
			ie67 = browser.bScrollOversize,
			headerTrgEls, footerTrgEls,
			headerSrcEls, footerSrcEls,
			headerCopy, footerCopy,
			headerWidths = [], footerWidths = [],
			headerContent = [],
			idx, correction, sanityWidth,
			zeroOut = function (nSizer) {
			    var style = nSizer.style;
			    style.paddingTop = "0";
			    style.paddingBottom = "0";
			    style.borderTopWidth = "0";
			    style.borderBottomWidth = "0";
			    style.height = 0;
			};

        /*
        * 1. Re-create the table inside the scrolling div
        */

        // Remove the old minimised thead and tfoot elements in the inner table
        table.children('thead, tfoot').remove();

        // Clone the current header and footer elements and then place it into the inner table
        headerCopy = header.clone().prependTo(table);
        headerTrgEls = header.find('tr'); // original header is in its own table
        headerSrcEls = headerCopy.find('tr');
        headerCopy.find('th, td').removeAttr('tabindex');

        if (footer) {
            footerCopy = footer.clone().prependTo(table);
            footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized
            footerSrcEls = footerCopy.find('tr');
        }


        /*
        * 2. Take live measurements from the DOM - do not alter the DOM itself!
        */

        // Remove old sizing and apply the calculated column widths
        // Get the unique column headers in the newly created (cloned) header. We want to apply the
        // calculated sizes to this header
        if (!scrollX) {
            divBodyStyle.width = '100%';
            divHeader[0].style.width = '100%';
        }

        $.each(_fnGetUniqueThs(settings, headerCopy), function (i, el) {
            idx = _fnVisibleToColumnIndex(settings, i);
            el.style.width = settings.aoColumns[idx].sWidth;
        });

        if (footer) {
            _fnApplyToChildren(function (n) {
                n.style.width = "";
            }, footerSrcEls);
        }

        // If scroll collapse is enabled, when we put the headers back into the body for sizing, we
        // will end up forcing the scrollbar to appear, making our measurements wrong for when we
        // then hide it (end of this function), so add the header height to the body scroller.
        if (scroll.bCollapse && scrollY !== "") {
            divBodyStyle.height = (divBody[0].offsetHeight + header[0].offsetHeight) + "px";
        }

        // Size the table as a whole
        sanityWidth = table.outerWidth();
        if (scrollX === "") {
            // No x scrolling
            tableStyle.width = "100%";

            // IE7 will make the width of the table when 100% include the scrollbar
            // - which is shouldn't. When there is a scrollbar we need to take this
            // into account.
            if (ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight ||
				divBody.css('overflow-y') == "scroll")
			) {
                tableStyle.width = _fnStringToCss(table.outerWidth() - barWidth);
            }
        }
        else {
            // x scrolling
            if (scrollXInner !== "") {
                // x scroll inner has been given - use it
                tableStyle.width = _fnStringToCss(scrollXInner);
            }
            else if (sanityWidth == divBody.width() && divBody.height() < table.height()) {
                // There is y-scrolling - try to take account of the y scroll bar
                tableStyle.width = _fnStringToCss(sanityWidth - barWidth);
                if (table.outerWidth() > sanityWidth - barWidth) {
                    // Not possible to take account of it
                    tableStyle.width = _fnStringToCss(sanityWidth);
                }
            }
            else {
                // When all else fails
                tableStyle.width = _fnStringToCss(sanityWidth);
            }
        }

        // Recalculate the sanity width - now that we've applied the required width,
        // before it was a temporary variable. This is required because the column
        // width calculation is done before this table DOM is created.
        sanityWidth = table.outerWidth();

        // Hidden header should have zero height, so remove padding and borders. Then
        // set the width based on the real headers

        // Apply all styles in one pass
        _fnApplyToChildren(zeroOut, headerSrcEls);

        // Read all widths in next pass
        _fnApplyToChildren(function (nSizer) {
            headerContent.push(nSizer.innerHTML);
            headerWidths.push(_fnStringToCss($(nSizer).css('width')));
        }, headerSrcEls);

        // Apply all widths in final pass
        _fnApplyToChildren(function (nToSize, i) {
            nToSize.style.width = headerWidths[i];
        }, headerTrgEls);

        $(headerSrcEls).height(0);

        /* Same again with the footer if we have one */
        if (footer) {
            _fnApplyToChildren(zeroOut, footerSrcEls);

            _fnApplyToChildren(function (nSizer) {
                footerWidths.push(_fnStringToCss($(nSizer).css('width')));
            }, footerSrcEls);

            _fnApplyToChildren(function (nToSize, i) {
                nToSize.style.width = footerWidths[i];
            }, footerTrgEls);

            $(footerSrcEls).height(0);
        }


        /*
        * 3. Apply the measurements
        */

        // "Hide" the header and footer that we used for the sizing. We need to keep
        // the content of the cell so that the width applied to the header and body
        // both match, but we want to hide it completely. We want to also fix their
        // width to what they currently are
        _fnApplyToChildren(function (nSizer, i) {
            nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">' + headerContent[i] + '</div>';
            nSizer.style.width = headerWidths[i];
        }, headerSrcEls);

        if (footer) {
            _fnApplyToChildren(function (nSizer, i) {
                nSizer.innerHTML = "";
                nSizer.style.width = footerWidths[i];
            }, footerSrcEls);
        }

        // Sanity check that the table is of a sensible width. If not then we are going to get
        // misalignment - try to prevent this by not allowing the table to shrink below its min width
        if (table.outerWidth() < sanityWidth) {
            // The min width depends upon if we have a vertical scrollbar visible or not */
            correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight ||
				divBody.css('overflow-y') == "scroll")) ?
					sanityWidth + barWidth :
					sanityWidth;

            // IE6/7 are a law unto themselves...
            if (ie67 && (divBodyEl.scrollHeight >
				divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")
			) {
                tableStyle.width = _fnStringToCss(correction - barWidth);
            }

            // And give the user a warning that we've stopped the table getting too small
            if (scrollX === "" || scrollXInner !== "") {
                _fnLog(settings, 1, 'Possible column misalignment', 6);
            }
        }
        else {
            correction = '100%';
        }

        // Apply to the container elements
        divBodyStyle.width = _fnStringToCss(correction);
        divHeaderStyle.width = _fnStringToCss(correction);

        if (footer) {
            settings.nScrollFoot.style.width = _fnStringToCss(correction);
        }


        /*
        * 4. Clean up
        */
        if (!scrollY) {
            /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
            * the scrollbar height from the visible display, rather than adding it on. We need to
            * set the height in order to sort this. Don't want to do it in any other browsers.
            */
            if (ie67) {
                divBodyStyle.height = _fnStringToCss(tableEl.offsetHeight + barWidth);
            }
        }

        if (scrollY && scroll.bCollapse) {
            divBodyStyle.height = _fnStringToCss(scrollY);

            var iExtra = (scrollX && tableEl.offsetWidth > divBodyEl.offsetWidth) ?
				barWidth :
				0;

            if (tableEl.offsetHeight < divBodyEl.offsetHeight) {
                divBodyStyle.height = _fnStringToCss(tableEl.offsetHeight + iExtra);
            }
        }

        /* Finally set the width's of the header and footer tables */
        var iOuterWidth = table.outerWidth();
        divHeaderTable[0].style.width = _fnStringToCss(iOuterWidth);
        divHeaderInnerStyle.width = _fnStringToCss(iOuterWidth);

        // Figure out if there are scrollbar present - if so then we need a the header and footer to
        // provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
        var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll";
        var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right');
        divHeaderInnerStyle[padding] = bScrolling ? barWidth + "px" : "0px";

        if (footer) {
            divFooterTable[0].style.width = _fnStringToCss(iOuterWidth);
            divFooterInner[0].style.width = _fnStringToCss(iOuterWidth);
            divFooterInner[0].style[padding] = bScrolling ? barWidth + "px" : "0px";
        }

        /* Adjust the position of the header in case we loose the y-scrollbar */
        divBody.scroll();

        /* If sorting or filtering has occurred, jump the scrolling back to the top */
        if (settings.bSorted || settings.bFiltered) {
            divBodyEl.scrollTop = 0;
        }
    }



    /**
    * Apply a given function to the display child nodes of an element array (typically
    * TD children of TR rows
    *  @param {function} fn Method to apply to the objects
    *  @param array {nodes} an1 List of elements to look through for display children
    *  @param array {nodes} an2 Another list (identical structure to the first) - optional
    *  @memberof DataTable#oApi
    */
    function _fnApplyToChildren(fn, an1, an2) {
        var index = 0, i = 0, iLen = an1.length;
        var nNode1, nNode2;

        while (i < iLen) {
            nNode1 = an1[i].firstChild;
            nNode2 = an2 ? an2[i].firstChild : null;

            while (nNode1) {
                if (nNode1.nodeType === 1) {
                    if (an2) {
                        fn(nNode1, nNode2, index);
                    }
                    else {
                        fn(nNode1, index);
                    }

                    index++;
                }

                nNode1 = nNode1.nextSibling;
                nNode2 = an2 ? nNode2.nextSibling : null;
            }

            i++;
        }
    }



    var __re_html_remove = /<.*?>/g;


    /**
    * Calculate the width of columns for the table
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnCalculateColumnWidths(oSettings) {
        var 
			table = oSettings.nTable,
			columns = oSettings.aoColumns,
			scroll = oSettings.oScroll,
			scrollY = scroll.sY,
			scrollX = scroll.sX,
			scrollXInner = scroll.sXInner,
			columnCount = columns.length,
			visibleColumns = _fnGetColumns(oSettings, 'bVisible'),
			headerCells = $('th', oSettings.nTHead),
			tableWidthAttr = table.getAttribute('width'),
			tableContainer = table.parentNode,
			userInputs = false,
			i, column, columnIdx, width, outerWidth;

        /* Convert any user input sizes into pixel sizes */
        for (i = 0; i < visibleColumns.length; i++) {
            column = columns[visibleColumns[i]];

            if (column.sWidth !== null) {
                column.sWidth = _fnConvertToWidth(column.sWidthOrig, tableContainer);

                userInputs = true;
            }
        }

        /* If the number of columns in the DOM equals the number that we have to
        * process in DataTables, then we can use the offsets that are created by
        * the web- browser. No custom sizes can be set in order for this to happen,
        * nor scrolling used
        */
        if (!userInputs && !scrollX && !scrollY &&
		    columnCount == _fnVisbleColumns(oSettings) &&
			columnCount == headerCells.length
		) {
            for (i = 0; i < columnCount; i++) {
                columns[i].sWidth = _fnStringToCss(headerCells.eq(i).width());
            }
        }
        else {
            // Otherwise construct a single row table with the widest node in the
            // data, assign any user defined widths, then insert it into the DOM and
            // allow the browser to do all the hard work of calculating table widths
            var tmpTable = $(table.cloneNode(false))
				.css('visibility', 'hidden')
				.removeAttr('id')
				.append($(oSettings.nTHead).clone(false))
				.append($(oSettings.nTFoot).clone(false))
				.append($('<tbody><tr/></tbody>'));

            // Remove any assigned widths from the footer (from scrolling)
            tmpTable.find('tfoot th, tfoot td').css('width', '');

            var tr = tmpTable.find('tbody tr');

            // Apply custom sizing to the cloned header
            headerCells = _fnGetUniqueThs(oSettings, tmpTable.find('thead')[0]);

            for (i = 0; i < visibleColumns.length; i++) {
                column = columns[visibleColumns[i]];

                headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
					_fnStringToCss(column.sWidthOrig) :
					'';
            }

            // Find the widest cell for each column and put it into the table
            if (oSettings.aoData.length) {
                for (i = 0; i < visibleColumns.length; i++) {
                    columnIdx = visibleColumns[i];
                    column = columns[columnIdx];

                    $(_fnGetWidestNode(oSettings, columnIdx))
						.clone(false)
						.append(column.sContentPadding)
						.appendTo(tr);
                }
            }

            // Table has been built, attach to the document so we can work with it
            tmpTable.appendTo(tableContainer);

            // When scrolling (X or Y) we want to set the width of the table as 
            // appropriate. However, when not scrolling leave the table width as it
            // is. This results in slightly different, but I think correct behaviour
            if (scrollX && scrollXInner) {
                tmpTable.width(scrollXInner);
            }
            else if (scrollX) {
                tmpTable.css('width', 'auto');

                if (tmpTable.width() < tableContainer.offsetWidth) {
                    tmpTable.width(tableContainer.offsetWidth);
                }
            }
            else if (scrollY) {
                tmpTable.width(tableContainer.offsetWidth);
            }
            else if (tableWidthAttr) {
                tmpTable.width(tableWidthAttr);
            }

            // Take into account the y scrollbar
            _fnScrollingWidthAdjust(oSettings, tmpTable[0]);

            // Browsers need a bit of a hand when a width is assigned to any columns
            // when x-scrolling as they tend to collapse the table to the min-width,
            // even if we sent the column widths. So we need to keep track of what
            // the table width should be by summing the user given values, and the
            // automatic values
            if (scrollX) {
                var total = 0;

                for (i = 0; i < visibleColumns.length; i++) {
                    column = columns[visibleColumns[i]];
                    outerWidth = $(headerCells[i]).outerWidth();

                    total += column.sWidthOrig === null ?
						outerWidth :
						parseInt(column.sWidth, 10) + outerWidth - $(headerCells[i]).width();
                }

                tmpTable.width(_fnStringToCss(total));
                table.style.width = _fnStringToCss(total);
            }

            // Get the width of each column in the constructed table
            for (i = 0; i < visibleColumns.length; i++) {
                column = columns[visibleColumns[i]];
                width = $(headerCells[i]).width();

                if (width) {
                    column.sWidth = _fnStringToCss(width);
                }
            }

            table.style.width = _fnStringToCss(tmpTable.css('width'));

            // Finished with the table - ditch it
            tmpTable.remove();
        }

        // If there is a width attr, we want to attach an event listener which
        // allows the table sizing to automatically adjust when the window is
        // resized. Use the width attr rather than CSS, since we can't know if the
        // CSS is a relative value or absolute - DOM read is always px.
        if (tableWidthAttr) {
            table.style.width = _fnStringToCss(tableWidthAttr);
        }

        if ((tableWidthAttr || scrollX) && !oSettings._reszEvt) {
            $(window).bind('resize.DT-' + oSettings.sInstance, _fnThrottle(function () {
                _fnAdjustColumnSizing(oSettings);
            }));

            oSettings._reszEvt = true;
        }
    }


    /**
    * Throttle the calls to a function. Arguments and context are maintained for
    * the throttled function
    *  @param {function} fn Function to be called
    *  @param {int} [freq=200] call frequency in mS
    *  @returns {function} wrapped function
    *  @memberof DataTable#oApi
    */
    function _fnThrottle(fn, freq) {
        var 
			frequency = freq || 200,
			last,
			timer;

        return function () {
            var 
				that = this,
				now = +new Date(),
				args = arguments;

            if (last && now < last + frequency) {
                clearTimeout(timer);

                timer = setTimeout(function () {
                    last = undefined;
                    fn.apply(that, args);
                }, frequency);
            }
            else if (last) {
                last = now;
                fn.apply(that, args);
            }
            else {
                last = now;
            }
        };
    }


    /**
    * Convert a CSS unit width to pixels (e.g. 2em)
    *  @param {string} width width to be converted
    *  @param {node} parent parent to get the with for (required for relative widths) - optional
    *  @returns {int} width in pixels
    *  @memberof DataTable#oApi
    */
    function _fnConvertToWidth(width, parent) {
        if (!width) {
            return 0;
        }

        var n = $('<div/>')
			.css('width', _fnStringToCss(width))
			.appendTo(parent || document.body);

        var val = n[0].offsetWidth;
        n.remove();

        return val;
    }


    /**
    * Adjust a table's width to take account of vertical scroll bar
    *  @param {object} oSettings dataTables settings object
    *  @param {node} n table node
    *  @memberof DataTable#oApi
    */

    function _fnScrollingWidthAdjust(settings, n) {
        var scroll = settings.oScroll;

        if (scroll.sX || scroll.sY) {
            // When y-scrolling only, we want to remove the width of the scroll bar
            // so the table + scroll bar will fit into the area available, otherwise
            // we fix the table at its current size with no adjustment
            var correction = !scroll.sX ? scroll.iBarWidth : 0;
            n.style.width = _fnStringToCss($(n).outerWidth() - correction);
        }
    }


    /**
    * Get the widest node
    *  @param {object} settings dataTables settings object
    *  @param {int} colIdx column of interest
    *  @returns {node} widest table node
    *  @memberof DataTable#oApi
    */
    function _fnGetWidestNode(settings, colIdx) {
        var idx = _fnGetMaxLenString(settings, colIdx);
        if (idx < 0) {
            return null;
        }

        var data = settings.aoData[idx];
        ////console.log("5!");
        return !data.nTr ? // Might not have been created when deferred rendering
			$('<td/>').html(_fnGetCellData(settings, idx, colIdx, 'display'))[0] :
			data.anCells[colIdx];
    }


    /**
    * Get the maximum strlen for each data column
    *  @param {object} settings dataTables settings object
    *  @param {int} colIdx column of interest
    *  @returns {string} max string length for each column
    *  @memberof DataTable#oApi
    */
    function _fnGetMaxLenString(settings, colIdx) {
        var s, max = -1, maxIdx = -1;
        ////console.log("6!");
        for (var i = 0, ien = settings.aoData.length; i < ien; i++) {
            s = _fnGetCellData(settings, i, colIdx, 'display') + '';
            s = s.replace(__re_html_remove, '');

            if (s.length > max) {
                max = s.length;
                maxIdx = i;
            }
        }

        return maxIdx;
    }


    /**
    * Append a CSS unit (only if required) to a string
    *  @param {string} value to css-ify
    *  @returns {string} value with css unit
    *  @memberof DataTable#oApi
    */
    function _fnStringToCss(s) {
        if (s === null) {
            return '0px';
        }

        if (typeof s == 'number') {
            return s < 0 ?
				'0px' :
				s + 'px';
        }

        // Check it has a unit character already
        return s.match(/\d$/) ?
			s + 'px' :
			s;
    }


    /**
    * Get the width of a scroll bar in this browser being used
    *  @returns {int} width in pixels
    *  @memberof DataTable#oApi
    */
    function _fnScrollBarWidth() {
        // On first run a static variable is set, since this is only needed once.
        // Subsequent runs will just use the previously calculated value
        if (!DataTable.__scrollbarWidth) {
            var inner = $('<p/>').css({
                width: '100%',
                height: 200,
                padding: 0
            })[0];

            var outer = $('<div/>')
				.css({
				    position: 'absolute',
				    top: 0,
				    left: 0,
				    width: 200,
				    height: 150,
				    padding: 0,
				    overflow: 'hidden',
				    visibility: 'hidden'
				})
				.append(inner)
				.appendTo('body');

            var w1 = inner.offsetWidth;
            outer.css('overflow', 'scroll');
            var w2 = inner.offsetWidth;

            if (w1 === w2) {
                w2 = outer[0].clientWidth;
            }

            outer.remove();

            DataTable.__scrollbarWidth = w1 - w2;
        }

        return DataTable.__scrollbarWidth;
    }



    function _fnSortFlatten(settings) {
        var 
			i, iLen, k, kLen,
			aSort = [],
			aiOrig = [],
			aoColumns = settings.aoColumns,
			aDataSort, iCol, sType, srcCol,
			fixed = settings.aaSortingFixed,
			fixedObj = $.isPlainObject(fixed),
			nestedSort = [],
			add = function (a) {
			    if (a.length && !$.isArray(a[0])) {
			        // 1D array
			        nestedSort.push(a);
			    }
			    else {
			        // 2D array
			        nestedSort.push.apply(nestedSort, a);
			    }
			};

        // Build the sort array, with pre-fix and post-fix options if they have been
        // specified
        if ($.isArray(fixed)) {
            add(fixed);
        }

        if (fixedObj && fixed.pre) {
            add(fixed.pre);
        }

        add(settings.aaSorting);

        if (fixedObj && fixed.post) {
            add(fixed.post);
        }

        for (i = 0; i < nestedSort.length; i++) {
            srcCol = nestedSort[i][0];
            aDataSort = aoColumns[srcCol].aDataSort;

            for (k = 0, kLen = aDataSort.length; k < kLen; k++) {
                iCol = aDataSort[k];
                sType = aoColumns[iCol].sType || 'string';

                aSort.push({
                    src: srcCol,
                    col: iCol,
                    dir: nestedSort[i][1],
                    index: nestedSort[i][2],
                    type: sType,
                    formatter: DataTable.ext.type.order[sType + "-pre"]
                });
            }
        }

        return aSort;
    }

    /**
    * Change the order of the table
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    *  @todo This really needs split up!
    */
    function _fnSort(oSettings) {
        var 
			i, ien, iLen, j, jLen, k, kLen,
			sDataType, nTh,
			aiOrig = [],
			oExtSort = DataTable.ext.type.order,
			aoData = oSettings.aoData,
			aoColumns = oSettings.aoColumns,
			aDataSort, data, iCol, sType, oSort,
			formatters = 0,
			sortCol,
			displayMaster = oSettings.aiDisplayMaster,
			aSort;

        // Resolve any column types that are unknown due to addition or invalidation
        // @todo Can this be moved into a 'data-ready' handler which is called when
        //   data is going to be used in the table?
        _fnColumnTypes(oSettings);

        aSort = _fnSortFlatten(oSettings);
        for (i = 0, ien = aSort.length; i < ien; i++) {
            sortCol = aSort[i];

            // Track if we can use the fast sort algorithm
            if (sortCol.formatter) {
                formatters++;
            }

            // Load the data needed for the sort, for each cell
            _fnSortData(oSettings, sortCol.col);
        }

        /* No sorting required if server-side or no sorting array */
        if (_fnDataSource(oSettings) != 'ssp' && aSort.length !== 0) {
            // Create a value - key array of the current row positions such that we can use their
            // current position during the sort, if values match, in order to perform stable sorting
            for (i = 0, iLen = displayMaster.length; i < iLen; i++) {
                aiOrig[displayMaster[i]] = i;
            }

            /* Do the sort - here we want multi-column sorting based on a given data source (column)
            * and sorting function (from oSort) in a certain direction. It's reasonably complex to
            * follow on it's own, but this is what we want (example two column sorting):
            *  fnLocalSorting = function(a,b){
            *    var iTest;
            *    iTest = oSort['string-asc']('data11', 'data12');
            *      if (iTest !== 0)
            *        return iTest;
            *    iTest = oSort['numeric-desc']('data21', 'data22');
            *    if (iTest !== 0)
            *      return iTest;
            *    return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
            *  }
            * Basically we have a test for each sorting column, if the data in that column is equal,
            * test the next column. If all columns match, then we use a numeric sort on the row
            * positions in the original data array to provide a stable sort.
            *
            * Note - I know it seems excessive to have two sorting methods, but the first is around
            * 15% faster, so the second is only maintained for backwards compatibility with sorting
            * methods which do not have a pre-sort formatting function.
            */
            if (formatters === aSort.length) {
                // All sort types have formatting functions
                displayMaster.sort(function (a, b) {
                    var 
						x, y, k, test, sort,
						len = aSort.length,
						dataA = aoData[a]._aSortData,
						dataB = aoData[b]._aSortData;

                    for (k = 0; k < len; k++) {
                        sort = aSort[k];

                        x = dataA[sort.col];
                        y = dataB[sort.col];

                        test = x < y ? -1 : x > y ? 1 : 0;
                        if (test !== 0) {
                            return sort.dir === 'asc' ? test : -test;
                        }
                    }

                    x = aiOrig[a];
                    y = aiOrig[b];
                    return x < y ? -1 : x > y ? 1 : 0;
                });
            }
            else {
                // Depreciated - remove in 1.11 (providing a plug-in option)
                // Not all sort types have formatting methods, so we have to call their sorting
                // methods.
                displayMaster.sort(function (a, b) {
                    var 
						x, y, k, l, test, sort, fn,
						len = aSort.length,
						dataA = aoData[a]._aSortData,
						dataB = aoData[b]._aSortData;

                    for (k = 0; k < len; k++) {
                        sort = aSort[k];

                        x = dataA[sort.col];
                        y = dataB[sort.col];

                        fn = oExtSort[sort.type + "-" + sort.dir] || oExtSort["string-" + sort.dir];
                        test = fn(x, y);
                        if (test !== 0) {
                            return test;
                        }
                    }

                    x = aiOrig[a];
                    y = aiOrig[b];
                    return x < y ? -1 : x > y ? 1 : 0;
                });
            }
        }

        /* Tell the draw function that we have sorted the data */
        oSettings.bSorted = true;

    }


    function _fnSortAria(settings) {
        var label;
        var nextSort;
        var columns = settings.aoColumns;
        var aSort = _fnSortFlatten(settings);
        var oAria = settings.oLanguage.oAria;

        // ARIA attributes - need to loop all columns, to update all (removing old
        // attributes as needed)
        for (var i = 0, iLen = columns.length; i < iLen; i++) {
            var col = columns[i];
            var asSorting = col.asSorting;
            var sTitle = col.sTitle.replace(/<.*?>/g, "");
            var th = col.nTh;

            // IE7 is throwing an error when setting these properties with jQuery's
            // attr() and removeAttr() methods...
            th.removeAttribute('aria-sort');

            /* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
            if (col.bSortable) {
                if (aSort.length > 0 && aSort[0].col == i) {
                    th.setAttribute('aria-sort', aSort[0].dir == "asc" ? "ascending" : "descending");
                    nextSort = asSorting[aSort[0].index + 1] || asSorting[0];
                }
                else {
                    nextSort = asSorting[0];
                }

                label = sTitle + (nextSort === "asc" ?
					oAria.sSortAscending :
					oAria.sSortDescending
				);
            }
            else {
                label = sTitle;
            }

            th.setAttribute('aria-label', label);
        }
    }


    /**
    * Function to run on user sort request
    *  @param {object} settings dataTables settings object
    *  @param {node} attachTo node to attach the handler to
    *  @param {int} colIdx column sorting index
    *  @param {boolean} [append=false] Append the requested sort to the existing
    *    sort if true (i.e. multi-column sort)
    *  @param {function} [callback] callback function
    *  @memberof DataTable#oApi
    */
    function _fnSortListener(settings, colIdx, append, callback) {
        var col = settings.aoColumns[colIdx];
        var sorting = settings.aaSorting;
        var asSorting = col.asSorting;
        var nextSortIdx;
        var next = function (a) {
            var idx = a._idx;
            if (idx === undefined) {
                idx = $.inArray(a[1], asSorting);
            }

            return idx + 1 >= asSorting.length ? 0 : idx + 1;
        };

        // If appending the sort then we are multi-column sorting
        if (append && settings.oFeatures.bSortMulti) {
            // Are we already doing some kind of sort on this column?
            var sortIdx = $.inArray(colIdx, _pluck(sorting, '0'));

            if (sortIdx !== -1) {
                // Yes, modify the sort
                nextSortIdx = next(sorting[sortIdx]);

                sorting[sortIdx][1] = asSorting[nextSortIdx];
                sorting[sortIdx]._idx = nextSortIdx;
            }
            else {
                // No sort on this column yet
                sorting.push([colIdx, asSorting[0], 0]);
                sorting[sorting.length - 1]._idx = 0;
            }
        }
        else if (sorting.length && sorting[0][0] == colIdx) {
            // Single column - already sorting on this column, modify the sort
            nextSortIdx = next(sorting[0]);

            sorting.length = 1;
            sorting[0][1] = asSorting[nextSortIdx];
            sorting[0]._idx = nextSortIdx;
        }
        else {
            // Single column - sort only on this column
            sorting.length = 0;
            sorting.push([colIdx, asSorting[0]]);
            sorting[0]._idx = 0;
        }

        // Run the sort by calling a full redraw
        _fnReDraw(settings);

        // callback used for async user interaction
        if (typeof callback == 'function') {
            callback(settings);
        }
    }


    /**
    * Attach a sort handler (click) to a node
    *  @param {object} settings dataTables settings object
    *  @param {node} attachTo node to attach the handler to
    *  @param {int} colIdx column sorting index
    *  @param {function} [callback] callback function
    *  @memberof DataTable#oApi
    */
    function _fnSortAttachListener(settings, attachTo, colIdx, callback) {
        var col = settings.aoColumns[colIdx];

        _fnBindAction(attachTo, {}, function (e) {
            /* If the column is not sortable - don't to anything */
            if (col.bSortable === false) {
                return;
            }

            // If processing is enabled use a timeout to allow the processing
            // display to be shown - otherwise to it synchronously
            if (settings.oFeatures.bProcessing) {
                _fnProcessingDisplay(settings, true);

                setTimeout(function () {
                    _fnSortListener(settings, colIdx, e.shiftKey, callback);

                    // In server-side processing, the draw callback will remove the
                    // processing display
                    if (_fnDataSource(settings) !== 'ssp') {
                        _fnProcessingDisplay(settings, false);
                    }
                }, 0);
            }
            else {
                _fnSortListener(settings, colIdx, e.shiftKey, callback);
            }
        });
    }


    /**
    * Set the sorting classes on table's body, Note: it is safe to call this function
    * when bSort and bSortClasses are false
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnSortingClasses(settings) {
        var oldSort = settings.aLastSort;
        var sortClass = settings.oClasses.sSortColumn;
        var sort = _fnSortFlatten(settings);
        var features = settings.oFeatures;
        var i, ien, colIdx;

        if (features.bSort && features.bSortClasses) {
            // Remove old sorting classes
            for (i = 0, ien = oldSort.length; i < ien; i++) {
                colIdx = oldSort[i].src;

                // Remove column sorting
                $(_pluck(settings.aoData, 'anCells', colIdx))
					.removeClass(sortClass + (i < 2 ? i + 1 : 3));
            }

            // Add new column sorting
            for (i = 0, ien = sort.length; i < ien; i++) {
                colIdx = sort[i].src;

                $(_pluck(settings.aoData, 'anCells', colIdx))
					.addClass(sortClass + (i < 2 ? i + 1 : 3));
            }
        }

        settings.aLastSort = sort;
    }


    // Get the data to sort a column, be it from cache, fresh (populating the
    // cache), or from a sort formatter
    function _fnSortData(settings, idx) {
        // Custom sorting function - provided by the sort data type
        var column = settings.aoColumns[idx];
        var customSort = DataTable.ext.order[column.sSortDataType];
        var customData;

        if (customSort) {
            customData = customSort.call(settings.oInstance, settings, idx,
				_fnColumnIndexToVisible(settings, idx)
			);
        }

        // Use / populate cache
        var row, cellData;
        var formatter = DataTable.ext.type.order[column.sType + "-pre"];

        for (var i = 0, ien = settings.aoData.length; i < ien; i++) {
            row = settings.aoData[i];
            //console.log(row);

            if (!row._aSortData) {
                row._aSortData = [];
            }

            if (!row._aSortData[idx] || customSort) {
                var colonneOriginale = (settings.sDom.indexOf('R') >= 0 ? settings.aoColumns[idx]._ColReorder_iOrigCol : idx);
                //console.log("7!" + idx + "!" + row._aSortData[idx]);
                cellData = customSort ?
					customData[i] : // If there was a custom sort function, use data from there
					_fnGetCellData(settings, i, colonneOriginale, 'sort');

                row._aSortData[idx] = formatter ?
					formatter(cellData) :
					cellData;
            }
        }
    }



    /**
    * Save the state of a table
    *  @param {object} oSettings dataTables settings object
    *  @memberof DataTable#oApi
    */
    function _fnSaveState(oSettings) {
        // //console.log("interne_ 11 " + oSettings);
        if (!oSettings.oFeatures.bStateSave || oSettings.bDestroying) {
            return;
        }

        /* Store the interesting variables */
        var i, iLen;
        var oState = {
            "iCreate": +new Date(),
            "iStart": oSettings._iDisplayStart,
            "iLength": oSettings._iDisplayLength,
            "aaSorting": $.extend(true, [], oSettings.aaSorting),
            "oSearch": $.extend(true, {}, oSettings.oPreviousSearch),
            "aoSearchCols": $.extend(true, [], oSettings.aoPreSearchCols),
            "abVisCols": _pluck(oSettings.aoColumns, 'bVisible')
        };

        _fnCallbackFire(oSettings, "aoStateSaveParams", 'stateSaveParams', [oSettings, oState]);

        oSettings.fnStateSaveCallback.call(oSettings.oInstance, oSettings, oState);
    }


    /**
    * Attempt to load a saved table state
    *  @param {object} oSettings dataTables settings object
    *  @param {object} oInit DataTables init object so we can override settings
    *  @memberof DataTable#oApi
    */
    function _fnLoadState(oSettings, oInit) {
        ////console.log("interne_ " + oSettings);
        var i, ien;
        var columns = oSettings.aoColumns;

        if (!oSettings.oFeatures.bStateSave) {
            return;
        }

        var oData = oSettings.fnStateLoadCallback.call(oSettings.oInstance, oSettings);
        if (!oData) {
            return;
        }

        /* Allow custom and plug-in manipulation functions to alter the saved data set and
        * cancelling of loading by returning false
        */
        var abStateLoad = _fnCallbackFire(oSettings, 'aoStateLoadParams', 'stateLoadParams', [oSettings, oData]);
        if ($.inArray(false, abStateLoad) !== -1) {
            return;
        }

        /* Reject old data */
        var duration = oSettings.iStateDuration;
        if (duration > 0 && oData.iCreate < +new Date() - (duration * 1000)) {
            return;
        }

        // Number of columns have changed - all bets are off, no restore of settings
        if (columns.length !== oData.aoSearchCols.length) {
            return;
        }

        /* Store the saved state so it might be accessed at any time */
        oSettings.oLoadedState = $.extend(true, {}, oData);

        /* Restore key features */
        oSettings._iDisplayStart = oData.iStart;
        oSettings.iInitDisplayStart = oData.iStart;
        oSettings._iDisplayLength = oData.iLength;
        oSettings.aaSorting = [];

        $.each(oData.aaSorting, function (i, col) {
            oSettings.aaSorting.push(col[0] >= columns.length ? [0, col[1]] : col);
        });
        /* Search filtering  */
        $.extend(oSettings.oPreviousSearch, oData.oSearch);
        $.extend(true, oSettings.aoPreSearchCols, oData.aoSearchCols);

        /* Column visibility state */
        var visColumns = oData.abVisCols;
        for (i = 0, ien = visColumns.length; i < ien; i++) {
            columns[i].bVisible = visColumns[i];
        }

        _fnCallbackFire(oSettings, 'aoStateLoaded', 'stateLoaded', [oSettings, oData]);
    }


    /**
    * Return the settings object for a particular table
    *  @param {node} table table we are using as a dataTable
    *  @returns {object} Settings object - or null if not found
    *  @memberof DataTable#oApi
    */
    function _fnSettingsFromNode(table) {
        var settings = DataTable.settings;
        var idx = $.inArray(table, _pluck(settings, 'nTable'));

        return idx !== -1 ?
			settings[idx] :
			null;
    }


    /**
    * Log an error message
    *  @param {object} settings dataTables settings object
    *  @param {int} level log error messages, or display them to the user
    *  @param {string} msg error message
    *  @param {int} tn Technical note id to get more information about the error.
    *  @memberof DataTable#oApi
    */
    function _fnLog(settings, level, msg, tn) {
        msg = 'DataTables warning: ' +
			(settings !== null ? 'table id=' + settings.sTableId + ' - ' : '') + msg;

        if (tn) {
            msg += '. For more information about this error, please see ' +
			'http://datatables.net/tn/' + tn;
        }

        if (!level) {
            // Backwards compatibility pre 1.10
            var ext = DataTable.ext;
            var type = ext.sErrMode || ext.errMode;

            if (type == 'alert') {
                alert(msg);
            }
            else {
                throw new Error(msg);
            }
        }
        else if (window.console && console.log) {
            console.log(msg);
        }
    }


    /**
    * See if a property is defined on one object, if so assign it to the other object
    *  @param {object} ret target object
    *  @param {object} src source object
    *  @param {string} name property
    *  @param {string} [mappedName] name to map too - optional, name used if not given
    *  @memberof DataTable#oApi
    */
    function _fnMap(ret, src, name, mappedName) {
        if ($.isArray(name)) {
            $.each(name, function (i, val) {
                if ($.isArray(val)) {
                    _fnMap(ret, src, val[0], val[1]);
                }
                else {
                    _fnMap(ret, src, val);
                }
            });

            return;
        }

        if (mappedName === undefined) {
            mappedName = name;
        }

        if (src[name] !== undefined) {
            ret[mappedName] = src[name];
        }
    }


    /**
    * Extend objects - very similar to jQuery.extend, but deep copy objects, and
    * shallow copy arrays. The reason we need to do this, is that we don't want to
    * deep copy array init values (such as aaSorting) since the dev wouldn't be
    * able to override them, but we do want to deep copy arrays.
    *  @param {object} out Object to extend
    *  @param {object} extender Object from which the properties will be applied to
    *      out
    *  @param {boolean} breakRefs If true, then arrays will be sliced to take an
    *      independent copy with the exception of the `data` or `aaData` parameters
    *      if they are present. This is so you can pass in a collection to
    *      DataTables and have that used as your data source without breaking the
    *      references
    *  @returns {object} out Reference, just for convenience - out === the return.
    *  @memberof DataTable#oApi
    *  @todo This doesn't take account of arrays inside the deep copied objects.
    */
    function _fnExtend(out, extender, breakRefs) {
        var val;

        for (var prop in extender) {
            if (extender.hasOwnProperty(prop)) {
                val = extender[prop];

                if ($.isPlainObject(val)) {
                    if (!$.isPlainObject(out[prop])) {
                        out[prop] = {};
                    }
                    $.extend(true, out[prop], val);
                }
                else if (breakRefs && prop !== 'data' && prop !== 'aaData' && $.isArray(val)) {
                    out[prop] = val.slice();
                }
                else {
                    out[prop] = val;
                }
            }
        }

        return out;
    }


    /**
    * Bind an event handers to allow a click or return key to activate the callback.
    * This is good for accessibility since a return on the keyboard will have the
    * same effect as a click, if the element has focus.
    *  @param {element} n Element to bind the action to
    *  @param {object} oData Data object to pass to the triggered function
    *  @param {function} fn Callback function for when the event is triggered
    *  @memberof DataTable#oApi
    */
    function _fnBindAction(n, oData, fn) {
        $(n)
			.bind('click.DT', oData, function (e) {
			    n.blur(); // Remove focus outline for mouse users
			    fn(e);
			})
			.bind('keypress.DT', oData, function (e) {
			    if (e.which === 13) {
			        e.preventDefault();
			        fn(e);
			    }
			})
			.bind('selectstart.DT', function () {
			    /* Take the brutal approach to cancelling text selection */
			    return false;
			});
    }


    /**
    * Register a callback function. Easily allows a callback function to be added to
    * an array store of callback functions that can then all be called together.
    *  @param {object} oSettings dataTables settings object
    *  @param {string} sStore Name of the array storage for the callbacks in oSettings
    *  @param {function} fn Function to be called back
    *  @param {string} sName Identifying name for the callback (i.e. a label)
    *  @memberof DataTable#oApi
    */
    function _fnCallbackReg(oSettings, sStore, fn, sName) {
        if (fn) {
            oSettings[sStore].push({
                "fn": fn,
                "sName": sName
            });
        }
    }


    /**
    * Fire callback functions and trigger events. Note that the loop over the
    * callback array store is done backwards! Further note that you do not want to
    * fire off triggers in time sensitive applications (for example cell creation)
    * as its slow.
    *  @param {object} settings dataTables settings object
    *  @param {string} callbackArr Name of the array storage for the callbacks in
    *      oSettings
    *  @param {string} event Name of the jQuery custom event to trigger. If null no
    *      trigger is fired
    *  @param {array} args Array of arguments to pass to the callback function /
    *      trigger
    *  @memberof DataTable#oApi
    */
    function _fnCallbackFire(settings, callbackArr, event, args) {
        var ret = [];

        if (callbackArr) {
            ret = $.map(settings[callbackArr].slice().reverse(), function (val, i) {
                return val.fn.apply(settings.oInstance, args);
            });
        }

        if (event !== null) {
            $(settings.nTable).trigger(event + '.dt', args);
        }

        return ret;
    }


    function _fnLengthOverflow(settings) {
        var 
			start = settings._iDisplayStart,
			end = settings.fnDisplayEnd(),
			len = settings._iDisplayLength;

        /* If we have space to show extra rows (backing up from the end point - then do so */
        if (end === settings.fnRecordsDisplay()) {
            start = end - len;
        }

        if (len === -1 || start < 0) {
            start = 0;
        }

        settings._iDisplayStart = start;
    }


    function _fnRenderer(settings, type) {
        var renderer = settings.renderer;
        var host = DataTable.ext.renderer[type];

        if ($.isPlainObject(renderer) && renderer[type]) {
            // Specific renderer for this type. If available use it, otherwise use
            // the default.
            return host[renderer[type]] || host._;
        }
        else if (typeof renderer === 'string') {
            // Common renderer - if there is one available for this type use it,
            // otherwise use the default
            return host[renderer] || host._;
        }

        // Use the default
        return host._;
    }


    /**
    * Detect the data source being used for the table. Used to simplify the code
    * a little (ajax) and to make it compress a little smaller.
    *
    *  @param {object} settings dataTables settings object
    *  @returns {string} Data source
    *  @memberof DataTable#oApi
    */
    function _fnDataSource(settings) {
        if (settings.oFeatures.bServerSide) {
            return 'ssp';
        }
        else if (settings.ajax || settings.sAjaxSource) {
            return 'ajax';
        }
        return 'dom';
    }


    DataTable = function (options) {
        /**
        * Perform a jQuery selector action on the table's TR elements (from the tbody) and
        * return the resulting jQuery object.
        *  @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
        *  @param {object} [oOpts] Optional parameters for modifying the rows to be included
        *  @param {string} [oOpts.filter=none] Select TR elements that meet the current filter
        *    criterion ("applied") or all TR elements (i.e. no filter).
        *  @param {string} [oOpts.order=current] Order of the TR elements in the processed array.
        *    Can be either 'current', whereby the current sorting of the table is used, or
        *    'original' whereby the original order the data was read into the table is used.
        *  @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
        *    ("current") or not ("all"). If 'current' is given, then order is assumed to be
        *    'current' and filter is 'applied', regardless of what they might be given as.
        *  @returns {object} jQuery object, filtered by the given selector.
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Highlight every second row
        *      oTable.$('tr:odd').css('backgroundColor', 'blue');
        *    } );
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Filter to rows with 'Webkit' in them, add a background colour and then
        *      // remove the filter, thus highlighting the 'Webkit' rows only.
        *      oTable.fnFilter('Webkit');
        *      oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue');
        *      oTable.fnFilter('');
        *    } );
        */
        this.$ = function (sSelector, oOpts) {
            return this.api(true).$(sSelector, oOpts);
        };


        /**
        * Almost identical to $ in operation, but in this case returns the data for the matched
        * rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
        * rather than any descendants, so the data can be obtained for the row/cell. If matching
        * rows are found, the data returned is the original data array/object that was used to
        * create the row (or a generated array if from a DOM source).
        *
        * This method is often useful in-combination with $ where both functions are given the
        * same parameters and the array indexes will match identically.
        *  @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
        *  @param {object} [oOpts] Optional parameters for modifying the rows to be included
        *  @param {string} [oOpts.filter=none] Select elements that meet the current filter
        *    criterion ("applied") or all elements (i.e. no filter).
        *  @param {string} [oOpts.order=current] Order of the data in the processed array.
        *    Can be either 'current', whereby the current sorting of the table is used, or
        *    'original' whereby the original order the data was read into the table is used.
        *  @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
        *    ("current") or not ("all"). If 'current' is given, then order is assumed to be
        *    'current' and filter is 'applied', regardless of what they might be given as.
        *  @returns {array} Data for the matched elements. If any elements, as a result of the
        *    selector, were not TR, TD or TH elements in the DataTable, they will have a null
        *    entry in the array.
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Get the data from the first row in the table
        *      var data = oTable._('tr:first');
        *
        *      // Do something useful with the data
        *      alert( "First cell is: "+data[0] );
        *    } );
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Filter to 'Webkit' and get all data for
        *      oTable.fnFilter('Webkit');
        *      var data = oTable._('tr', {"search": "applied"});
        *
        *      // Do something with the data
        *      alert( data.length+" rows matched the search" );
        *    } );
        */
        this._ = function (sSelector, oOpts) {
            return this.api(true).rows(sSelector, oOpts).data();
        };


        /**
        * Create a DataTables Api instance, with the currently selected tables for
        * the Api's context.
        * @param {boolean} [traditional=false] Set the API instance's context to be
        *   only the table referred to by the `DataTable.ext.iApiIndex` option, as was
        *   used in the API presented by DataTables 1.9- (i.e. the traditional mode),
        *   or if all tables captured in the jQuery object should be used.
        * @return {DataTables.Api}
        */
        this.api = function (traditional) {
            return traditional ?
				new _Api(
					_fnSettingsFromNode(this[_ext.iApiIndex])
				) :
				new _Api(this);
        };


        /**
        * Add a single new row or multiple rows of data to the table. Please note
        * that this is suitable for client-side processing only - if you are using
        * server-side processing (i.e. "bServerSide": true), then to add data, you
        * must add it to the data source, i.e. the server-side, through an Ajax call.
        *  @param {array|object} data The data to be added to the table. This can be:
        *    <ul>
        *      <li>1D array of data - add a single row with the data provided</li>
        *      <li>2D array of arrays - add multiple rows in a single call</li>
        *      <li>object - data object when using <i>mData</i></li>
        *      <li>array of objects - multiple data objects when using <i>mData</i></li>
        *    </ul>
        *  @param {bool} [redraw=true] redraw the table or not
        *  @returns {array} An array of integers, representing the list of indexes in
        *    <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
        *    the table.
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    // Global var for counter
        *    var giCount = 2;
        *
        *    $(document).ready(function() {
        *      $('#example').dataTable();
        *    } );
        *
        *    function fnClickAddRow() {
        *      $('#example').dataTable().fnAddData( [
        *        giCount+".1",
        *        giCount+".2",
        *        giCount+".3",
        *        giCount+".4" ]
        *      );
        *
        *      giCount++;
        *    }
        */
        this.fnAddData = function (data, redraw) {
            var api = this.api(true);

            /* Check if we want to add multiple rows or not */
            var rows = $.isArray(data) && ($.isArray(data[0]) || $.isPlainObject(data[0])) ?
				api.rows.add(data) :
				api.row.add(data);

            if (redraw === undefined || redraw) {
                api.draw();
            }

            return rows.flatten().toArray();
        };


        /**
        * This function will make DataTables recalculate the column sizes, based on the data
        * contained in the table and the sizes applied to the columns (in the DOM, CSS or
        * through the sWidth parameter). This can be useful when the width of the table's
        * parent element changes (for example a window resize).
        *  @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable( {
        *        "sScrollY": "200px",
        *        "bPaginate": false
        *      } );
        *
        *      $(window).bind('resize', function () {
        *        oTable.fnAdjustColumnSizing();
        *      } );
        *    } );
        */
        this.fnAdjustColumnSizing = function (bRedraw) {
            var api = this.api(true).columns.adjust();
            var settings = api.settings()[0];
            var scroll = settings.oScroll;

            if (bRedraw === undefined || bRedraw) {
                api.draw(false);
            }
            else if (scroll.sX !== "" || scroll.sY !== "") {
                /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */
                _fnScrollDraw(settings);
            }
        };


        /**
        * Quickly and simply clear a table
        *  @param {bool} [bRedraw=true] redraw the table or not
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...)
        *      oTable.fnClearTable();
        *    } );
        */
        this.fnClearTable = function (bRedraw) {
            var api = this.api(true).clear();

            if (bRedraw === undefined || bRedraw) {
                api.draw();
            }
        };


        /**
        * The exact opposite of 'opening' a row, this function will close any rows which
        * are currently 'open'.
        *  @param {node} nTr the table row to 'close'
        *  @returns {int} 0 on success, or 1 if failed (can't find the row)
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable;
        *
        *      // 'open' an information row when a row is clicked on
        *      $('#example tbody tr').click( function () {
        *        if ( oTable.fnIsOpen(this) ) {
        *          oTable.fnClose( this );
        *        } else {
        *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
        *        }
        *      } );
        *
        *      oTable = $('#example').dataTable();
        *    } );
        */
        this.fnClose = function (nTr) {
            this.api(true).row(nTr).child.hide();
        };


        /**
        * Remove a row for the table
        *  @param {mixed} target The index of the row from aoData to be deleted, or
        *    the TR element you want to delete
        *  @param {function|null} [callBack] Callback function
        *  @param {bool} [redraw=true] Redraw the table or not
        *  @returns {array} The row that was deleted
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Immediately remove the first row
        *      oTable.fnDeleteRow( 0 );
        *    } );
        */
        this.fnDeleteRow = function (target, callback, redraw) {
            var api = this.api(true);
            var rows = api.rows(target);
            var settings = rows.settings()[0];
            var data = settings.aoData[rows[0][0]];

            rows.remove();

            if (callback) {
                callback.call(this, settings, data);
            }

            if (redraw === undefined || redraw) {
                api.draw();
            }

            return data;
        };


        /**
        * Restore the table to it's original state in the DOM by removing all of DataTables
        * enhancements, alterations to the DOM structure of the table and event listeners.
        *  @param {boolean} [remove=false] Completely remove the table from the DOM
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      // This example is fairly pointless in reality, but shows how fnDestroy can be used
        *      var oTable = $('#example').dataTable();
        *      oTable.fnDestroy();
        *    } );
        */
        this.fnDestroy = function (remove) {
            this.api(true).destroy(remove);
        };


        /**
        * Redraw the table
        *  @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw.
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Re-draw the table - you wouldn't want to do it here, but it's an example :-)
        *      oTable.fnDraw();
        *    } );
        */
        this.fnDraw = function (complete) {
            // Note that this isn't an exact match to the old call to _fnDraw - it takes
            // into account the new data, but can old position.
            this.api(true).draw(!complete);
        };


        /**
        * Filter the input based on data
        *  @param {string} sInput String to filter the table on
        *  @param {int|null} [iColumn] Column to limit filtering to
        *  @param {bool} [bRegex=false] Treat as regular expression or not
        *  @param {bool} [bSmart=true] Perform smart filtering or not
        *  @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es)
        *  @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false)
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Sometime later - filter...
        *      oTable.fnFilter( 'test string' );
        *    } );
        */
        this.fnFilter = function (sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive) {
            var api = this.api(true);

            if (iColumn === null || iColumn === undefined) {
                api.search(sInput, bRegex, bSmart, bCaseInsensitive);
            }
            else {
                api.column(iColumn).search(sInput, bRegex, bSmart, bCaseInsensitive);
            }

            api.draw();
        };


        /**
        * Get the data for the whole table, an individual row or an individual cell based on the
        * provided parameters.
        *  @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as
        *    a TR node then the data source for the whole row will be returned. If given as a
        *    TD/TH cell node then iCol will be automatically calculated and the data for the
        *    cell returned. If given as an integer, then this is treated as the aoData internal
        *    data index for the row (see fnGetPosition) and the data for that row used.
        *  @param {int} [col] Optional column index that you want the data of.
        *  @returns {array|object|string} If mRow is undefined, then the data for all rows is
        *    returned. If mRow is defined, just data for that row, and is iCol is
        *    defined, only data for the designated cell is returned.
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    // Row data
        *    $(document).ready(function() {
        *      oTable = $('#example').dataTable();
        *
        *      oTable.$('tr').click( function () {
        *        var data = oTable.fnGetData( this );
        *        // ... do something with the array / object of data for the row
        *      } );
        *    } );
        *
        *  @example
        *    // Individual cell data
        *    $(document).ready(function() {
        *      oTable = $('#example').dataTable();
        *
        *      oTable.$('td').click( function () {
        *        var sData = oTable.fnGetData( this );
        *        alert( 'The cell clicked on had the value of '+sData );
        *      } );
        *    } );
        */
        this.fnGetData = function (src, col) {
            //console.log("test template1");
            var api = this.api(true);
            //console.log("test template2");
            if (src !== undefined) {
                var type = src.nodeName ? src.nodeName.toLowerCase() : '';
                //console.log("test template3");
                return col !== undefined || type == 'td' || type == 'th' ?
					api.cell(src, col).data() :
					api.row(src).data() || null;
            }
            //console.log("test template4");
            return api.data().toArray();
        };


        /**
        * Get an array of the TR nodes that are used in the table's body. Note that you will
        * typically want to use the '$' API method in preference to this as it is more
        * flexible.
        *  @param {int} [iRow] Optional row index for the TR element you want
        *  @returns {array|node} If iRow is undefined, returns an array of all TR elements
        *    in the table's body, or iRow is defined, just the TR element requested.
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Get the nodes from the table
        *      var nNodes = oTable.fnGetNodes( );
        *    } );
        */
        this.fnGetNodes = function (iRow) {
            var api = this.api(true);

            return iRow !== undefined ?
				api.row(iRow).node() :
				api.rows().nodes().flatten().toArray();
        };


        /**
        * Get the array indexes of a particular cell from it's DOM element
        * and column index including hidden columns
        *  @param {node} node this can either be a TR, TD or TH in the table's body
        *  @returns {int} If nNode is given as a TR, then a single index is returned, or
        *    if given as a cell, an array of [row index, column index (visible),
        *    column index (all)] is given.
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      $('#example tbody td').click( function () {
        *        // Get the position of the current data from the node
        *        var aPos = oTable.fnGetPosition( this );
        *
        *        // Get the data array for this row
        *        var aData = oTable.fnGetData( aPos[0] );
        *
        *        // Update the data array and return the value
        *        aData[ aPos[1] ] = 'clicked';
        *        this.innerHTML = 'clicked';
        *      } );
        *
        *      // Init DataTables
        *      oTable = $('#example').dataTable();
        *    } );
        */
        this.fnGetPosition = function (node) {
            var api = this.api(true);
            var nodeName = node.nodeName.toUpperCase();

            if (nodeName == 'TR') {
                return api.row(node).index();
            }
            else if (nodeName == 'TD' || nodeName == 'TH') {
                var cell = api.cell(node).index();

                return [
					cell.row,
					cell.columnVisible,
					cell.column
				];
            }
            return null;
        };


        /**
        * Check to see if a row is 'open' or not.
        *  @param {node} nTr the table row to check
        *  @returns {boolean} true if the row is currently open, false otherwise
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable;
        *
        *      // 'open' an information row when a row is clicked on
        *      $('#example tbody tr').click( function () {
        *        if ( oTable.fnIsOpen(this) ) {
        *          oTable.fnClose( this );
        *        } else {
        *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
        *        }
        *      } );
        *
        *      oTable = $('#example').dataTable();
        *    } );
        */
        this.fnIsOpen = function (nTr) {
            return this.api(true).row(nTr).child.isShown();
        };


        /**
        * This function will place a new row directly after a row which is currently
        * on display on the page, with the HTML contents that is passed into the
        * function. This can be used, for example, to ask for confirmation that a
        * particular record should be deleted.
        *  @param {node} nTr The table row to 'open'
        *  @param {string|node|jQuery} mHtml The HTML to put into the row
        *  @param {string} sClass Class to give the new TD cell
        *  @returns {node} The row opened. Note that if the table row passed in as the
        *    first parameter, is not found in the table, this method will silently
        *    return.
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable;
        *
        *      // 'open' an information row when a row is clicked on
        *      $('#example tbody tr').click( function () {
        *        if ( oTable.fnIsOpen(this) ) {
        *          oTable.fnClose( this );
        *        } else {
        *          oTable.fnOpen( this, "Temporary row opened", "info_row" );
        *        }
        *      } );
        *
        *      oTable = $('#example').dataTable();
        *    } );
        */
        this.fnOpen = function (nTr, mHtml, sClass) {
            return this.api(true)
				.row(nTr)
				.child(mHtml, sClass)
				.show()
				.child()[0];
        };


        /**
        * Change the pagination - provides the internal logic for pagination in a simple API
        * function. With this function you can have a DataTables table go to the next,
        * previous, first or last pages.
        *  @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
        *    or page number to jump to (integer), note that page 0 is the first page.
        *  @param {bool} [bRedraw=true] Redraw the table or not
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *      oTable.fnPageChange( 'next' );
        *    } );
        */
        this.fnPageChange = function (mAction, bRedraw) {
            var api = this.api(true).page(mAction);

            if (bRedraw === undefined || bRedraw) {
                api.draw(false);
            }
        };


        /**
        * Show a particular column
        *  @param {int} iCol The column whose display should be changed
        *  @param {bool} bShow Show (true) or hide (false) the column
        *  @param {bool} [bRedraw=true] Redraw the table or not
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Hide the second column after initialisation
        *      oTable.fnSetColumnVis( 1, false );
        *    } );
        */
        this.fnSetColumnVis = function (iCol, bShow, bRedraw) {
            var api = this.api(true).column(iCol).visible(bShow);

            if (bRedraw === undefined || bRedraw) {
                api.columns.adjust().draw();
            }
        };


        /**
        * Get the settings for a particular table for external manipulation
        *  @returns {object} DataTables settings object. See
        *    {@link DataTable.models.oSettings}
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *      var oSettings = oTable.fnSettings();
        *
        *      // Show an example parameter from the settings
        *      alert( oSettings._iDisplayStart );
        *    } );
        */
        this.fnSettings = function () {
            return _fnSettingsFromNode(this[_ext.iApiIndex]);
        };


        /**
        * Sort the table by a particular column
        *  @param {int} iCol the data index to sort on. Note that this will not match the
        *    'display index' if you have hidden data entries
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Sort immediately with columns 0 and 1
        *      oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
        *    } );
        */
        this.fnSort = function (aaSort) {
            this.api(true).order(aaSort).draw();
        };


        /**
        * Attach a sort listener to an element for a given column
        *  @param {node} nNode the element to attach the sort listener to
        *  @param {int} iColumn the column that a click on this node will sort on
        *  @param {function} [fnCallback] callback function when sort is run
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *
        *      // Sort on column 1, when 'sorter' is clicked on
        *      oTable.fnSortListener( document.getElementById('sorter'), 1 );
        *    } );
        */
        this.fnSortListener = function (nNode, iColumn, fnCallback) {
            this.api(true).order.listener(nNode, iColumn, fnCallback);
        };


        /**
        * Update a table cell or row - this method will accept either a single value to
        * update the cell with, an array of values with one element for each column or
        * an object in the same format as the original data source. The function is
        * self-referencing in order to make the multi column updates easier.
        *  @param {object|array|string} mData Data to update the cell/row with
        *  @param {node|int} mRow TR element you want to update or the aoData index
        *  @param {int} [iColumn] The column to update, give as null or undefined to
        *    update a whole row.
        *  @param {bool} [bRedraw=true] Redraw the table or not
        *  @param {bool} [bAction=true] Perform pre-draw actions or not
        *  @returns {int} 0 on success, 1 on error
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *      oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell
        *      oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row
        *    } );
        */
        this.fnUpdate = function (mData, mRow, iColumn, bRedraw, bAction) {
            var api = this.api(true);

            if (iColumn === undefined || iColumn === null) {
                api.row(mRow).data(mData);
            }
            else {
                api.cell(mRow, iColumn).data(mData);
            }

            if (bAction === undefined || bAction) {
                api.columns.adjust();
            }

            if (bRedraw === undefined || bRedraw) {
                api.draw();
            }
            return 0;
        };


        /**
        * Provide a common method for plug-ins to check the version of DataTables being used, in order
        * to ensure compatibility.
        *  @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
        *    formats "X" and "X.Y" are also acceptable.
        *  @returns {boolean} true if this version of DataTables is greater or equal to the required
        *    version, or false if this version of DataTales is not suitable
        *  @method
        *  @dtopt API
        *  @deprecated Since v1.10
        *
        *  @example
        *    $(document).ready(function() {
        *      var oTable = $('#example').dataTable();
        *      alert( oTable.fnVersionCheck( '1.9.0' ) );
        *    } );
        */
        this.fnVersionCheck = _ext.fnVersionCheck;


        var _that = this;
        var emptyInit = options === undefined;
        var len = this.length;

        if (emptyInit) {
            options = {};
        }

        this.oApi = this.internal = _ext.internal;

        // Extend with old style plug-in API methods
        for (var fn in DataTable.ext.internal) {
            if (fn) {
                this[fn] = _fnExternApiFunc(fn);
            }
        }

        this.each(function () {
            // For each initialisation we want to give it a clean initialisation
            // object that can be bashed around
            var o = {};
            var oInit = len > 1 ? // optimisation for single table case
				_fnExtend(o, options, true) :
				options;

            /*global oInit,_that,emptyInit*/
            var i = 0, iLen, j, jLen, k, kLen;
            var sId = this.getAttribute('id');
            var bInitHandedOff = false;
            var defaults = DataTable.defaults;


            /* Sanity check */
            if (this.nodeName.toLowerCase() != 'table') {
                _fnLog(null, 0, 'Non-table node initialisation (' + this.nodeName + ')', 2);
                return;
            }

            /* Backwards compatibility for the defaults */
            _fnCompatOpts(defaults);
            _fnCompatCols(defaults.column);

            /* Convert the camel-case defaults to Hungarian */
            _fnCamelToHungarian(defaults, defaults, true);
            _fnCamelToHungarian(defaults.column, defaults.column, true);

            /* Setting up the initialisation object */
            _fnCamelToHungarian(defaults, oInit);

            /* Check to see if we are re-initialising a table */
            var allSettings = DataTable.settings;
            for (i = 0, iLen = allSettings.length; i < iLen; i++) {
                /* Base check on table node */
                if (allSettings[i].nTable == this) {
                    var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve;
                    var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy;

                    if (emptyInit || bRetrieve) {
                        return allSettings[i].oInstance;
                    }
                    else if (bDestroy) {
                        allSettings[i].oInstance.fnDestroy();
                        break;
                    }
                    else {
                        _fnLog(allSettings[i], 0, 'Cannot reinitialise DataTable', 3);
                        return;
                    }
                }

                /* If the element we are initialising has the same ID as a table which was previously
                * initialised, but the table nodes don't match (from before) then we destroy the old
                * instance by simply deleting it. This is under the assumption that the table has been
                * destroyed by other methods. Anyone using non-id selectors will need to do this manually
                */
                if (allSettings[i].sTableId == this.id) {
                    allSettings.splice(i, 1);
                    break;
                }
            }

            /* Ensure the table has an ID - required for accessibility */
            if (sId === null || sId === "") {
                sId = "DataTables_Table_" + (DataTable.ext._unique++);
                this.id = sId;
            }

            /* Create the settings object for this table and set some of the default parameters */
            var oSettings = $.extend(true, {}, DataTable.models.oSettings, {
                "nTable": this,
                "oApi": _that.internal,
                "oInit": oInit,
                "sDestroyWidth": $(this)[0].style.width,
                "sInstance": sId,
                "sTableId": sId
            });
            allSettings.push(oSettings);

            // Need to add the instance after the instance after the settings object has been added
            // to the settings array, so we can self reference the table instance if more than one
            oSettings.oInstance = (_that.length === 1) ? _that : $(this).dataTable();

            // Backwards compatibility, before we apply all the defaults
            _fnCompatOpts(oInit);

            if (oInit.oLanguage) {
                _fnLanguageCompat(oInit.oLanguage);
            }

            // If the length menu is given, but the init display length is not, use the length menu
            if (oInit.aLengthMenu && !oInit.iDisplayLength) {
                oInit.iDisplayLength = $.isArray(oInit.aLengthMenu[0]) ?
					oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0];
            }

            // Apply the defaults and init options to make a single init object will all
            // options defined from defaults and instance options.
            oInit = _fnExtend($.extend(true, {}, defaults), oInit);


            // Map the initialisation options onto the settings object
            _fnMap(oSettings.oFeatures, oInit, [
				"bPaginate",
				"bLengthChange",
				"bFilter",
				"bSort",
				"bSortMulti",
				"bInfo",
				"bProcessing",
				"bAutoWidth",
				"bSortClasses",
				"bServerSide",
				"bDeferRender"
			]);
            _fnMap(oSettings, oInit, [
				"asStripeClasses",
				"ajax",
				"fnServerData",
				"fnFormatNumber",
				"sServerMethod",
				"aaSorting",
				"aaSortingFixed",
				"aLengthMenu",
				"sPaginationType",
				"sAjaxSource",
				"sAjaxDataProp",
				"iStateDuration",
				"sDom",
				"bSortCellsTop",
				"iTabIndex",
				"fnStateLoadCallback",
				"fnStateSaveCallback",
				"renderer",
				["iCookieDuration", "iStateDuration"], // backwards compat
				["oSearch", "oPreviousSearch"],
				["aoSearchCols", "aoPreSearchCols"],
				["iDisplayLength", "_iDisplayLength"],
				["bJQueryUI", "bJUI"]
			]);
            _fnMap(oSettings.oScroll, oInit, [
				["sScrollX", "sX"],
				["sScrollXInner", "sXInner"],
				["sScrollY", "sY"],
				["bScrollCollapse", "bCollapse"]
			]);
            _fnMap(oSettings.oLanguage, oInit, "fnInfoCallback");

            /* Callback functions which are array driven */
            _fnCallbackReg(oSettings, 'aoDrawCallback', oInit.fnDrawCallback, 'user');
            _fnCallbackReg(oSettings, 'aoServerParams', oInit.fnServerParams, 'user');
            _fnCallbackReg(oSettings, 'aoStateSaveParams', oInit.fnStateSaveParams, 'user');
            _fnCallbackReg(oSettings, 'aoStateLoadParams', oInit.fnStateLoadParams, 'user');
            _fnCallbackReg(oSettings, 'aoStateLoaded', oInit.fnStateLoaded, 'user');
            _fnCallbackReg(oSettings, 'aoRowCallback', oInit.fnRowCallback, 'user');
            _fnCallbackReg(oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow, 'user');
            _fnCallbackReg(oSettings, 'aoHeaderCallback', oInit.fnHeaderCallback, 'user');
            _fnCallbackReg(oSettings, 'aoFooterCallback', oInit.fnFooterCallback, 'user');
            _fnCallbackReg(oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user');
            _fnCallbackReg(oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user');

            var oClasses = oSettings.oClasses;

            // @todo Remove in 1.11
            if (oInit.bJQueryUI) {
                /* Use the JUI classes object for display. You could clone the oStdClasses object if
                * you want to have multiple tables with multiple independent classes
                */
                $.extend(oClasses, DataTable.ext.oJUIClasses, oInit.oClasses);

                if (oInit.sDom === defaults.sDom && defaults.sDom === "lfrtip") {
                    /* Set the DOM to use a layout suitable for jQuery UI's theming */
                    oSettings.sDom = '<"H"lfr>t<"F"ip>';
                }

                if (!oSettings.renderer) {
                    oSettings.renderer = 'jqueryui';
                }
                else if ($.isPlainObject(oSettings.renderer) && !oSettings.renderer.header) {
                    oSettings.renderer.header = 'jqueryui';
                }
            }
            else {
                $.extend(oClasses, DataTable.ext.classes, oInit.oClasses);
            }
            $(this).addClass(oClasses.sTable);

            /* Calculate the scroll bar width and cache it for use later on */
            if (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") {
                oSettings.oScroll.iBarWidth = _fnScrollBarWidth();
            }
            if (oSettings.oScroll.sX === true) { // Easy initialisation of x-scrolling
                oSettings.oScroll.sX = '100%';
            }

            if (oSettings.iInitDisplayStart === undefined) {
                /* Display start point, taking into account the save saving */
                oSettings.iInitDisplayStart = oInit.iDisplayStart;
                oSettings._iDisplayStart = oInit.iDisplayStart;
            }

            if (oInit.iDeferLoading !== null) {
                oSettings.bDeferLoading = true;
                var tmp = $.isArray(oInit.iDeferLoading);
                oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading;
                oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading;
            }

            /* Language definitions */
            if (oInit.oLanguage.sUrl !== "") {
                /* Get the language definitions from a file - because this Ajax call makes the language
                * get async to the remainder of this function we use bInitHandedOff to indicate that
                * _fnInitialise will be fired by the returned Ajax handler, rather than the constructor
                */
                oSettings.oLanguage.sUrl = oInit.oLanguage.sUrl;
                $.getJSON(oSettings.oLanguage.sUrl, null, function (json) {
                    _fnLanguageCompat(json);
                    _fnCamelToHungarian(defaults.oLanguage, json);
                    $.extend(true, oSettings.oLanguage, oInit.oLanguage, json);
                    _fnInitialise(oSettings);
                });
                bInitHandedOff = true;
            }
            else {
                $.extend(true, oSettings.oLanguage, oInit.oLanguage);
            }


            /*
            * Stripes
            */
            if (oInit.asStripeClasses === null) {
                oSettings.asStripeClasses = [
					oClasses.sStripeOdd,
					oClasses.sStripeEven
				];
            }

            /* Remove row stripe classes if they are already on the table row */
            var stripeClasses = oSettings.asStripeClasses;
            var rowOne = $('tbody tr:eq(0)', this);
            if ($.inArray(true, $.map(stripeClasses, function (el, i) {
                return rowOne.hasClass(el);
            })) !== -1) {
                $('tbody tr', this).removeClass(stripeClasses.join(' '));
                oSettings.asDestroyStripes = stripeClasses.slice();
            }

            /*
            * Columns
            * See if we should load columns automatically or use defined ones
            */
            var anThs = [];
            var aoColumnsInit;
            var nThead = this.getElementsByTagName('thead');
            if (nThead.length !== 0) {
                _fnDetectHeader(oSettings.aoHeader, nThead[0]);
                anThs = _fnGetUniqueThs(oSettings);
            }

            /* If not given a column array, generate one with nulls */
            if (oInit.aoColumns === null) {
                aoColumnsInit = [];
                for (i = 0, iLen = anThs.length; i < iLen; i++) {
                    aoColumnsInit.push(null);
                }
            }
            else {
                aoColumnsInit = oInit.aoColumns;
            }

            /* Add the columns */
            for (i = 0, iLen = aoColumnsInit.length; i < iLen; i++) {
                _fnAddColumn(oSettings, anThs ? anThs[i] : null);
            }

            /* Apply the column definitions */
            _fnApplyColumnDefs(oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) {
                _fnColumnOptions(oSettings, iCol, oDef);
            });

            /* HTML5 attribute detection - build an mData object automatically if the
            * attributes are found
            */
            if (rowOne.length) {
                var a = function (cell, name) {
                    return cell.getAttribute('data-' + name) ? name : null;
                };

                $.each(_fnGetRowElements(oSettings, rowOne[0]).cells, function (i, cell) {
                    var col = oSettings.aoColumns[i];

                    if (col.mData === i) {
                        var sort = a(cell, 'sort') || a(cell, 'order');
                        var filter = a(cell, 'filter') || a(cell, 'search');

                        if (sort !== null || filter !== null) {
                            col.mData = {
                                _: i + '.display',
                                sort: sort !== null ? i + '.@data-' + sort : undefined,
                                type: sort !== null ? i + '.@data-' + sort : undefined,
                                filter: filter !== null ? i + '.@data-' + filter : undefined
                            };

                            _fnColumnOptions(oSettings, i);
                        }
                    }
                });
            }

            var features = oSettings.oFeatures;

            /* Must be done after everything which can be overridden by the state saving! */
            if (oInit.bStateSave) {
                features.bStateSave = true;
                _fnLoadState(oSettings, oInit);
                _fnCallbackReg(oSettings, 'aoDrawCallback', _fnSaveState, 'state_save');
            }


            /*
            * Sorting
            * @todo For modularisation (1.11) this needs to do into a sort start up handler
            */

            // If aaSorting is not defined, then we use the first indicator in asSorting
            // in case that has been altered, so the default sort reflects that option
            if (oInit.aaSorting === undefined) {
                var sorting = oSettings.aaSorting;
                for (i = 0, iLen = sorting.length; i < iLen; i++) {
                    sorting[i][1] = oSettings.aoColumns[i].asSorting[0];
                }
            }

            /* Do a first pass on the sorting classes (allows any size changes to be taken into
            * account, and also will apply sorting disabled classes if disabled
            */
            _fnSortingClasses(oSettings);

            if (features.bSort) {
                _fnCallbackReg(oSettings, 'aoDrawCallback', function () {
                    if (oSettings.bSorted) {
                        var aSort = _fnSortFlatten(oSettings);
                        var sortedColumns = {};

                        $.each(aSort, function (i, val) {
                            sortedColumns[val.src] = val.dir;
                        });

                        _fnCallbackFire(oSettings, null, 'order', [oSettings, aSort, sortedColumns]);
                        _fnSortAria(oSettings);
                    }
                });
            }

            _fnCallbackReg(oSettings, 'aoDrawCallback', function () {
                if (oSettings.bSorted || _fnDataSource(oSettings) === 'ssp' || features.bDeferRender) {
                    _fnSortingClasses(oSettings);
                }
            }, 'sc');


            /*
            * Final init
            * Cache the header, body and footer as required, creating them if needed
            */

            /* Browser support detection */
            _fnBrowserDetect(oSettings);

            // Work around for Webkit bug 83867 - store the caption-side before removing from doc
            var captions = $(this).children('caption').each(function () {
                this._captionSide = $(this).css('caption-side');
            });

            var thead = $(this).children('thead');
            if (thead.length === 0) {
                thead = $('<thead/>').appendTo(this);
            }
            oSettings.nTHead = thead[0];

            var tbody = $(this).children('tbody');
            if (tbody.length === 0) {
                tbody = $('<tbody/>').appendTo(this);
            }
            oSettings.nTBody = tbody[0];

            var tfoot = $(this).children('tfoot');
            if (tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "")) {
                // If we are a scrolling table, and no footer has been given, then we need to create
                // a tfoot element for the caption element to be appended to
                tfoot = $('<tfoot/>').appendTo(this);
            }

            if (tfoot.length === 0 || tfoot.children().length === 0) {
                $(this).addClass(oClasses.sNoFooter);
            }
            else if (tfoot.length > 0) {
                oSettings.nTFoot = tfoot[0];
                _fnDetectHeader(oSettings.aoFooter, oSettings.nTFoot);
            }
            ////console.log("p4");
            /* Check if there is data passing into the constructor */
            if (oInit.aaData) {
                for (i = 0; i < oInit.aaData.length; i++) {
                    _fnAddData(oSettings, oInit.aaData[i]);
                }
            }
            else if (oSettings.bDeferLoading || _fnDataSource(oSettings) == 'dom') {
                /* Grab the data from the page - only do this when deferred loading or no Ajax
                * source since there is no point in reading the DOM data if we are then going
                * to replace it with Ajax data
                */
                _fnAddTr(oSettings, $(oSettings.nTBody).children('tr'));
            }

            /* Copy the data index array */
            oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();

            /* Initialisation complete - table can be drawn */
            oSettings.bInitialised = true;

            /* Check if we need to initialise the table (it might not have been handed off to the
            * language processor)
            */
            if (bInitHandedOff === false) {
                _fnInitialise(oSettings);
            }
        });
        _that = null;
        return this;
    };



    /**
    * Computed structure of the DataTables API, defined by the options passed to
    * `DataTable.Api.register()` when building the API.
    *
    * The structure is built in order to speed creation and extension of the Api
    * objects since the extensions are effectively pre-parsed.
    *
    * The array is an array of objects with the following structure, where this
    * base array represents the Api prototype base:
    *
    *     [
    *       {
    *         name:      'data'                -- string   - Property name
    *         val:       function () {},       -- function - Api method (or undefined if just an object
    *         methodExt: [ ... ],              -- array    - Array of Api object definitions to extend the method result
    *         propExt:   [ ... ]               -- array    - Array of Api object definitions to extend the property
    *       },
    *       {
    *         name:     'row'
    *         val:       {},
    *         methodExt: [ ... ],
    *         propExt:   [
    *           {
    *             name:      'data'
    *             val:       function () {},
    *             methodExt: [ ... ],
    *             propExt:   [ ... ]
    *           },
    *           ...
    *         ]
    *       }
    *     ]
    *
    * @type {Array}
    * @ignore
    */
    var __apiStruct = [];


    /**
    * `Array.prototype` reference.
    *
    * @type object
    * @ignore
    */
    var __arrayProto = Array.prototype;


    /**
    * Abstraction for `context` parameter of the `Api` constructor to allow it to
    * take several different forms for ease of use.
    *
    * Each of the input parameter types will be converted to a DataTables settings
    * object where possible.
    *
    * @param  {string|node|jQuery|object} mixed DataTable identifier. Can be one
    *   of:
    *
    *   * `string` - jQuery selector. Any DataTables' matching the given selector
    *     with be found and used.
    *   * `node` - `TABLE` node which has already been formed into a DataTable.
    *   * `jQuery` - A jQuery object of `TABLE` nodes.
    *   * `object` - DataTables settings object
    *   * `DataTables.Api` - API instance
    * @return {array|null} Matching DataTables settings objects. `null` or
    *   `undefined` is returned if no matching DataTable is found.
    * @ignore
    */
    var _toSettings = function (mixed) {
        var idx, jq;
        var settings = DataTable.settings;
        var tables = $.map(settings, function (el, i) {
            return el.nTable;
        });

        if (!mixed) {
            return [];
        }
        else if (mixed.nTable && mixed.oApi) {
            // DataTables settings object
            return [mixed];
        }
        else if (mixed.nodeName && mixed.nodeName.toLowerCase() === 'table') {
            // Table node
            idx = $.inArray(mixed, tables);
            return idx !== -1 ? [settings[idx]] : null;
        }
        else if (mixed && typeof mixed.settings === 'function') {
            return mixed.settings().toArray();
        }
        else if (typeof mixed === 'string') {
            // jQuery selector
            jq = $(mixed);
        }
        else if (mixed instanceof $) {
            // jQuery object (also DataTables instance)
            jq = mixed;
        }

        if (jq) {
            return jq.map(function (i) {
                idx = $.inArray(this, tables);
                return idx !== -1 ? settings[idx] : null;
            }).toArray();
        }
    };


    /**
    * DataTables API class - used to control and interface with  one or more
    * DataTables enhanced tables.
    *
    * The API class is heavily based on jQuery, presenting a chainable interface
    * that you can use to interact with tables. Each instance of the API class has
    * a "context" - i.e. the tables that it will operate on. This could be a single
    * table, all tables on a page or a sub-set thereof.
    *
    * Additionally the API is designed to allow you to easily work with the data in
    * the tables, retrieving and manipulating it as required. This is done by
    * presenting the API class as an array like interface. The contents of the
    * array depend upon the actions requested by each method (for example
    * `rows().nodes()` will return an array of nodes, while `rows().data()` will
    * return an array of objects or arrays depending upon your table's
    * configuration). The API object has a number of array like methods (`push`,
    * `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`,
    * `unique` etc) to assist your working with the data held in a table.
    *
    * Most methods (those which return an Api instance) are chainable, which means
    * the return from a method call also has all of the methods available that the
    * top level object had. For example, these two calls are equivalent:
    *
    *     // Not chained
    *     api.row.add( {...} );
    *     api.draw();
    *
    *     // Chained
    *     api.row.add( {...} ).draw();
    *
    * @class DataTable.Api
    * @param {array|object|string|jQuery} context DataTable identifier. This is
    *   used to define which DataTables enhanced tables this API will operate on.
    *   Can be one of:
    *
    *   * `string` - jQuery selector. Any DataTables' matching the given selector
    *     with be found and used.
    *   * `node` - `TABLE` node which has already been formed into a DataTable.
    *   * `jQuery` - A jQuery object of `TABLE` nodes.
    *   * `object` - DataTables settings object
    * @param {array} [data] Data to initialise the Api instance with.
    *
    * @example
    *   // Direct initialisation during DataTables construction
    *   var api = $('#example').DataTable();
    *
    * @example
    *   // Initialisation using a DataTables jQuery object
    *   var api = $('#example').dataTable().api();
    *
    * @example
    *   // Initialisation as a constructor
    *   var api = new $.fn.DataTable.Api( 'table.dataTable' );
    */
    DataTable.Api = _Api = function (context, data) {
        if (!this instanceof _Api) {
            throw 'DT API must be constructed as a new object';
            // or should it do the 'new' for the caller?
            // return new _Api.apply( this, arguments );
        }

        var settings = [];
        var ctxSettings = function (o) {
            var a = _toSettings(o);
            if (a) {
                settings.push.apply(settings, a);
            }
        };

        if ($.isArray(context)) {
            for (var i = 0, ien = context.length; i < ien; i++) {
                ctxSettings(context[i]);
            }
        }
        else {
            ctxSettings(context);
        }

        // Remove duplicates
        this.context = _unique(settings);

        // Initial data
        if (data) {
            this.push.apply(this, data.toArray ? data.toArray() : data);
        }

        // selector
        this.selector = {
            rows: null,
            cols: null,
            opts: null
        };

        _Api.extend(this, this, __apiStruct);
    };


    _Api.prototype = /** @lends DataTables.Api */{
    /**
    * Return a new Api instance, comprised of the data held in the current
    * instance, join with the other array(s) and/or value(s).
    *
    * An alias for `Array.prototype.concat`.
    *
    * @type method
    * @param {*} value1 Arrays and/or values to concatenate.
    * @param {*} [...] Additional arrays and/or values to concatenate.
    * @returns {DataTables.Api} New API instance, comprising of the combined
    *   array.
    */
    concat: __arrayProto.concat,


    context: [], // array of table settings objects


    each: function (fn) {
        if (__arrayProto.forEach) {
            // Where possible, use the built-in forEach
            __arrayProto.forEach.call(this, fn, this);
        }
        else {
            // Compatibility for browsers without EMCA-252-5 (JS 1.6)
            for (var i = 0, ien = this.length; i < ien; i++) {
                // In strict mode the execution scope is the passed value
                fn.call(this, this[i], i, this);
            }
        }

        return this;
    },


    eq: function (idx) {
        var ctx = this.context;

        return ctx.length > idx ?
				new _Api(ctx[idx], this[idx]) :
				null;
    },


    filter: function (fn) {
        var a = [];

        if (__arrayProto.filter) {
            a = __arrayProto.filter.call(this, fn, this);
        }
        else {
            // Compatibility for browsers without EMCA-252-5 (JS 1.6)
            for (var i = 0, ien = this.length; i < ien; i++) {
                if (fn.call(this, this[i], i, this)) {
                    a.push(this[i]);
                }
            }
        }

        return new _Api(this.context, a);
    },


    flatten: function () {
        var a = [];
        return new _Api(this.context, a.concat.apply(a, this.toArray()));
    },


    join: __arrayProto.join,


    indexOf: __arrayProto.indexOf || function (obj, start) {
        for (var i = (start || 0), ien = this.length; i < ien; i++) {
            if (this[i] === obj) {
                return i;
            }
        }
        return -1;
    },

    // Internal only at the moment - relax?
    iterator: function (flatten, type, fn) {
        var 
				a = [], ret,
				i, ien, j, jen,
				context = this.context,
				rows, items, item,
				selector = this.selector;

        // Argument shifting
        if (typeof flatten === 'string') {
            fn = type;
            type = flatten;
            flatten = false;
        }

        for (i = 0, ien = context.length; i < ien; i++) {
            if (type === 'table') {
                ret = fn(context[i], i);

                if (ret !== undefined) {
                    a.push(ret);
                }
            }
            else if (type === 'columns' || type === 'rows') {
                // this has same length as context - one entry for each table
                ret = fn(context[i], this[i], i);

                if (ret !== undefined) {
                    a.push(ret);
                }
            }
            else if (type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell') {
                // columns and rows share the same structure.
                // 'this' is an array of column indexes for each context
                items = this[i];

                if (type === 'column-rows') {
                    rows = _selector_row_indexes(context[i], selector.opts);
                }

                for (j = 0, jen = items.length; j < jen; j++) {
                    item = items[j];

                    if (type === 'cell') {
                        ret = fn(context[i], item.row, item.column, i, j);
                    }
                    else {
                        ret = fn(context[i], item, i, j, rows);
                    }

                    if (ret !== undefined) {
                        a.push(ret);
                    }
                }
            }
        }

        if (a.length) {
            var api = new _Api(context, flatten ? a.concat.apply([], a) : a);
            var apiSelector = api.selector;
            apiSelector.rows = selector.rows;
            apiSelector.cols = selector.cols;
            apiSelector.opts = selector.opts;
            return api;
        }
        return this;
    },


    lastIndexOf: __arrayProto.lastIndexOf || function (obj, start) {
        // Bit cheeky...
        return this.indexOf.apply(this.toArray.reverse(), arguments);
    },


    length: 0,


    map: function (fn) {
        var a = [];

        if (__arrayProto.map) {
            a = __arrayProto.map.call(this, fn, this);
        }
        else {
            // Compatibility for browsers without EMCA-252-5 (JS 1.6)
            for (var i = 0, ien = this.length; i < ien; i++) {
                a.push(fn.call(this, this[i], i));
            }
        }

        return new _Api(this.context, a);
    },


    pluck: function (prop) {
        return this.map(function (el) {
            return el[prop];
        });
    },

    pop: __arrayProto.pop,


    push: __arrayProto.push,


    // Does not return an API instance
    reduce: __arrayProto.reduce || function (fn, init) {
        return _fnReduce(this, fn, init, 0, this.length, 1);
    },


    reduceRight: __arrayProto.reduceRight || function (fn, init) {
        return _fnReduce(this, fn, init, this.length - 1, -1, -1);
    },


    reverse: __arrayProto.reverse,


    // Object with rows, columns and opts
    selector: null,


    shift: __arrayProto.shift,


    sort: __arrayProto.sort, // ? name - order?


    splice: __arrayProto.splice,


    toArray: function () {
        return __arrayProto.slice.call(this);
    },


    to$: function () {
        return $(this);
    },


    toJQuery: function () {
        return $(this);
    },


    unique: function () {
        return new _Api(this.context, _unique(this));
    },


    unshift: __arrayProto.unshift
};


_Api.extend = function (scope, obj, ext) {
    // Only extend API instances and static properties of the API
    if (!obj || (!(obj instanceof _Api) && !obj.__dt_wrapper)) {
        return;
    }

    var 
			i, ien,
			j, jen,
			struct, inner,
			methodScoping = function (fn, struc) {
			    return function () {
			        var ret = fn.apply(scope, arguments);

			        // Method extension
			        _Api.extend(ret, ret, struc.methodExt);
			        return ret;
			    };
			};

    for (i = 0, ien = ext.length; i < ien; i++) {
        struct = ext[i];

        // Value
        obj[struct.name] = typeof struct.val === 'function' ?
				methodScoping(struct.val, struct) :
				$.isPlainObject(struct.val) ?
					{} :
					struct.val;

        obj[struct.name].__dt_wrapper = true;

        // Property extension
        _Api.extend(scope, obj[struct.name], struct.propExt);
    }
};


// @todo - Is there need for an augment function?
// _Api.augment = function ( inst, name )
// {
// 	// Find src object in the structure from the name
// 	var parts = name.split('.');

// 	_Api.extend( inst, obj );
// };


//     [
//       {
//         name:      'data'                -- string   - Property name
//         val:       function () {},       -- function - Api method (or undefined if just an object
//         methodExt: [ ... ],              -- array    - Array of Api object definitions to extend the method result
//         propExt:   [ ... ]               -- array    - Array of Api object definitions to extend the property
//       },
//       {
//         name:     'row'
//         val:       {},
//         methodExt: [ ... ],
//         propExt:   [
//           {
//             name:      'data'
//             val:       function () {},
//             methodExt: [ ... ],
//             propExt:   [ ... ]
//           },
//           ...
//         ]
//       }
//     ]

_Api.register = _api_register = function (name, val) {
    if ($.isArray(name)) {
        for (var j = 0, jen = name.length; j < jen; j++) {
            _Api.register(name[j], val);
        }
        return;
    }

    var 
			i, ien,
			heir = name.split('.'),
			struct = __apiStruct,
			key, method;

    var find = function (src, name) {
        for (var i = 0, ien = src.length; i < ien; i++) {
            if (src[i].name === name) {
                return src[i];
            }
        }
        return null;
    };

    for (i = 0, ien = heir.length; i < ien; i++) {
        method = heir[i].indexOf('()') !== -1;
        key = method ?
				heir[i].replace('()', '') :
				heir[i];

        var src = find(struct, key);
        if (!src) {
            src = {
                name: key,
                val: {},
                methodExt: [],
                propExt: []
            };
            struct.push(src);
        }

        if (i === ien - 1) {
            src.val = val;
        }
        else {
            struct = method ?
					src.methodExt :
					src.propExt;
        }
    }

    // Rebuild the API with the new construct
    if (_Api.ready) {
        DataTable.api.build();
    }
};


_Api.registerPlural = _api_registerPlural = function (pluralName, singularName, val) {
    _Api.register(pluralName, val);

    _Api.register(singularName, function () {
        var ret = val.apply(this, arguments);

        if (ret === this) {
            // Returned item is the API instance that was passed in, return it
            return this;
        }
        else if (ret instanceof _Api) {
            // New API instance returned, want the value from the first item
            // in the returned array for the singular result.
            return ret.length ?
					$.isArray(ret[0]) ?
						new _Api(ret.context, ret[0]) : // Array results are 'enhanced'
						ret[0] :
					undefined;
        }

        // Non-API return - just fire it back
        return ret;
    });
};


/**
* Selector for HTML tables. Apply the given selector to the give array of
* DataTables settings objects.
*
* @param {string|integer} [selector] jQuery selector string or integer
* @param  {array} Array of DataTables settings objects to be filtered
* @return {array}
* @ignore
*/
var __table_selector = function (selector, a) {
    // Integer is used to pick out a table by index
    if (typeof selector === 'number') {
        return [a[selector]];
    }

    // Perform a jQuery selector on the table nodes
    var nodes = $.map(a, function (el, i) {
        return el.nTable;
    });

    return $(nodes)
			.filter(selector)
			.map(function (i) {
			    // Need to translate back from the table node to the settings
			    var idx = $.inArray(this, nodes);
			    return a[idx];
			})
			.toArray();
};



/**
* Context selector for the API's context (i.e. the tables the API instance
* refers to.
*
* @name    DataTable.Api#tables
* @param {string|integer} [selector] Selector to pick which tables the iterator
*   should operate on. If not given, all tables in the current context are
*   used. This can be given as a jQuery selector (for example `':gt(0)'`) to
*   select multiple tables or as an integer to select a single table.
* @returns {DataTable.Api} Returns a new API instance if a selector is given.
*/
_api_register('tables()', function (selector) {
    // A new instance is created if there was a selector specified
    return selector ?
			new _Api(__table_selector(selector, this.context)) :
			this;
});


_api_register('table()', function (selector) {
    var tables = this.tables(selector);
    var ctx = tables.context;

    // Truncate to the first matched table
    return ctx.length ?
			new _Api(ctx[0]) :
			tables;
});


_api_registerPlural('tables().nodes()', 'table().node()', function () {
    return this.iterator('table', function (ctx) {
        return ctx.nTable;
    });
});


_api_registerPlural('tables().body()', 'table().body()', function () {
    return this.iterator('table', function (ctx) {
        return ctx.nTBody;
    });
});


_api_registerPlural('tables().header()', 'table().header()', function () {
    return this.iterator('table', function (ctx) {
        return ctx.nTHead;
    });
});


_api_registerPlural('tables().footer()', 'table().footer()', function () {
    return this.iterator('table', function (ctx) {
        return ctx.nTFoot;
    });
});



/**
* Redraw the tables in the current context.
*
* @param {boolean} [reset=true] Reset (default) or hold the current paging
*   position. A full re-sort and re-filter is performed when this method is
*   called, which is why the pagination reset is the default action.
* @returns {DataTables.Api} this
*/
_api_register('draw()', function (resetPaging) {
    //changements test

    return this.iterator('table', function (settings) {
        _fnReDraw(settings, resetPaging === false);
    });

});



/**
* Get the current page index.
*
* @return {integer} Current page index (zero based)
*/
/**
* Set the current page.
*
* Note that if you attempt to show a page which does not exist, DataTables will
* not throw an error, but rather reset the paging.
*
* @param {integer|string} action The paging action to take. This can be one of:
*  * `integer` - The page index to jump to
*  * `string` - An action to take:
*    * `first` - Jump to first page.
*    * `next` - Jump to the next page
*    * `previous` - Jump to previous page
*    * `last` - Jump to the last page.
* @returns {DataTables.Api} this
*/
_api_register('page()', function (action) {
    if (action === undefined) {
        return this.page.info().page; // not an expensive call
    }

    // else, have an action to take on all tables
    return this.iterator('table', function (settings) {
        _fnPageChange(settings, action);
    });
});


/**
* Paging information for the first table in the current context.
*
* If you require paging information for another table, use the `table()` method
* with a suitable selector.
*
* @return {object} Object with the following properties set:
*  * `page` - Current page index (zero based - i.e. the first page is `0`)
*  * `pages` - Total number of pages
*  * `start` - Display index for the first record shown on the current page
*  * `end` - Display index for the last record shown on the current page
*  * `length` - Display length (number of records). Note that generally `start
*    + length = end`, but this is not always true, for example if there are
*    only 2 records to show on the final page, with a length of 10.
*  * `recordsTotal` - Full data set length
*  * `recordsDisplay` - Data set length once the current filtering criterion
*    are applied.
*/
_api_register('page.info()', function (action) {
    if (this.context.length === 0) {
        return undefined;
    }

    var 
			settings = this.context[0],
			start = settings._iDisplayStart,
			len = settings._iDisplayLength,
			visRecords = settings.fnRecordsDisplay(),
			all = len === -1;

    return {
        "page": all ? 0 : Math.floor(start / len),
        "pages": all ? 1 : Math.ceil(visRecords / len),
        "start": start,
        "end": settings.fnDisplayEnd(),
        "length": len,
        "recordsTotal": settings.fnRecordsTotal(),
        "recordsDisplay": visRecords
    };
});


/**
* Get the current page length.
*
* @return {integer} Current page length. Note `-1` indicates that all records
*   are to be shown.
*/
/**
* Set the current page length.
*
* @param {integer} Page length to set. Use `-1` to show all records.
* @returns {DataTables.Api} this
*/
_api_register('page.len()', function (len) {
    // Note that we can't call this function 'length()' because `length`
    // is a Javascript property of functions which defines how many arguments
    // the function expects.
    if (len === undefined) {
        return this.context.length !== 0 ?
				this.context[0]._iDisplayLength :
				undefined;
    }

    // else, set the page length
    return this.iterator('table', function (settings) {
        _fnLengthChange(settings, len);
    });
});



var __reload = function (settings, holdPosition, callback) {
    if (_fnDataSource(settings) == 'ssp') {
        _fnReDraw(settings, holdPosition);
    }
    else {
        // Trigger xhr
        _fnProcessingDisplay(settings, true);

        _fnBuildAjax(settings, [], function (json) {
            _fnClearTable(settings);
            ////console.log("p5");
            var data = _fnAjaxDataSrc(settings, json);
            for (var i = 0, ien = data.length; i < ien; i++) {
                _fnAddData(settings, data[i]);
            }

            _fnReDraw(settings, holdPosition);
            _fnProcessingDisplay(settings, false);
        });
    }

    // Use the draw event to trigger a callback, regardless of if it is an async
    // or sync draw
    if (callback) {
        var api = new _Api(settings);

        api.one('draw', function () {
            callback(api.ajax.json());
        });
    }
};


/**
* Get the JSON response from the last Ajax request that DataTables made to the
* server. Note that this returns the JSON from the first table in the current
* context.
*
* @return {object} JSON received from the server.
*/
_api_register('ajax.json()', function () {
    var ctx = this.context;

    if (ctx.length > 0) {
        return ctx[0].json;
    }

    // else return undefined;
});


/**
* Get the data submitted in the last Ajax request
*/
_api_register('ajax.params()', function () {
    var ctx = this.context;

    if (ctx.length > 0) {
        return ctx[0].oAjaxData;
    }

    // else return undefined;
});


/**
* Reload tables from the Ajax data source. Note that this function will
* automatically re-draw the table when the remote data has been loaded.
*
* @param {boolean} [reset=true] Reset (default) or hold the current paging
*   position. A full re-sort and re-filter is performed when this method is
*   called, which is why the pagination reset is the default action.
* @returns {DataTables.Api} this
*/
_api_register('ajax.reload()', function (callback, resetPaging) {
    return this.iterator('table', function (settings) {
        __reload(settings, resetPaging === false, callback);
    });
});


/**
* Get the current Ajax URL. Note that this returns the URL from the first
* table in the current context.
*
* @return {string} Current Ajax source URL
*/
/**
* Set the Ajax URL. Note that this will set the URL for all tables in the
* current context.
*
* @param {string} url URL to set.
* @returns {DataTables.Api} this
*/
_api_register('ajax.url()', function (url) {
    var ctx = this.context;

    if (url === undefined) {
        // get
        if (ctx.length === 0) {
            return undefined;
        }
        ctx = ctx[0];

        return ctx.ajax ?
				$.isPlainObject(ctx.ajax) ?
					ctx.ajax.url :
					ctx.ajax :
				ctx.sAjaxSource;
    }

    // set
    return this.iterator('table', function (settings) {
        if ($.isPlainObject(settings.ajax)) {
            settings.ajax.url = url;
        }
        else {
            settings.ajax = url;
        }
        // No need to consider sAjaxSource here since DataTables gives priority
        // to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any
        // value of `sAjaxSource` redundant.
    });
});


/**
* Load data from the newly set Ajax URL. Note that this method is only
* available when `ajax.url()` is used to set a URL. Additionally, this method
* has the same effect as calling `ajax.reload()` but is provided for
* convenience when setting a new URL. Like `ajax.reload()` it will
* automatically redraw the table once the remote data has been loaded.
*
* @returns {DataTables.Api} this
*/
_api_register('ajax.url().load()', function (callback, resetPaging) {
    // Same as a reload, but makes sense to present it for easy access after a
    // url change
    return this.iterator('table', function (ctx) {
        __reload(ctx, resetPaging === false, callback);
    });
});




var _selector_run = function (selector, select) {
    var 
			out = [], res,
			a, i, ien, j, jen;

    // Can't just check for isArray here, as an API or jQuery instance might be
    // given with their array like look
    if (!selector || typeof selector === 'string' || selector.length === undefined) {
        selector = [selector];
    }

    for (i = 0, ien = selector.length; i < ien; i++) {
        a = selector[i] && selector[i].split ?
				selector[i].split(',') :
				[selector[i]];

        for (j = 0, jen = a.length; j < jen; j++) {
            res = select(typeof a[j] === 'string' ? $.trim(a[j]) : a[j]);

            if (res && res.length) {
                out.push.apply(out, res);
            }
        }
    }

    return out;
};


var _selector_opts = function (opts) {
    if (!opts) {
        opts = {};
    }

    // Backwards compatibility for 1.9- which used the terminology filter rather
    // than search
    if (opts.filter && !opts.search) {
        opts.search = opts.filter;
    }

    return {
        search: opts.search || 'none',
        order: opts.order || 'current',
        page: opts.page || 'all'
    };
};


var _selector_first = function (inst) {
    // Reduce the API instance to the first item found
    for (var i = 0, ien = inst.length; i < ien; i++) {
        if (inst[i].length > 0) {
            // Assign the first element to the first item in the instance
            // and truncate the instance and context
            inst[0] = inst[i];
            inst.length = 1;
            inst.context = [inst.context[i]];

            return inst;
        }
    }

    // Not found - return an empty instance
    inst.length = 0;
    return inst;
};


var _selector_row_indexes = function (settings, opts) {
    var 
			i, ien, tmp, a = [],
			displayFiltered = settings.aiDisplay,
			displayMaster = settings.aiDisplayMaster;

    var 
			search = opts.search,  // none, applied, removed
			order = opts.order,   // applied, current, index (original - compatibility with 1.9)
			page = opts.page;    // all, current

    if (_fnDataSource(settings) == 'ssp') {
        // In server-side processing mode, most options are irrelevant since
        // rows not shown don't exist and the index order is the applied order
        // Removed is a special case - for consistency just return an empty
        // array
        return search === 'removed' ?
				[] :
				_range(0, displayMaster.length);
    }
    else if (page == 'current') {
        // Current page implies that order=current and fitler=applied, since it is
        // fairly senseless otherwise, regardless of what order and search actually
        // are
        for (i = settings._iDisplayStart, ien = settings.fnDisplayEnd(); i < ien; i++) {
            a.push(displayFiltered[i]);
        }
    }
    else if (order == 'current' || order == 'applied') {
        a = search == 'none' ?
				displayMaster.slice() :                      // no search
				search == 'applied' ?
					displayFiltered.slice() :                // applied search
					$.map(displayMaster, function (el, i) { // removed search
					    return $.inArray(el, displayFiltered) === -1 ? el : null;
					});
    }
    else if (order == 'index' || order == 'original') {
        for (i = 0, ien = settings.aoData.length; i < ien; i++) {
            if (search == 'none') {
                a.push(i);
            }
            else { // applied | removed
                tmp = $.inArray(i, displayFiltered);

                if ((tmp === -1 && search == 'removed') ||
						(tmp === 1 && search == 'applied')) {
                    a.push(i);
                }
            }
        }
    }

    return a;
};


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Rows
*
* {}          - no selector - use all available rows
* {integer}   - row aoData index
* {node}      - TR node
* {string}    - jQuery selector to apply to the TR elements
* {array}     - jQuery array of nodes, or simply an array of TR nodes
*
*/


var __row_selector = function (settings, selector, opts) {
    return _selector_run(selector, function (sel) {
        var selInt = _intVal(sel);

        // Short cut - selector is a number and no options provided (default is
        // all records, so no need to check if the index is in there, since it
        // must be - dev error if the index doesn't exist).
        if (selInt !== null && !opts) {
            return [selInt];
        }

        var rows = _selector_row_indexes(settings, opts);

        if (selInt !== null && $.inArray(selInt, rows) !== -1) {
            // Selector - integer
            return [selInt];
        }
        else if (!sel) {
            // Selector - none
            return rows;
        }

        // Get nodes in the order from the `rows` array (can't use `pluck`) @todo - use pluck_order
        var nodes = [];
        for (var i = 0, ien = rows.length; i < ien; i++) {
            nodes.push(settings.aoData[rows[i]].nTr);
        }

        if (sel.nodeName) {
            // Selector - node
            if ($.inArray(sel, nodes) !== -1) {
                return [sel._DT_RowIndex]; // sel is a TR node that is in the table
                // and DataTables adds a prop for fast lookup
            }
        }

        // Selector - jQuery selector string, array of nodes or jQuery object/
        // As jQuery's .filter() allows jQuery objects to be passed in filter,
        // it also allows arrays, so this will cope with all three options
        return $(nodes)
				.filter(sel)
				.map(function () {
				    return this._DT_RowIndex;
				})
				.toArray();
    });
};


/**
*
*/
_api_register('rows()', function (selector, opts) {
    // argument shifting
    if (selector === undefined) {
        selector = '';
    }
    else if ($.isPlainObject(selector)) {
        opts = selector;
        selector = '';
    }

    opts = _selector_opts(opts);

    var inst = this.iterator('table', function (settings) {
        return __row_selector(settings, selector, opts);
    });

    // Want argument shifting here and in __row_selector?
    inst.selector.rows = selector;
    inst.selector.opts = opts;

    return inst;
});


_api_register('rows().nodes()', function () {
    return this.iterator('row', function (settings, row) {
        return settings.aoData[row].nTr || undefined;
    });
});

_api_register('rows().data()', function () {
    return this.iterator(true, 'rows', function (settings, rows) {
        return _pluck_order(settings.aoData, rows, '_aData');
    });
});

_api_registerPlural('rows().cache()', 'row().cache()', function (type) {
    return this.iterator('row', function (settings, row) {
        var r = settings.aoData[row];
        return type === 'search' ? r._aFilterData : r._aSortData;
    });
});

_api_registerPlural('rows().invalidate()', 'row().invalidate()', function (src) {
    return this.iterator('row', function (settings, row) {
        _fnInvalidateRow(settings, row, src);
    });
});

_api_registerPlural('rows().indexes()', 'row().index()', function () {
    return this.iterator('row', function (settings, row) {
        return row;
    });
});

_api_registerPlural('rows().remove()', 'row().remove()', function () {
    var that = this;

    return this.iterator('row', function (settings, row, thatIdx) {
        var data = settings.aoData;

        data.splice(row, 1);

        // Update the _DT_RowIndex parameter on all rows in the table
        for (var i = 0, ien = data.length; i < ien; i++) {
            if (data[i].nTr !== null) {
                data[i].nTr._DT_RowIndex = i;
            }
        }

        // Remove the target row from the search array
        var displayIndex = $.inArray(row, settings.aiDisplay);

        // Delete from the display arrays
        _fnDeleteIndex(settings.aiDisplayMaster, row);
        _fnDeleteIndex(settings.aiDisplay, row);
        _fnDeleteIndex(that[thatIdx], row, false); // maintain local indexes

        // Check for an 'overflow' they case for displaying the table
        _fnLengthOverflow(settings);
    });
});


_api_register('rows.add()', function (rows) {
    var newRows = this.iterator('table', function (settings) {
        var row, i, ien;
        var out = [];
        ////console.log("p6");
        for (i = 0, ien = rows.length; i < ien; i++) {
            row = rows[i];

            if (row.nodeName && row.nodeName.toUpperCase() === 'TR') {
                out.push(_fnAddTr(settings, row)[0]);
            }
            else {
                out.push(_fnAddData(settings, row));
            }
        }

        return out;
    });

    // Return an Api.rows() extended instance, so rows().nodes() etc can be used
    var modRows = this.rows(-1);
    modRows.pop();
    modRows.push.apply(modRows, newRows.toArray());

    return modRows;
});





/**
*
*/
_api_register('row()', function (selector, opts) {
    return _selector_first(this.rows(selector, opts));
});


_api_register('row().data()', function (data) {
    var ctx = this.context;

    if (data === undefined) {
        // Get
        return ctx.length && this.length ?
				ctx[0].aoData[this[0]]._aData :
				undefined;
    }

    // Set
    ctx[0].aoData[this[0]]._aData = data;

    // Automatically invalidate
    _fnInvalidateRow(ctx[0], this[0], 'data');

    return this;
});


_api_register('row().node()', function () {
    var ctx = this.context;

    return ctx.length && this.length ?
			ctx[0].aoData[this[0]].nTr || null :
			null;
});


_api_register('row.add()', function (row) {
    // Allow a jQuery object to be passed in - only a single row is added from
    // it though - the first element in the set
    if (row instanceof $ && row.length) {
        row = row[0];
    }
    ////console.log("p7");
    var rows = this.iterator('table', function (settings) {
        if (row.nodeName && row.nodeName.toUpperCase() === 'TR') {
            return _fnAddTr(settings, row)[0];
        }
        return _fnAddData(settings, row);
    });

    // Return an Api.rows() extended instance, with the newly added row selected
    return this.row(rows[0]);
});



var __details_add = function (ctx, row, data, klass) {
    // Convert to array of TR elements
    var rows = [];
    var addRow = function (r, k) {
        // If we get a TR element, then just add it directly - up to the dev
        // to add the correct number of columns etc
        if (r.nodeName && r.nodeName.toLowerCase() === 'tr') {
            rows.push(r);
        }
        else {
            // Otherwise create a row with a wrapper
            var created = $('<tr><td/></tr>');
            $('td', created)
					.addClass(k)
					.html(r)
					[0].colSpan = _fnVisbleColumns(ctx);

            rows.push(created[0]);
        }
    };

    if ($.isArray(data) || data instanceof $) {
        for (var i = 0, ien = data.length; i < ien; i++) {
            addRow(data[i], klass);
        }
    }
    else {
        addRow(data, klass);
    }

    if (row._details) {
        row._details.remove();
    }

    row._details = $(rows);

    // If the children were already shown, that state should be retained
    if (row._detailsShow) {
        row._details.insertAfter(row.nTr);
    }
};


var __details_display = function (show) {
    var ctx = this.context;

    if (ctx.length && this.length) {
        var row = ctx[0].aoData[this[0]];

        if (row._details) {
            row._detailsShow = show;
            if (show) {
                row._details.insertAfter(row.nTr);
            }
            else {
                row._details.remove();
            }

            __details_events(ctx[0]);
        }
    }

    return this;
};


var __details_events = function (settings) {
    var api = new _Api(settings);
    var namespace = '.dt.DT_details';
    var drawEvent = 'draw' + namespace;
    var colvisEvent = 'column-visibility' + namespace;

    api.off(drawEvent + ' ' + colvisEvent);

    if (_pluck(settings.aoData, '_details').length > 0) {
        // On each draw, insert the required elements into the document
        api.on(drawEvent, function () {
            api.rows({ page: 'current' }).eq(0).each(function (idx) {
                // Internal data grab
                var row = settings.aoData[idx];

                if (row._detailsShow) {
                    row._details.insertAfter(row.nTr);
                }
            });
        });

        // Column visibility change - update the colspan
        api.on(colvisEvent, function (e, settings, idx, vis) {
            // Update the colspan for the details rows (note, only if it already has
            // a colspan)
            var row, visible = _fnVisbleColumns(settings);

            for (var i = 0, ien = settings.aoData.length; i < ien; i++) {
                row = settings.aoData[i];

                if (row._details) {
                    row._details.children('td[colspan]').attr('colspan', visible);
                }
            }
        });
    }
};

// data can be:
//  tr
//  string
//  jQuery or array of any of the above
_api_register('row().child()', function (data, klass) {
    var ctx = this.context;

    if (data === undefined) {
        // get
        return ctx.length && this.length ?
				ctx[0].aoData[this[0]]._details :
				undefined;
    }
    else if (ctx.length && this.length) {
        // set
        __details_add(ctx[0], ctx[0].aoData[this[0]], data, klass);
    }

    return this;
});

_api_register([
		'row().child.show()',
		'row().child().show()'
	], function () {
	    __details_display.call(this, true);
	    return this;
	});

_api_register([
		'row().child.hide()',
		'row().child().hide()'
	], function () {
	    __details_display.call(this, false);
	    return this;
	});

_api_register('row().child.isShown()', function () {
    var ctx = this.context;

    if (ctx.length && this.length) {
        // _detailsShown as false or undefined will fall through to return false
        return ctx[0].aoData[this[0]]._detailsShow || false;
    }
    return false;
});



/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Columns
*
* {integer}           - column index (>=0 count from left, <0 count from right)
* "{integer}:visIdx"  - visible column index (i.e. translate to column index)  (>=0 count from left, <0 count from right)
* "{integer}:visible" - alias for {integer}:visIdx  (>=0 count from left, <0 count from right)
* "{string}:name"     - column name
* "{string}"          - jQuery selector on column header nodes
*
*/

// can be an array of these items, comma separated list, or an array of comma
// separated lists

var __re_column_selector = /^(.*):(name|visIdx|visible)$/;

var __column_selector = function (settings, selector, opts) {
    var 
			columns = settings.aoColumns,
			names = _pluck(columns, 'sName'),
			nodes = _pluck(columns, 'nTh');

    return _selector_run(selector, function (s) {
        var selInt = _intVal(s);

        if (s === '') {
            // All columns
            return _range(columns.length);
        }
        else if (selInt !== null) {
            // Integer selector
            return [selInt >= 0 ?
					selInt : // Count from left
					columns.length + selInt // Count from right (+ because its a negative value)
				];
        }
        else {
            var match = typeof s === 'string' ?
					s.match(__re_column_selector) :
					'';

            if (match) {
                switch (match[2]) {
                    case 'visIdx':
                    case 'visible':
                        var idx = parseInt(match[1], 10);
                        // Visible index given, convert to column index
                        if (idx < 0) {
                            // Counting from the right
                            var visColumns = $.map(columns, function (col, i) {
                                return col.bVisible ? i : null;
                            });
                            return [visColumns[visColumns.length + idx]];
                        }
                        // Counting from the left
                        return [_fnVisibleToColumnIndex(settings, idx)];

                    case 'name':
                        // match by name. `names` is column index complete and in order
                        return $.map(names, function (name, i) {
                            return name === match[1] ? i : null;
                        });
                }
            }
            else {
                // jQuery selector on the TH elements for the columns
                return $(nodes)
						.filter(s)
						.map(function () {
						    return $.inArray(this, nodes); // `nodes` is column index complete and in order
						})
						.toArray();
            }
        }
    });
};





var __setColumnVis = function (settings, column, vis) {
    var 
			cols = settings.aoColumns,
			col = cols[column],
			data = settings.aoData,
			row, cells, i, ien, tr;

    // Get
    if (vis === undefined) {
        return col.bVisible;
    }

    // Set
    // No change
    if (col.bVisible === vis) {
        return;
    }

    if (vis) {
        // Insert column
        // Need to decide if we should use appendChild or insertBefore
        var insertBefore = $.inArray(true, _pluck(cols, 'bVisible'), column + 1);

        for (i = 0, ien = data.length; i < ien; i++) {
            tr = data[i].nTr;
            cells = data[i].anCells;

            if (tr) {
                // insertBefore can act like appendChild if 2nd arg is null
                tr.insertBefore(cells[column], cells[insertBefore] || null);
            }
        }
    }
    else {
        // Remove column
        $(_pluck(settings.aoData, 'anCells', column)).detach();

        col.bVisible = false;
        _fnDrawHead(settings, settings.aoHeader);
        _fnDrawHead(settings, settings.aoFooter);

        _fnSaveState(settings);
    }

    // Common actions
    col.bVisible = vis;
    _fnDrawHead(settings, settings.aoHeader);
    _fnDrawHead(settings, settings.aoFooter);

    // Automatically adjust column sizing
    _fnAdjustColumnSizing(settings);

    // Realign columns for scrolling
    if (settings.oScroll.sX || settings.oScroll.sY) {
        _fnScrollDraw(settings);
    }

    _fnCallbackFire(settings, null, 'column-visibility', [settings, column, vis]);

    _fnSaveState(settings);
};


/**
*
*/
_api_register('columns()', function (selector, opts) {
    // argument shifting
    if (selector === undefined) {
        selector = '';
    }
    else if ($.isPlainObject(selector)) {
        opts = selector;
        selector = '';
    }

    opts = _selector_opts(opts);

    var inst = this.iterator('table', function (settings) {
        return __column_selector(settings, selector, opts);
    });

    // Want argument shifting here and in _row_selector?
    inst.selector.cols = selector;
    inst.selector.opts = opts;

    return inst;
});


/**
*
*/
_api_registerPlural('columns().header()', 'column().header()', function (selector, opts) {
    return this.iterator('column', function (settings, column) {
        return settings.aoColumns[column].nTh;
    });
});


/**
*
*/
_api_registerPlural('columns().footer()', 'column().footer()', function (selector, opts) {
    return this.iterator('column', function (settings, column) {
        return settings.aoColumns[column].nTf;
    });
});


/**
*
*/
_api_registerPlural('columns().data()', 'column().data()', function () {
    return this.iterator('column-rows', function (settings, column, i, j, rows) {
        var a = [];
        ////console.log("8!");
        for (var row = 0, ien = rows.length; row < ien; row++) {
            a.push(_fnGetCellData(settings, rows[row], column, ''));
        }
        return a;
    });
});


_api_registerPlural('columns().cache()', 'column().cache()', function (type) {
    return this.iterator('column-rows', function (settings, column, i, j, rows) {
        return _pluck_order(settings.aoData, rows,
				type === 'search' ? '_aFilterData' : '_aSortData', column
			);
    });
});


_api_registerPlural('columns().nodes()', 'column().nodes()', function () {
    return this.iterator('column-rows', function (settings, column, i, j, rows) {
        return _pluck_order(settings.aoData, rows, 'anCells', column);
    });
});



_api_registerPlural('columns().visible()', 'column().visible()', function (vis) {
    return this.iterator('column', function (settings, column) {
        return vis === undefined ?
				settings.aoColumns[column].bVisible :
				__setColumnVis(settings, column, vis);
    });
});



_api_registerPlural('columns().indexes()', 'column().index()', function (type) {
    return this.iterator('column', function (settings, column) {
        return type === 'visible' ?
				_fnColumnIndexToVisible(settings, column) :
				column;
    });
});


// _api_register( 'columns().show()', function () {
// 	var selector = this.selector;
// 	return this.columns( selector.cols, selector.opts ).visible( true );
// } );


// _api_register( 'columns().hide()', function () {
// 	var selector = this.selector;
// 	return this.columns( selector.cols, selector.opts ).visible( false );
// } );



_api_register('columns.adjust()', function () {
    return this.iterator('table', function (settings) {
        _fnAdjustColumnSizing(settings);
    });
});


// Convert from one column index type, to another type
_api_register('column.index()', function (type, idx) {
    if (this.context.length !== 0) {
        var ctx = this.context[0];

        if (type === 'fromVisible' || type === 'toData') {
            return _fnVisibleToColumnIndex(ctx, idx);
        }
        else if (type === 'fromData' || type === 'toVisible') {
            return _fnColumnIndexToVisible(ctx, idx);
        }
    }
});


_api_register('column()', function (selector, opts) {
    return _selector_first(this.columns(selector, opts));
});




var __cell_selector = function (settings, selector, opts) {
    var data = settings.aoData;
    var rows = _selector_row_indexes(settings, opts);
    var cells = _pluck_order(data, rows, 'anCells');
    var allCells = $([].concat.apply([], cells));
    var row;
    var columns = settings.aoColumns.length;
    var a, i, ien, j;

    return _selector_run(selector, function (s) {
        if (!s) {
            // All cells
            a = [];

            for (i = 0, ien = rows.length; i < ien; i++) {
                row = rows[i];

                for (j = 0; j < columns; j++) {
                    a.push({
                        row: row,
                        column: j
                    });
                }
            }

            return a;
        }
        else if ($.isPlainObject(s)) {
            return [s];
        }

        // jQuery filtered cells
        return allCells
				.filter(s)
				.map(function (i, el) {
				    row = el.parentNode._DT_RowIndex;

				    return {
				        row: row,
				        column: $.inArray(el, data[row].anCells)
				    };
				})
				.toArray();
    });
};




_api_register('cells()', function (rowSelector, columnSelector, opts) {
    // Argument shifting
    if ($.isPlainObject(rowSelector)) {
        // If passing in a cell index
        if (rowSelector.row) {
            opts = columnSelector;
            columnSelector = null;
        }
        else {
            opts = rowSelector;
            rowSelector = null;
        }
    }
    if ($.isPlainObject(columnSelector)) {
        opts = columnSelector;
        columnSelector = null;
    }

    // Cell selector
    if (columnSelector === null || columnSelector === undefined) {
        return this.iterator('table', function (settings) {
            return __cell_selector(settings, rowSelector, _selector_opts(opts));
        });
    }

    // Row + column selector
    var columns = this.columns(columnSelector, opts);
    var rows = this.rows(rowSelector, opts);
    var a, i, ien, j, jen;

    var cells = this.iterator('table', function (settings, idx) {
        a = [];

        for (i = 0, ien = rows[idx].length; i < ien; i++) {
            for (j = 0, jen = columns[idx].length; j < jen; j++) {
                a.push({
                    row: rows[idx][i],
                    column: columns[idx][j]
                });
            }
        }

        return a;
    });

    $.extend(cells.selector, {
        cols: columnSelector,
        rows: rowSelector,
        opts: opts
    });

    return cells;
});


_api_registerPlural('cells().nodes()', 'cell().node()', function () {
    return this.iterator('cell', function (settings, row, column) {
        return settings.aoData[row].anCells[column];
    });
});


_api_register('cells().data()', function () {
    ////console.log("9!");
    return this.iterator('cell', function (settings, row, column) {
        return _fnGetCellData(settings, row, column);
    });
});


_api_registerPlural('cells().cache()', 'cell().cache()', function (type) {
    type = type === 'search' ? '_aFilterData' : '_aSortData';

    return this.iterator('cell', function (settings, row, column) {
        return settings.aoData[row][type][column];
    });
});


_api_registerPlural('cells().indexes()', 'cell().index()', function () {
    return this.iterator('cell', function (settings, row, column) {
        return {
            row: row,
            column: column,
            columnVisible: _fnColumnIndexToVisible(settings, column)
        };
    });
});


_api_register([
		'cells().invalidate()',
		'cell().invalidate()'
	], function (src) {
	    var selector = this.selector;

	    // Use the rows method of the instance to perform the invalidation, rather
	    // than doing it here. This avoids needing to handle duplicate rows from
	    // the cells.
	    this.rows(selector.rows, selector.opts).invalidate(src);

	    return this;
	});




_api_register('cell()', function (rowSelector, columnSelector, opts) {
    return _selector_first(this.cells(rowSelector, columnSelector, opts));
});



_api_register('cell().data()', function (data) {
    var ctx = this.context;
    var cell = this[0];

    if (data === undefined) {
        // Get
        ////console.log("10!");
        return ctx.length && cell.length ?
				_fnGetCellData(ctx[0], cell[0].row, cell[0].column) :
				undefined;
    }

    // Set
    _fnSetCellData(ctx[0], cell[0].row, cell[0].column, data);
    _fnInvalidateRow(ctx[0], cell[0].row, 'data', cell[0].column);

    return this;
});



/**
* Get current ordering (sorting) that has been applied to the table.
*
* @returns {array} 2D array containing the sorting information for the first
*   table in the current context. Each element in the parent array represents
*   a column being sorted upon (i.e. multi-sorting with two columns would have
*   2 inner arrays). The inner arrays may have 2 or 3 elements. The first is
*   the column index that the sorting condition applies to, the second is the
*   direction of the sort (`desc` or `asc`) and, optionally, the third is the
*   index of the sorting order from the `column.sorting` initialisation array.
*/
/**
* Set the ordering for the table.
*
* @param {integer} order Column index to sort upon.
* @param {string} direction Direction of the sort to be applied (`asc` or `desc`)
* @returns {DataTables.Api} this
*/
/**
* Set the ordering for the table.
*
* @param {array} order 1D array of sorting information to be applied.
* @param {array} [...] Optional additional sorting conditions
* @returns {DataTables.Api} this
*/
/**
* Set the ordering for the table.
*
* @param {array} order 2D array of sorting information to be applied.
* @returns {DataTables.Api} this
*/
_api_register('order()', function (order, dir) {

    var ctx = this.context;

    if (order === undefined) {
        // get
        return ctx.length !== 0 ?
				ctx[0].aaSorting :
				undefined;
    }

    // set
    if (typeof order === 'number') {
        // Simple column / direction passed in
        order = [[order, dir]];
    }
    else if (!$.isArray(order[0])) {
        // Arguments passed in (list of 1D arrays)
        order = Array.prototype.slice.call(arguments);
    }
    // otherwise a 2D array was passed in

    return this.iterator('table', function (settings) {
        settings.aaSorting = order.slice();
    });
});


/**
* Attach a sort listener to an element for a given column
*
* @param {node|jQuery|string} node Identifier for the element(s) to attach the
*   listener to. This can take the form of a single DOM node, a jQuery
*   collection of nodes or a jQuery selector which will identify the node(s).
* @param {integer} column the column that a click on this node will sort on
* @param {function} [callback] callback function when sort is run
* @returns {DataTables.Api} this
*/
_api_register('order.listener()', function (node, column, callback) {
    return this.iterator('table', function (settings) {
        _fnSortAttachListener(settings, node, column, callback);
    });
});


// Order by the selected column(s)
_api_register([
		'columns().order()',
		'column().order()'
	], function (dir) {
	    var that = this;

	    return this.iterator('table', function (settings, i) {
	        var sort = [];

	        $.each(that[i], function (j, col) {
	            sort.push([col, dir]);
	        });

	        settings.aaSorting = sort;
	    });
	});



_api_register('search()', function (input, regex, smart, caseInsen) {
    var ctx = this.context;

    if (input === undefined) {
        // get
        return ctx.length !== 0 ?
				ctx[0].oPreviousSearch.sSearch :
				undefined;
    }

    // set
    return this.iterator('table', function (settings) {
        if (!settings.oFeatures.bFilter) {
            return;
        }

        _fnFilterComplete(settings, $.extend({}, settings.oPreviousSearch, {
            "sSearch": input + "",
            "bRegex": regex === null ? false : regex,
            "bSmart": smart === null ? true : smart,
            "bCaseInsensitive": caseInsen === null ? true : caseInsen
        }), 1);
    });
});


_api_register([
		'columns().search()',
		'column().search()'
	], function (input, regex, smart, caseInsen) {
	    return this.iterator('column', function (settings, column) {
	        var preSearch = settings.aoPreSearchCols;

	        if (input === undefined) {
	            // get
	            return preSearch[column].sSearch;
	        }

	        // set
	        if (!settings.oFeatures.bFilter) {
	            return;
	        }

	        $.extend(preSearch[column], {
	            "sSearch": input + "",
	            "bRegex": regex === null ? false : regex,
	            "bSmart": smart === null ? true : smart,
	            "bCaseInsensitive": caseInsen === null ? true : caseInsen
	        });

	        _fnFilterComplete(settings, settings.oPreviousSearch, 1);
	    });
	});



/**
* Provide a common method for plug-ins to check the version of DataTables being
* used, in order to ensure compatibility.
*
*  @param {string} version Version string to check for, in the format "X.Y.Z".
*    Note that the formats "X" and "X.Y" are also acceptable.
*  @returns {boolean} true if this version of DataTables is greater or equal to
*    the required version, or false if this version of DataTales is not
*    suitable
*  @static
*  @dtopt API-Static
*
*  @example
*    alert( $.fn.dataTable.versionCheck( '1.9.0' ) );
*/
DataTable.versionCheck = DataTable.fnVersionCheck = function (version) {
    var aThis = DataTable.version.split('.');
    var aThat = version.split('.');
    var iThis, iThat;

    for (var i = 0, iLen = aThat.length; i < iLen; i++) {
        iThis = parseInt(aThis[i], 10) || 0;
        iThat = parseInt(aThat[i], 10) || 0;

        // Parts are the same, keep comparing
        if (iThis === iThat) {
            continue;
        }

        // Parts are different, return immediately
        return iThis > iThat;
    }

    return true;
};


/**
* Check if a `<table>` node is a DataTable table already or not.
*
*  @param {node|jquery|string} table Table node, jQuery object or jQuery
*      selector for the table to test. Note that if more than more than one
*      table is passed on, only the first will be checked
*  @returns {boolean} true the table given is a DataTable, or false otherwise
*  @static
*  @dtopt API-Static
*
*  @example
*    if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
*      $('#example').dataTable();
*    }
*/
DataTable.isDataTable = DataTable.fnIsDataTable = function (table) {
    var t = $(table).get(0);
    var is = false;

    $.each(DataTable.settings, function (i, o) {
        if (o.nTable === t || o.nScrollHead === t || o.nScrollFoot === t) {
            is = true;
        }
    });

    return is;
};


/**
* Get all DataTable tables that have been initialised - optionally you can
* select to get only currently visible tables.
*
*  @param {boolean} [visible=false] Flag to indicate if you want all (default)
*    or visible tables only.
*  @returns {array} Array of `table` nodes (not DataTable instances) which are
*    DataTables
*  @static
*  @dtopt API-Static
*
*  @example
*    $.each( $.fn.dataTable.tables(true), function () {
*      $(table).DataTable().columns.adjust();
*    } );
*/
DataTable.tables = DataTable.fnTables = function (visible) {
    return jQuery.map(DataTable.settings, function (o) {
        if (!visible || (visible && $(o.nTable).is(':visible'))) {
            return o.nTable;
        }
    });
};


/**
* Convert from camel case parameters to Hungarian notation. This is made public
* for the extensions to provide the same ability as DataTables core to accept
* either the 1.9 style Hungarian notation, or the 1.10+ style camelCase
* parameters.
*
*  @param {object} src The model object which holds all parameters that can be
*    mapped.
*  @param {object} user The object to convert from camel case to Hungarian.
*  @param {boolean} force When set to `true`, properties which already have a
*    Hungarian value in the `user` object will be overwritten. Otherwise they
*    won't be.
*/
DataTable.camelToHungarian = _fnCamelToHungarian;



/**
*
*/
_api_register('$()', function (selector, opts) {
    var 
			rows = this.rows(opts).nodes(), // Get all rows
			jqRows = $(rows);

    return $([].concat(
			jqRows.filter(selector).toArray(),
			jqRows.find(selector).toArray()
		));
});


// jQuery functions to operate on the tables
$.each(['on', 'one', 'off'], function (i, key) {
    _api_register(key + '()', function ( /* event, handler */) {
        var args = Array.prototype.slice.call(arguments);

        // Add the `dt` namespace automatically if it isn't already present
        if (args[0].indexOf('.dt') === -1) {
            args[0] += '.dt';
        }

        var inst = $(this.tables().nodes());
        inst[key].apply(inst, args);
        return this;
    });
});


_api_register('clear()', function () {
    return this.iterator('table', function (settings) {
        _fnClearTable(settings);
    });
});


_api_register('settings()', function () {
    return new _Api(this.context, this.context);
});


_api_register('data()', function () {
    return this.iterator('table', function (settings) {
        return _pluck(settings.aoData, '_aData');
    }).flatten();
});


_api_register('destroy()', function (remove) {
    remove = remove || false;

    return this.iterator('table', function (settings) {
        var orig = settings.nTableWrapper.parentNode;
        var classes = settings.oClasses;
        var table = settings.nTable;
        var tbody = settings.nTBody;
        var thead = settings.nTHead;
        var tfoot = settings.nTFoot;
        var jqTable = $(table);
        var jqTbody = $(tbody);
        var jqWrapper = $(settings.nTableWrapper);
        var rows = $.map(settings.aoData, function (r) { return r.nTr; });
        var i, ien;

        // Flag to note that the table is currently being destroyed - no action
        // should be taken
        settings.bDestroying = true;

        // Fire off the destroy callbacks for plug-ins etc
        _fnCallbackFire(settings, "aoDestroyCallback", "destroy", [settings]);

        // If not being removed from the document, make all columns visible
        if (!remove) {
            new _Api(settings).columns().visible(true);
        }

        // Blitz all `DT` namespaced events (these are internal events, the
        // lowercase, `dt` events are user subscribed and they are responsible
        // for removing them
        jqWrapper.unbind('.DT').find(':not(tbody *)').unbind('.DT');
        $(window).unbind('.DT-' + settings.sInstance);

        // When scrolling we had to break the table up - restore it
        if (table != thead.parentNode) {
            jqTable.children('thead').detach();
            jqTable.append(thead);
        }

        if (tfoot && table != tfoot.parentNode) {
            jqTable.children('tfoot').detach();
            jqTable.append(tfoot);
        }

        // Remove the DataTables generated nodes, events and classes
        jqTable.detach();
        jqWrapper.detach();

        settings.aaSorting = [];
        settings.aaSortingFixed = [];
        _fnSortingClasses(settings);

        $(rows).removeClass(settings.asStripeClasses.join(' '));

        $('th, td', thead).removeClass(classes.sSortable + ' ' +
				classes.sSortableAsc + ' ' + classes.sSortableDesc + ' ' + classes.sSortableNone
			);

        if (settings.bJUI) {
            $('th span.' + classes.sSortIcon + ', td span.' + classes.sSortIcon, thead).detach();
            $('th, td', thead).each(function () {
                var wrapper = $('div.' + classes.sSortJUIWrapper, this);
                $(this).append(wrapper.contents());
                wrapper.detach();
            });
        }

        if (!remove && orig) {
            // insertBefore acts like appendChild if !arg[1]
            orig.insertBefore(table, settings.nTableReinsertBefore);
        }

        // Add the TR elements back into the table in their original order
        jqTbody.children().detach();
        jqTbody.append(rows);

        // Restore the width of the original table - was read from the style property,
        // so we can restore directly to that
        jqTable
				.css('width', settings.sDestroyWidth)
				.removeClass(classes.sTable);

        // If the were originally stripe classes - then we add them back here.
        // Note this is not fool proof (for example if not all rows had stripe
        // classes - but it's a good effort without getting carried away
        ien = settings.asDestroyStripes.length;

        if (ien) {
            jqTbody.children().each(function (i) {
                $(this).addClass(settings.asDestroyStripes[i % ien]);
            });
        }

        /* Remove the settings object from the settings array */
        var idx = $.inArray(settings, DataTable.settings);
        if (idx !== -1) {
            DataTable.settings.splice(idx, 1);
        }
    });
});


/**
* Version string for plug-ins to check compatibility. Allowed format is
* `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used
* only for non-release builds. See http://semver.org/ for more information.
*  @member
*  @type string
*  @default Version number
*/
DataTable.version = "1.10.0";

/**
* Private data store, containing all of the settings objects that are
* created for the tables on a given page.
*
* Note that the `DataTable.settings` object is aliased to
* `jQuery.fn.dataTableExt` through which it may be accessed and
* manipulated, or `jQuery.fn.dataTable.settings`.
*  @member
*  @type array
*  @default []
*  @private
*/
DataTable.settings = [];

/**
* Object models container, for the various models that DataTables has
* available to it. These models define the objects that are used to hold
* the active state and configuration of the table.
*  @namespace
*/
DataTable.models = {};



/**
* Template object for the way in which DataTables holds information about
* search information for the global filter and individual column filters.
*  @namespace
*/
DataTable.models.oSearch = {
    /**
    * Flag to indicate if the filtering should be case insensitive or not
    *  @type boolean
    *  @default true
    */
    "bCaseInsensitive": true,

    /**
    * Applied search term
    *  @type string
    *  @default <i>Empty string</i>
    */
    "sSearch": "",

    /**
    * Flag to indicate if the search term should be interpreted as a
    * regular expression (true) or not (false) and therefore and special
    * regex characters escaped.
    *  @type boolean
    *  @default false
    */
    "bRegex": false,

    /**
    * Flag to indicate if DataTables is to use its smart filtering or not.
    *  @type boolean
    *  @default true
    */
    "bSmart": true
};




/**
* Template object for the way in which DataTables holds information about
* each individual row. This is the object format used for the settings
* aoData array.
*  @namespace
*/
DataTable.models.oRow = {
    /**
    * TR element for the row
    *  @type node
    *  @default null
    */
    "nTr": null,

    /**
    * Array of TD elements for each row. This is null until the row has been
    * created.
    *  @type array nodes
    *  @default []
    */
    "anCells": null,

    /**
    * Data object from the original data source for the row. This is either
    * an array if using the traditional form of DataTables, or an object if
    * using mData options. The exact type will depend on the passed in
    * data from the data source, or will be an array if using DOM a data
    * source.
    *  @type array|object
    *  @default []
    */
    "_aData": [],

    /**
    * Sorting data cache - this array is ostensibly the same length as the
    * number of columns (although each index is generated only as it is
    * needed), and holds the data that is used for sorting each column in the
    * row. We do this cache generation at the start of the sort in order that
    * the formatting of the sort data need be done only once for each cell
    * per sort. This array should not be read from or written to by anything
    * other than the master sorting methods.
    *  @type array
    *  @default null
    *  @private
    */
    "_aSortData": null,

    /**
    * Per cell filtering data cache. As per the sort data cache, used to
    * increase the performance of the filtering in DataTables
    *  @type array
    *  @default null
    *  @private
    */
    "_aFilterData": null,

    /**
    * Filtering data cache. This is the same as the cell filtering cache, but
    * in this case a string rather than an array. This is easily computed with
    * a join on `_aFilterData`, but is provided as a cache so the join isn't
    * needed on every search (memory traded for performance)
    *  @type array
    *  @default null
    *  @private
    */
    "_sFilterRow": null,

    /**
    * Cache of the class name that DataTables has applied to the row, so we
    * can quickly look at this variable rather than needing to do a DOM check
    * on className for the nTr property.
    *  @type string
    *  @default <i>Empty string</i>
    *  @private
    */
    "_sRowStripe": "",

    /**
    * Denote if the original data source was from the DOM, or the data source
    * object. This is used for invalidating data, so DataTables can
    * automatically read data from the original source, unless uninstructed
    * otherwise.
    *  @type string
    *  @default null
    *  @private
    */
    "src": null
};


/**
* Template object for the column information object in DataTables. This object
* is held in the settings aoColumns array and contains all the information that
* DataTables needs about each individual column.
*
* Note that this object is related to {@link DataTable.defaults.column}
* but this one is the internal data store for DataTables's cache of columns.
* It should NOT be manipulated outside of DataTables. Any configuration should
* be done through the initialisation options.
*  @namespace
*/
DataTable.models.oColumn = {
    /**
    * Column index. This could be worked out on-the-fly with $.inArray, but it
    * is faster to just hold it as a variable
    *  @type integer
    *  @default null
    */
    "idx": null,

    /**
    * A list of the columns that sorting should occur on when this column
    * is sorted. That this property is an array allows multi-column sorting
    * to be defined for a column (for example first name / last name columns
    * would benefit from this). The values are integers pointing to the
    * columns to be sorted on (typically it will be a single integer pointing
    * at itself, but that doesn't need to be the case).
    *  @type array
    */
    "aDataSort": null,

    /**
    * Define the sorting directions that are applied to the column, in sequence
    * as the column is repeatedly sorted upon - i.e. the first value is used
    * as the sorting direction when the column if first sorted (clicked on).
    * Sort it again (click again) and it will move on to the next index.
    * Repeat until loop.
    *  @type array
    */
    "asSorting": null,

    /**
    * Flag to indicate if the column is searchable, and thus should be included
    * in the filtering or not.
    *  @type boolean
    */
    "bSearchable": null,

    /**
    * Flag to indicate if the column is sortable or not.
    *  @type boolean
    */
    "bSortable": null,

    /**
    * Flag to indicate if the column is currently visible in the table or not
    *  @type boolean
    */
    "bVisible": null,

    /**
    * Store for manual type assignment using the `column.type` option. This
    * is held in store so we can manipulate the column's `sType` property.
    *  @type string
    *  @default null
    *  @private
    */
    "_sManualType": null,

    /**
    * Flag to indicate if HTML5 data attributes should be used as the data
    * source for filtering or sorting. True is either are.
    *  @type boolean
    *  @default false
    *  @private
    */
    "_bAttrSrc": false,

    /**
    * Developer definable function that is called whenever a cell is created (Ajax source,
    * etc) or processed for input (DOM source). This can be used as a compliment to mRender
    * allowing you to modify the DOM element (add background colour for example) when the
    * element is available.
    *  @type function
    *  @param {element} nTd The TD node that has been created
    *  @param {*} sData The Data for the cell
    *  @param {array|object} oData The data for the whole row
    *  @param {int} iRow The row index for the aoData data store
    *  @default null
    */
    "fnCreatedCell": null,

    /**
    * Function to get data from a cell in a column. You should <b>never</b>
    * access data directly through _aData internally in DataTables - always use
    * the method attached to this property. It allows mData to function as
    * required. This function is automatically assigned by the column
    * initialisation method
    *  @type function
    *  @param {array|object} oData The data array/object for the array
    *    (i.e. aoData[]._aData)
    *  @param {string} sSpecific The specific data type you want to get -
    *    'display', 'type' 'filter' 'sort'
    *  @returns {*} The data for the cell from the given row's data
    *  @default null
    */
    "fnGetData": null,

    /**
    * Function to set data for a cell in the column. You should <b>never</b>
    * set the data directly to _aData internally in DataTables - always use
    * this method. It allows mData to function as required. This function
    * is automatically assigned by the column initialisation method
    *  @type function
    *  @param {array|object} oData The data array/object for the array
    *    (i.e. aoData[]._aData)
    *  @param {*} sValue Value to set
    *  @default null
    */
    "fnSetData": null,

    /**
    * Property to read the value for the cells in the column from the data
    * source array / object. If null, then the default content is used, if a
    * function is given then the return from the function is used.
    *  @type function|int|string|null
    *  @default null
    */
    "mData": null,

    /**
    * Partner property to mData which is used (only when defined) to get
    * the data - i.e. it is basically the same as mData, but without the
    * 'set' option, and also the data fed to it is the result from mData.
    * This is the rendering method to match the data method of mData.
    *  @type function|int|string|null
    *  @default null
    */
    "mRender": null,

    /**
    * Unique header TH/TD element for this column - this is what the sorting
    * listener is attached to (if sorting is enabled.)
    *  @type node
    *  @default null
    */
    "nTh": null,

    /**
    * Unique footer TH/TD element for this column (if there is one). Not used
    * in DataTables as such, but can be used for plug-ins to reference the
    * footer for each column.
    *  @type node
    *  @default null
    */
    "nTf": null,

    /**
    * The class to apply to all TD elements in the table's TBODY for the column
    *  @type string
    *  @default null
    */
    "sClass": null,

    /**
    * When DataTables calculates the column widths to assign to each column,
    * it finds the longest string in each column and then constructs a
    * temporary table and reads the widths from that. The problem with this
    * is that "mmm" is much wider then "iiii", but the latter is a longer
    * string - thus the calculation can go wrong (doing it properly and putting
    * it into an DOM object and measuring that is horribly(!) slow). Thus as
    * a "work around" we provide this option. It will append its value to the
    * text that is found to be the longest string for the column - i.e. padding.
    *  @type string
    */
    "sContentPadding": null,

    /**
    * Allows a default value to be given for a column's data, and will be used
    * whenever a null data source is encountered (this can be because mData
    * is set to null, or because the data source itself is null).
    *  @type string
    *  @default null
    */
    "sDefaultContent": null,

    /**
    * Name for the column, allowing reference to the column by name as well as
    * by index (needs a lookup to work by name).
    *  @type string
    */
    "sName": null,

    /**
    * Custom sorting data type - defines which of the available plug-ins in
    * afnSortData the custom sorting will use - if any is defined.
    *  @type string
    *  @default std
    */
    "sSortDataType": 'std',

    /**
    * Class to be applied to the header element when sorting on this column
    *  @type string
    *  @default null
    */
    "sSortingClass": null,

    /**
    * Class to be applied to the header element when sorting on this column -
    * when jQuery UI theming is used.
    *  @type string
    *  @default null
    */
    "sSortingClassJUI": null,

    /**
    * Title of the column - what is seen in the TH element (nTh).
    *  @type string
    */
    "sTitle": null,

    /**
    * Column sorting and filtering type
    *  @type string
    *  @default null
    */
    "sType": null,

    /**
    * Width of the column
    *  @type string
    *  @default null
    */
    "sWidth": null,

    /**
    * Width of the column when it was first "encountered"
    *  @type string
    *  @default null
    */
    "sWidthOrig": null
};


/*
* Developer note: The properties of the object below are given in Hungarian
* notation, that was used as the interface for DataTables prior to v1.10, however
* from v1.10 onwards the primary interface is camel case. In order to avoid
* breaking backwards compatibility utterly with this change, the Hungarian
* version is still, internally the primary interface, but is is not documented
* - hence the @name tags in each doc comment. This allows a Javascript function
* to create a map from Hungarian notation to camel case (going the other direction
* would require each property to be listed, which would at around 3K to the size
* of DataTables, while this method is about a 0.5K hit.
*
* Ultimately this does pave the way for Hungarian notation to be dropped
* completely, but that is a massive amount of work and will break current
* installs (therefore is on-hold until v2).
*/

/**
* Initialisation options that can be given to DataTables at initialisation
* time.
*  @namespace
*/
DataTable.defaults = {
    /**
    * An array of data to use for the table, passed in at initialisation which
    * will be used in preference to any data which is already in the DOM. This is
    * particularly useful for constructing tables purely in Javascript, for
    * example with a custom Ajax call.
    *  @type array
    *  @default null
    *
    *  @dtopt Option
    *  @name DataTable.defaults.data
    *
    *  @example
    *    // Using a 2D array data source
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "data": [
    *          ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'],
    *          ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'],
    *        ],
    *        "columns": [
    *          { "title": "Engine" },
    *          { "title": "Browser" },
    *          { "title": "Platform" },
    *          { "title": "Version" },
    *          { "title": "Grade" }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using an array of objects as a data source (`data`)
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "data": [
    *          {
    *            "engine":   "Trident",
    *            "browser":  "Internet Explorer 4.0",
    *            "platform": "Win 95+",
    *            "version":  4,
    *            "grade":    "X"
    *          },
    *          {
    *            "engine":   "Trident",
    *            "browser":  "Internet Explorer 5.0",
    *            "platform": "Win 95+",
    *            "version":  5,
    *            "grade":    "C"
    *          }
    *        ],
    *        "columns": [
    *          { "title": "Engine",   "data": "engine" },
    *          { "title": "Browser",  "data": "browser" },
    *          { "title": "Platform", "data": "platform" },
    *          { "title": "Version",  "data": "version" },
    *          { "title": "Grade",    "data": "grade" }
    *        ]
    *      } );
    *    } );
    */
    "aaData": null,


    /**
    * If ordering is enabled, then DataTables will perform a first pass sort on
    * initialisation. You can define which column(s) the sort is performed
    * upon, and the sorting direction, with this variable. The `sorting` array
    * should contain an array for each column to be sorted initially containing
    * the column's index and a direction string ('asc' or 'desc').
    *  @type array
    *  @default [[0,'asc']]
    *
    *  @dtopt Option
    *  @name DataTable.defaults.order
    *
    *  @example
    *    // Sort by 3rd column first, and then 4th column
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "order": [[2,'asc'], [3,'desc']]
    *      } );
    *    } );
    *
    *    // No initial sorting
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "order": []
    *      } );
    *    } );
    */
    "aaSorting": [[0, 'asc']],


    /**
    * This parameter is basically identical to the `sorting` parameter, but
    * cannot be overridden by user interaction with the table. What this means
    * is that you could have a column (visible or hidden) which the sorting
    * will always be forced on first - any sorting after that (from the user)
    * will then be performed as required. This can be useful for grouping rows
    * together.
    *  @type array
    *  @default null
    *
    *  @dtopt Option
    *  @name DataTable.defaults.orderFixed
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "orderFixed": [[0,'asc']]
    *      } );
    *    } )
    */
    "aaSortingFixed": [],


    /**
    * DataTables can be instructed to load data to display in the table from a
    * Ajax source. This option defines how that Ajax call is made and where to.
    *
    * The `ajax` property has three different modes of operation, depending on
    * how it is defined. These are:
    *
    * * `string` - Set the URL from where the data should be loaded from.
    * * `object` - Define properties for `jQuery.ajax`.
    * * `function` - Custom data get function
    *
    * `string`
    * --------
    *
    * As a string, the `ajax` property simply defines the URL from which
    * DataTables will load data.
    *
    * `object`
    * --------
    *
    * As an object, the parameters in the object are passed to
    * [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control
    * of the Ajax request. DataTables has a number of default parameters which
    * you can override using this option. Please refer to the jQuery
    * documentation for a full description of the options available, although
    * the following parameters provide additional options in DataTables or
    * require special consideration:
    *
    * * `data` - As with jQuery, `data` can be provided as an object, but it
    *   can also be used as a function to manipulate the data DataTables sends
    *   to the server. The function takes a single parameter, an object of
    *   parameters with the values that DataTables has readied for sending. An
    *   object may be returned which will be merged into the DataTables
    *   defaults, or you can add the items to the object that was passed in and
    *   not return anything from the function. This supersedes `fnServerParams`
    *   from DataTables 1.9-.
    *
    * * `dataSrc` - By default DataTables will look for the property `data` (or
    *   `aaData` for compatibility with DataTables 1.9-) when obtaining data
    *   from an Ajax source or for server-side processing - this parameter
    *   allows that property to be changed. You can use Javascript dotted
    *   object notation to get a data source for multiple levels of nesting, or
    *   it my be used as a function. As a function it takes a single parameter,
    *   the JSON returned from the server, which can be manipulated as
    *   required, with the returned value being that used by DataTables as the
    *   data source for the table. This supersedes `sAjaxDataProp` from
    *   DataTables 1.9-.
    *
    * * `success` - Should not be overridden it is used internally in
    *   DataTables. To manipulate / transform the data returned by the server
    *   use `ajax.dataSrc`, or use `ajax` as a function (see below).
    *
    * `function`
    * ----------
    *
    * As a function, making the Ajax call is left up to yourself allowing
    * complete control of the Ajax request. Indeed, if desired, a method other
    * than Ajax could be used to obtain the required data, such as Web storage
    * or an AIR database.
    *
    * The function is given four parameters and no return is required. The
    * parameters are:
    *
    * 1. _object_ - Data to send to the server
    * 2. _function_ - Callback function that must be executed when the required
    *    data has been obtained. That data should be passed into the callback
    *    as the only parameter
    * 3. _object_ - DataTables settings object for the table
    *
    * Note that this supersedes `fnServerData` from DataTables 1.9-.
    *
    *  @type string|object|function
    *  @default null
    *
    *  @dtopt Option
    *  @name DataTable.defaults.ajax
    *  @since 1.10.0
    *
    * @example
    *   // Get JSON data from a file via Ajax.
    *   // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default).
    *   $('#example').dataTable( {
    *     "ajax": "data.json"
    *   } );
    *
    * @example
    *   // Get JSON data from a file via Ajax, using `dataSrc` to change
    *   // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`)
    *   $('#example').dataTable( {
    *     "ajax": {
    *       "url": "data.json",
    *       "dataSrc": "tableData"
    *     }
    *   } );
    *
    * @example
    *   // Get JSON data from a file via Ajax, using `dataSrc` to read data
    *   // from a plain array rather than an array in an object
    *   $('#example').dataTable( {
    *     "ajax": {
    *       "url": "data.json",
    *       "dataSrc": ""
    *     }
    *   } );
    *
    * @example
    *   // Manipulate the data returned from the server - add a link to data
    *   // (note this can, should, be done using `render` for the column - this
    *   // is just a simple example of how the data can be manipulated).
    *   $('#example').dataTable( {
    *     "ajax": {
    *       "url": "data.json",
    *       "dataSrc": function ( json ) {
    *         for ( var i=0, ien=json.length ; i<ien ; i++ ) {
    *           json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>';
    *         }
    *         return json;
    *       }
    *     }
    *   } );
    *
    * @example
    *   // Add data to the request
    *   $('#example').dataTable( {
    *     "ajax": {
    *       "url": "data.json",
    *       "data": function ( d ) {
    *         return {
    *           "extra_search": $('#extra').val()
    *         };
    *       }
    *     }
    *   } );
    *
    * @example
    *   // Send request as POST
    *   $('#example').dataTable( {
    *     "ajax": {
    *       "url": "data.json",
    *       "type": "POST"
    *     }
    *   } );
    *
    * @example
    *   // Get the data from localStorage (could interface with a form for
    *   // adding, editing and removing rows).
    *   $('#example').dataTable( {
    *     "ajax": function (data, callback, settings) {
    *       callback(
    *         JSON.parse( localStorage.getItem('dataTablesData') )
    *       );
    *     }
    *   } );
    */
    "ajax": null,


    /**
    * This parameter allows you to readily specify the entries in the length drop
    * down menu that DataTables shows when pagination is enabled. It can be
    * either a 1D array of options which will be used for both the displayed
    * option and the value, or a 2D array which will use the array in the first
    * position as the value, and the array in the second position as the
    * displayed options (useful for language strings such as 'All').
    *
    * Note that the `pageLength` property will be automatically set to the
    * first value given in this array, unless `pageLength` is also provided.
    *  @type array
    *  @default [ 10, 25, 50, 100 ]
    *
    *  @dtopt Option
    *  @name DataTable.defaults.lengthMenu
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
    *      } );
    *    } );
    */
    "aLengthMenu": [10, 25, 50, 100],


    /**
    * The `columns` option in the initialisation parameter allows you to define
    * details about the way individual columns behave. For a full list of
    * column options that can be set, please see
    * {@link DataTable.defaults.column}. Note that if you use `columns` to
    * define your columns, you must have an entry in the array for every single
    * column that you have in your table (these can be null if you don't which
    * to specify any options).
    *  @member
    *
    *  @name DataTable.defaults.column
    */
    "aoColumns": null,

    /**
    * Very similar to `columns`, `columnDefs` allows you to target a specific
    * column, multiple columns, or all columns, using the `targets` property of
    * each object in the array. This allows great flexibility when creating
    * tables, as the `columnDefs` arrays can be of any length, targeting the
    * columns you specifically want. `columnDefs` may use any of the column
    * options available: {@link DataTable.defaults.column}, but it _must_
    * have `targets` defined in each object in the array. Values in the `targets`
    * array may be:
    *   <ul>
    *     <li>a string - class name will be matched on the TH for the column</li>
    *     <li>0 or a positive integer - column index counting from the left</li>
    *     <li>a negative integer - column index counting from the right</li>
    *     <li>the string "_all" - all columns (i.e. assign a default)</li>
    *   </ul>
    *  @member
    *
    *  @name DataTable.defaults.columnDefs
    */
    "aoColumnDefs": null,


    /**
    * Basically the same as `search`, this parameter defines the individual column
    * filtering state at initialisation time. The array must be of the same size
    * as the number of columns, and each element be an object with the parameters
    * `search` and `escapeRegex` (the latter is optional). 'null' is also
    * accepted and the default will be used.
    *  @type array
    *  @default []
    *
    *  @dtopt Option
    *  @name DataTable.defaults.searchCols
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "searchCols": [
    *          null,
    *          { "search": "My filter" },
    *          null,
    *          { "search": "^[0-9]", "escapeRegex": false }
    *        ]
    *      } );
    *    } )
    */
    "aoSearchCols": [],


    /**
    * An array of CSS classes that should be applied to displayed rows. This
    * array may be of any length, and DataTables will apply each class
    * sequentially, looping when required.
    *  @type array
    *  @default null <i>Will take the values determined by the `oClasses.stripe*`
    *    options</i>
    *
    *  @dtopt Option
    *  @name DataTable.defaults.stripeClasses
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "stripeClasses": [ 'strip1', 'strip2', 'strip3' ]
    *      } );
    *    } )
    */
    "asStripeClasses": null,


    /**
    * Enable or disable automatic column width calculation. This can be disabled
    * as an optimisation (it takes some time to calculate the widths) if the
    * tables widths are passed in using `columns`.
    *  @type boolean
    *  @default true
    *
    *  @dtopt Features
    *  @name DataTable.defaults.autoWidth
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "autoWidth": false
    *      } );
    *    } );
    */
    "bAutoWidth": true,


    /**
    * Deferred rendering can provide DataTables with a huge speed boost when you
    * are using an Ajax or JS data source for the table. This option, when set to
    * true, will cause DataTables to defer the creation of the table elements for
    * each row until they are needed for a draw - saving a significant amount of
    * time.
    *  @type boolean
    *  @default false
    *
    *  @dtopt Features
    *  @name DataTable.defaults.deferRender
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "ajax": "sources/arrays.txt",
    *        "deferRender": true
    *      } );
    *    } );
    */
    "bDeferRender": false,


    /**
    * Replace a DataTable which matches the given selector and replace it with
    * one which has the properties of the new initialisation object passed. If no
    * table matches the selector, then the new DataTable will be constructed as
    * per normal.
    *  @type boolean
    *  @default false
    *
    *  @dtopt Options
    *  @name DataTable.defaults.destroy
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "srollY": "200px",
    *        "paginate": false
    *      } );
    *
    *      // Some time later....
    *      $('#example').dataTable( {
    *        "filter": false,
    *        "destroy": true
    *      } );
    *    } );
    */
    "bDestroy": false,


    /**
    * Enable or disable filtering of data. Filtering in DataTables is "smart" in
    * that it allows the end user to input multiple words (space separated) and
    * will match a row containing those words, even if not in the order that was
    * specified (this allow matching across multiple columns). Note that if you
    * wish to use filtering in DataTables this must remain 'true' - to remove the
    * default filtering input box and retain filtering abilities, please use
    * {@link DataTable.defaults.dom}.
    *  @type boolean
    *  @default true
    *
    *  @dtopt Features
    *  @name DataTable.defaults.searching
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "searching": false
    *      } );
    *    } );
    */
    "bFilter": true,


    /**
    * Enable or disable the table information display. This shows information
    * about the data that is currently visible on the page, including information
    * about filtered data if that action is being performed.
    *  @type boolean
    *  @default true
    *
    *  @dtopt Features
    *  @name DataTable.defaults.info
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "info": false
    *      } );
    *    } );
    */
    "bInfo": true,


    /**
    * Enable jQuery UI ThemeRoller support (required as ThemeRoller requires some
    * slightly different and additional mark-up from what DataTables has
    * traditionally used).
    *  @type boolean
    *  @default false
    *
    *  @dtopt Features
    *  @name DataTable.defaults.jQueryUI
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "jQueryUI": true
    *      } );
    *    } );
    */
    "bJQueryUI": false,


    /**
    * Allows the end user to select the size of a formatted page from a select
    * menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`).
    *  @type boolean
    *  @default true
    *
    *  @dtopt Features
    *  @name DataTable.defaults.lengthChange
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "lengthChange": false
    *      } );
    *    } );
    */
    "bLengthChange": true,


    /**
    * Enable or disable pagination.
    *  @type boolean
    *  @default true
    *
    *  @dtopt Features
    *  @name DataTable.defaults.paging
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "paging": false
    *      } );
    *    } );
    */
    "bPaginate": true,


    /**
    * Enable or disable the display of a 'processing' indicator when the table is
    * being processed (e.g. a sort). This is particularly useful for tables with
    * large amounts of data where it can take a noticeable amount of time to sort
    * the entries.
    *  @type boolean
    *  @default false
    *
    *  @dtopt Features
    *  @name DataTable.defaults.processing
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "processing": true
    *      } );
    *    } );
    */
    "bProcessing": false,


    /**
    * Retrieve the DataTables object for the given selector. Note that if the
    * table has already been initialised, this parameter will cause DataTables
    * to simply return the object that has already been set up - it will not take
    * account of any changes you might have made to the initialisation object
    * passed to DataTables (setting this parameter to true is an acknowledgement
    * that you understand this). `destroy` can be used to reinitialise a table if
    * you need.
    *  @type boolean
    *  @default false
    *
    *  @dtopt Options
    *  @name DataTable.defaults.retrieve
    *
    *  @example
    *    $(document).ready( function() {
    *      initTable();
    *      tableActions();
    *    } );
    *
    *    function initTable ()
    *    {
    *      return $('#example').dataTable( {
    *        "scrollY": "200px",
    *        "paginate": false,
    *        "retrieve": true
    *      } );
    *    }
    *
    *    function tableActions ()
    *    {
    *      var table = initTable();
    *      // perform API operations with oTable
    *    }
    */
    "bRetrieve": false,


    /**
    * When vertical (y) scrolling is enabled, DataTables will force the height of
    * the table's viewport to the given height at all times (useful for layout).
    * However, this can look odd when filtering data down to a small data set,
    * and the footer is left "floating" further down. This parameter (when
    * enabled) will cause DataTables to collapse the table's viewport down when
    * the result set will fit within the given Y height.
    *  @type boolean
    *  @default false
    *
    *  @dtopt Options
    *  @name DataTable.defaults.scrollCollapse
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "scrollY": "200",
    *        "scrollCollapse": true
    *      } );
    *    } );
    */
    "bScrollCollapse": false,


    /**
    * Configure DataTables to use server-side processing. Note that the
    * `ajax` parameter must also be given in order to give DataTables a
    * source to obtain the required data for each draw.
    *  @type boolean
    *  @default false
    *
    *  @dtopt Features
    *  @dtopt Server-side
    *  @name DataTable.defaults.serverSide
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "serverSide": true,
    *        "ajax": "xhr.php"
    *      } );
    *    } );
    */
    "bServerSide": false,


    /**
    * Enable or disable sorting of columns. Sorting of individual columns can be
    * disabled by the `sortable` option for each column.
    *  @type boolean
    *  @default true
    *
    *  @dtopt Features
    *  @name DataTable.defaults.ordering
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "ordering": false
    *      } );
    *    } );
    */
    "bSort": true,


    /**
    * Enable or display DataTables' ability to sort multiple columns at the
    * same time (activated by shift-click by the user).
    *  @type boolean
    *  @default true
    *
    *  @dtopt Options
    *  @name DataTable.defaults.orderMulti
    *
    *  @example
    *    // Disable multiple column sorting ability
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "orderMulti": false
    *      } );
    *    } );
    */
    "bSortMulti": true,


    /**
    * Allows control over whether DataTables should use the top (true) unique
    * cell that is found for a single column, or the bottom (false - default).
    * This is useful when using complex headers.
    *  @type boolean
    *  @default false
    *
    *  @dtopt Options
    *  @name DataTable.defaults.orderCellsTop
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "orderCellsTop": true
    *      } );
    *    } );
    */
    "bSortCellsTop": false,


    /**
    * Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and
    * `sorting\_3` to the columns which are currently being sorted on. This is
    * presented as a feature switch as it can increase processing time (while
    * classes are removed and added) so for large data sets you might want to
    * turn this off.
    *  @type boolean
    *  @default true
    *
    *  @dtopt Features
    *  @name DataTable.defaults.orderClasses
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "orderClasses": false
    *      } );
    *    } );
    */
    "bSortClasses": true,


    /**
    * Enable or disable state saving. When enabled HTML5 `localStorage` will be
    * used to save table display information such as pagination information,
    * display length, filtering and sorting. As such when the end user reloads
    * the page the display display will match what thy had previously set up.
    *
    * Due to the use of `localStorage` the default state saving is not supported
    * in IE6 or 7. If state saving is required in those browsers, use
    * `stateSaveCallback` to provide a storage solution such as cookies.
    *  @type boolean
    *  @default false
    *
    *  @dtopt Features
    *  @name DataTable.defaults.stateSave
    *
    *  @example
    *    $(document).ready( function () {
    *      $('#example').dataTable( {
    *        "stateSave": true
    *      } );
    *    } );
    */
    "bStateSave": false,


    /**
    * This function is called when a TR element is created (and all TD child
    * elements have been inserted), or registered if using a DOM source, allowing
    * manipulation of the TR element (adding classes etc).
    *  @type function
    *  @param {node} row "TR" element for the current row
    *  @param {array} data Raw data array for this row
    *  @param {int} dataIndex The index of this row in the internal aoData array
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.createdRow
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "createdRow": function( row, data, dataIndex ) {
    *          // Bold the grade for all 'A' grade browsers
    *          if ( data[4] == "A" )
    *          {
    *            $('td:eq(4)', row).html( '<b>A</b>' );
    *          }
    *        }
    *      } );
    *    } );
    */
    "fnCreatedRow": null,


    /**
    * This function is called on every 'draw' event, and allows you to
    * dynamically modify any aspect you want about the created DOM.
    *  @type function
    *  @param {object} settings DataTables settings object
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.drawCallback
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "drawCallback": function( settings ) {
    *          alert( 'DataTables has redrawn the table' );
    *        }
    *      } );
    *    } );
    */
    "fnDrawCallback": null,


    /**
    * Identical to fnHeaderCallback() but for the table footer this function
    * allows you to modify the table footer on every 'draw' event.
    *  @type function
    *  @param {node} foot "TR" element for the footer
    *  @param {array} data Full table data (as derived from the original HTML)
    *  @param {int} start Index for the current display starting point in the
    *    display array
    *  @param {int} end Index for the current display ending point in the
    *    display array
    *  @param {array int} display Index array to translate the visual position
    *    to the full data array
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.footerCallback
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "footerCallback": function( tfoot, data, start, end, display ) {
    *          tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start;
    *        }
    *      } );
    *    } )
    */
    "fnFooterCallback": null,


    /**
    * When rendering large numbers in the information element for the table
    * (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers
    * to have a comma separator for the 'thousands' units (e.g. 1 million is
    * rendered as "1,000,000") to help readability for the end user. This
    * function will override the default method DataTables uses.
    *  @type function
    *  @member
    *  @param {int} toFormat number to be formatted
    *  @returns {string} formatted string for DataTables to show the number
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.formatNumber
    *
    *  @example
    *    // Format a number using a single quote for the separator (note that
    *    // this can also be done with the language.thousands option)
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "formatNumber": function ( toFormat ) {
    *          return toFormat.toString().replace(
    *            /\B(?=(\d{3})+(?!\d))/g, "'"
    *          );
    *        };
    *      } );
    *    } );
    */
    "fnFormatNumber": function (toFormat) {
        return toFormat.toString().replace(
				/\B(?=(\d{3})+(?!\d))/g,
				this.oLanguage.sThousands
			);
    },


    /**
    * This function is called on every 'draw' event, and allows you to
    * dynamically modify the header row. This can be used to calculate and
    * display useful information about the table.
    *  @type function
    *  @param {node} head "TR" element for the header
    *  @param {array} data Full table data (as derived from the original HTML)
    *  @param {int} start Index for the current display starting point in the
    *    display array
    *  @param {int} end Index for the current display ending point in the
    *    display array
    *  @param {array int} display Index array to translate the visual position
    *    to the full data array
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.headerCallback
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "fheaderCallback": function( head, data, start, end, display ) {
    *          head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records";
    *        }
    *      } );
    *    } )
    */
    "fnHeaderCallback": null,


    /**
    * The information element can be used to convey information about the current
    * state of the table. Although the internationalisation options presented by
    * DataTables are quite capable of dealing with most customisations, there may
    * be times where you wish to customise the string further. This callback
    * allows you to do exactly that.
    *  @type function
    *  @param {object} oSettings DataTables settings object
    *  @param {int} start Starting position in data for the draw
    *  @param {int} end End position in data for the draw
    *  @param {int} max Total number of rows in the table (regardless of
    *    filtering)
    *  @param {int} total Total number of rows in the data set, after filtering
    *  @param {string} pre The string that DataTables has formatted using it's
    *    own rules
    *  @returns {string} The string to be displayed in the information element.
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.infoCallback
    *
    *  @example
    *    $('#example').dataTable( {
    *      "infoCallback": function( settings, start, end, max, total, pre ) {
    *        return start +" to "+ end;
    *      }
    *    } );
    */
    "fnInfoCallback": null,


    /**
    * Called when the table has been initialised. Normally DataTables will
    * initialise sequentially and there will be no need for this function,
    * however, this does not hold true when using external language information
    * since that is obtained using an async XHR call.
    *  @type function
    *  @param {object} settings DataTables settings object
    *  @param {object} json The JSON object request from the server - only
    *    present if client-side Ajax sourced data is used
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.initComplete
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "initComplete": function(settings, json) {
    *          alert( 'DataTables has finished its initialisation.' );
    *        }
    *      } );
    *    } )
    */
    "fnInitComplete": null,


    /**
    * Called at the very start of each table draw and can be used to cancel the
    * draw by returning false, any other return (including undefined) results in
    * the full draw occurring).
    *  @type function
    *  @param {object} settings DataTables settings object
    *  @returns {boolean} False will cancel the draw, anything else (including no
    *    return) will allow it to complete.
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.preDrawCallback
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "preDrawCallback": function( settings ) {
    *          if ( $('#test').val() == 1 ) {
    *            return false;
    *          }
    *        }
    *      } );
    *    } );
    */
    "fnPreDrawCallback": null,


    /**
    * This function allows you to 'post process' each row after it have been
    * generated for each table draw, but before it is rendered on screen. This
    * function might be used for setting the row class name etc.
    *  @type function
    *  @param {node} row "TR" element for the current row
    *  @param {array} data Raw data array for this row
    *  @param {int} displayIndex The display index for the current table draw
    *  @param {int} displayIndexFull The index of the data in the full list of
    *    rows (after filtering)
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.rowCallback
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "rowCallback": function( row, data, displayIndex, displayIndexFull ) {
    *          // Bold the grade for all 'A' grade browsers
    *          if ( data[4] == "A" ) {
    *            $('td:eq(4)', row).html( '<b>A</b>' );
    *          }
    *        }
    *      } );
    *    } );
    */
    "fnRowCallback": null,


    /**
    * __Deprecated__ The functionality provided by this parameter has now been
    * superseded by that provided through `ajax`, which should be used instead.
    *
    * This parameter allows you to override the default function which obtains
    * the data from the server so something more suitable for your application.
    * For example you could use POST data, or pull information from a Gears or
    * AIR database.
    *  @type function
    *  @member
    *  @param {string} source HTTP source to obtain the data from (`ajax`)
    *  @param {array} data A key/value pair object containing the data to send
    *    to the server
    *  @param {function} callback to be called on completion of the data get
    *    process that will draw the data on the page.
    *  @param {object} settings DataTables settings object
    *
    *  @dtopt Callbacks
    *  @dtopt Server-side
    *  @name DataTable.defaults.serverData
    *
    *  @deprecated 1.10. Please use `ajax` for this functionality now.
    */
    "fnServerData": null,


    /**
    * __Deprecated__ The functionality provided by this parameter has now been
    * superseded by that provided through `ajax`, which should be used instead.
    *
    *  It is often useful to send extra data to the server when making an Ajax
    * request - for example custom filtering information, and this callback
    * function makes it trivial to send extra information to the server. The
    * passed in parameter is the data set that has been constructed by
    * DataTables, and you can add to this or modify it as you require.
    *  @type function
    *  @param {array} data Data array (array of objects which are name/value
    *    pairs) that has been constructed by DataTables and will be sent to the
    *    server. In the case of Ajax sourced data with server-side processing
    *    this will be an empty array, for server-side processing there will be a
    *    significant number of parameters!
    *  @returns {undefined} Ensure that you modify the data array passed in,
    *    as this is passed by reference.
    *
    *  @dtopt Callbacks
    *  @dtopt Server-side
    *  @name DataTable.defaults.serverParams
    *
    *  @deprecated 1.10. Please use `ajax` for this functionality now.
    */
    "fnServerParams": null,


    /**
    * Load the table state. With this function you can define from where, and how, the
    * state of a table is loaded. By default DataTables will load from `localStorage`
    * but you might wish to use a server-side database or cookies.
    *  @type function
    *  @member
    *  @param {object} settings DataTables settings object
    *  @return {object} The DataTables state object to be loaded
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.stateLoadCallback
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "stateSave": true,
    *        "stateLoadCallback": function (settings) {
    *          var o;
    *
    *          // Send an Ajax request to the server to get the data. Note that
    *          // this is a synchronous request.
    *          $.ajax( {
    *            "url": "/state_load",
    *            "async": false,
    *            "dataType": "json",
    *            "success": function (json) {
    *              o = json;
    *            }
    *          } );
    *
    *          return o;
    *        }
    *      } );
    *    } );
    */
    "fnStateLoadCallback": function (settings) {
        try {
            return JSON.parse(
					(settings.iStateDuration === -1 ? sessionStorage : localStorage).getItem(
						'DataTables_' + settings.sInstance + '_' + location.pathname
					)
				);
        } catch (e) { }
    },


    /**
    * Callback which allows modification of the saved state prior to loading that state.
    * This callback is called when the table is loading state from the stored data, but
    * prior to the settings object being modified by the saved state. Note that for
    * plug-in authors, you should use the `stateLoadParams` event to load parameters for
    * a plug-in.
    *  @type function
    *  @param {object} settings DataTables settings object
    *  @param {object} data The state object that is to be loaded
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.stateLoadParams
    *
    *  @example
    *    // Remove a saved filter, so filtering is never loaded
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "stateSave": true,
    *        "stateLoadParams": function (settings, data) {
    *          data.oSearch.sSearch = "";
    *        }
    *      } );
    *    } );
    *
    *  @example
    *    // Disallow state loading by returning false
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "stateSave": true,
    *        "stateLoadParams": function (settings, data) {
    *          return false;
    *        }
    *      } );
    *    } );
    */
    "fnStateLoadParams": null,


    /**
    * Callback that is called when the state has been loaded from the state saving method
    * and the DataTables settings object has been modified as a result of the loaded state.
    *  @type function
    *  @param {object} settings DataTables settings object
    *  @param {object} data The state object that was loaded
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.stateLoaded
    *
    *  @example
    *    // Show an alert with the filtering value that was saved
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "stateSave": true,
    *        "stateLoaded": function (settings, data) {
    *          alert( 'Saved filter was: '+data.oSearch.sSearch );
    *        }
    *      } );
    *    } );
    */
    "fnStateLoaded": null,


    /**
    * Save the table state. This function allows you to define where and how the state
    * information for the table is stored By default DataTables will use `localStorage`
    * but you might wish to use a server-side database or cookies.
    *  @type function
    *  @member
    *  @param {object} settings DataTables settings object
    *  @param {object} data The state object to be saved
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.stateSaveCallback
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "stateSave": true,
    *        "stateSaveCallback": function (settings, data) {
    *          // Send an Ajax request to the server with the state object
    *          $.ajax( {
    *            "url": "/state_save",
    *            "data": data,
    *            "dataType": "json",
    *            "method": "POST"
    *            "success": function () {}
    *          } );
    *        }
    *      } );
    *    } );
    */
    "fnStateSaveCallback": function (settings, data) {
        try {
            (settings.iStateDuration === -1 ? sessionStorage : localStorage).setItem(
					'DataTables_' + settings.sInstance + '_' + location.pathname,
					JSON.stringify(data)
				);
        } catch (e) { }
    },


    /**
    * Callback which allows modification of the state to be saved. Called when the table
    * has changed state a new state save is required. This method allows modification of
    * the state saving object prior to actually doing the save, including addition or
    * other state properties or modification. Note that for plug-in authors, you should
    * use the `stateSaveParams` event to save parameters for a plug-in.
    *  @type function
    *  @param {object} settings DataTables settings object
    *  @param {object} data The state object to be saved
    *
    *  @dtopt Callbacks
    *  @name DataTable.defaults.stateSaveParams
    *
    *  @example
    *    // Remove a saved filter, so filtering is never saved
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "stateSave": true,
    *        "stateSaveParams": function (settings, data) {
    *          data.oSearch.sSearch = "";
    *        }
    *      } );
    *    } );
    */
    "fnStateSaveParams": null,


    /**
    * Duration for which the saved state information is considered valid. After this period
    * has elapsed the state will be returned to the default.
    * Value is given in seconds.
    *  @type int
    *  @default 7200 <i>(2 hours)</i>
    *
    *  @dtopt Options
    *  @name DataTable.defaults.stateDuration
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "stateDuration": 60*60*24; // 1 day
    *      } );
    *    } )
    */
    "iStateDuration": 7200,


    /**
    * When enabled DataTables will not make a request to the server for the first
    * page draw - rather it will use the data already on the page (no sorting etc
    * will be applied to it), thus saving on an XHR at load time. `deferLoading`
    * is used to indicate that deferred loading is required, but it is also used
    * to tell DataTables how many records there are in the full table (allowing
    * the information element and pagination to be displayed correctly). In the case
    * where a filtering is applied to the table on initial load, this can be
    * indicated by giving the parameter as an array, where the first element is
    * the number of records available after filtering and the second element is the
    * number of records without filtering (allowing the table information element
    * to be shown correctly).
    *  @type int | array
    *  @default null
    *
    *  @dtopt Options
    *  @name DataTable.defaults.deferLoading
    *
    *  @example
    *    // 57 records available in the table, no filtering applied
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "serverSide": true,
    *        "ajax": "scripts/server_processing.php",
    *        "deferLoading": 57
    *      } );
    *    } );
    *
    *  @example
    *    // 57 records after filtering, 100 without filtering (an initial filter applied)
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "serverSide": true,
    *        "ajax": "scripts/server_processing.php",
    *        "deferLoading": [ 57, 100 ],
    *        "search": {
    *          "search": "my_filter"
    *        }
    *      } );
    *    } );
    */
    "iDeferLoading": null,


    /**
    * Number of rows to display on a single page when using pagination. If
    * feature enabled (`lengthChange`) then the end user will be able to override
    * this to a custom setting using a pop-up menu.
    *  @type int
    *  @default 10
    *
    *  @dtopt Options
    *  @name DataTable.defaults.pageLength
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "pageLength": 50
    *      } );
    *    } )
    */
    "iDisplayLength": 10,


    /**
    * Define the starting point for data display when using DataTables with
    * pagination. Note that this parameter is the number of records, rather than
    * the page number, so if you have 10 records per page and want to start on
    * the third page, it should be "20".
    *  @type int
    *  @default 0
    *
    *  @dtopt Options
    *  @name DataTable.defaults.displayStart
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "displayStart": 20
    *      } );
    *    } )
    */
    "iDisplayStart": 0,


    /**
    * By default DataTables allows keyboard navigation of the table (sorting, paging,
    * and filtering) by adding a `tabindex` attribute to the required elements. This
    * allows you to tab through the controls and press the enter key to activate them.
    * The tabindex is default 0, meaning that the tab follows the flow of the document.
    * You can overrule this using this parameter if you wish. Use a value of -1 to
    * disable built-in keyboard navigation.
    *  @type int
    *  @default 0
    *
    *  @dtopt Options
    *  @name DataTable.defaults.tabIndex
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "tabIndex": 1
    *      } );
    *    } );
    */
    "iTabIndex": 0,


    /**
    * Classes that DataTables assigns to the various components and features
    * that it adds to the HTML table. This allows classes to be configured
    * during initialisation in addition to through the static
    * {@link DataTable.ext.oStdClasses} object).
    *  @namespace
    *  @name DataTable.defaults.classes
    */
    "oClasses": {},


    /**
    * All strings that DataTables uses in the user interface that it creates
    * are defined in this object, allowing you to modified them individually or
    * completely replace them all as required.
    *  @namespace
    *  @name DataTable.defaults.language
    */
    "oLanguage": {
        /**
        * Strings that are used for WAI-ARIA labels and controls only (these are not
        * actually visible on the page, but will be read by screenreaders, and thus
        * must be internationalised as well).
        *  @namespace
        *  @name DataTable.defaults.language.aria
        */
        "oAria": {
            /**
            * ARIA label that is added to the table headers when the column may be
            * sorted ascending by activing the column (click or return when focused).
            * Note that the column header is prefixed to this string.
            *  @type string
            *  @default : activate to sort column ascending
            *
            *  @dtopt Language
            *  @name DataTable.defaults.language.aria.sortAscending
            *
            *  @example
            *    $(document).ready( function() {
            *      $('#example').dataTable( {
            *        "language": {
            *          "aria": {
            *            "sortAscending": " - click/return to sort ascending"
            *          }
            *        }
            *      } );
            *    } );
            */
            "sSortAscending": ": activate to sort column ascending",

            /**
            * ARIA label that is added to the table headers when the column may be
            * sorted descending by activing the column (click or return when focused).
            * Note that the column header is prefixed to this string.
            *  @type string
            *  @default : activate to sort column ascending
            *
            *  @dtopt Language
            *  @name DataTable.defaults.language.aria.sortDescending
            *
            *  @example
            *    $(document).ready( function() {
            *      $('#example').dataTable( {
            *        "language": {
            *          "aria": {
            *            "sortDescending": " - click/return to sort descending"
            *          }
            *        }
            *      } );
            *    } );
            */
            "sSortDescending": ": activate to sort column descending"
        },

        /**
        * Pagination string used by DataTables for the built-in pagination
        * control types.
        *  @namespace
        *  @name DataTable.defaults.language.paginate
        */
        "oPaginate": {
            /**
            * Text to use when using the 'full_numbers' type of pagination for the
            * button to take the user to the first page.
            *  @type string
            *  @default First
            *
            *  @dtopt Language
            *  @name DataTable.defaults.language.paginate.first
            *
            *  @example
            *    $(document).ready( function() {
            *      $('#example').dataTable( {
            *        "language": {
            *          "paginate": {
            *            "first": "First page"
            *          }
            *        }
            *      } );
            *    } );
            */
            "sFirst": "First",


            /**
            * Text to use when using the 'full_numbers' type of pagination for the
            * button to take the user to the last page.
            *  @type string
            *  @default Last
            *
            *  @dtopt Language
            *  @name DataTable.defaults.language.paginate.last
            *
            *  @example
            *    $(document).ready( function() {
            *      $('#example').dataTable( {
            *        "language": {
            *          "paginate": {
            *            "last": "Last page"
            *          }
            *        }
            *      } );
            *    } );
            */
            "sLast": "Last",


            /**
            * Text to use for the 'next' pagination button (to take the user to the
            * next page).
            *  @type string
            *  @default Next
            *
            *  @dtopt Language
            *  @name DataTable.defaults.language.paginate.next
            *
            *  @example
            *    $(document).ready( function() {
            *      $('#example').dataTable( {
            *        "language": {
            *          "paginate": {
            *            "next": "Next page"
            *          }
            *        }
            *      } );
            *    } );
            */
            "sNext": "Next",


            /**
            * Text to use for the 'previous' pagination button (to take the user to
            * the previous page).
            *  @type string
            *  @default Previous
            *
            *  @dtopt Language
            *  @name DataTable.defaults.language.paginate.previous
            *
            *  @example
            *    $(document).ready( function() {
            *      $('#example').dataTable( {
            *        "language": {
            *          "paginate": {
            *            "previous": "Previous page"
            *          }
            *        }
            *      } );
            *    } );
            */
            "sPrevious": "Previous"
        },

        /**
        * This string is shown in preference to `zeroRecords` when the table is
        * empty of data (regardless of filtering). Note that this is an optional
        * parameter - if it is not given, the value of `zeroRecords` will be used
        * instead (either the default or given value).
        *  @type string
        *  @default No data available in table
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.emptyTable
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "emptyTable": "No data available in table"
        *        }
        *      } );
        *    } );
        */
        "sEmptyTable": "No data available in table",


        /**
        * This string gives information to the end user about the information
        * that is current on display on the page. The following tokens can be
        * used in the string and will be dynamically replaced as the table
        * display updates. This tokens can be placed anywhere in the string, or
        * removed as needed by the language requires:
        *
        * * `\_START\_` - Display index of the first record on the current page
        * * `\_END\_` - Display index of the last record on the current page
        * * `\_TOTAL\_` - Number of records in the table after filtering
        * * `\_MAX\_` - Number of records in the table without filtering
        * * `\_PAGE\_` - Current page number
        * * `\_PAGES\_` - Total number of pages of data in the table
        *
        *  @type string
        *  @default Showing _START_ to _END_ of _TOTAL_ entries
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.info
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "info": "Showing page _PAGE_ of _PAGES_"
        *        }
        *      } );
        *    } );
        */
        "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",


        /**
        * Display information string for when the table is empty. Typically the
        * format of this string should match `info`.
        *  @type string
        *  @default Showing 0 to 0 of 0 entries
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.infoEmpty
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "infoEmpty": "No entries to show"
        *        }
        *      } );
        *    } );
        */
        "sInfoEmpty": "Showing 0 to 0 of 0 entries",


        /**
        * When a user filters the information in a table, this string is appended
        * to the information (`info`) to give an idea of how strong the filtering
        * is. The variable _MAX_ is dynamically updated.
        *  @type string
        *  @default (filtered from _MAX_ total entries)
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.infoFiltered
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "infoFiltered": " - filtering from _MAX_ records"
        *        }
        *      } );
        *    } );
        */
        "sInfoFiltered": "(filtered from _MAX_ total entries)",


        /**
        * If can be useful to append extra information to the info string at times,
        * and this variable does exactly that. This information will be appended to
        * the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are
        * being used) at all times.
        *  @type string
        *  @default <i>Empty string</i>
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.infoPostFix
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "infoPostFix": "All records shown are derived from real information."
        *        }
        *      } );
        *    } );
        */
        "sInfoPostFix": "",


        /**
        * This decimal place operator is a little different from the other
        * language options since DataTables doesn't output floating point
        * numbers, so it won't ever use this for display of a number. Rather,
        * what this parameter does is modify the sort methods of the table so
        * that numbers which are in a format which has a character other than
        * a period (`.`) as a decimal place will be sorted numerically.
        *
        * Note that numbers with different decimal places cannot be shown in
        * the same table and still be sortable, the table must be consistent.
        * However, multiple different tables on the page can use different
        * decimal place characters.
        *  @type string
        *  @default 
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.decimal
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "decimal": ","
        *          "thousands": "."
        *        }
        *      } );
        *    } );
        */
        "sDecimal": "",


        /**
        * DataTables has a build in number formatter (`formatNumber`) which is
        * used to format large numbers that are used in the table information.
        * By default a comma is used, but this can be trivially changed to any
        * character you wish with this parameter.
        *  @type string
        *  @default ,
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.thousands
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "thousands": "'"
        *        }
        *      } );
        *    } );
        */
        "sThousands": ",",


        /**
        * Detail the action that will be taken when the drop down menu for the
        * pagination length option is changed. The '_MENU_' variable is replaced
        * with a default select list of 10, 25, 50 and 100, and can be replaced
        * with a custom select box if required.
        *  @type string
        *  @default Show _MENU_ entries
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.lengthMenu
        *
        *  @example
        *    // Language change only
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "lengthMenu": "Display _MENU_ records"
        *        }
        *      } );
        *    } );
        *
        *  @example
        *    // Language and options change
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "lengthMenu": 'Display <select>'+
        *            '<option value="10">10</option>'+
        *            '<option value="20">20</option>'+
        *            '<option value="30">30</option>'+
        *            '<option value="40">40</option>'+
        *            '<option value="50">50</option>'+
        *            '<option value="-1">All</option>'+
        *            '</select> records'
        *        }
        *      } );
        *    } );
        */
        "sLengthMenu": "Show _MENU_ entries",


        /**
        * When using Ajax sourced data and during the first draw when DataTables is
        * gathering the data, this message is shown in an empty row in the table to
        * indicate to the end user the the data is being loaded. Note that this
        * parameter is not used when loading data by server-side processing, just
        * Ajax sourced data with client-side processing.
        *  @type string
        *  @default Loading...
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.loadingRecords
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "loadingRecords": "Please wait - loading..."
        *        }
        *      } );
        *    } );
        */
        "sLoadingRecords": "Loading...",


        /**
        * Text which is displayed when the table is processing a user action
        * (usually a sort command or similar).
        *  @type string
        *  @default Processing...
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.processing
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "processing": "DataTables is currently busy"
        *        }
        *      } );
        *    } );
        */
        "sProcessing": "Processing...",


        /**
        * Details the actions that will be taken when the user types into the
        * filtering input text box. The variable "_INPUT_", if used in the string,
        * is replaced with the HTML text box for the filtering input allowing
        * control over where it appears in the string. If "_INPUT_" is not given
        * then the input box is appended to the string automatically.
        *  @type string
        *  @default Search:
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.search
        *
        *  @example
        *    // Input text box will be appended at the end automatically
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "search": "Filter records:"
        *        }
        *      } );
        *    } );
        *
        *  @example
        *    // Specify where the filter should appear
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "search": "Apply filter _INPUT_ to table"
        *        }
        *      } );
        *    } );
        */
        "sSearch": "Search:",


        /**
        * All of the language information can be stored in a file on the
        * server-side, which DataTables will look up if this parameter is passed.
        * It must store the URL of the language file, which is in a JSON format,
        * and the object has the same properties as the oLanguage object in the
        * initialiser object (i.e. the above parameters). Please refer to one of
        * the example language files to see how this works in action.
        *  @type string
        *  @default <i>Empty string - i.e. disabled</i>
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.url
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "url": "http://www.sprymedia.co.uk/dataTables/lang.txt"
        *        }
        *      } );
        *    } );
        */
        "sUrl": "",


        /**
        * Text shown inside the table records when the is no information to be
        * displayed after filtering. `emptyTable` is shown when there is simply no
        * information in the table at all (regardless of filtering).
        *  @type string
        *  @default No matching records found
        *
        *  @dtopt Language
        *  @name DataTable.defaults.language.zeroRecords
        *
        *  @example
        *    $(document).ready( function() {
        *      $('#example').dataTable( {
        *        "language": {
        *          "zeroRecords": "No records to display"
        *        }
        *      } );
        *    } );
        */
        "sZeroRecords": "No matching records found"
    },


    /**
    * This parameter allows you to have define the global filtering state at
    * initialisation time. As an object the `search` parameter must be
    * defined, but all other parameters are optional. When `regex` is true,
    * the search string will be treated as a regular expression, when false
    * (default) it will be treated as a straight string. When `smart`
    * DataTables will use it's smart filtering methods (to word match at
    * any point in the data), when false this will not be done.
    *  @namespace
    *  @extends DataTable.models.oSearch
    *
    *  @dtopt Options
    *  @name DataTable.defaults.search
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "search": {"search": "Initial search"}
    *      } );
    *    } )
    */
    "oSearch": $.extend({}, DataTable.models.oSearch),


    /**
    * __Deprecated__ The functionality provided by this parameter has now been
    * superseded by that provided through `ajax`, which should be used instead.
    *
    * By default DataTables will look for the property `data` (or `aaData` for
    * compatibility with DataTables 1.9-) when obtaining data from an Ajax
    * source or for server-side processing - this parameter allows that
    * property to be changed. You can use Javascript dotted object notation to
    * get a data source for multiple levels of nesting.
    *  @type string
    *  @default data
    *
    *  @dtopt Options
    *  @dtopt Server-side
    *  @name DataTable.defaults.ajaxDataProp
    *
    *  @deprecated 1.10. Please use `ajax` for this functionality now.
    */
    "sAjaxDataProp": "data",


    /**
    * __Deprecated__ The functionality provided by this parameter has now been
    * superseded by that provided through `ajax`, which should be used instead.
    *
    * You can instruct DataTables to load data from an external
    * source using this parameter (use aData if you want to pass data in you
    * already have). Simply provide a url a JSON object can be obtained from.
    *  @type string
    *  @default null
    *
    *  @dtopt Options
    *  @dtopt Server-side
    *  @name DataTable.defaults.ajaxSource
    *
    *  @deprecated 1.10. Please use `ajax` for this functionality now.
    */
    "sAjaxSource": null,


    /**
    * This initialisation variable allows you to specify exactly where in the
    * DOM you want DataTables to inject the various controls it adds to the page
    * (for example you might want the pagination controls at the top of the
    * table). DIV elements (with or without a custom class) can also be added to
    * aid styling. The follow syntax is used:
    *   <ul>
    *     <li>The following options are allowed:
    *       <ul>
    *         <li>'l' - Length changing</li>
    *         <li>'f' - Filtering input</li>
    *         <li>'t' - The table!</li>
    *         <li>'i' - Information</li>
    *         <li>'p' - Pagination</li>
    *         <li>'r' - pRocessing</li>
    *       </ul>
    *     </li>
    *     <li>The following constants are allowed:
    *       <ul>
    *         <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li>
    *         <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li>
    *       </ul>
    *     </li>
    *     <li>The following syntax is expected:
    *       <ul>
    *         <li>'&lt;' and '&gt;' - div elements</li>
    *         <li>'&lt;"class" and '&gt;' - div with a class</li>
    *         <li>'&lt;"#id" and '&gt;' - div with an ID</li>
    *       </ul>
    *     </li>
    *     <li>Examples:
    *       <ul>
    *         <li>'&lt;"wrapper"flipt&gt;'</li>
    *         <li>'&lt;lf&lt;t&gt;ip&gt;'</li>
    *       </ul>
    *     </li>
    *   </ul>
    *  @type string
    *  @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b>
    *    <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i>
    *
    *  @dtopt Options
    *  @name DataTable.defaults.dom
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "dom": '&lt;"top"i&gt;rt&lt;"bottom"flp&gt;&lt;"clear"&gt;'
    *      } );
    *    } );
    */
    "sDom": "lfrtip",


    /**
    * DataTables features four different built-in options for the buttons to
    * display for pagination control:
    *
    * * `simple` - 'Previous' and 'Next' buttons only
    * * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers
    * * `full` - 'First', 'Previous', 'Next' and 'Last' buttons
    * * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus
    *   page numbers
    *  
    * Further methods can be added using {@link DataTable.ext.oPagination}.
    *  @type string
    *  @default simple_numbers
    *
    *  @dtopt Options
    *  @name DataTable.defaults.pagingType
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "pagingType": "full_numbers"
    *      } );
    *    } )
    */
    "sPaginationType": "simple_numbers",


    /**
    * Enable horizontal scrolling. When a table is too wide to fit into a
    * certain layout, or you have a large number of columns in the table, you
    * can enable x-scrolling to show the table in a viewport, which can be
    * scrolled. This property can be `true` which will allow the table to
    * scroll horizontally when needed, or any CSS unit, or a number (in which
    * case it will be treated as a pixel measurement). Setting as simply `true`
    * is recommended.
    *  @type boolean|string
    *  @default <i>blank string - i.e. disabled</i>
    *
    *  @dtopt Features
    *  @name DataTable.defaults.scrollX
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "scrollX": true,
    *        "scrollCollapse": true
    *      } );
    *    } );
    */
    "sScrollX": "",


    /**
    * This property can be used to force a DataTable to use more width than it
    * might otherwise do when x-scrolling is enabled. For example if you have a
    * table which requires to be well spaced, this parameter is useful for
    * "over-sizing" the table, and thus forcing scrolling. This property can by
    * any CSS unit, or a number (in which case it will be treated as a pixel
    * measurement).
    *  @type string
    *  @default <i>blank string - i.e. disabled</i>
    *
    *  @dtopt Options
    *  @name DataTable.defaults.scrollXInner
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "scrollX": "100%",
    *        "scrollXInner": "110%"
    *      } );
    *    } );
    */
    "sScrollXInner": "",


    /**
    * Enable vertical scrolling. Vertical scrolling will constrain the DataTable
    * to the given height, and enable scrolling for any data which overflows the
    * current viewport. This can be used as an alternative to paging to display
    * a lot of data in a small area (although paging and scrolling can both be
    * enabled at the same time). This property can be any CSS unit, or a number
    * (in which case it will be treated as a pixel measurement).
    *  @type string
    *  @default <i>blank string - i.e. disabled</i>
    *
    *  @dtopt Features
    *  @name DataTable.defaults.scrollY
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "scrollY": "200px",
    *        "paginate": false
    *      } );
    *    } );
    */
    "sScrollY": "",


    /**
    * __Deprecated__ The functionality provided by this parameter has now been
    * superseded by that provided through `ajax`, which should be used instead.
    *
    * Set the HTTP method that is used to make the Ajax call for server-side
    * processing or Ajax sourced data.
    *  @type string
    *  @default GET
    *
    *  @dtopt Options
    *  @dtopt Server-side
    *  @name DataTable.defaults.serverMethod
    *
    *  @deprecated 1.10. Please use `ajax` for this functionality now.
    */
    "sServerMethod": "GET",


    /**
    * DataTables makes use of renderers when displaying HTML elements for
    * a table. These renderers can be added or modified by plug-ins to
    * generate suitable mark-up for a site. For example the Bootstrap
    * integration plug-in for DataTables uses a paging button renderer to
    * display pagination buttons in the mark-up required by Bootstrap.
    *
    * For further information about the renderers available see
    * DataTable.ext.renderer
    *  @type string|object
    *  @default null
    *
    *  @name DataTable.defaults.renderer
    *
    */
    "renderer": null
};

_fnHungarianMap(DataTable.defaults);



/*
* Developer note - See note in model.defaults.js about the use of Hungarian
* notation and camel case.
*/

/**
* Column options that can be given to DataTables at initialisation time.
*  @namespace
*/
DataTable.defaults.column = {
    /**
    * Define which column(s) an order will occur on for this column. This
    * allows a column's ordering to take multiple columns into account when
    * doing a sort or use the data from a different column. For example first
    * name / last name columns make sense to do a multi-column sort over the
    * two columns.
    *  @type array|int
    *  @default null <i>Takes the value of the column index automatically</i>
    *
    *  @name DataTable.defaults.column.orderData
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "orderData": [ 0, 1 ], "targets": [ 0 ] },
    *          { "orderData": [ 1, 0 ], "targets": [ 1 ] },
    *          { "orderData": 2, "targets": [ 2 ] }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "orderData": [ 0, 1 ] },
    *          { "orderData": [ 1, 0 ] },
    *          { "orderData": 2 },
    *          null,
    *          null
    *        ]
    *      } );
    *    } );
    */
    "aDataSort": null,
    "iDataSort": -1,


    /**
    * You can control the default ordering direction, and even alter the
    * behaviour of the sort handler (i.e. only allow ascending ordering etc)
    * using this parameter.
    *  @type array
    *  @default [ 'asc', 'desc' ]
    *
    *  @name DataTable.defaults.column.orderSequence
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "orderSequence": [ "asc" ], "targets": [ 1 ] },
    *          { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] },
    *          { "orderSequence": [ "desc" ], "targets": [ 3 ] }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          null,
    *          { "orderSequence": [ "asc" ] },
    *          { "orderSequence": [ "desc", "asc", "asc" ] },
    *          { "orderSequence": [ "desc" ] },
    *          null
    *        ]
    *      } );
    *    } );
    */
    "asSorting": ['asc', 'desc'],


    /**
    * Enable or disable filtering on the data in this column.
    *  @type boolean
    *  @default true
    *
    *  @name DataTable.defaults.column.searchable
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "searchable": false, "targets": [ 0 ] }
    *        ] } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "searchable": false },
    *          null,
    *          null,
    *          null,
    *          null
    *        ] } );
    *    } );
    */
    "bSearchable": true,


    /**
    * Enable or disable ordering on this column.
    *  @type boolean
    *  @default true
    *
    *  @name DataTable.defaults.column.orderable
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "orderable": false, "targets": [ 0 ] }
    *        ] } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "orderable": false },
    *          null,
    *          null,
    *          null,
    *          null
    *        ] } );
    *    } );
    */
    "bSortable": true,


    /**
    * Enable or disable the display of this column.
    *  @type boolean
    *  @default true
    *
    *  @name DataTable.defaults.column.visible
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "visible": false, "targets": [ 0 ] }
    *        ] } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "visible": false },
    *          null,
    *          null,
    *          null,
    *          null
    *        ] } );
    *    } );
    */
    "bVisible": true,


    /**
    * Developer definable function that is called whenever a cell is created (Ajax source,
    * etc) or processed for input (DOM source). This can be used as a compliment to mRender
    * allowing you to modify the DOM element (add background colour for example) when the
    * element is available.
    *  @type function
    *  @param {element} td The TD node that has been created
    *  @param {*} cellData The Data for the cell
    *  @param {array|object} rowData The data for the whole row
    *  @param {int} row The row index for the aoData data store
    *  @param {int} col The column index for aoColumns
    *
    *  @name DataTable.defaults.column.createdCell
    *  @dtopt Columns
    *
    *  @example
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [ {
    *          "targets": [3],
    *          "createdCell": function (td, cellData, rowData, row, col) {
    *            if ( cellData == "1.7" ) {
    *              $(td).css('color', 'blue')
    *            }
    *          }
    *        } ]
    *      });
    *    } );
    */
    "fnCreatedCell": null,


    /**
    * This parameter has been replaced by `data` in DataTables to ensure naming
    * consistency. `dataProp` can still be used, as there is backwards
    * compatibility in DataTables for this option, but it is strongly
    * recommended that you use `data` in preference to `dataProp`.
    *  @name DataTable.defaults.column.dataProp
    */


    /**
    * This property can be used to read data from any data source property,
    * including deeply nested objects / properties. `data` can be given in a
    * number of different ways which effect its behaviour:
    *
    * * `integer` - treated as an array index for the data source. This is the
    *   default that DataTables uses (incrementally increased for each column).
    * * `string` - read an object property from the data source. There are
    *   three 'special' options that can be used in the string to alter how
    *   DataTables reads the data from the source object:
    *    * `.` - Dotted Javascript notation. Just as you use a `.` in
    *      Javascript to read from nested objects, so to can the options
    *      specified in `data`. For example: `browser.version` or
    *      `browser.name`. If your object parameter name contains a period, use
    *      `\\` to escape it - i.e. `first\\.name`.
    *    * `[]` - Array notation. DataTables can automatically combine data
    *      from and array source, joining the data with the characters provided
    *      between the two brackets. For example: `name[, ]` would provide a
    *      comma-space separated list from the source array. If no characters
    *      are provided between the brackets, the original array source is
    *      returned.
    *    * `()` - Function notation. Adding `()` to the end of a parameter will
    *      execute a function of the name given. For example: `browser()` for a
    *      simple function on the data source, `browser.version()` for a
    *      function in a nested property or even `browser().version` to get an
    *      object property if the function called returns an object. Note that
    *      function notation is recommended for use in `render` rather than
    *      `data` as it is much simpler to use as a renderer.
    * * `null` - use the original data source for the row rather than plucking
    *   data directly from it. This action has effects on two other
    *   initialisation options:
    *    * `defaultContent` - When null is given as the `data` option and
    *      `defaultContent` is specified for the column, the value defined by
    *      `defaultContent` will be used for the cell.
    *    * `render` - When null is used for the `data` option and the `render`
    *      option is specified for the column, the whole data source for the
    *      row is used for the renderer.
    * * `function` - the function given will be executed whenever DataTables
    *   needs to set or get the data for a cell in the column. The function
    *   takes three parameters:
    *    * Parameters:
    *      * `{array|object}` The data source for the row
    *      * `{string}` The type call data requested - this will be 'set' when
    *        setting data or 'filter', 'display', 'type', 'sort' or undefined
    *        when gathering data. Note that when `undefined` is given for the
    *        type DataTables expects to get the raw data for the object back<
    *      * `{*}` Data to set when the second parameter is 'set'.
    *    * Return:
    *      * The return value from the function is not required when 'set' is
    *        the type of call, but otherwise the return is what will be used
    *        for the data requested.
    *
    * Note that `data` is a getter and setter option. If you just require
    * formatting of data for output, you will likely want to use `render` which
    * is simply a getter and thus simpler to use.
    *
    * Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The
    * name change reflects the flexibility of this property and is consistent
    * with the naming of mRender. If 'mDataProp' is given, then it will still
    * be used by DataTables, as it automatically maps the old name to the new
    * if required.
    *
    *  @type string|int|function|null
    *  @default null <i>Use automatically calculated column index</i>
    *
    *  @name DataTable.defaults.column.data
    *  @dtopt Columns
    *
    *  @example
    *    // Read table data from objects
    *    // JSON structure for each row:
    *    //   {
    *    //      "engine": {value},
    *    //      "browser": {value},
    *    //      "platform": {value},
    *    //      "version": {value},
    *    //      "grade": {value}
    *    //   }
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "ajaxSource": "sources/objects.txt",
    *        "columns": [
    *          { "data": "engine" },
    *          { "data": "browser" },
    *          { "data": "platform" },
    *          { "data": "version" },
    *          { "data": "grade" }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Read information from deeply nested objects
    *    // JSON structure for each row:
    *    //   {
    *    //      "engine": {value},
    *    //      "browser": {value},
    *    //      "platform": {
    *    //         "inner": {value}
    *    //      },
    *    //      "details": [
    *    //         {value}, {value}
    *    //      ]
    *    //   }
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "ajaxSource": "sources/deep.txt",
    *        "columns": [
    *          { "data": "engine" },
    *          { "data": "browser" },
    *          { "data": "platform.inner" },
    *          { "data": "platform.details.0" },
    *          { "data": "platform.details.1" }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `data` as a function to provide different information for
    *    // sorting, filtering and display. In this case, currency (price)
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [ {
    *          "targets": [ 0 ],
    *          "data": function ( source, type, val ) {
    *            if (type === 'set') {
    *              source.price = val;
    *              // Store the computed dislay and filter values for efficiency
    *              source.price_display = val=="" ? "" : "$"+numberFormat(val);
    *              source.price_filter  = val=="" ? "" : "$"+numberFormat(val)+" "+val;
    *              return;
    *            }
    *            else if (type === 'display') {
    *              return source.price_display;
    *            }
    *            else if (type === 'filter') {
    *              return source.price_filter;
    *            }
    *            // 'sort', 'type' and undefined all just use the integer
    *            return source.price;
    *          }
    *        } ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using default content
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [ {
    *          "targets": [ 0 ],
    *          "data": null,
    *          "defaultContent": "Click to edit"
    *        } ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using array notation - outputting a list from an array
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [ {
    *          "targets": [ 0 ],
    *          "data": "name[, ]"
    *        } ]
    *      } );
    *    } );
    *
    */
    "mData": null,


    /**
    * This property is the rendering partner to `data` and it is suggested that
    * when you want to manipulate data for display (including filtering,
    * sorting etc) without altering the underlying data for the table, use this
    * property. `render` can be considered to be the the read only companion to
    * `data` which is read / write (then as such more complex). Like `data`
    * this option can be given in a number of different ways to effect its
    * behaviour:
    *
    * * `integer` - treated as an array index for the data source. This is the
    *   default that DataTables uses (incrementally increased for each column).
    * * `string` - read an object property from the data source. There are
    *   three 'special' options that can be used in the string to alter how
    *   DataTables reads the data from the source object:
    *    * `.` - Dotted Javascript notation. Just as you use a `.` in
    *      Javascript to read from nested objects, so to can the options
    *      specified in `data`. For example: `browser.version` or
    *      `browser.name`. If your object parameter name contains a period, use
    *      `\\` to escape it - i.e. `first\\.name`.
    *    * `[]` - Array notation. DataTables can automatically combine data
    *      from and array source, joining the data with the characters provided
    *      between the two brackets. For example: `name[, ]` would provide a
    *      comma-space separated list from the source array. If no characters
    *      are provided between the brackets, the original array source is
    *      returned.
    *    * `()` - Function notation. Adding `()` to the end of a parameter will
    *      execute a function of the name given. For example: `browser()` for a
    *      simple function on the data source, `browser.version()` for a
    *      function in a nested property or even `browser().version` to get an
    *      object property if the function called returns an object.
    * * `object` - use different data for the different data types requested by
    *   DataTables ('filter', 'display', 'type' or 'sort'). The property names
    *   of the object is the data type the property refers to and the value can
    *   defined using an integer, string or function using the same rules as
    *   `render` normally does. Note that an `_` option _must_ be specified.
    *   This is the default value to use if you haven't specified a value for
    *   the data type requested by DataTables.
    * * `function` - the function given will be executed whenever DataTables
    *   needs to set or get the data for a cell in the column. The function
    *   takes three parameters:
    *    * Parameters:
    *      * {array|object} The data source for the row (based on `data`)
    *      * {string} The type call data requested - this will be 'filter',
    *        'display', 'type' or 'sort'.
    *      * {array|object} The full data source for the row (not based on
    *        `data`)
    *    * Return:
    *      * The return value from the function is what will be used for the
    *        data requested.
    *
    *  @type string|int|function|object|null
    *  @default null Use the data source value.
    *
    *  @name DataTable.defaults.column.render
    *  @dtopt Columns
    *
    *  @example
    *    // Create a comma separated list from an array of objects
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "ajaxSource": "sources/deep.txt",
    *        "columns": [
    *          { "data": "engine" },
    *          { "data": "browser" },
    *          {
    *            "data": "platform",
    *            "render": "[, ].name"
    *          }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Execute a function to obtain data
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [ {
    *          "targets": [ 0 ],
    *          "data": null, // Use the full data source object for the renderer's source
    *          "render": "browserName()"
    *        } ]
    *      } );
    *    } );
    *
    *  @example
    *    // As an object, extracting different data for the different types
    *    // This would be used with a data source such as:
    *    //   { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" }
    *    // Here the `phone` integer is used for sorting and type detection, while `phone_filter`
    *    // (which has both forms) is used for filtering for if a user inputs either format, while
    *    // the formatted phone number is the one that is shown in the table.
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [ {
    *          "targets": [ 0 ],
    *          "data": null, // Use the full data source object for the renderer's source
    *          "render": {
    *            "_": "phone",
    *            "filter": "phone_filter",
    *            "display": "phone_display"
    *          }
    *        } ]
    *      } );
    *    } );
    *
    *  @example
    *    // Use as a function to create a link from the data source
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [ {
    *          "targets": [ 0 ],
    *          "data": "download_link",
    *          "render": function ( data, type, full ) {
    *            return '<a href="'+data+'">Download</a>';
    *          }
    *        } ]
    *      } );
    *    } );
    */
    "mRender": null,


    /**
    * Change the cell type created for the column - either TD cells or TH cells. This
    * can be useful as TH cells have semantic meaning in the table body, allowing them
    * to act as a header for a row (you may wish to add scope='row' to the TH elements).
    *  @type string
    *  @default td
    *
    *  @name DataTable.defaults.column.cellType
    *  @dtopt Columns
    *
    *  @example
    *    // Make the first column use TH cells
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [ {
    *          "targets": [ 0 ],
    *          "cellType": "th"
    *        } ]
    *      } );
    *    } );
    */
    "sCellType": "td",


    /**
    * Class to give to each cell in this column.
    *  @type string
    *  @default <i>Empty string</i>
    *
    *  @name DataTable.defaults.column.class
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "class": "my_class", "targets": [ 0 ] }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "class": "my_class" },
    *          null,
    *          null,
    *          null,
    *          null
    *        ]
    *      } );
    *    } );
    */
    "sClass": "",

    /**
    * When DataTables calculates the column widths to assign to each column,
    * it finds the longest string in each column and then constructs a
    * temporary table and reads the widths from that. The problem with this
    * is that "mmm" is much wider then "iiii", but the latter is a longer
    * string - thus the calculation can go wrong (doing it properly and putting
    * it into an DOM object and measuring that is horribly(!) slow). Thus as
    * a "work around" we provide this option. It will append its value to the
    * text that is found to be the longest string for the column - i.e. padding.
    * Generally you shouldn't need this!
    *  @type string
    *  @default <i>Empty string<i>
    *
    *  @name DataTable.defaults.column.contentPadding
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          null,
    *          null,
    *          null,
    *          {
    *            "contentPadding": "mmm"
    *          }
    *        ]
    *      } );
    *    } );
    */
    "sContentPadding": "",


    /**
    * Allows a default value to be given for a column's data, and will be used
    * whenever a null data source is encountered (this can be because `data`
    * is set to null, or because the data source itself is null).
    *  @type string
    *  @default null
    *
    *  @name DataTable.defaults.column.defaultContent
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          {
    *            "data": null,
    *            "defaultContent": "Edit",
    *            "targets": [ -1 ]
    *          }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          null,
    *          null,
    *          null,
    *          {
    *            "data": null,
    *            "defaultContent": "Edit"
    *          }
    *        ]
    *      } );
    *    } );
    */
    "sDefaultContent": null,


    /**
    * This parameter is only used in DataTables' server-side processing. It can
    * be exceptionally useful to know what columns are being displayed on the
    * client side, and to map these to database fields. When defined, the names
    * also allow DataTables to reorder information from the server if it comes
    * back in an unexpected order (i.e. if you switch your columns around on the
    * client-side, your server-side code does not also need updating).
    *  @type string
    *  @default <i>Empty string</i>
    *
    *  @name DataTable.defaults.column.name
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "name": "engine", "targets": [ 0 ] },
    *          { "name": "browser", "targets": [ 1 ] },
    *          { "name": "platform", "targets": [ 2 ] },
    *          { "name": "version", "targets": [ 3 ] },
    *          { "name": "grade", "targets": [ 4 ] }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "name": "engine" },
    *          { "name": "browser" },
    *          { "name": "platform" },
    *          { "name": "version" },
    *          { "name": "grade" }
    *        ]
    *      } );
    *    } );
    */
    "sName": "",


    /**
    * Defines a data source type for the ordering which can be used to read
    * real-time information from the table (updating the internally cached
    * version) prior to ordering. This allows ordering to occur on user
    * editable elements such as form inputs.
    *  @type string
    *  @default std
    *
    *  @name DataTable.defaults.column.orderDataType
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "orderDataType": "dom-text", "targets": [ 2, 3 ] },
    *          { "type": "numeric", "targets": [ 3 ] },
    *          { "orderDataType": "dom-select", "targets": [ 4 ] },
    *          { "orderDataType": "dom-checkbox", "targets": [ 5 ] }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          null,
    *          null,
    *          { "orderDataType": "dom-text" },
    *          { "orderDataType": "dom-text", "type": "numeric" },
    *          { "orderDataType": "dom-select" },
    *          { "orderDataType": "dom-checkbox" }
    *        ]
    *      } );
    *    } );
    */
    "sSortDataType": "std",


    /**
    * The title of this column.
    *  @type string
    *  @default null <i>Derived from the 'TH' value for this column in the
    *    original HTML table.</i>
    *
    *  @name DataTable.defaults.column.title
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "title": "My column title", "targets": [ 0 ] }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "title": "My column title" },
    *          null,
    *          null,
    *          null,
    *          null
    *        ]
    *      } );
    *    } );
    */
    "sTitle": null,


    /**
    * The type allows you to specify how the data for this column will be
    * ordered. Four types (string, numeric, date and html (which will strip
    * HTML tags before ordering)) are currently available. Note that only date
    * formats understood by Javascript's Date() object will be accepted as type
    * date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string',
    * 'numeric', 'date' or 'html' (by default). Further types can be adding
    * through plug-ins.
    *  @type string
    *  @default null <i>Auto-detected from raw data</i>
    *
    *  @name DataTable.defaults.column.type
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "type": "html", "targets": [ 0 ] }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "type": "html" },
    *          null,
    *          null,
    *          null,
    *          null
    *        ]
    *      } );
    *    } );
    */
    "sType": null,


    /**
    * Defining the width of the column, this parameter may take any CSS value
    * (3em, 20px etc). DataTables applies 'smart' widths to columns which have not
    * been given a specific width through this interface ensuring that the table
    * remains readable.
    *  @type string
    *  @default null <i>Automatic</i>
    *
    *  @name DataTable.defaults.column.width
    *  @dtopt Columns
    *
    *  @example
    *    // Using `columnDefs`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columnDefs": [
    *          { "width": "20%", "targets": [ 0 ] }
    *        ]
    *      } );
    *    } );
    *
    *  @example
    *    // Using `columns`
    *    $(document).ready( function() {
    *      $('#example').dataTable( {
    *        "columns": [
    *          { "width": "20%" },
    *          null,
    *          null,
    *          null,
    *          null
    *        ]
    *      } );
    *    } );
    */
    "sWidth": null
};

_fnHungarianMap(DataTable.defaults.column);



/**
* DataTables settings object - this holds all the information needed for a
* given table, including configuration, data and current application of the
* table options. DataTables does not have a single instance for each DataTable
* with the settings attached to that instance, but rather instances of the
* DataTable "class" are created on-the-fly as needed (typically by a
* $().dataTable() call) and the settings object is then applied to that
* instance.
*
* Note that this object is related to {@link DataTable.defaults} but this
* one is the internal data store for DataTables's cache of columns. It should
* NOT be manipulated outside of DataTables. Any configuration should be done
* through the initialisation options.
*  @namespace
*  @todo Really should attach the settings object to individual instances so we
*    don't need to create new instances on each $().dataTable() call (if the
*    table already exists). It would also save passing oSettings around and
*    into every single function. However, this is a very significant
*    architecture change for DataTables and will almost certainly break
*    backwards compatibility with older installations. This is something that
*    will be done in 2.0.
*/
DataTable.models.oSettings = {
    /**
    * Primary features of DataTables and their enablement state.
    *  @namespace
    */
    "oFeatures": {

        /**
        * Flag to say if DataTables should automatically try to calculate the
        * optimum table and columns widths (true) or not (false).
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bAutoWidth": null,

        /**
        * Delay the creation of TR and TD elements until they are actually
        * needed by a driven page draw. This can give a significant speed
        * increase for Ajax source and Javascript source data, but makes no
        * difference at all fro DOM and server-side processing tables.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bDeferRender": null,

        /**
        * Enable filtering on the table or not. Note that if this is disabled
        * then there is no filtering at all on the table, including fnFilter.
        * To just remove the filtering input use sDom and remove the 'f' option.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bFilter": null,

        /**
        * Table information element (the 'Showing x of y records' div) enable
        * flag.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bInfo": null,

        /**
        * Present a user control allowing the end user to change the page size
        * when pagination is enabled.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bLengthChange": null,

        /**
        * Pagination enabled or not. Note that if this is disabled then length
        * changing must also be disabled.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bPaginate": null,

        /**
        * Processing indicator enable flag whenever DataTables is enacting a
        * user request - typically an Ajax request for server-side processing.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bProcessing": null,

        /**
        * Server-side processing enabled flag - when enabled DataTables will
        * get all data from the server for every draw - there is no filtering,
        * sorting or paging done on the client-side.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bServerSide": null,

        /**
        * Sorting enablement flag.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bSort": null,

        /**
        * Multi-column sorting
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bSortMulti": null,

        /**
        * Apply a class to the columns which are being sorted to provide a
        * visual highlight or not. This can slow things down when enabled since
        * there is a lot of DOM interaction.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bSortClasses": null,

        /**
        * State saving enablement flag.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bStateSave": null
    },


    /**
    * Scrolling settings for a table.
    *  @namespace
    */
    "oScroll": {
        /**
        * When the table is shorter in height than sScrollY, collapse the
        * table container down to the height of the table (when true).
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type boolean
        */
        "bCollapse": null,

        /**
        * Width of the scrollbar for the web-browser's platform. Calculated
        * during table initialisation.
        *  @type int
        *  @default 0
        */
        "iBarWidth": 0,

        /**
        * Viewport width for horizontal scrolling. Horizontal scrolling is
        * disabled if an empty string.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type string
        */
        "sX": null,

        /**
        * Width to expand the table to when using x-scrolling. Typically you
        * should not need to use this.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type string
        *  @deprecated
        */
        "sXInner": null,

        /**
        * Viewport height for vertical scrolling. Vertical scrolling is disabled
        * if an empty string.
        * Note that this parameter will be set by the initialisation routine. To
        * set a default use {@link DataTable.defaults}.
        *  @type string
        */
        "sY": null
    },

    /**
    * Language information for the table.
    *  @namespace
    *  @extends DataTable.defaults.oLanguage
    */
    "oLanguage": {
        /**
        * Information callback function. See
        * {@link DataTable.defaults.fnInfoCallback}
        *  @type function
        *  @default null
        */
        "fnInfoCallback": null
    },

    /**
    * Browser support parameters
    *  @namespace
    */
    "oBrowser": {
        /**
        * Indicate if the browser incorrectly calculates width:100% inside a
        * scrolling element (IE6/7)
        *  @type boolean
        *  @default false
        */
        "bScrollOversize": false,

        /**
        * Determine if the vertical scrollbar is on the right or left of the
        * scrolling container - needed for rtl language layout, although not
        * all browsers move the scrollbar (Safari).
        *  @type boolean
        *  @default false
        */
        "bScrollbarLeft": false
    },


    "ajax": null,


    /**
    * Array referencing the nodes which are used for the features. The
    * parameters of this object match what is allowed by sDom - i.e.
    *   <ul>
    *     <li>'l' - Length changing</li>
    *     <li>'f' - Filtering input</li>
    *     <li>'t' - The table!</li>
    *     <li>'i' - Information</li>
    *     <li>'p' - Pagination</li>
    *     <li>'r' - pRocessing</li>
    *   </ul>
    *  @type array
    *  @default []
    */
    "aanFeatures": [],

    /**
    * Store data information - see {@link DataTable.models.oRow} for detailed
    * information.
    *  @type array
    *  @default []
    */
    "aoData": [],

    /**
    * Array of indexes which are in the current display (after filtering etc)
    *  @type array
    *  @default []
    */
    "aiDisplay": [],

    /**
    * Array of indexes for display - no filtering
    *  @type array
    *  @default []
    */
    "aiDisplayMaster": [],

    /**
    * Store information about each column that is in use
    *  @type array
    *  @default []
    */
    "aoColumns": [],

    /**
    * Store information about the table's header
    *  @type array
    *  @default []
    */
    "aoHeader": [],

    /**
    * Store information about the table's footer
    *  @type array
    *  @default []
    */
    "aoFooter": [],

    /**
    * Store the applied global search information in case we want to force a
    * research or compare the old search to a new one.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @namespace
    *  @extends DataTable.models.oSearch
    */
    "oPreviousSearch": {},

    /**
    * Store the applied search for each column - see
    * {@link DataTable.models.oSearch} for the format that is used for the
    * filtering information for each column.
    *  @type array
    *  @default []
    */
    "aoPreSearchCols": [],

    /**
    * Sorting that is applied to the table. Note that the inner arrays are
    * used in the following manner:
    * <ul>
    *   <li>Index 0 - column number</li>
    *   <li>Index 1 - current sorting direction</li>
    * </ul>
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type array
    *  @todo These inner arrays should really be objects
    */
    "aaSorting": null,

    /**
    * Sorting that is always applied to the table (i.e. prefixed in front of
    * aaSorting).
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type array
    *  @default []
    */
    "aaSortingFixed": [],

    /**
    * Classes to use for the striping of a table.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type array
    *  @default []
    */
    "asStripeClasses": null,

    /**
    * If restoring a table - we should restore its striping classes as well
    *  @type array
    *  @default []
    */
    "asDestroyStripes": [],

    /**
    * If restoring a table - we should restore its width
    *  @type int
    *  @default 0
    */
    "sDestroyWidth": 0,

    /**
    * Callback functions array for every time a row is inserted (i.e. on a draw).
    *  @type array
    *  @default []
    */
    "aoRowCallback": [],

    /**
    * Callback functions for the header on each draw.
    *  @type array
    *  @default []
    */
    "aoHeaderCallback": [],

    /**
    * Callback function for the footer on each draw.
    *  @type array
    *  @default []
    */
    "aoFooterCallback": [],

    /**
    * Array of callback functions for draw callback functions
    *  @type array
    *  @default []
    */
    "aoDrawCallback": [],

    /**
    * Array of callback functions for row created function
    *  @type array
    *  @default []
    */
    "aoRowCreatedCallback": [],

    /**
    * Callback functions for just before the table is redrawn. A return of
    * false will be used to cancel the draw.
    *  @type array
    *  @default []
    */
    "aoPreDrawCallback": [],

    /**
    * Callback functions for when the table has been initialised.
    *  @type array
    *  @default []
    */
    "aoInitComplete": [],


    /**
    * Callbacks for modifying the settings to be stored for state saving, prior to
    * saving state.
    *  @type array
    *  @default []
    */
    "aoStateSaveParams": [],

    /**
    * Callbacks for modifying the settings that have been stored for state saving
    * prior to using the stored values to restore the state.
    *  @type array
    *  @default []
    */
    "aoStateLoadParams": [],

    /**
    * Callbacks for operating on the settings object once the saved state has been
    * loaded
    *  @type array
    *  @default []
    */
    "aoStateLoaded": [],

    /**
    * Cache the table ID for quick access
    *  @type string
    *  @default <i>Empty string</i>
    */
    "sTableId": "",

    /**
    * The TABLE node for the main table
    *  @type node
    *  @default null
    */
    "nTable": null,

    /**
    * Permanent ref to the thead element
    *  @type node
    *  @default null
    */
    "nTHead": null,

    /**
    * Permanent ref to the tfoot element - if it exists
    *  @type node
    *  @default null
    */
    "nTFoot": null,

    /**
    * Permanent ref to the tbody element
    *  @type node
    *  @default null
    */
    "nTBody": null,

    /**
    * Cache the wrapper node (contains all DataTables controlled elements)
    *  @type node
    *  @default null
    */
    "nTableWrapper": null,

    /**
    * Indicate if when using server-side processing the loading of data
    * should be deferred until the second draw.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type boolean
    *  @default false
    */
    "bDeferLoading": false,

    /**
    * Indicate if all required information has been read in
    *  @type boolean
    *  @default false
    */
    "bInitialised": false,

    /**
    * Information about open rows. Each object in the array has the parameters
    * 'nTr' and 'nParent'
    *  @type array
    *  @default []
    */
    "aoOpenRows": [],

    /**
    * Dictate the positioning of DataTables' control elements - see
    * {@link DataTable.model.oInit.sDom}.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type string
    *  @default null
    */
    "sDom": null,

    /**
    * Which type of pagination should be used.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type string
    *  @default two_button
    */
    "sPaginationType": "two_button",

    /**
    * The state duration (for `stateSave`) in seconds.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type int
    *  @default 0
    */
    "iStateDuration": 0,

    /**
    * Array of callback functions for state saving. Each array element is an
    * object with the following parameters:
    *   <ul>
    *     <li>function:fn - function to call. Takes two parameters, oSettings
    *       and the JSON string to save that has been thus far created. Returns
    *       a JSON string to be inserted into a json object
    *       (i.e. '"param": [ 0, 1, 2]')</li>
    *     <li>string:sName - name of callback</li>
    *   </ul>
    *  @type array
    *  @default []
    */
    "aoStateSave": [],

    /**
    * Array of callback functions for state loading. Each array element is an
    * object with the following parameters:
    *   <ul>
    *     <li>function:fn - function to call. Takes two parameters, oSettings
    *       and the object stored. May return false to cancel state loading</li>
    *     <li>string:sName - name of callback</li>
    *   </ul>
    *  @type array
    *  @default []
    */
    "aoStateLoad": [],

    /**
    * State that was loaded. Useful for back reference
    *  @type object
    *  @default null
    */
    "oLoadedState": null,

    /**
    * Source url for AJAX data for the table.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type string
    *  @default null
    */
    "sAjaxSource": null,

    /**
    * Property from a given object from which to read the table data from. This
    * can be an empty string (when not server-side processing), in which case
    * it is  assumed an an array is given directly.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type string
    */
    "sAjaxDataProp": null,

    /**
    * Note if draw should be blocked while getting data
    *  @type boolean
    *  @default true
    */
    "bAjaxDataGet": true,

    /**
    * The last jQuery XHR object that was used for server-side data gathering.
    * This can be used for working with the XHR information in one of the
    * callbacks
    *  @type object
    *  @default null
    */
    "jqXHR": null,

    /**
    * JSON returned from the server in the last Ajax request
    *  @type object
    *  @default undefined
    */
    "json": undefined,

    /**
    * Data submitted as part of the last Ajax request
    *  @type object
    *  @default undefined
    */
    "oAjaxData": undefined,

    /**
    * Function to get the server-side data.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type function
    */
    "fnServerData": null,

    /**
    * Functions which are called prior to sending an Ajax request so extra
    * parameters can easily be sent to the server
    *  @type array
    *  @default []
    */
    "aoServerParams": [],

    /**
    * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
    * required).
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type string
    */
    "sServerMethod": null,

    /**
    * Format numbers for display.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type function
    */
    "fnFormatNumber": null,

    /**
    * List of options that can be used for the user selectable length menu.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type array
    *  @default []
    */
    "aLengthMenu": null,

    /**
    * Counter for the draws that the table does. Also used as a tracker for
    * server-side processing
    *  @type int
    *  @default 0
    */
    "iDraw": 0,

    /**
    * Indicate if a redraw is being done - useful for Ajax
    *  @type boolean
    *  @default false
    */
    "bDrawing": false,

    /**
    * Draw index (iDraw) of the last error when parsing the returned data
    *  @type int
    *  @default -1
    */
    "iDrawError": -1,

    /**
    * Paging display length
    *  @type int
    *  @default 10
    */
    "_iDisplayLength": 10,

    /**
    * Paging start point - aiDisplay index
    *  @type int
    *  @default 0
    */
    "_iDisplayStart": 0,

    /**
    * Server-side processing - number of records in the result set
    * (i.e. before filtering), Use fnRecordsTotal rather than
    * this property to get the value of the number of records, regardless of
    * the server-side processing setting.
    *  @type int
    *  @default 0
    *  @private
    */
    "_iRecordsTotal": 0,

    /**
    * Server-side processing - number of records in the current display set
    * (i.e. after filtering). Use fnRecordsDisplay rather than
    * this property to get the value of the number of records, regardless of
    * the server-side processing setting.
    *  @type boolean
    *  @default 0
    *  @private
    */
    "_iRecordsDisplay": 0,

    /**
    * Flag to indicate if jQuery UI marking and classes should be used.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type boolean
    */
    "bJUI": null,

    /**
    * The classes to use for the table
    *  @type object
    *  @default {}
    */
    "oClasses": {},

    /**
    * Flag attached to the settings object so you can check in the draw
    * callback if filtering has been done in the draw. Deprecated in favour of
    * events.
    *  @type boolean
    *  @default false
    *  @deprecated
    */
    "bFiltered": false,

    /**
    * Flag attached to the settings object so you can check in the draw
    * callback if sorting has been done in the draw. Deprecated in favour of
    * events.
    *  @type boolean
    *  @default false
    *  @deprecated
    */
    "bSorted": false,

    /**
    * Indicate that if multiple rows are in the header and there is more than
    * one unique cell per column, if the top one (true) or bottom one (false)
    * should be used for sorting / title by DataTables.
    * Note that this parameter will be set by the initialisation routine. To
    * set a default use {@link DataTable.defaults}.
    *  @type boolean
    */
    "bSortCellsTop": null,

    /**
    * Initialisation object that is used for the table
    *  @type object
    *  @default null
    */
    "oInit": null,

    /**
    * Destroy callback functions - for plug-ins to attach themselves to the
    * destroy so they can clean up markup and events.
    *  @type array
    *  @default []
    */
    "aoDestroyCallback": [],


    /**
    * Get the number of records in the current record set, before filtering
    *  @type function
    */
    "fnRecordsTotal": function () {
        return _fnDataSource(this) == 'ssp' ?
				this._iRecordsTotal * 1 :
				this.aiDisplayMaster.length;
    },

    /**
    * Get the number of records in the current record set, after filtering
    *  @type function
    */
    "fnRecordsDisplay": function () {
        return _fnDataSource(this) == 'ssp' ?
				this._iRecordsDisplay * 1 :
				this.aiDisplay.length;
    },

    /**
    * Get the display end point - aiDisplay index
    *  @type function
    */
    "fnDisplayEnd": function () {
        var 
				len = this._iDisplayLength,
				start = this._iDisplayStart,
				calc = start + len,
				records = this.aiDisplay.length,
				features = this.oFeatures,
				paginate = features.bPaginate;

        if (features.bServerSide) {
            return paginate === false || len === -1 ?
					start + records :
					Math.min(start + len, this._iRecordsDisplay);
        }
        else {
            return !paginate || calc > records || len === -1 ?
					records :
					calc;
        }
    },

    /**
    * The DataTables object for this table
    *  @type object
    *  @default null
    */
    "oInstance": null,

    /**
    * Unique identifier for each instance of the DataTables object. If there
    * is an ID on the table node, then it takes that value, otherwise an
    * incrementing internal counter is used.
    *  @type string
    *  @default null
    */
    "sInstance": null,

    /**
    * tabindex attribute value that is added to DataTables control elements, allowing
    * keyboard navigation of the table and its controls.
    */
    "iTabIndex": 0,

    /**
    * DIV container for the footer scrolling table if scrolling
    */
    "nScrollHead": null,

    /**
    * DIV container for the footer scrolling table if scrolling
    */
    "nScrollFoot": null,

    /**
    * Last applied sort
    *  @type array
    *  @default []
    */
    "aLastSort": [],

    /**
    * Stored plug-in instances
    *  @type object
    *  @default {}
    */
    "oPlugins": {}
};

/**
* Extension object for DataTables that is used to provide all extension
* options.
*
* Note that the `DataTable.ext` object is available through
* `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is
* also aliased to `jQuery.fn.dataTableExt` for historic reasons.
*  @namespace
*  @extends DataTable.models.ext
*/


/**
* DataTables extensions
* 
* This namespace acts as a collection area for plug-ins that can be used to
* extend DataTables capabilities. Indeed many of the build in methods
* use this method to provide their own capabilities (sorting methods for
* example).
*
* Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy
* reasons
*
*  @namespace
*/
DataTable.ext = _ext = {
    /**
    * Element class names
    *
    *  @type object
    *  @default {}
    */
    classes: {},


    /**
    * Error reporting.
    * 
    * How should DataTables report an error. Can take the value 'alert' or
    * 'throw'
    *
    *  @type string
    *  @default alert
    */
    errMode: "alert",


    /**
    * Feature plug-ins.
    * 
    * This is an array of objects which describe the feature plug-ins that are
    * available to DataTables. These feature plug-ins are then available for
    * use through the `dom` initialisation option.
    * 
    * Each feature plug-in is described by an object which must have the
    * following properties:
    * 
    * * `fnInit` - function that is used to initialise the plug-in,
    * * `cFeature` - a character so the feature can be enabled by the `dom`
    *   instillation option. This is case sensitive.
    *
    * The `fnInit` function has the following input parameters:
    *
    * 1. `{object}` DataTables settings object: see
    *    {@link DataTable.models.oSettings}
    *
    * And the following return is expected:
    * 
    * * {node|null} The element which contains your feature. Note that the
    *   return may also be void if your plug-in does not require to inject any
    *   DOM elements into DataTables control (`dom`) - for example this might
    *   be useful when developing a plug-in which allows table control via
    *   keyboard entry
    *
    *  @type array
    *
    *  @example
    *    $.fn.dataTable.ext.features.push( {
    *      "fnInit": function( oSettings ) {
    *        return new TableTools( { "oDTSettings": oSettings } );
    *      },
    *      "cFeature": "T"
    *    } );
    */
    feature: [],


    /**
    * Row searching.
    * 
    * This method of searching is complimentary to the default type based
    * searching, and a lot more comprehensive as it allows you complete control
    * over the searching logic. Each element in this array is a function
    * (parameters described below) that is called for every row in the table,
    * and your logic decides if it should be included in the searching data set
    * or not.
    *
    * Searching functions have the following input parameters:
    *
    * 1. `{object}` DataTables settings object: see
    *    {@link DataTable.models.oSettings}
    * 2. `{array|object}` Data for the row to be processed (same as the
    *    original format that was passed in as the data source, or an array
    *    from a DOM data source
    * 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which
    *    can be useful to retrieve the `TR` element if you need DOM interaction.
    *
    * And the following return is expected:
    *
    * * {boolean} Include the row in the searched result set (true) or not
    *   (false)
    *
    * Note that as with the main search ability in DataTables, technically this
    * is "filtering", since it is subtractive. However, for consistency in
    * naming we call it searching here.
    *
    *  @type array
    *  @default []
    *
    *  @example
    *    // The following example shows custom search being applied to the
    *    // fourth column (i.e. the data[3] index) based on two input values
    *    // from the end-user, matching the data in a certain range.
    *    $.fn.dataTable.ext.search.push(
    *      function( settings, data, dataIndex ) {
    *        var min = document.getElementById('min').value * 1;
    *        var max = document.getElementById('max').value * 1;
    *        var version = data[3] == "-" ? 0 : data[3]*1;
    *
    *        if ( min == "" && max == "" ) {
    *          return true;
    *        }
    *        else if ( min == "" && version < max ) {
    *          return true;
    *        }
    *        else if ( min < version && "" == max ) {
    *          return true;
    *        }
    *        else if ( min < version && version < max ) {
    *          return true;
    *        }
    *        return false;
    *      }
    *    );
    */
    search: [],


    /**
    * Internal functions, exposed for used in plug-ins.
    * 
    * Please note that you should not need to use the internal methods for
    * anything other than a plug-in (and even then, try to avoid if possible).
    * The internal function may change between releases.
    *
    *  @type object
    *  @default {}
    */
    internal: {},


    /**
    * Legacy configuration options. Enable and disable legacy options that
    * are available in DataTables.
    *
    *  @type object
    */
    legacy: {
        /**
        * Enable / disable DataTables 1.9 compatible server-side processing
        * requests
        *
        *  @type boolean
        *  @default null
        */
        ajax: null
    },


    /**
    * Pagination plug-in methods.
    * 
    * Each entry in this object is a function and defines which buttons should
    * be shown by the pagination rendering method that is used for the table:
    * {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the
    * buttons are displayed in the document, while the functions here tell it
    * what buttons to display. This is done by returning an array of button
    * descriptions (what each button will do).
    *
    * Pagination types (the four built in options and any additional plug-in
    * options defined here) can be used through the `paginationType`
    * initialisation parameter.
    *
    * The functions defined take two parameters:
    *
    * 1. `{int} page` The current page index
    * 2. `{int} pages` The number of pages in the table
    *
    * Each function is expected to return an array where each element of the
    * array can be one of:
    *
    * * `first` - Jump to first page when activated
    * * `last` - Jump to last page when activated
    * * `previous` - Show previous page when activated
    * * `next` - Show next page when activated
    * * `{int}` - Show page of the index given
    * * `{array}` - A nested array containing the above elements to add a
    *   containing 'DIV' element (might be useful for styling).
    *
    * Note that DataTables v1.9- used this object slightly differently whereby
    * an object with two functions would be defined for each plug-in. That
    * ability is still supported by DataTables 1.10+ to provide backwards
    * compatibility, but this option of use is now decremented and no longer
    * documented in DataTables 1.10+.
    *
    *  @type object
    *  @default {}
    *
    *  @example
    *    // Show previous, next and current page buttons only
    *    $.fn.dataTableExt.oPagination.current = function ( page, pages ) {
    *      return [ 'previous', page, 'next' ];
    *    };
    */
    pager: {},


    renderer: {
        pageButton: {},
        header: {}
    },


    /**
    * Ordering plug-ins - custom data source
    * 
    * The extension options for ordering of data available here is complimentary
    * to the default type based ordering that DataTables typically uses. It
    * allows much greater control over the the data that is being used to
    * order a column, but is necessarily therefore more complex.
    * 
    * This type of ordering is useful if you want to do ordering based on data
    * live from the DOM (for example the contents of an 'input' element) rather
    * than just the static string that DataTables knows of.
    * 
    * The way these plug-ins work is that you create an array of the values you
    * wish to be ordering for the column in question and then return that
    * array. The data in the array much be in the index order of the rows in
    * the table (not the currently ordering order!). Which order data gathering
    * function is run here depends on the `dt-init columns.orderDataType`
    * parameter that is used for the column (if any).
    *
    * The functions defined take two parameters:
    *
    * 1. `{object}` DataTables settings object: see
    *    {@link DataTable.models.oSettings}
    * 2. `{int}` Target column index
    *
    * Each function is expected to return an array:
    *
    * * `{array}` Data for the column to be ordering upon
    *
    *  @type array
    *
    *  @example
    *    // Ordering using `input` node values
    *    $.fn.dataTable.ext.order['dom-text'] = function  ( settings, col )
    *    {
    *      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
    *        return $('input', td).val();
    *      } );
    *    }
    */
    order: {},


    /**
    * Type based plug-ins.
    *
    * Each column in DataTables has a type assigned to it, either by automatic
    * detection or by direct assignment using the `type` option for the column.
    * The type of a column will effect how it is ordering and search (plug-ins
    * can also make use of the column type if required).
    *
    * @namespace
    */
    type: {
        /**
        * Type detection functions.
        *
        * The functions defined in this object are used to automatically detect
        * a column's type, making initialisation of DataTables super easy, even
        * when complex data is in the table.
        *
        * The functions defined take two parameters:
        *
        *  1. `{*}` Data from the column cell to be analysed
        *  2. `{settings}` DataTables settings object. This can be used to
        *     perform context specific type detection - for example detection
        *     based on language settings such as using a comma for a decimal
        *     place. Generally speaking the options from the settings will not
        *     be required
        *
        * Each function is expected to return:
        *
        * * `{string|null}` Data type detected, or null if unknown (and thus
        *   pass it on to the other type detection functions.
        *
        *  @type array
        *
        *  @example
        *    // Currency type detection plug-in:
        *    $.fn.dataTable.ext.type.detect.push(
        *      function ( data, settings ) {
        *        // Check the numeric part
        *        if ( ! $.isNumeric( data.substring(1) ) ) {
        *          return null;
        *        }
        *
        *        // Check prefixed by currency
        *        if ( data.charAt(0) == '$' || data.charAt(0) == '&pound;' ) {
        *          return 'currency';
        *        }
        *        return null;
        *      }
        *    );
        */
        detect: [],


        /**
        * Type based search formatting.
        *
        * The type based searching functions can be used to pre-format the
        * data to be search on. For example, it can be used to strip HTML
        * tags or to de-format telephone numbers for numeric only searching.
        *
        * Note that is a search is not defined for a column of a given type,
        * no search formatting will be performed.
        * 
        * Pre-processing of searching data plug-ins - When you assign the sType
        * for a column (or have it automatically detected for you by DataTables
        * or a type detection plug-in), you will typically be using this for
        * custom sorting, but it can also be used to provide custom searching
        * by allowing you to pre-processing the data and returning the data in
        * the format that should be searched upon. This is done by adding
        * functions this object with a parameter name which matches the sType
        * for that target column. This is the corollary of <i>afnSortData</i>
        * for searching data.
        *
        * The functions defined take a single parameter:
        *
        *  1. `{*}` Data from the column cell to be prepared for searching
        *
        * Each function is expected to return:
        *
        * * `{string|null}` Formatted string that will be used for the searching.
        *
        *  @type object
        *  @default {}
        *
        *  @example
        *    $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
        *      return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
        *    }
        */
        search: {},


        /**
        * Type based ordering.
        *
        * The column type tells DataTables what ordering to apply to the table
        * when a column is sorted upon. The order for each type that is defined,
        * is defined by the functions available in this object.
        *
        * Each ordering option can be described by three properties added to
        * this object:
        *
        * * `{type}-pre` - Pre-formatting function
        * * `{type}-asc` - Ascending order function
        * * `{type}-desc` - Descending order function
        *
        * All three can be used together, only `{type}-pre` or only
        * `{type}-asc` and `{type}-desc` together. It is generally recommended
        * that only `{type}-pre` is used, as this provides the optimal
        * implementation in terms of speed, although the others are provided
        * for compatibility with existing Javascript sort functions.
        *
        * `{type}-pre`: Functions defined take a single parameter:
        *
        *  1. `{*}` Data from the column cell to be prepared for ordering
        *
        * And return:
        *
        * * `{*}` Data to be sorted upon
        *
        * `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort
        * functions, taking two parameters:
        *
        *  1. `{*}` Data to compare to the second parameter
        *  2. `{*}` Data to compare to the first parameter
        *
        * And returning:
        *
        * * `{*}` Ordering match: <0 if first parameter should be sorted lower
        *   than the second parameter, ===0 if the two parameters are equal and
        *   >0 if the first parameter should be sorted height than the second
        *   parameter.
        * 
        *  @type object
        *  @default {}
        *
        *  @example
        *    // Numeric ordering of formatted numbers with a pre-formatter
        *    $.extend( $.fn.dataTable.ext.type.order, {
        *      "string-pre": function(x) {
        *        a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" );
        *        return parseFloat( a );
        *      }
        *    } );
        *
        *  @example
        *    // Case-sensitive string ordering, with no pre-formatting method
        *    $.extend( $.fn.dataTable.ext.order, {
        *      "string-case-asc": function(x,y) {
        *        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        *      },
        *      "string-case-desc": function(x,y) {
        *        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
        *      }
        *    } );
        */
        order: {}
    },

    /**
    * Unique DataTables instance counter
    *
    * @type int
    * @private
    */
    _unique: 0,


    //
    // Depreciated
    // The following properties are retained for backwards compatiblity only.
    // The should not be used in new projects and will be removed in a future
    // version
    //

    /**
    * Version check function.
    *  @type function
    *  @depreciated Since 1.10
    */
    fnVersionCheck: DataTable.fnVersionCheck,


    /**
    * Index for what 'this' index API functions should use
    *  @type int
    *  @deprecated Since v1.10
    */
    iApiIndex: 0,


    /**
    * jQuery UI class container
    *  @type object
    *  @deprecated Since v1.10
    */
    oJUIClasses: {},


    /**
    * Software version
    *  @type string
    *  @deprecated Since v1.10
    */
    sVersion: DataTable.version
};


//
// Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts
//
$.extend(_ext, {
    afnFiltering: _ext.search,
    aTypes: _ext.type.detect,
    ofnSearch: _ext.type.search,
    oSort: _ext.type.order,
    afnSortData: _ext.order,
    aoFeatures: _ext.feature,
    oApi: _ext.internal,
    oStdClasses: _ext.classes,
    oPagination: _ext.pager
});


$.extend(DataTable.ext.classes, {
    "sTable": "dataTable",
    "sNoFooter": "no-footer",

    /* Paging buttons */
    "sPageButton": "paginate_button",
    "sPageButtonActive": "current",
    "sPageButtonDisabled": "disabled",

    /* Striping classes */
    "sStripeOdd": "odd",
    "sStripeEven": "even",

    /* Empty row */
    "sRowEmpty": "dataTables_empty",

    /* Features */
    "sWrapper": "dataTables_wrapper",
    "sFilter": "dataTables_filter",
    "sInfo": "dataTables_info",
    "sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */
    "sLength": "dataTables_length",
    "sProcessing": "dataTables_processing",

    /* Sorting */
    "sSortAsc": "sorting_asc",
    "sSortDesc": "sorting_desc",
    "sSortable": "sorting", /* Sortable in both directions */
    "sSortableAsc": "sorting_asc_disabled",
    "sSortableDesc": "sorting_desc_disabled",
    "sSortableNone": "sorting_disabled",
    "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */

    /* Filtering */
    "sFilterInput": "",

    /* Page length */
    "sLengthSelect": "",

    /* Scrolling */
    "sScrollWrapper": "dataTables_scroll",
    "sScrollHead": "dataTables_scrollHead",
    "sScrollHeadInner": "dataTables_scrollHeadInner",
    "sScrollBody": "dataTables_scrollBody",
    "sScrollFoot": "dataTables_scrollFoot",
    "sScrollFootInner": "dataTables_scrollFootInner",

    /* Misc */
    "sHeaderTH": "",
    "sFooterTH": "",

    // Deprecated
    "sSortJUIAsc": "",
    "sSortJUIDesc": "",
    "sSortJUI": "",
    "sSortJUIAscAllowed": "",
    "sSortJUIDescAllowed": "",
    "sSortJUIWrapper": "",
    "sSortIcon": "",
    "sJUIHeader": "",
    "sJUIFooter": ""
});


(function () {

    // Reused strings for better compression. Closure compiler appears to have a
    // weird edge case where it is trying to expand strings rather than use the
    // variable version. This results in about 200 bytes being added, for very
    // little preference benefit since it this run on script load only.
    var _empty = '';
    _empty = '';

    var _stateDefault = _empty + 'ui-state-default';
    var _sortIcon = _empty + 'css_right ui-icon ui-icon-';
    var _headerFooter = _empty + 'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix';

    $.extend(DataTable.ext.oJUIClasses, DataTable.ext.classes, {
        /* Full numbers paging buttons */
        "sPageButton": "fg-button ui-button " + _stateDefault,
        "sPageButtonActive": "ui-state-disabled",
        "sPageButtonDisabled": "ui-state-disabled",

        /* Features */
        "sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi " +
			"ui-buttonset-multi paging_", /* Note that the type is postfixed */

        /* Sorting */
        "sSortAsc": _stateDefault + " sorting_asc",
        "sSortDesc": _stateDefault + " sorting_desc",
        "sSortable": _stateDefault + " sorting",
        "sSortableAsc": _stateDefault + " sorting_asc_disabled",
        "sSortableDesc": _stateDefault + " sorting_desc_disabled",
        "sSortableNone": _stateDefault + " sorting_disabled",
        "sSortJUIAsc": _sortIcon + "triangle-1-n",
        "sSortJUIDesc": _sortIcon + "triangle-1-s",
        "sSortJUI": _sortIcon + "carat-2-n-s",
        "sSortJUIAscAllowed": _sortIcon + "carat-1-n",
        "sSortJUIDescAllowed": _sortIcon + "carat-1-s",
        "sSortJUIWrapper": "DataTables_sort_wrapper",
        "sSortIcon": "DataTables_sort_icon",

        /* Scrolling */
        "sScrollHead": "dataTables_scrollHead " + _stateDefault,
        "sScrollFoot": "dataTables_scrollFoot " + _stateDefault,

        /* Misc */
        "sHeaderTH": _stateDefault,
        "sFooterTH": _stateDefault,
        "sJUIHeader": _headerFooter + " ui-corner-tl ui-corner-tr",
        "sJUIFooter": _headerFooter + " ui-corner-bl ui-corner-br"
    });

} ());



var extPagination = DataTable.ext.pager;

function _numbers(page, pages) {
    var 
			numbers = [],
			buttons = extPagination.numbers_length,
			half = Math.floor(buttons / 2),
			i = 1;

    if (pages <= buttons) {
        numbers = _range(0, pages);
    }
    else if (page <= half) {
        numbers = _range(0, buttons - 2);
        numbers.push('ellipsis');
        numbers.push(pages - 1);
    }
    else if (page >= pages - 1 - half) {
        numbers = _range(pages - (buttons - 2), pages);
        numbers.splice(0, 0, 'ellipsis'); // no unshift in ie6
        numbers.splice(0, 0, 0);
    }
    else {
        numbers = _range(page - 1, page + 2);
        numbers.push('ellipsis');
        numbers.push(pages - 1);
        numbers.splice(0, 0, 'ellipsis');
        numbers.splice(0, 0, 0);
    }

    numbers.DT_el = 'span';
    return numbers;
}


$.extend(extPagination, {
    simple: function (page, pages) {
        return ['previous', 'next'];
    },

    full: function (page, pages) {
        return ['first', 'previous', 'next', 'last'];
    },

    simple_numbers: function (page, pages) {
        return ['previous', _numbers(page, pages), 'next'];
    },

    full_numbers: function (page, pages) {
        return ['first', 'previous', _numbers(page, pages), 'next', 'last'];
    },

    // For testing and plug-ins to use
    _numbers: _numbers,
    numbers_length: 7
});


$.extend(true, DataTable.ext.renderer, {
    pageButton: {
        _: function (settings, host, idx, buttons, page, pages) {
            var classes = settings.oClasses;
            var lang = settings.oLanguage.oPaginate;
            var btnDisplay, btnClass, counter = 0;

            var attach = function (container, buttons) {
                var i, ien, node, button;
                var clickHandler = function (e) {
                    _fnPageChange(settings, e.data.action, true);
                };

                for (i = 0, ien = buttons.length; i < ien; i++) {
                    button = buttons[i];

                    if ($.isArray(button)) {
                        var inner = $('<' + (button.DT_el || 'div') + '/>')
								.appendTo(container);
                        attach(inner, button);
                    }
                    else {
                        btnDisplay = '';
                        btnClass = '';

                        switch (button) {
                            case 'ellipsis':
                                container.append('<span>&hellip;</span>');
                                break;

                            case 'first':
                                btnDisplay = lang.sFirst;
                                btnClass = button + (page > 0 ?
										'' : ' ' + classes.sPageButtonDisabled);
                                break;

                            case 'previous':
                                btnDisplay = lang.sPrevious;
                                btnClass = button + (page > 0 ?
										'' : ' ' + classes.sPageButtonDisabled);
                                break;

                            case 'next':
                                btnDisplay = lang.sNext;
                                btnClass = button + (page < pages - 1 ?
										'' : ' ' + classes.sPageButtonDisabled);
                                break;

                            case 'last':
                                btnDisplay = lang.sLast;
                                btnClass = button + (page < pages - 1 ?
										'' : ' ' + classes.sPageButtonDisabled);
                                break;

                            default:
                                btnDisplay = button + 1;
                                btnClass = page === button ?
										classes.sPageButtonActive : '';
                                break;
                        }

                        if (btnDisplay) {
                            node = $('<a>', {
                                'class': classes.sPageButton + ' ' + btnClass,
                                'aria-controls': settings.sTableId,
                                'data-dt-idx': counter,
                                'tabindex': settings.iTabIndex,
                                'id': idx === 0 && typeof button === 'string' ?
											settings.sTableId + '_' + button :
											null
                            })
									.html(btnDisplay)
									.appendTo(container);

                            _fnBindAction(
									node, { action: button }, clickHandler
								);

                            counter++;
                        }
                    }
                }
            };

            // Because this approach is destroying and recreating the paging
            // elements, focus is lost on the select button which is bad for
            // accessibility. So we want to restore focus once the draw has
            // completed
            var activeEl = $(document.activeElement).data('dt-idx');

            attach($(host).empty(), buttons);

            if (activeEl !== null) {
                $(host).find('[data-dt-idx=' + activeEl + ']').focus();
            }
        }
    }
});



var __numericReplace = function (d, decimalPlace, re1, re2) {
    if (!d || d === '-') {
        return -Infinity;
    }

    // If a decimal place other than `.` is used, it needs to be given to the
    // function so we can detect it and replace with a `.` which is the only
    // decimal place Javascript recognises - it is not locale aware.
    if (decimalPlace) {
        d = _numToDecimal(d, decimalPlace);
    }

    if (d.replace) {
        if (re1) {
            d = d.replace(re1, '');
        }

        if (re2) {
            d = d.replace(re2, '');
        }
    }

    return d * 1;
};


// Add the numeric 'deformatting' functions for sorting. This is done in a
// function to provide an easy ability for the language options to add
// additional methods if a non-period decimal place is used.
function _addNumericSort(decimalPlace) {
    $.each(
			{
			    // Plain numbers
			    "num": function (d) {
			        return __numericReplace(d, decimalPlace);
			    },

			    // Formatted numbers
			    "num-fmt": function (d) {
			        return __numericReplace(d, decimalPlace, _re_formatted_numeric);
			    },

			    // HTML numeric
			    "html-num": function (d) {
			        return __numericReplace(d, decimalPlace, _re_html);
			    },

			    // HTML numeric, formatted
			    "html-num-fmt": function (d) {
			        return __numericReplace(d, decimalPlace, _re_html, _re_formatted_numeric);
			    }
			},
			function (key, fn) {
			    _ext.type.order[key + decimalPlace + '-pre'] = fn;
			}
		);
}


// Default sort methods
$.extend(_ext.type.order, {
    // Dates
    "date-pre": function (d) {
        return Date.parse(d) || 0;
    },

    // html
    "html-pre": function (a) {
        return !a ?
				'' :
				a.replace ?
					a.replace(/<.*?>/g, "").toLowerCase() :
					a + '';
    },

    // string
    "string-pre": function (a) {
        return typeof a === 'string' ?
				a.toLowerCase() :
				!a || !a.toString ?
					'' :
					a.toString();
    },

    // string-asc and -desc are retained only for compatibility with the old
    // sort methods
    "string-asc": function (x, y) {
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    },

    "string-desc": function (x, y) {
        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    }
});


// Numeric sorting types - order doesn't matter here
_addNumericSort('');


// Built in type detection. See model.ext.aTypes for information about
// what is required from this methods.
$.extend(DataTable.ext.type.detect, [
// Plain numbers - first since V8 detects some plain numbers as dates
// e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...).
		function (d, settings) {
		    var decimal = settings.oLanguage.sDecimal;
		    return _isNumber(d, decimal) ? 'num' + decimal : null;
		},

// Dates (only those recognised by the browser's Date.parse)
		function (d, settings) {
		    // V8 will remove any unknown characters at the start of the expression,
		    // leading to false matches such as `$245.12` being a valid date. See
		    // forum thread 18941 for detail.
		    if (d && !_re_date_start.test(d)) {
		        return null;
		    }
		    var parsed = Date.parse(d);
		    return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null;
		},

// Formatted numbers
		function (d, settings) {
		    var decimal = settings.oLanguage.sDecimal;
		    return _isNumber(d, decimal, true) ? 'num-fmt' + decimal : null;
		},

// HTML numeric
		function (d, settings) {
		    var decimal = settings.oLanguage.sDecimal;
		    return _htmlNumeric(d, decimal) ? 'html-num' + decimal : null;
		},

// HTML numeric, formatted
		function (d, settings) {
		    var decimal = settings.oLanguage.sDecimal;
		    return _htmlNumeric(d, decimal, true) ? 'html-num-fmt' + decimal : null;
		},

// HTML (this is strict checking - there must be html)
		function (d, settings) {
		    return _empty(d) || (typeof d === 'string' && d.indexOf('<') !== -1) ?
				'html' : null;
		}
	]);



// Filter formatting functions. See model.ext.ofnSearch for information about
// what is required from these methods.


$.extend(DataTable.ext.type.search, {
    html: function (data) {
        return _empty(data) ?
				'' :
				typeof data === 'string' ?
					data
						.replace(_re_new_lines, " ")
						.replace(_re_html, "") :
					'';
    },

    string: function (data) {
        return _empty(data) ?
				'' :
				typeof data === 'string' ?
					data.replace(_re_new_lines, " ") :
					data;
    }
});



$.extend(true, DataTable.ext.renderer, {
    header: {
        _: function (settings, cell, column, classes) {
            // No additional mark-up required
            // Attach a sort listener to update on sort - note that using the
            // `DT` namespace will allow the event to be removed automatically
            // on destroy, while the `dt` namespaced event is the one we are
            // listening for
            $(settings.nTable).on('order.dt.DT', function (e, settings, sorting, columns) {
                var colIdx = column.idx;

                cell
						.removeClass(
							column.sSortingClass + ' ' +
							classes.sSortAsc + ' ' +
							classes.sSortDesc
						)
						.addClass(columns[colIdx] == 'asc' ?
							classes.sSortAsc : columns[colIdx] == 'desc' ?
								classes.sSortDesc :
								column.sSortingClass
						);
            });
        },

        jqueryui: function (settings, cell, column, classes) {
            var colIdx = column.idx;

            $('<div/>')
					.addClass(classes.sSortJUIWrapper)
					.append(cell.contents())
					.append($('<span/>')
						.addClass(classes.sSortIcon + ' ' + column.sSortingClassJUI)
					)
					.appendTo(cell);

            // Attach a sort listener to update on sort
            $(settings.nTable).on('order.dt.DT', function (e, settings, sorting, columns) {
                cell
						.removeClass(classes.sSortAsc + " " + classes.sSortDesc)
						.addClass(columns[colIdx] == 'asc' ?
							classes.sSortAsc : columns[colIdx] == 'desc' ?
								classes.sSortDesc :
								column.sSortingClass
						);

                cell
						.find('span.' + classes.sSortIcon)
						.removeClass(
							classes.sSortJUIAsc + " " +
							classes.sSortJUIDesc + " " +
							classes.sSortJUI + " " +
							classes.sSortJUIAscAllowed + " " +
							classes.sSortJUIDescAllowed
						)
						.addClass(columns[colIdx] == 'asc' ?
							classes.sSortJUIAsc : columns[colIdx] == 'desc' ?
								classes.sSortJUIDesc :
								column.sSortingClassJUI
						);
            });
        }
    }
});

/*
* Public helper functions. These aren't used internally by DataTables, or
* called by any of the options passed into DataTables, but they can be used
* externally by developers working with DataTables. They are helper functions
* to make working with DataTables a little bit easier.
*/

/**
* Helpers for `columns.render`.
*
* The options defined here can be used with the `columns.render` initialisation
* option to provide a display renderer. The following functions are defined:
*
* * `number` - Will format numeric data (defined by `columns.data`) for
*   display, retaining the original unformatted data for sorting and filtering.
*   It takes 4 parameters:
*   * `string` - Thousands grouping separator
*   * `string` - Decimal point indicator
*   * `integer` - Number of decimal points to show
*   * `string` (optional) - Prefix.
*
* @example
*   // Column definition using the number renderer
*   {
*     data: "salary",
*     render: $.fn.dataTable.render.number( '\'', '.', 0, '$' )
*   }
*
* @namespace
*/
DataTable.render = {
    number: function (thousands, decimal, precision, prefix) {
        return {
            display: function (d) {
                d = parseFloat(d);
                var intPart = parseInt(d, 10);
                var floatPart = precision ?
						(decimal + (d - intPart).toFixed(precision)).substring(2) :
						'';

                return (prefix || '') +
						intPart.toString().replace(
							/\B(?=(\d{3})+(?!\d))/g, thousands
						) +
						floatPart;
            }
        };
    }
};


/*
* This is really a good bit rubbish this method of exposing the internal methods
* publicly... - To be fixed in 2.0 using methods on the prototype
*/


/**
* Create a wrapper function for exporting an internal functions to an external API.
*  @param {string} fn API function name
*  @returns {function} wrapped function
*  @memberof DataTable#internal
*/
function _fnExternApiFunc(fn) {
    return function () {
        var args = [_fnSettingsFromNode(this[DataTable.ext.iApiIndex])].concat(
				Array.prototype.slice.call(arguments)
			);
        return DataTable.ext.internal[fn].apply(this, args);
    };
}


/**
* Reference to internal functions for use by plug-in developers. Note that
* these methods are references to internal functions and are considered to be
* private. If you use these methods, be aware that they are liable to change
* between versions.
*  @namespace
*/
$.extend(DataTable.ext.internal, {
    _fnExternApiFunc: _fnExternApiFunc,
    _fnBuildAjax: _fnBuildAjax,
    _fnAjaxUpdate: _fnAjaxUpdate,
    _fnAjaxParameters: _fnAjaxParameters,
    _fnAjaxUpdateDraw: _fnAjaxUpdateDraw,
    _fnAjaxDataSrc: _fnAjaxDataSrc,
    _fnAddColumn: _fnAddColumn,
    _fnColumnOptions: _fnColumnOptions,
    _fnAdjustColumnSizing: _fnAdjustColumnSizing,
    _fnVisibleToColumnIndex: _fnVisibleToColumnIndex,
    _fnColumnIndexToVisible: _fnColumnIndexToVisible,
    _fnVisbleColumns: _fnVisbleColumns,
    _fnGetColumns: _fnGetColumns,
    _fnColumnTypes: _fnColumnTypes,
    _fnApplyColumnDefs: _fnApplyColumnDefs,
    _fnHungarianMap: _fnHungarianMap,
    _fnCamelToHungarian: _fnCamelToHungarian,
    _fnLanguageCompat: _fnLanguageCompat,
    _fnBrowserDetect: _fnBrowserDetect,
    _fnAddData: _fnAddData,
    _fnAddTr: _fnAddTr,
    _fnNodeToDataIndex: _fnNodeToDataIndex,
    _fnNodeToColumnIndex: _fnNodeToColumnIndex,
    _fnGetCellData: _fnGetCellData,
    _fnSetCellData: _fnSetCellData,
    _fnSplitObjNotation: _fnSplitObjNotation,
    _fnGetObjectDataFn: _fnGetObjectDataFn,
    _fnSetObjectDataFn: _fnSetObjectDataFn,
    _fnGetDataMaster: _fnGetDataMaster,
    _fnClearTable: _fnClearTable,
    _fnDeleteIndex: _fnDeleteIndex,
    _fnInvalidateRow: _fnInvalidateRow,
    _fnGetRowElements: _fnGetRowElements,
    _fnCreateTr: _fnCreateTr,
    _fnBuildHead: _fnBuildHead,
    _fnDrawHead: _fnDrawHead,
    _fnDraw: _fnDraw,
    _fnReDraw: _fnReDraw,
    _fnAddOptionsHtml: _fnAddOptionsHtml,
    _fnDetectHeader: _fnDetectHeader,
    _fnGetUniqueThs: _fnGetUniqueThs,
    _fnFeatureHtmlFilter: _fnFeatureHtmlFilter,
    _fnFilterComplete: _fnFilterComplete,
    _fnFilterCustom: _fnFilterCustom,
    _fnFilterColumn: _fnFilterColumn,
    _fnFilter: _fnFilter,
    _fnFilterCreateSearch: _fnFilterCreateSearch,
    _fnEscapeRegex: _fnEscapeRegex,
    _fnFilterData: _fnFilterData,
    _fnFeatureHtmlInfo: _fnFeatureHtmlInfo,
    _fnUpdateInfo: _fnUpdateInfo,
    _fnInfoMacros: _fnInfoMacros,
    _fnInitialise: _fnInitialise,
    _fnInitComplete: _fnInitComplete,
    _fnLengthChange: _fnLengthChange,
    _fnFeatureHtmlLength: _fnFeatureHtmlLength,
    _fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate,
    _fnPageChange: _fnPageChange,
    _fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing,
    _fnProcessingDisplay: _fnProcessingDisplay,
    _fnFeatureHtmlTable: _fnFeatureHtmlTable,
    _fnScrollDraw: _fnScrollDraw,
    _fnApplyToChildren: _fnApplyToChildren,
    _fnCalculateColumnWidths: _fnCalculateColumnWidths,
    _fnThrottle: _fnThrottle,
    _fnConvertToWidth: _fnConvertToWidth,
    _fnScrollingWidthAdjust: _fnScrollingWidthAdjust,
    _fnGetWidestNode: _fnGetWidestNode,
    _fnGetMaxLenString: _fnGetMaxLenString,
    _fnStringToCss: _fnStringToCss,
    _fnScrollBarWidth: _fnScrollBarWidth,
    _fnSortFlatten: _fnSortFlatten,
    _fnSort: _fnSort,
    _fnSortAria: _fnSortAria,
    _fnSortListener: _fnSortListener,
    _fnSortAttachListener: _fnSortAttachListener,
    _fnSortingClasses: _fnSortingClasses,
    _fnSortData: _fnSortData,
    _fnSaveState: _fnSaveState,
    _fnLoadState: _fnLoadState,
    _fnSettingsFromNode: _fnSettingsFromNode,
    _fnLog: _fnLog,
    _fnMap: _fnMap,
    _fnBindAction: _fnBindAction,
    _fnCallbackReg: _fnCallbackReg,
    _fnCallbackFire: _fnCallbackFire,
    _fnLengthOverflow: _fnLengthOverflow,
    _fnRenderer: _fnRenderer,
    _fnDataSource: _fnDataSource,
    _fnRowAttributes: _fnRowAttributes,
    _fnCalculateEnd: function () { } // Used by a lot of plug-ins, but redundant
    // in 1.10, so this dead-end function is
    // added to prevent errors
});


// jQuery access
$.fn.dataTable = DataTable;

// Legacy aliases
$.fn.dataTableSettings = DataTable.settings;
$.fn.dataTableExt = DataTable.ext;

// With a capital `D` we return a DataTables API instance rather than a
// jQuery object
$.fn.DataTable = function (opts) {
    return $(this).dataTable(opts).api();
};

// All properties that are available to $.fn.dataTable should also be
// available on $.fn.DataTable
$.each(DataTable, function (prop, val) {
    $.fn.DataTable[prop] = val;
});


// Information about events fired by DataTables - for documentation.
/**
* Draw event, fired whenever the table is redrawn on the page, at the same
* point as fnDrawCallback. This may be useful for binding events or
* performing calculations when the table is altered at all.
*  @name DataTable#draw.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/

/**
* Search event, fired when the searching applied to the table (using the
* built-in global search, or column filters) is altered.
*  @name DataTable#search.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/

/**
* Page change event, fired when the paging of the table is altered.
*  @name DataTable#page.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/

/**
* Order event, fired when the ordering applied to the table is altered.
*  @name DataTable#order.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/

/**
* DataTables initialisation complete event, fired when the table is fully
* drawn, including Ajax data loaded, if Ajax data is required.
*  @name DataTable#init.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} oSettings DataTables settings object
*  @param {object} json The JSON object request from the server - only
*    present if client-side Ajax sourced data is used</li></ol>
*/

/**
* State save event, fired when the table has changed state a new state save
* is required. This event allows modification of the state saving object
* prior to actually doing the save, including addition or other state
* properties (for plug-ins) or modification of a DataTables core property.
*  @name DataTable#stateSaveParams.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} oSettings DataTables settings object
*  @param {object} json The state information to be saved
*/

/**
* State load event, fired when the table is loading state from the stored
* data, but prior to the settings object being modified by the saved state
* - allowing modification of the saved state is required or loading of
* state for a plug-in.
*  @name DataTable#stateLoadParams.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} oSettings DataTables settings object
*  @param {object} json The saved state information
*/

/**
* State loaded event, fired when state has been loaded from stored data and
* the settings object has been modified by the loaded data.
*  @name DataTable#stateLoaded.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} oSettings DataTables settings object
*  @param {object} json The saved state information
*/

/**
* Processing event, fired when DataTables is doing some kind of processing
* (be it, order, searcg or anything else). It can be used to indicate to
* the end user that there is something happening, or that something has
* finished.
*  @name DataTable#processing.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} oSettings DataTables settings object
*  @param {boolean} bShow Flag for if DataTables is doing processing or not
*/

/**
* Ajax (XHR) event, fired whenever an Ajax request is completed from a
* request to made to the server for new data. This event is called before
* DataTables processed the returned data, so it can also be used to pre-
* process the data returned from the server, if needed.
*
* Note that this trigger is called in `fnServerData`, if you override
* `fnServerData` and which to use this event, you need to trigger it in you
* success function.
*  @name DataTable#xhr.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*  @param {object} json JSON returned from the server
*
*  @example
*     // Use a custom property returned from the server in another DOM element
*     $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
*       $('#status').html( json.status );
*     } );
*
*  @example
*     // Pre-process the data returned from the server
*     $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
*       for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) {
*         json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;
*       }
*       // Note no return - manipulate the data directly in the JSON object.
*     } );
*/

/**
* Destroy event, fired when the DataTable is destroyed by calling fnDestroy
* or passing the bDestroy:true parameter in the initialisation object. This
* can be used to remove bound events, added DOM nodes, etc.
*  @name DataTable#destroy.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/

/**
* Page length change event, fired when number of records to show on each
* page (the length) is changed.
*  @name DataTable#length.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*  @param {integer} len New length
*/

/**
* Column sizing has changed.
*  @name DataTable#column-sizing.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/

/**
* Column visibility has changed.
*  @name DataTable#column-visibility.dt
*  @event
*  @param {event} e jQuery event object
*  @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*  @param {int} column Column index
*  @param {bool} vis `false` if column now hidden, or `true` if visible
*/

return $.fn.dataTable;
}));

} (window, document));


// Simple Set Clipboard System
// Author: Joseph Huckaby

var ZeroClipboard_TableTools = {
	
	version: "1.0.4-TableTools2",
	clients: {}, // registered upload clients on page, indexed by id
	moviePath: '', // URL to movie
	nextId: 1, // ID of next movie
	
	$: function(thingy) {
		// simple DOM lookup utility function
		if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
		if (!thingy.addClass) {
			// extend element with a few useful methods
			thingy.hide = function() { this.style.display = 'none'; };
			thingy.show = function() { this.style.display = ''; };
			thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
			thingy.removeClass = function(name) {
				this.className = this.className.replace( new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, '');
			};
			thingy.hasClass = function(name) {
				return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
			}
		}
		return thingy;
	},
	
	setMoviePath: function(path) {
		// set path to ZeroClipboard.swf
		this.moviePath = path;
	},
	
	dispatch: function(id, eventName, args) {
		// receive event from flash movie, send to client		
		var client = this.clients[id];
		if (client) {
			client.receiveEvent(eventName, args);
		}
	},
	
	register: function(id, client) {
		// register new client to receive events
		this.clients[id] = client;
	},
	
	getDOMObjectPosition: function(obj) {
		// get absolute coordinates for dom element
		var info = {
			left: 0, 
			top: 0, 
			width: obj.width ? obj.width : obj.offsetWidth, 
			height: obj.height ? obj.height : obj.offsetHeight
		};
		
		if ( obj.style.width != "" )
			info.width = obj.style.width.replace("px","");
		
		if ( obj.style.height != "" )
			info.height = obj.style.height.replace("px","");

		while (obj) {
			info.left += obj.offsetLeft;
			info.top += obj.offsetTop;
			obj = obj.offsetParent;
		}

		return info;
	},
	
	Client: function(elem) {
		// constructor for new simple upload client
		this.handlers = {};
		
		// unique ID
		this.id = ZeroClipboard_TableTools.nextId++;
		this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id;
		
		// register client with singleton to receive flash events
		ZeroClipboard_TableTools.register(this.id, this);
		
		// create movie
		if (elem) this.glue(elem);
	}
};

ZeroClipboard_TableTools.Client.prototype = {
	
	id: 0, // unique ID for us
	ready: false, // whether movie is ready to receive events or not
	movie: null, // reference to movie object
	clipText: '', // text to copy to clipboard
	fileName: '', // default file save name
	action: 'copy', // action to perform
	handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
	cssEffects: true, // enable CSS mouse effects on dom container
	handlers: null, // user event handlers
	sized: false,
	
	glue: function(elem, title) {
		// glue to DOM element
		// elem can be ID or actual DOM element object
		this.domElement = ZeroClipboard_TableTools.$(elem);
		
		// float just above object, or zIndex 99 if dom element isn't set
		var zIndex = 99;
		if (this.domElement.style.zIndex) {
			zIndex = parseInt(this.domElement.style.zIndex) + 1;
		}
		
		// find X/Y position of domElement
		var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
		
		// create floating DIV above element
		this.div = document.createElement('div');
		var style = this.div.style;
		style.position = 'absolute';
		style.left = '0px';
		style.top = '0px';
		style.width = (box.width) + 'px';
		style.height = box.height + 'px';
		style.zIndex = zIndex;
		
		if ( typeof title != "undefined" && title != "" ) {
			this.div.title = title;
		}
		if ( box.width != 0 && box.height != 0 ) {
			this.sized = true;
		}
		
		// style.backgroundColor = '#f00'; // debug
		if ( this.domElement ) {
			this.domElement.appendChild(this.div);
			this.div.innerHTML = this.getHTML( box.width, box.height );
		}
	},
	
	positionElement: function() {
		var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
		var style = this.div.style;
		
		style.position = 'absolute';
		//style.left = (this.domElement.offsetLeft)+'px';
		//style.top = this.domElement.offsetTop+'px';
		style.width = box.width + 'px';
		style.height = box.height + 'px';
		
		if ( box.width != 0 && box.height != 0 ) {
			this.sized = true;
		} else {
			return;
		}
		
		var flash = this.div.childNodes[0];
		flash.width = box.width;
		flash.height = box.height;
	},
	
	getHTML: function(width, height) {
		// return HTML for movie
		var html = '';
		var flashvars = 'id=' + this.id + 
			'&width=' + width + 
			'&height=' + height;
			
		if (navigator.userAgent.match(/MSIE/)) {
			// IE gets an OBJECT tag
			var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
			html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard_TableTools.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
		}
		else {
			// all other browsers get an EMBED tag
			html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard_TableTools.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
		}
		return html;
	},
	
	hide: function() {
		// temporarily hide floater offscreen
		if (this.div) {
			this.div.style.left = '-2000px';
		}
	},
	
	show: function() {
		// show ourselves after a call to hide()
		this.reposition();
	},
	
	destroy: function() {
		// destroy control and floater
		if (this.domElement && this.div) {
			this.hide();
			this.div.innerHTML = '';
			
			var body = document.getElementsByTagName('body')[0];
			try { body.removeChild( this.div ); } catch(e) {;}
			
			this.domElement = null;
			this.div = null;
		}
	},
	
	reposition: function(elem) {
		// reposition our floating div, optionally to new container
		// warning: container CANNOT change size, only position
		if (elem) {
			this.domElement = ZeroClipboard_TableTools.$(elem);
			if (!this.domElement) this.hide();
		}
		
		if (this.domElement && this.div) {
			var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
			var style = this.div.style;
			style.left = '' + box.left + 'px';
			style.top = '' + box.top + 'px';
		}
	},
	
	clearText: function() {
		// clear the text to be copy / saved
		this.clipText = '';
		if (this.ready) this.movie.clearText();
	},
	
	appendText: function(newText) {
		// append text to that which is to be copied / saved
		this.clipText += newText;
		if (this.ready) { this.movie.appendText(newText) ;}
	},
	
	setText: function(newText) {
		// set text to be copied to be copied / saved
		this.clipText = newText;
		if (this.ready) { this.movie.setText(newText) ;}
	},
	
	setCharSet: function(charSet) {
		// set the character set (UTF16LE or UTF8)
		this.charSet = charSet;
		if (this.ready) { this.movie.setCharSet(charSet) ;}
	},
	
	setBomInc: function(bomInc) {
		// set if the BOM should be included or not
		this.incBom = bomInc;
		if (this.ready) { this.movie.setBomInc(bomInc) ;}
	},
	
	setFileName: function(newText) {
		// set the file name
		this.fileName = newText;
		if (this.ready) this.movie.setFileName(newText);
	},
	
	setAction: function(newText) {
		// set action (save or copy)
		this.action = newText;
		if (this.ready) this.movie.setAction(newText);
	},
	
	addEventListener: function(eventName, func) {
		// add user event listener for event
		// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');
		if (!this.handlers[eventName]) this.handlers[eventName] = [];
		this.handlers[eventName].push(func);
	},
	
	setHandCursor: function(enabled) {
		// enable hand cursor (true), or default arrow cursor (false)
		this.handCursorEnabled = enabled;
		if (this.ready) this.movie.setHandCursor(enabled);
	},
	
	setCSSEffects: function(enabled) {
		// enable or disable CSS effects on DOM container
		this.cssEffects = !!enabled;
	},
	
	receiveEvent: function(eventName, args) {
		// receive event from flash
		eventName = eventName.toString().toLowerCase().replace(/^on/, '');
		
		// special behavior for certain events
		switch (eventName) {
			case 'load':
				// movie claims it is ready, but in IE this isn't always the case...
				// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
				this.movie = document.getElementById(this.movieId);
				if (!this.movie) {
					var self = this;
					setTimeout( function() { self.receiveEvent('load', null); }, 1 );
					return;
				}
				
				// firefox on pc needs a "kick" in order to set these in certain cases
				if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
					var self = this;
					setTimeout( function() { self.receiveEvent('load', null); }, 100 );
					this.ready = true;
					return;
				}
				
				this.ready = true;
				this.movie.clearText();
				this.movie.appendText( this.clipText );
				this.movie.setFileName( this.fileName );
				this.movie.setAction( this.action );
				this.movie.setCharSet( this.charSet );
				this.movie.setBomInc( this.incBom );
				this.movie.setHandCursor( this.handCursorEnabled );
				break;
			
			case 'mouseover':
				if (this.domElement && this.cssEffects) {
					//this.domElement.addClass('hover');
					if (this.recoverActive) this.domElement.addClass('active');
				}
				break;
			
			case 'mouseout':
				if (this.domElement && this.cssEffects) {
					this.recoverActive = false;
					if (this.domElement.hasClass('active')) {
						this.domElement.removeClass('active');
						this.recoverActive = true;
					}
					//this.domElement.removeClass('hover');
				}
				break;
			
			case 'mousedown':
				if (this.domElement && this.cssEffects) {
					this.domElement.addClass('active');
				}
				break;
			
			case 'mouseup':
				if (this.domElement && this.cssEffects) {
					this.domElement.removeClass('active');
					this.recoverActive = false;
				}
				break;
		} // switch eventName
		
		if (this.handlers[eventName]) {
			for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
				var func = this.handlers[eventName][idx];
			
				if (typeof(func) == 'function') {
					// actual function reference
					func(this, args);
				}
				else if ((typeof(func) == 'object') && (func.length == 2)) {
					// PHP style object + method, i.e. [myObject, 'myMethod']
					func[0][ func[1] ](this, args);
				}
				else if (typeof(func) == 'string') {
					// name of function
					window[func](this, args);
				}
			} // foreach event handler defined
		} // user defined handler for event
	}
	
};

/*! TableTools 2.2.1
* 2009-2014 SpryMedia Ltd - datatables.net/license
*
* ZeroClipboard 1.0.4
* Author: Joseph Huckaby - MIT licensed
*/

/**
* @summary     TableTools
* @description Tools and buttons for DataTables
* @version     2.2.1
* @file        dataTables.tableTools.js
* @author      SpryMedia Ltd (www.sprymedia.co.uk)
* @contact     www.sprymedia.co.uk/contact
* @copyright   Copyright 2009-2014 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
*   MIT license - http://datatables.net/license/mit
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.datatables.net
*/


/* Global scope for TableTools for backwards compatibility.
* Will be removed in 2.3
*/
var TableTools;

(function (window, document, undefined) {


    var factory = function ($, DataTable) {
        "use strict";


        //include ZeroClipboard.js
        /* ZeroClipboard 1.0.4
        * Author: Joseph Huckaby
        */

        var ZeroClipboard_TableTools = {

            version: "1.0.4-TableTools2",
            clients: {}, // registered upload clients on page, indexed by id
            moviePath: '', // URL to movie
            nextId: 1, // ID of next movie

            $: function (thingy) {
                // simple DOM lookup utility function
                if (typeof (thingy) == 'string') {
                    thingy = document.getElementById(thingy);
                }
                if (!thingy.addClass) {
                    // extend element with a few useful methods
                    thingy.hide = function () { this.style.display = 'none'; };
                    thingy.show = function () { this.style.display = ''; };
                    thingy.addClass = function (name) { this.removeClass(name); this.className += ' ' + name; };
                    thingy.removeClass = function (name) {
                        this.className = this.className.replace(new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, '');
                    };
                    thingy.hasClass = function (name) {
                        return !!this.className.match(new RegExp("\\s*" + name + "\\s*"));
                    };
                }
                return thingy;
            },

            setMoviePath: function (path) {
                // set path to ZeroClipboard.swf
                this.moviePath = path;
            },

            dispatch: function (id, eventName, args) {
                // receive event from flash movie, send to client
                var client = this.clients[id];
                if (client) {
                    client.receiveEvent(eventName, args);
                }
            },

            register: function (id, client) {
                // register new client to receive events
                this.clients[id] = client;
            },

            getDOMObjectPosition: function (obj) {
                // get absolute coordinates for dom element
                var info = {
                    left: 0,
                    top: 0,
                    width: obj.width ? obj.width : obj.offsetWidth,
                    height: obj.height ? obj.height : obj.offsetHeight
                };

                if (obj.style.width !== "") {
                    info.width = obj.style.width.replace("px", "");
                }

                if (obj.style.height !== "") {
                    info.height = obj.style.height.replace("px", "");
                }

                while (obj) {
                    info.left += obj.offsetLeft;
                    info.top += obj.offsetTop;
                    obj = obj.offsetParent;
                }

                return info;
            },

            Client: function (elem) {
                // constructor for new simple upload client
                this.handlers = {};

                // unique ID
                this.id = ZeroClipboard_TableTools.nextId++;
                this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id;

                // register client with singleton to receive flash events
                ZeroClipboard_TableTools.register(this.id, this);

                // create movie
                if (elem) {
                    this.glue(elem);
                }
            }
        };

        ZeroClipboard_TableTools.Client.prototype = {

            id: 0, // unique ID for us
            ready: false, // whether movie is ready to receive events or not
            movie: null, // reference to movie object
            clipText: '', // text to copy to clipboard
            fileName: '', // default file save name
            action: 'copy', // action to perform
            handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
            cssEffects: true, // enable CSS mouse effects on dom container
            handlers: null, // user event handlers
            sized: false,

            glue: function (elem, title) {
                // glue to DOM element
                // elem can be ID or actual DOM element object
                this.domElement = ZeroClipboard_TableTools.$(elem);

                // float just above object, or zIndex 99 if dom element isn't set
                var zIndex = 99;
                if (this.domElement.style.zIndex) {
                    zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
                }

                // find X/Y position of domElement
                var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);

                // create floating DIV above element
                this.div = document.createElement('div');
                var style = this.div.style;
                style.position = 'absolute';
                style.left = '0px';
                style.top = '0px';
                style.width = (box.width) + 'px';
                style.height = box.height + 'px';
                style.zIndex = zIndex;

                if (typeof title != "undefined" && title !== "") {
                    this.div.title = title;
                }
                if (box.width !== 0 && box.height !== 0) {
                    this.sized = true;
                }

                // style.backgroundColor = '#f00'; // debug
                if (this.domElement) {
                    this.domElement.appendChild(this.div);
                    this.div.innerHTML = this.getHTML(box.width, box.height).replace(/&/g, '&amp;');
                }
            },

            positionElement: function () {
                var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
                var style = this.div.style;

                style.position = 'absolute';
                //style.left = (this.domElement.offsetLeft)+'px';
                //style.top = this.domElement.offsetTop+'px';
                style.width = box.width + 'px';
                style.height = box.height + 'px';

                if (box.width !== 0 && box.height !== 0) {
                    this.sized = true;
                } else {
                    return;
                }

                var flash = this.div.childNodes[0];
                flash.width = box.width;
                flash.height = box.height;
            },

            getHTML: function (width, height) {
                // return HTML for movie
                var html = '';
                var flashvars = 'id=' + this.id +
			'&width=' + width +
			'&height=' + height;

                if (navigator.userAgent.match(/MSIE/)) {
                    // IE gets an OBJECT tag
                    var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
                    html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + protocol + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="' + width + '" height="' + height + '" id="' + this.movieId + '" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="' + ZeroClipboard_TableTools.moviePath + '" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="' + flashvars + '"/><param name="wmode" value="transparent"/></object>';
                }
                else {
                    // all other browsers get an EMBED tag
                    html += '<embed id="' + this.movieId + '" src="' + ZeroClipboard_TableTools.moviePath + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="' + this.movieId + '" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" wmode="transparent" />';
                }
                return html;
            },

            hide: function () {
                // temporarily hide floater offscreen
                if (this.div) {
                    this.div.style.left = '-2000px';
                }
            },

            show: function () {
                // show ourselves after a call to hide()
                this.reposition();
            },

            destroy: function () {
                // destroy control and floater
                if (this.domElement && this.div) {
                    this.hide();
                    this.div.innerHTML = '';

                    var body = document.getElementsByTagName('body')[0];
                    try { body.removeChild(this.div); } catch (e) { }

                    this.domElement = null;
                    this.div = null;
                }
            },

            reposition: function (elem) {
                // reposition our floating div, optionally to new container
                // warning: container CANNOT change size, only position
                if (elem) {
                    this.domElement = ZeroClipboard_TableTools.$(elem);
                    if (!this.domElement) {
                        this.hide();
                    }
                }

                if (this.domElement && this.div) {
                    var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
                    var style = this.div.style;
                    style.left = '' + box.left + 'px';
                    style.top = '' + box.top + 'px';
                }
            },

            clearText: function () {
                // clear the text to be copy / saved
                this.clipText = '';
                if (this.ready) {
                    this.movie.clearText();
                }
            },

            appendText: function (newText) {
                // append text to that which is to be copied / saved
                this.clipText += newText;
                if (this.ready) { this.movie.appendText(newText); }
            },

            setText: function (newText) {
                // set text to be copied to be copied / saved
                this.clipText = newText;
                if (this.ready) { this.movie.setText(newText); }
            },

            setCharSet: function (charSet) {
                // set the character set (UTF16LE or UTF8)
                this.charSet = charSet;
                if (this.ready) { this.movie.setCharSet(charSet); }
            },

            setBomInc: function (bomInc) {
                // set if the BOM should be included or not
                this.incBom = bomInc;
                if (this.ready) { this.movie.setBomInc(bomInc); }
            },

            setFileName: function (newText) {
                // set the file name
                this.fileName = newText;
                if (this.ready) {
                    this.movie.setFileName(newText);
                }
            },

            setAction: function (newText) {
                // set action (save or copy)
                this.action = newText;
                if (this.ready) {
                    this.movie.setAction(newText);
                }
            },

            addEventListener: function (eventName, func) {
                // add user event listener for event
                // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
                eventName = eventName.toString().toLowerCase().replace(/^on/, '');
                if (!this.handlers[eventName]) {
                    this.handlers[eventName] = [];
                }
                this.handlers[eventName].push(func);
            },

            setHandCursor: function (enabled) {
                // enable hand cursor (true), or default arrow cursor (false)
                this.handCursorEnabled = enabled;
                if (this.ready) {
                    this.movie.setHandCursor(enabled);
                }
            },

            setCSSEffects: function (enabled) {
                // enable or disable CSS effects on DOM container
                this.cssEffects = !!enabled;
            },

            receiveEvent: function (eventName, args) {
                var self;

                // receive event from flash
                eventName = eventName.toString().toLowerCase().replace(/^on/, '');

                // special behavior for certain events
                switch (eventName) {
                    case 'load':
                        // movie claims it is ready, but in IE this isn't always the case...
                        // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
                        this.movie = document.getElementById(this.movieId);
                        if (!this.movie) {
                            self = this;
                            setTimeout(function () { self.receiveEvent('load', null); }, 1);
                            return;
                        }

                        // firefox on pc needs a "kick" in order to set these in certain cases
                        if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
                            self = this;
                            setTimeout(function () { self.receiveEvent('load', null); }, 100);
                            this.ready = true;
                            return;
                        }

                        this.ready = true;
                        this.movie.clearText();
                        this.movie.appendText(this.clipText);
                        this.movie.setFileName(this.fileName);
                        this.movie.setAction(this.action);
                        this.movie.setCharSet(this.charSet);
                        this.movie.setBomInc(this.incBom);
                        this.movie.setHandCursor(this.handCursorEnabled);
                        break;

                    case 'mouseover':
                        if (this.domElement && this.cssEffects) {
                            //this.domElement.addClass('hover');
                            if (this.recoverActive) {
                                this.domElement.addClass('active');
                            }
                        }
                        break;

                    case 'mouseout':
                        if (this.domElement && this.cssEffects) {
                            this.recoverActive = false;
                            if (this.domElement.hasClass('active')) {
                                this.domElement.removeClass('active');
                                this.recoverActive = true;
                            }
                            //this.domElement.removeClass('hover');
                        }
                        break;

                    case 'mousedown':
                        if (this.domElement && this.cssEffects) {
                            this.domElement.addClass('active');
                        }
                        break;

                    case 'mouseup':
                        if (this.domElement && this.cssEffects) {
                            this.domElement.removeClass('active');
                            this.recoverActive = false;
                        }
                        break;
                } // switch eventName

                if (this.handlers[eventName]) {
                    for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
                        var func = this.handlers[eventName][idx];

                        if (typeof (func) == 'function') {
                            // actual function reference
                            func(this, args);
                        }
                        else if ((typeof (func) == 'object') && (func.length == 2)) {
                            // PHP style object + method, i.e. [myObject, 'myMethod']
                            func[0][func[1]](this, args);
                        }
                        else if (typeof (func) == 'string') {
                            // name of function
                            window[func](this, args);
                        }
                    } // foreach event handler defined
                } // user defined handler for event
            }

        };

        // For the Flash binding to work, ZeroClipboard_TableTools must be on the global
        // object list
        window.ZeroClipboard_TableTools = ZeroClipboard_TableTools;
        //include TableTools.js
        /* TableTools
        * 2009-2014 SpryMedia Ltd - datatables.net/license
        */

        /*globals TableTools,ZeroClipboard_TableTools*/


        (function ($, window, document) {

            /** 
            * TableTools provides flexible buttons and other tools for a DataTables enhanced table
            * @class TableTools
            * @constructor
            * @param {Object} oDT DataTables instance. When using DataTables 1.10 this can
            *   also be a jQuery collection, jQuery selector, table node, DataTables API
            *   instance or DataTables settings object.
            * @param {Object} oOpts TableTools options
            * @param {String} oOpts.sSwfPath ZeroClipboard SWF path
            * @param {String} oOpts.sRowSelect Row selection options - 'none', 'single', 'multi' or 'os'
            * @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection
            * @param {Function} oOpts.fnRowSelected Callback function just after row selection
            * @param {Function} oOpts.fnRowDeselected Callback function when row is deselected
            * @param {Array} oOpts.aButtons List of buttons to be used
            */
            TableTools = function (oDT, oOpts) {
                /* Santiy check that we are a new instance */
                if (!this instanceof TableTools) {
                    alert("Warning: TableTools must be initialised with the keyword 'new'");
                }

                // In 1.10 we can use the API to get the settings object from a number of
                // sources
                var dtSettings = $.fn.dataTable.Api ?
		new $.fn.dataTable.Api(oDT).settings()[0] :
		oDT.fnSettings();


                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Public class variables
                * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

                /**
                * @namespace Settings object which contains customisable information for TableTools instance
                */
                this.s = {
                    /**
                    * Store 'this' so the instance can be retrieved from the settings object
                    * @property that
                    * @type	 object
                    * @default  this
                    */
                    "that": this,

                    /** 
                    * DataTables settings objects
                    * @property dt
                    * @type	 object
                    * @default  <i>From the oDT init option</i>
                    */
                    "dt": dtSettings,

                    /**
                    * @namespace Print specific information
                    */
                    "print": {
                        /** 
                        * DataTables draw 'start' point before the printing display was shown
                        *  @property saveStart
                        *  @type	 int
                        *  @default  -1
                        */
                        "saveStart": -1,

                        /** 
                        * DataTables draw 'length' point before the printing display was shown
                        *  @property saveLength
                        *  @type	 int
                        *  @default  -1
                        */
                        "saveLength": -1,

                        /** 
                        * Page scrolling point before the printing display was shown so it can be restored
                        *  @property saveScroll
                        *  @type	 int
                        *  @default  -1
                        */
                        "saveScroll": -1,

                        /** 
                        * Wrapped function to end the print display (to maintain scope)
                        *  @property funcEnd
                        *  @type	 Function
                        *  @default  function () {}
                        */
                        "funcEnd": function () { }
                    },

                    /**
                    * A unique ID is assigned to each button in each instance
                    * @property buttonCounter
                    *  @type	 int
                    * @default  0
                    */
                    "buttonCounter": 0,

                    /**
                    * @namespace Select rows specific information
                    */
                    "select": {
                        /**
                        * Select type - can be 'none', 'single' or 'multi'
                        * @property type
                        *  @type	 string
                        * @default  ""
                        */
                        "type": "",

                        /**
                        * Array of nodes which are currently selected
                        *  @property selected
                        *  @type	 array
                        *  @default  []
                        */
                        "selected": [],

                        /**
                        * Function to run before the selection can take place. Will cancel the select if the
                        * function returns false
                        *  @property preRowSelect
                        *  @type	 Function
                        *  @default  null
                        */
                        "preRowSelect": null,

                        /**
                        * Function to run when a row is selected
                        *  @property postSelected
                        *  @type	 Function
                        *  @default  null
                        */
                        "postSelected": null,

                        /**
                        * Function to run when a row is deselected
                        *  @property postDeselected
                        *  @type	 Function
                        *  @default  null
                        */
                        "postDeselected": null,

                        /**
                        * Indicate if all rows are selected (needed for server-side processing)
                        *  @property all
                        *  @type	 boolean
                        *  @default  false
                        */
                        "all": false,

                        /**
                        * Class name to add to selected TR nodes
                        *  @property selectedClass
                        *  @type	 String
                        *  @default  ""
                        */
                        "selectedClass": ""
                    },

                    /**
                    * Store of the user input customisation object
                    *  @property custom
                    *  @type	 object
                    *  @default  {}
                    */
                    "custom": {},

                    /**
                    * SWF movie path
                    *  @property swfPath
                    *  @type	 string
                    *  @default  ""
                    */
                    "swfPath": "",

                    /**
                    * Default button set
                    *  @property buttonSet
                    *  @type	 array
                    *  @default  []
                    */
                    "buttonSet": [],

                    /**
                    * When there is more than one TableTools instance for a DataTable, there must be a 
                    * master which controls events (row selection etc)
                    *  @property master
                    *  @type	 boolean
                    *  @default  false
                    */
                    "master": false,

                    /**
                    * Tag names that are used for creating collections and buttons
                    *  @namesapce
                    */
                    "tags": {}
                };


                /**
                * @namespace Common and useful DOM elements for the class instance
                */
                this.dom = {
                    /**
                    * DIV element that is create and all TableTools buttons (and their children) put into
                    *  @property container
                    *  @type	 node
                    *  @default  null
                    */
                    "container": null,

                    /**
                    * The table node to which TableTools will be applied
                    *  @property table
                    *  @type	 node
                    *  @default  null
                    */
                    "table": null,

                    /**
                    * @namespace Nodes used for the print display
                    */
                    "print": {
                        /**
                        * Nodes which have been removed from the display by setting them to display none
                        *  @property hidden
                        *  @type	 array
                        *  @default  []
                        */
                        "hidden": [],

                        /**
                        * The information display saying telling the user about the print display
                        *  @property message
                        *  @type	 node
                        *  @default  null
                        */
                        "message": null
                    },

                    /**
                    * @namespace Nodes used for a collection display. This contains the currently used collection
                    */
                    "collection": {
                        /**
                        * The div wrapper containing the buttons in the collection (i.e. the menu)
                        *  @property collection
                        *  @type	 node
                        *  @default  null
                        */
                        "collection": null,

                        /**
                        * Background display to provide focus and capture events
                        *  @property background
                        *  @type	 node
                        *  @default  null
                        */
                        "background": null
                    }
                };

                /**
                * @namespace Name space for the classes that this TableTools instance will use
                * @extends TableTools.classes
                */
                this.classes = $.extend(true, {}, TableTools.classes);
                if (this.s.dt.bJUI) {
                    $.extend(true, this.classes, TableTools.classes_themeroller);
                }


                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Public class methods
                * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

                /**
                * Retreieve the settings object from an instance
                *  @method fnSettings
                *  @returns {object} TableTools settings object
                */
                this.fnSettings = function () {
                    return this.s;
                };


                /* Constructor logic */
                if (typeof oOpts == 'undefined') {
                    oOpts = {};
                }

                this._fnConstruct(oOpts);

                return this;
            };



            TableTools.prototype = {
                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Public methods
                * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

                /**
                * Retreieve the settings object from an instance
                *  @returns {array} List of TR nodes which are currently selected
                *  @param {boolean} [filtered=false] Get only selected rows which are  
                *    available given the filtering applied to the table. By default
                *    this is false -  i.e. all rows, regardless of filtering are 
                selected.
                */
                "fnGetSelected": function (filtered) {
                    var 
			out = [],
			data = this.s.dt.aoData,
			displayed = this.s.dt.aiDisplay,
			i, iLen;

                    if (filtered) {
                        // Only consider filtered rows
                        for (i = 0, iLen = displayed.length; i < iLen; i++) {
                            if (data[displayed[i]]._DTTT_selected) {
                                out.push(data[displayed[i]].nTr);
                            }
                        }
                    }
                    else {
                        // Use all rows
                        for (i = 0, iLen = data.length; i < iLen; i++) {
                            if (data[i]._DTTT_selected) {
                                out.push(data[i].nTr);
                            }
                        }
                    }

                    return out;
                },


                /**
                * Get the data source objects/arrays from DataTables for the selected rows (same as
                * fnGetSelected followed by fnGetData on each row from the table)
                *  @returns {array} Data from the TR nodes which are currently selected
                */
                "fnGetSelectedData": function () {
                    var out = [];
                    var data = this.s.dt.aoData;
                    var i, iLen;

                    for (i = 0, iLen = data.length; i < iLen; i++) {
                        if (data[i]._DTTT_selected) {
                            out.push(this.s.dt.oInstance.fnGetData(i));
                        }
                    }

                    return out;
                },


                /**
                * Check to see if a current row is selected or not
                *  @param {Node} n TR node to check if it is currently selected or not
                *  @returns {Boolean} true if select, false otherwise
                */
                "fnIsSelected": function (n) {
                    var pos = this.s.dt.oInstance.fnGetPosition(n);
                    return (this.s.dt.aoData[pos]._DTTT_selected === true) ? true : false;
                },


                /**
                * Select all rows in the table
                *  @param {boolean} [filtered=false] Select only rows which are available 
                *    given the filtering applied to the table. By default this is false - 
                *    i.e. all rows, regardless of filtering are selected.
                */
                "fnSelectAll": function (filtered) {
                    var s = this._fnGetMasterSettings();

                    this._fnRowSelect((filtered === true) ?
			s.dt.aiDisplay :
			s.dt.aoData
		);
                },


                /**
                * Deselect all rows in the table
                *  @param {boolean} [filtered=false] Deselect only rows which are available 
                *    given the filtering applied to the table. By default this is false - 
                *    i.e. all rows, regardless of filtering are deselected.
                */
                "fnSelectNone": function (filtered) {
                    var s = this._fnGetMasterSettings();

                    this._fnRowDeselect(this.fnGetSelected(filtered));
                },


                /**
                * Select row(s)
                *  @param {node|object|array} n The row(s) to select. Can be a single DOM
                *    TR node, an array of TR nodes or a jQuery object.
                */
                "fnSelect": function (n) {
                    if (this.s.select.type == "single") {
                        this.fnSelectNone();
                        this._fnRowSelect(n);
                    }
                    else {
                        this._fnRowSelect(n);
                    }
                },


                /**
                * Deselect row(s)
                *  @param {node|object|array} n The row(s) to deselect. Can be a single DOM
                *    TR node, an array of TR nodes or a jQuery object.
                */
                "fnDeselect": function (n) {
                    this._fnRowDeselect(n);
                },


                /**
                * Get the title of the document - useful for file names. The title is retrieved from either
                * the configuration object's 'title' parameter, or the HTML document title
                *  @param   {Object} oConfig Button configuration object
                *  @returns {String} Button title
                */
                "fnGetTitle": function (oConfig) {
                    var sTitle = "";
                    if (typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "") {
                        sTitle = oConfig.sTitle;
                    } else {
                        var anTitle = document.getElementsByTagName('title');
                        if (anTitle.length > 0) {
                            sTitle = anTitle[0].innerHTML;
                        }
                    }

                    /* Strip characters which the OS will object to - checking for UTF8 support in the scripting
                    * engine
                    */
                    if ("\u00A1".toString().length < 4) {
                        return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, "");
                    } else {
                        return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, "");
                    }
                },


                /**
                * Calculate a unity array with the column width by proportion for a set of columns to be
                * included for a button. This is particularly useful for PDF creation, where we can use the
                * column widths calculated by the browser to size the columns in the PDF.
                *  @param   {Object} oConfig Button configuration object
                *  @returns {Array} Unity array of column ratios
                */
                "fnCalcColRatios": function (oConfig) {
                    var 
			aoCols = this.s.dt.aoColumns,
			aColumnsInc = this._fnColumnTargets(oConfig.mColumns),
			aColWidths = [],
			iWidth = 0, iTotal = 0, i, iLen;

                    for (i = 0, iLen = aColumnsInc.length; i < iLen; i++) {
                        if (aColumnsInc[i]) {
                            iWidth = aoCols[i].nTh.offsetWidth;
                            iTotal += iWidth;
                            aColWidths.push(iWidth);
                        }
                    }

                    for (i = 0, iLen = aColWidths.length; i < iLen; i++) {
                        aColWidths[i] = aColWidths[i] / iTotal;
                    }

                    return aColWidths.join('\t');
                },


                /**
                * Get the information contained in a table as a string
                *  @param   {Object} oConfig Button configuration object
                *  @returns {String} Table data as a string
                */
                "fnGetTableData": function (oConfig) {
                    /* In future this could be used to get data from a plain HTML source as well as DataTables */
                    if (this.s.dt) {
                        return this._fnGetDataTablesData(oConfig);
                    }
                },


                /**
                * Pass text to a flash button instance, which will be used on the button's click handler
                *  @param   {Object} clip Flash button object
                *  @param   {String} text Text to set
                */
                "fnSetText": function (clip, text) {
                    this._fnFlashSetText(clip, text);
                },


                /**
                * Resize the flash elements of the buttons attached to this TableTools instance - this is
                * useful for when initialising TableTools when it is hidden (display:none) since sizes can't
                * be calculated at that time.
                */
                "fnResizeButtons": function () {
                    for (var cli in ZeroClipboard_TableTools.clients) {
                        if (cli) {
                            var client = ZeroClipboard_TableTools.clients[cli];
                            if (typeof client.domElement != 'undefined' &&
					 client.domElement.parentNode) {
                                client.positionElement();
                            }
                        }
                    }
                },


                /**
                * Check to see if any of the ZeroClipboard client's attached need to be resized
                */
                "fnResizeRequired": function () {
                    for (var cli in ZeroClipboard_TableTools.clients) {
                        if (cli) {
                            var client = ZeroClipboard_TableTools.clients[cli];
                            if (typeof client.domElement != 'undefined' &&
					 client.domElement.parentNode == this.dom.container &&
					 client.sized === false) {
                                return true;
                            }
                        }
                    }
                    return false;
                },


                /**
                * Programmatically enable or disable the print view
                *  @param {boolean} [bView=true] Show the print view if true or not given. If false, then
                *    terminate the print view and return to normal.
                *  @param {object} [oConfig={}] Configuration for the print view
                *  @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true
                *  @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the
                *    user to let them know what the print view is.
                *  @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will
                *    be included in the printed document.
                */
                "fnPrint": function (bView, oConfig) {
                    if (oConfig === undefined) {
                        oConfig = {};
                    }

                    if (bView === undefined || bView) {
                        this._fnPrintStart(oConfig);
                    }
                    else {
                        this._fnPrintEnd();
                    }
                },


                /**
                * Show a message to the end user which is nicely styled
                *  @param {string} message The HTML string to show to the user
                *  @param {int} time The duration the message is to be shown on screen for (mS)
                */
                "fnInfo": function (message, time) {
                    var info = $('<div/>')
			.addClass(this.classes.print.info)
			.html(message)
			.appendTo('body');

                    setTimeout(function () {
                        info.fadeOut("normal", function () {
                            info.remove();
                        });
                    }, time);
                },



                /**
                * Get the container element of the instance for attaching to the DOM
                *   @returns {node} DOM node
                */
                "fnContainer": function () {
                    return this.dom.container;
                },



                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Private methods (they are of course public in JS, but recommended as private)
                * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

                /**
                * Constructor logic
                *  @method  _fnConstruct
                *  @param   {Object} oOpts Same as TableTools constructor
                *  @returns void
                *  @private 
                */
                "_fnConstruct": function (oOpts) {
                    var that = this;

                    this._fnCustomiseSettings(oOpts);

                    /* Container element */
                    this.dom.container = document.createElement(this.s.tags.container);
                    this.dom.container.className = this.classes.container;

                    /* Row selection config */
                    if (this.s.select.type != 'none') {
                        this._fnRowSelectConfig();
                    }

                    /* Buttons */
                    this._fnButtonDefinations(this.s.buttonSet, this.dom.container);

                    /* Destructor */
                    this.s.dt.aoDestroyCallback.push({
                        "sName": "TableTools",
                        "fn": function () {
                            $(that.s.dt.nTBody).off('click.DTTT_Select', 'tr');
                            $(that.dom.container).empty();

                            // Remove the instance
                            var idx = $.inArray(that, TableTools._aInstances);
                            if (idx !== -1) {
                                TableTools._aInstances.splice(idx, 1);
                            }
                        }
                    });
                },


                /**
                * Take the user defined settings and the default settings and combine them.
                *  @method  _fnCustomiseSettings
                *  @param   {Object} oOpts Same as TableTools constructor
                *  @returns void
                *  @private 
                */
                "_fnCustomiseSettings": function (oOpts) {
                    /* Is this the master control instance or not? */
                    if (typeof this.s.dt._TableToolsInit == 'undefined') {
                        this.s.master = true;
                        this.s.dt._TableToolsInit = true;
                    }

                    /* We can use the table node from comparisons to group controls */
                    this.dom.table = this.s.dt.nTable;

                    /* Clone the defaults and then the user options */
                    this.s.custom = $.extend({}, TableTools.DEFAULTS, oOpts);

                    /* Flash file location */
                    this.s.swfPath = this.s.custom.sSwfPath;
                    if (typeof ZeroClipboard_TableTools != 'undefined') {
                        ZeroClipboard_TableTools.moviePath = this.s.swfPath;
                    }

                    /* Table row selecting */
                    this.s.select.type = this.s.custom.sRowSelect;
                    this.s.select.preRowSelect = this.s.custom.fnPreRowSelect;
                    this.s.select.postSelected = this.s.custom.fnRowSelected;
                    this.s.select.postDeselected = this.s.custom.fnRowDeselected;

                    // Backwards compatibility - allow the user to specify a custom class in the initialiser
                    if (this.s.custom.sSelectedClass) {
                        this.classes.select.row = this.s.custom.sSelectedClass;
                    }

                    this.s.tags = this.s.custom.oTags;

                    /* Button set */
                    this.s.buttonSet = this.s.custom.aButtons;
                },


                /**
                * Take the user input arrays and expand them to be fully defined, and then add them to a given
                * DOM element
                *  @method  _fnButtonDefinations
                *  @param {array} buttonSet Set of user defined buttons
                *  @param {node} wrapper Node to add the created buttons to
                *  @returns void
                *  @private 
                */
                "_fnButtonDefinations": function (buttonSet, wrapper) {
                    var buttonDef;

                    for (var i = 0, iLen = buttonSet.length; i < iLen; i++) {
                        if (typeof buttonSet[i] == "string") {
                            if (typeof TableTools.BUTTONS[buttonSet[i]] == 'undefined') {
                                alert("TableTools: Warning - unknown button type: " + buttonSet[i]);
                                continue;
                            }
                            buttonDef = $.extend({}, TableTools.BUTTONS[buttonSet[i]], true);
                        }
                        else {
                            if (typeof TableTools.BUTTONS[buttonSet[i].sExtends] == 'undefined') {
                                alert("TableTools: Warning - unknown button type: " + buttonSet[i].sExtends);
                                continue;
                            }
                            var o = $.extend({}, TableTools.BUTTONS[buttonSet[i].sExtends], true);
                            buttonDef = $.extend(o, buttonSet[i], true);
                        }

                        wrapper.appendChild(this._fnCreateButton(
				buttonDef,
				$(wrapper).hasClass(this.classes.collection.container)
			));
                    }
                },


                /**
                * Create and configure a TableTools button
                *  @method  _fnCreateButton
                *  @param   {Object} oConfig Button configuration object
                *  @returns {Node} Button element
                *  @private 
                */
                "_fnCreateButton": function (oConfig, bCollectionButton) {
                    var nButton = this._fnButtonBase(oConfig, bCollectionButton);

                    if (oConfig.sAction.match(/flash/)) {
                        this._fnFlashConfig(nButton, oConfig);
                    }
                    else if (oConfig.sAction == "text") {
                        this._fnTextConfig(nButton, oConfig);
                    }
                    else if (oConfig.sAction == "div") {
                        this._fnTextConfig(nButton, oConfig);
                    }
                    else if (oConfig.sAction == "collection") {
                        this._fnTextConfig(nButton, oConfig);
                        this._fnCollectionConfig(nButton, oConfig);
                    }

                    return nButton;
                },


                /**
                * Create the DOM needed for the button and apply some base properties. All buttons start here
                *  @method  _fnButtonBase
                *  @param   {o} oConfig Button configuration object
                *  @returns {Node} DIV element for the button
                *  @private
                */
                "_fnButtonBase": function (o, bCollectionButton) {
                    var sTag, sLiner, sClass;

                    if (bCollectionButton) {
                        sTag = o.sTag && o.sTag !== "default" ? o.sTag : this.s.tags.collection.button;
                        sLiner = o.sLinerTag && o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner;
                        sClass = this.classes.collection.buttons.normal;
                    }
                    else {
                        sTag = o.sTag && o.sTag !== "default" ? o.sTag : this.s.tags.button;
                        sLiner = o.sLinerTag && o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner;
                        sClass = this.classes.buttons.normal;
                    }

                    var 
		  nButton = document.createElement(sTag),
		  nSpan = document.createElement(sLiner),
		  masterS = this._fnGetMasterSettings();

                    nButton.className = sClass + " " + o.sButtonClass;
                    nButton.setAttribute('id', "ToolTables_" + this.s.dt.sInstance + "_" + masterS.buttonCounter);
                    nButton.appendChild(nSpan);
                    nSpan.innerHTML = o.sButtonText;

                    masterS.buttonCounter++;

                    return nButton;
                },


                /**
                * Get the settings object for the master instance. When more than one TableTools instance is
                * assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such,
                * we will typically want to interact with that master for global properties.
                *  @method  _fnGetMasterSettings
                *  @returns {Object} TableTools settings object
                *  @private 
                */
                "_fnGetMasterSettings": function () {
                    if (this.s.master) {
                        return this.s;
                    }
                    else {
                        /* Look for the master which has the same DT as this one */
                        var instances = TableTools._aInstances;
                        for (var i = 0, iLen = instances.length; i < iLen; i++) {
                            if (this.dom.table == instances[i].s.dt.nTable) {
                                return instances[i].s;
                            }
                        }
                    }
                },



                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Button collection functions
                */

                /**
                * Create a collection button, when activated will present a drop down list of other buttons
                *  @param   {Node} nButton Button to use for the collection activation
                *  @param   {Object} oConfig Button configuration object
                *  @returns void
                *  @private
                */
                "_fnCollectionConfig": function (nButton, oConfig) {
                    var nHidden = document.createElement(this.s.tags.collection.container);
                    nHidden.style.display = "none";
                    nHidden.className = this.classes.collection.container;
                    oConfig._collection = nHidden;
                    document.body.appendChild(nHidden);

                    this._fnButtonDefinations(oConfig.aButtons, nHidden);
                },


                /**
                * Show a button collection
                *  @param   {Node} nButton Button to use for the collection
                *  @param   {Object} oConfig Button configuration object
                *  @returns void
                *  @private
                */
                "_fnCollectionShow": function (nButton, oConfig) {
                    var 
			that = this,
			oPos = $(nButton).offset(),
			nHidden = oConfig._collection,
			iDivX = oPos.left,
			iDivY = oPos.top + $(nButton).outerHeight(),
			iWinHeight = $(window).height(), iDocHeight = $(document).height(),
			iWinWidth = $(window).width(), iDocWidth = $(document).width();

                    nHidden.style.position = "absolute";
                    nHidden.style.left = iDivX + "px";
                    nHidden.style.top = iDivY + "px";
                    nHidden.style.display = "block";
                    $(nHidden).css('opacity', 0);

                    var nBackground = document.createElement('div');
                    nBackground.style.position = "absolute";
                    nBackground.style.left = "0px";
                    nBackground.style.top = "0px";
                    nBackground.style.height = ((iWinHeight > iDocHeight) ? iWinHeight : iDocHeight) + "px";
                    nBackground.style.width = ((iWinWidth > iDocWidth) ? iWinWidth : iDocWidth) + "px";
                    nBackground.className = this.classes.collection.background;
                    $(nBackground).css('opacity', 0);

                    document.body.appendChild(nBackground);
                    document.body.appendChild(nHidden);

                    /* Visual corrections to try and keep the collection visible */
                    var iDivWidth = $(nHidden).outerWidth();
                    var iDivHeight = $(nHidden).outerHeight();

                    if (iDivX + iDivWidth > iDocWidth) {
                        nHidden.style.left = (iDocWidth - iDivWidth) + "px";
                    }

                    if (iDivY + iDivHeight > iDocHeight) {
                        nHidden.style.top = (iDivY - iDivHeight - $(nButton).outerHeight()) + "px";
                    }

                    this.dom.collection.collection = nHidden;
                    this.dom.collection.background = nBackground;

                    /* This results in a very small delay for the end user but it allows the animation to be
                    * much smoother. If you don't want the animation, then the setTimeout can be removed
                    */
                    setTimeout(function () {
                        $(nHidden).animate({ "opacity": 1 }, 500);
                        $(nBackground).animate({ "opacity": 0.25 }, 500);
                    }, 10);

                    /* Resize the buttons to the Flash contents fit */
                    this.fnResizeButtons();

                    /* Event handler to remove the collection display */
                    $(nBackground).click(function () {
                        that._fnCollectionHide.call(that, null, null);
                    });
                },


                /**
                * Hide a button collection
                *  @param   {Node} nButton Button to use for the collection
                *  @param   {Object} oConfig Button configuration object
                *  @returns void
                *  @private
                */
                "_fnCollectionHide": function (nButton, oConfig) {
                    if (oConfig !== null && oConfig.sExtends == 'collection') {
                        return;
                    }

                    if (this.dom.collection.collection !== null) {
                        $(this.dom.collection.collection).animate({ "opacity": 0 }, 500, function (e) {
                            this.style.display = "none";
                        });

                        $(this.dom.collection.background).animate({ "opacity": 0 }, 500, function (e) {
                            this.parentNode.removeChild(this);
                        });

                        this.dom.collection.collection = null;
                        this.dom.collection.background = null;
                    }
                },



                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Row selection functions
                */

                /**
                * Add event handlers to a table to allow for row selection
                *  @method  _fnRowSelectConfig
                *  @returns void
                *  @private 
                */
                "_fnRowSelectConfig": function () {
                    if (this.s.master) {
                        var 
				that = this,
				i, iLen,
				dt = this.s.dt,
				aoOpenRows = this.s.dt.aoOpenRows;

                        $(dt.nTable).addClass(this.classes.select.table);

                        // When using OS style selection, we want to cancel the shift text
                        // selection, but only when the shift key is used (so you can
                        // actually still select text in the table)
                        if (this.s.select.type === 'os') {
                            $(dt.nTBody).on('mousedown.DTTT_Select', 'tr', function (e) {
                                if (e.shiftKey) {

                                    $(dt.nTBody)
							.css('-moz-user-select', 'none')
							.one('selectstart.DTTT_Select', 'tr', function () {
							    return false;
							});
                                }
                            });

                            $(dt.nTBody).on('mouseup.DTTT_Select', 'tr', function (e) {
                                $(dt.nTBody).css('-moz-user-select', '');
                            });
                        }

                        // Row selection
                        $(dt.nTBody).on('click.DTTT_Select', this.s.custom.sRowSelector, function (e) {
                            var row = this.nodeName.toLowerCase() === 'tr' ?
					this :
					$(this).parents('tr')[0];

                            var select = that.s.select;
                            var pos = that.s.dt.oInstance.fnGetPosition(row);

                            /* Sub-table must be ignored (odd that the selector won't do this with >) */
                            if (row.parentNode != dt.nTBody) {
                                return;
                            }

                            /* Check that we are actually working with a DataTables controlled row */
                            if (dt.oInstance.fnGetData(row) === null) {
                                return;
                            }

                            // Shift click, ctrl click and simple click handling to make
                            // row selection a lot like a file system in desktop OSs
                            if (select.type == 'os') {
                                if (e.ctrlKey || e.metaKey) {
                                    // Add or remove from the selection
                                    if (that.fnIsSelected(row)) {
                                        that._fnRowDeselect(row, e);
                                    }
                                    else {
                                        that._fnRowSelect(row, e);
                                    }
                                }
                                else if (e.shiftKey) {
                                    // Add a range of rows, from the last selected row to
                                    // this one
                                    var rowIdxs = that.s.dt.aiDisplay.slice(); // visible rows
                                    var idx1 = $.inArray(select.lastRow, rowIdxs);
                                    var idx2 = $.inArray(pos, rowIdxs);

                                    if (that.fnGetSelected().length === 0 || idx1 === -1) {
                                        // select from top to here - slightly odd, but both
                                        // Windows and Mac OS do this
                                        rowIdxs.splice($.inArray(pos, rowIdxs) + 1, rowIdxs.length);
                                    }
                                    else {
                                        // reverse so we can shift click 'up' as well as down
                                        if (idx1 > idx2) {
                                            var tmp = idx2;
                                            idx2 = idx1;
                                            idx1 = tmp;
                                        }

                                        rowIdxs.splice(idx2 + 1, rowIdxs.length);
                                        rowIdxs.splice(0, idx1);
                                    }

                                    if (!that.fnIsSelected(row)) {
                                        // Select range
                                        that._fnRowSelect(rowIdxs, e);
                                    }
                                    else {
                                        // Deselect range - need to keep the clicked on row selected
                                        rowIdxs.splice($.inArray(pos, rowIdxs), 1);
                                        that._fnRowDeselect(rowIdxs, e);
                                    }
                                }
                                else {
                                    // No cmd or shift click. Deselect current if selected,
                                    // or select this row only
                                    if (that.fnIsSelected(row) && that.fnGetSelected().length === 1) {
                                        that._fnRowDeselect(row, e);
                                    }
                                    else {
                                        that.fnSelectNone();
                                        that._fnRowSelect(row, e);
                                    }
                                }
                            }
                            else if (that.fnIsSelected(row)) {
                                that._fnRowDeselect(row, e);
                            }
                            else if (select.type == "single") {
                                that.fnSelectNone();
                                that._fnRowSelect(row, e);
                            }
                            else if (select.type == "multi") {
                                that._fnRowSelect(row, e);
                            }

                            select.lastRow = pos;
                        }); //.on('selectstart', function () { return false; } );

                        // Bind a listener to the DataTable for when new rows are created.
                        // This allows rows to be visually selected when they should be and
                        // deferred rendering is used.
                        dt.oApi._fnCallbackReg(dt, 'aoRowCreatedCallback', function (tr, data, index) {
                            if (dt.aoData[index]._DTTT_selected) {
                                $(tr).addClass(that.classes.select.row);
                            }
                        }, 'TableTools-SelectAll');
                    }
                },

                /**
                * Select rows
                *  @param   {*} src Rows to select - see _fnSelectData for a description of valid inputs
                *  @private 
                */
                "_fnRowSelect": function (src, e) {
                    var 
			that = this,
			data = this._fnSelectData(src),
			firstTr = data.length === 0 ? null : data[0].nTr,
			anSelected = [],
			i, len;

                    // Get all the rows that will be selected
                    for (i = 0, len = data.length; i < len; i++) {
                        if (data[i].nTr) {
                            anSelected.push(data[i].nTr);
                        }
                    }

                    // User defined pre-selection function
                    if (this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true)) {
                        return;
                    }

                    // Mark them as selected
                    for (i = 0, len = data.length; i < len; i++) {
                        data[i]._DTTT_selected = true;

                        if (data[i].nTr) {
                            $(data[i].nTr).addClass(that.classes.select.row);
                        }
                    }

                    // Post-selection function
                    if (this.s.select.postSelected !== null) {
                        this.s.select.postSelected.call(this, anSelected);
                    }

                    TableTools._fnEventDispatch(this, 'select', anSelected, true);
                },

                /**
                * Deselect rows
                *  @param   {*} src Rows to deselect - see _fnSelectData for a description of valid inputs
                *  @private 
                */
                "_fnRowDeselect": function (src, e) {
                    var 
			that = this,
			data = this._fnSelectData(src),
			firstTr = data.length === 0 ? null : data[0].nTr,
			anDeselectedTrs = [],
			i, len;

                    // Get all the rows that will be deselected
                    for (i = 0, len = data.length; i < len; i++) {
                        if (data[i].nTr) {
                            anDeselectedTrs.push(data[i].nTr);
                        }
                    }

                    // User defined pre-selection function
                    if (this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false)) {
                        return;
                    }

                    // Mark them as deselected
                    for (i = 0, len = data.length; i < len; i++) {
                        data[i]._DTTT_selected = false;

                        if (data[i].nTr) {
                            $(data[i].nTr).removeClass(that.classes.select.row);
                        }
                    }

                    // Post-deselection function
                    if (this.s.select.postDeselected !== null) {
                        this.s.select.postDeselected.call(this, anDeselectedTrs);
                    }

                    TableTools._fnEventDispatch(this, 'select', anDeselectedTrs, false);
                },

                /**
                * Take a data source for row selection and convert it into aoData points for the DT
                *   @param {*} src Can be a single DOM TR node, an array of TR nodes (including a
                *     a jQuery object), a single aoData point from DataTables, an array of aoData
                *     points or an array of aoData indexes
                *   @returns {array} An array of aoData points
                */
                "_fnSelectData": function (src) {
                    var out = [], pos, i, iLen;

                    if (src.nodeName) {
                        // Single node
                        pos = this.s.dt.oInstance.fnGetPosition(src);
                        out.push(this.s.dt.aoData[pos]);
                    }
                    else if (typeof src.length !== 'undefined') {
                        // jQuery object or an array of nodes, or aoData points
                        for (i = 0, iLen = src.length; i < iLen; i++) {
                            if (src[i].nodeName) {
                                pos = this.s.dt.oInstance.fnGetPosition(src[i]);
                                out.push(this.s.dt.aoData[pos]);
                            }
                            else if (typeof src[i] === 'number') {
                                out.push(this.s.dt.aoData[src[i]]);
                            }
                            else {
                                out.push(src[i]);
                            }
                        }

                        return out;
                    }
                    else {
                        // A single aoData point
                        out.push(src);
                    }

                    return out;
                },


                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Text button functions
                */

                /**
                * Configure a text based button for interaction events
                *  @method  _fnTextConfig
                *  @param   {Node} nButton Button element which is being considered
                *  @param   {Object} oConfig Button configuration object
                *  @returns void
                *  @private 
                */
                "_fnTextConfig": function (nButton, oConfig) {
                    var that = this;

                    if (oConfig.fnInit !== null) {
                        oConfig.fnInit.call(this, nButton, oConfig);
                    }

                    if (oConfig.sToolTip !== "") {
                        nButton.title = oConfig.sToolTip;
                    }

                    $(nButton).hover(function () {
                        if (oConfig.fnMouseover !== null) {
                            oConfig.fnMouseover.call(this, nButton, oConfig, null);
                        }
                    }, function () {
                        if (oConfig.fnMouseout !== null) {
                            oConfig.fnMouseout.call(this, nButton, oConfig, null);
                        }
                    });

                    if (oConfig.fnSelect !== null) {
                        TableTools._fnEventListen(this, 'select', function (n) {
                            oConfig.fnSelect.call(that, nButton, oConfig, n);
                        });
                    }

                    $(nButton).click(function (e) {
                        //e.preventDefault();

                        if (oConfig.fnClick !== null) {
                            oConfig.fnClick.call(that, nButton, oConfig, null, e);
                        }

                        /* Provide a complete function to match the behaviour of the flash elements */
                        if (oConfig.fnComplete !== null) {
                            oConfig.fnComplete.call(that, nButton, oConfig, null, null);
                        }

                        that._fnCollectionHide(nButton, oConfig);
                    });
                },



                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Flash button functions
                */

                /**
                * Configure a flash based button for interaction events
                *  @method  _fnFlashConfig
                *  @param   {Node} nButton Button element which is being considered
                *  @param   {o} oConfig Button configuration object
                *  @returns void
                *  @private 
                */
                "_fnFlashConfig": function (nButton, oConfig) {
                    var that = this;
                    var flash = new ZeroClipboard_TableTools.Client();

                    if (oConfig.fnInit !== null) {
                        oConfig.fnInit.call(this, nButton, oConfig);
                    }

                    flash.setHandCursor(true);

                    if (oConfig.sAction == "flash_save") {
                        flash.setAction('save');
                        flash.setCharSet((oConfig.sCharSet == "utf16le") ? 'UTF16LE' : 'UTF8');
                        flash.setBomInc(oConfig.bBomInc);
                        flash.setFileName(oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)));
                    }
                    else if (oConfig.sAction == "flash_pdf") {
                        flash.setAction('pdf');
                        flash.setFileName(oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)));
                    }
                    else {
                        flash.setAction('copy');
                    }

                    flash.addEventListener('mouseOver', function (client) {
                        if (oConfig.fnMouseover !== null) {
                            oConfig.fnMouseover.call(that, nButton, oConfig, flash);
                        }
                    });

                    flash.addEventListener('mouseOut', function (client) {
                        if (oConfig.fnMouseout !== null) {
                            oConfig.fnMouseout.call(that, nButton, oConfig, flash);
                        }
                    });

                    flash.addEventListener('mouseDown', function (client) {
                        if (oConfig.fnClick !== null) {
                            oConfig.fnClick.call(that, nButton, oConfig, flash);
                        }
                    });

                    flash.addEventListener('complete', function (client, text) {
                        if (oConfig.fnComplete !== null) {
                            oConfig.fnComplete.call(that, nButton, oConfig, flash, text);
                        }
                        that._fnCollectionHide(nButton, oConfig);
                    });

                    this._fnFlashGlue(flash, nButton, oConfig.sToolTip);
                },


                /**
                * Wait until the id is in the DOM before we "glue" the swf. Note that this function will call
                * itself (using setTimeout) until it completes successfully
                *  @method  _fnFlashGlue
                *  @param   {Object} clip Zero clipboard object
                *  @param   {Node} node node to glue swf to
                *  @param   {String} text title of the flash movie
                *  @returns void
                *  @private 
                */
                "_fnFlashGlue": function (flash, node, text) {
                    var that = this;
                    var id = node.getAttribute('id');

                    if (document.getElementById(id)) {
                        flash.glue(node, text);
                    }
                    else {
                        setTimeout(function () {
                            that._fnFlashGlue(flash, node, text);
                        }, 100);
                    }
                },


                /**
                * Set the text for the flash clip to deal with
                * 
                * This function is required for large information sets. There is a limit on the 
                * amount of data that can be transferred between Javascript and Flash in a single call, so
                * we use this method to build up the text in Flash by sending over chunks. It is estimated
                * that the data limit is around 64k, although it is undocumented, and appears to be different
                * between different flash versions. We chunk at 8KiB.
                *  @method  _fnFlashSetText
                *  @param   {Object} clip the ZeroClipboard object
                *  @param   {String} sData the data to be set
                *  @returns void
                *  @private 
                */
                "_fnFlashSetText": function (clip, sData) {
                    var asData = this._fnChunkData(sData, 8192);

                    clip.clearText();
                    for (var i = 0, iLen = asData.length; i < iLen; i++) {
                        clip.appendText(asData[i]);
                    }
                },



                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Data retrieval functions
                */

                /**
                * Convert the mixed columns variable into a boolean array the same size as the columns, which
                * indicates which columns we want to include
                *  @method  _fnColumnTargets
                *  @param   {String|Array} mColumns The columns to be included in data retrieval. If a string
                *			 then it can take the value of "visible" or "hidden" (to include all visible or
                *			 hidden columns respectively). Or an array of column indexes
                *  @returns {Array} A boolean array the length of the columns of the table, which each value
                *			 indicating if the column is to be included or not
                *  @private 
                */
                "_fnColumnTargets": function (mColumns) {
                    var aColumns = [];
                    var dt = this.s.dt;
                    var i, iLen;
                    if (typeof mColumns == "object") {
                        for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
                            aColumns.push(false);
                        }
                        //ajout visibilit� nerium
                        for (i = 0, iLen = mColumns.length; i < iLen; i++) {
                            aColumns[mColumns[i]] = (dt.aoColumns[mColumns[i]].bVisible ? true : false);
                        }
                    }
                    else if (mColumns == "visible") {
                        for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
                            aColumns.push(dt.aoColumns[i].bVisible ? true : false);
                        }
                    }
                    else if (mColumns == "hidden") {
                        for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
                            aColumns.push(dt.aoColumns[i].bVisible ? false : true);
                        }
                    }
                    else if (mColumns == "sortable") {
                        for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
                            aColumns.push(dt.aoColumns[i].bSortable ? true : false);
                        }
                    }
                    else /* all */
                    {
                        for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
                            aColumns.push(true);
                        }
                    }

                    return aColumns;
                },
                /*extension propre � nerium software
                /**
                * retourne les nouveaux indices des colonnes � exporter dans le cas de l'activation du colReorder
                *  @method  _fnNewColumns
                *  @param   {String|Array} mColumns The columns to be included in data retrieval. If a string
                *			 then it can take the value of "visible" or "hidden" (to include all visible or
                *			 hidden columns respectively). Or an array of column indexes
                *  @returns {Array} A boolean array the length of the columns of the table, which each value
                *			 indicating if the column is to be included or not
                *  @private 
                */
                
                "_fnNewColumns": function (mColumns) {
                    var aColumns = [];
                    var indicesNouveaux = [];
                    var dt = this.s.dt;
                    var i, iLen, j, jLen,trouve ;
                    for (j = 0, jLen = mColumns.length; j < jLen; j++) {
                        //initialisation au fur et � mesure du parcours
                        indicesNouveaux.push(-1);
                        i=0;
                        trouve = false;
                        while (i < dt.aoColumns.length && !trouve) {
                            if(dt.aoColumns[i]._ColReorder_iOrigCol == mColumns[j]) {
                               indicesNouveaux[j] = i; 
                               trouve=true;
                            }
                            i++;
                        }
                    }
                    return indicesNouveaux;
                },
                /**
                * New line character(s) depend on the platforms
                *  @method  method
                *  @param   {Object} oConfig Button configuration object - only interested in oConfig.sNewLine
                *  @returns {String} Newline character
                */
                "_fnNewline": function (oConfig) {
                    if (oConfig.sNewLine == "auto") {
                        return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n";
                    }
                    else {
                        return oConfig.sNewLine;
                    }
                },


                /**
                * Get data from DataTables' internals and format it for output
                *  @method  _fnGetDataTablesData
                *  @param   {Object} oConfig Button configuration object
                *  @param   {String} oConfig.sFieldBoundary Field boundary for the data cells in the string
                *  @param   {String} oConfig.sFieldSeperator Field separator for the data cells
                *  @param   {String} oConfig.sNewline New line options
                *  @param   {Mixed} oConfig.mColumns Which columns should be included in the output
                *  @param   {Boolean} oConfig.bHeader Include the header
                *  @param   {Boolean} oConfig.bFooter Include the footer
                *  @param   {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output
                *  @returns {String} Concatenated string of data
                *  @private 
                */
                "_fnGetDataTablesData": function (oConfig) {
                    var i, iLen, j, jLen;
                    var aRow, aData = [], sLoopData = '', arr;
                    var dt = this.s.dt, tr, child;
                    var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */
                    var mColumnsColReOrder;
                    if(dt.sDom.indexOf('R') >= 0) {
                        mColumnsColReOrder = this._fnNewColumns(oConfig.mColumns);
                    } else {
                        mColumnsColReOrder = oConfig.mColumns;
                    }
                    var aColumnsInc = this._fnColumnTargets(mColumnsColReOrder);
                    var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false;
                    /*
                    * Header
                    */
                    if (oConfig.bHeader) {
                        aRow = [];

                        for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
                            // ajout de la visibilit� par nerium
                            if (aColumnsInc[i] ) {
                                sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g, " ").replace(/<.*?>/g, "").replace(/^\s+|\s+$/g, "");
                                sLoopData = this._fnHtmlDecode(sLoopData);

                                aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
                            }
                        }

                        aData.push(aRow.join(oConfig.sFieldSeperator));
                    }

                    /*
                    * Body
                    */
//                   
                    var aSelected = this.fnGetSelected();
                    bSelectedOnly = this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0;

                    var aDataIndex = dt.oInstance
			.$('tr', oConfig.oSelectorOpts)
			.map(function (id, row) {
			    // If "selected only", then ensure that the row is in the selected list
			    return bSelectedOnly && $.inArray(row, aSelected) === -1 ?
					null :
					dt.oInstance.fnGetPosition(row);
			})
			.get();
                    var colonneIdx;
                    for (j = 0, jLen = aDataIndex.length; j < jLen; j++) {
                        tr = dt.aoData[aDataIndex[j]].nTr;
                        aRow = [];

                        /* Columns */
                        for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
                            // ajout de la visibilit� par nerium
                            if (aColumnsInc[i]) {
                                //ajout nerium 
                                colonneIdx = (dt.sDom.indexOf('R') >= 0 ? dt.aoColumns[i]._ColReorder_iOrigCol : i);
                                /* Convert to strings (with small optimisation) */
                                var mTypeData = dt.oApi._fnGetCellData(dt, aDataIndex[j], colonneIdx, 'display');
                                if (oConfig.fnCellRender) {
                                    sLoopData = oConfig.fnCellRender(mTypeData, colonneIdx, tr, aDataIndex[j]) + "";
                                }
                                else if (typeof mTypeData == "string") {
                                    /* Strip newlines, replace img tags with alt attr. and finally strip html... */
                                    sLoopData = mTypeData.replace(/\n/g, " ");
                                    sLoopData =
						    sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi,
						        '$1$2$3');
                                    sLoopData = sLoopData.replace(/<.*?>/g, "");
                                }
                                else {
                                    sLoopData = mTypeData + "";
                                }

                                /* Trim and clean the data */
                                sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, '');
                                sLoopData = this._fnHtmlDecode(sLoopData);

                                /* Bound it and add it to the total data */
                                aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
                            }
                        }

                        aData.push(aRow.join(oConfig.sFieldSeperator));

                        /* Details rows from fnOpen */
                        if (oConfig.bOpenRows) {
                            arr = $.grep(dt.aoOpenRows, function (o) { return o.nParent === tr; });

                            if (arr.length === 1) {
                                sLoopData = this._fnBoundData($('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex);
                                aData.push(sLoopData);
                            }
                        }
                    }

                    /*
                    * Footer
                    */
                    if (oConfig.bFooter && dt.nTFoot !== null) {
                        aRow = [];

                        for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
                            if (aColumnsInc[i] && dt.aoColumns[i].nTf !== null) {
                                sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g, " ").replace(/<.*?>/g, "");
                                sLoopData = this._fnHtmlDecode(sLoopData);

                                aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
                            }
                        }

                        aData.push(aRow.join(oConfig.sFieldSeperator));
                    }

                    var _sLastData = aData.join(this._fnNewline(oConfig));
                    return _sLastData;
                },


                /**
                * Wrap data up with a boundary string
                *  @method  _fnBoundData
                *  @param   {String} sData data to bound
                *  @param   {String} sBoundary bounding char(s)
                *  @param   {RegExp} regex search for the bounding chars - constructed outside for efficiency
                *			 in the loop
                *  @returns {String} bound data
                *  @private 
                */
                "_fnBoundData": function (sData, sBoundary, regex) {
                    if (sBoundary === "") {
                        return sData;
                    }
                    else {
                        return sBoundary + sData.replace(regex, sBoundary + sBoundary) + sBoundary;
                    }
                },


                /**
                * Break a string up into an array of smaller strings
                *  @method  _fnChunkData
                *  @param   {String} sData data to be broken up
                *  @param   {Int} iSize chunk size
                *  @returns {Array} String array of broken up text
                *  @private 
                */
                "_fnChunkData": function (sData, iSize) {
                    var asReturn = [];
                    var iStrlen = sData.length;

                    for (var i = 0; i < iStrlen; i += iSize) {
                        if (i + iSize < iStrlen) {
                            asReturn.push(sData.substring(i, i + iSize));
                        }
                        else {
                            asReturn.push(sData.substring(i, iStrlen));
                        }
                    }

                    return asReturn;
                },


                /**
                * Decode HTML entities
                *  @method  _fnHtmlDecode
                *  @param   {String} sData encoded string
                *  @returns {String} decoded string
                *  @private 
                */
                "_fnHtmlDecode": function (sData) {
                    if (sData.indexOf('&') === -1) {
                        return sData;
                    }

                    var n = document.createElement('div');

                    return sData.replace(/&([^\s]*);/g, function (match, match2) {
                        if (match.substr(1, 1) === '#') {
                            return String.fromCharCode(Number(match2.substr(1)));
                        }
                        else {
                            n.innerHTML = match;
                            return n.childNodes[0].nodeValue;
                        }
                    });
                },



                /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                * Printing functions
                */

                /**
                * Show print display
                *  @method  _fnPrintStart
                *  @param   {Event} e Event object
                *  @param   {Object} oConfig Button configuration object
                *  @returns void
                *  @private 
                */
                "_fnPrintStart": function (oConfig) {
                    var that = this;
                    var oSetDT = this.s.dt;

                    /* Parse through the DOM hiding everything that isn't needed for the table */
                    this._fnPrintHideNodes(oSetDT.nTable);

                    /* Show the whole table */
                    this.s.print.saveStart = oSetDT._iDisplayStart;
                    this.s.print.saveLength = oSetDT._iDisplayLength;

                    if (oConfig.bShowAll) {
                        oSetDT._iDisplayStart = 0;
                        oSetDT._iDisplayLength = -1;
                        if (oSetDT.oApi._fnCalculateEnd) {
                            oSetDT.oApi._fnCalculateEnd(oSetDT);
                        }
                        oSetDT.oApi._fnDraw(oSetDT);
                    }

                    /* Adjust the display for scrolling which might be done by DataTables */
                    if (oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "") {
                        this._fnPrintScrollStart(oSetDT);

                        // If the table redraws while in print view, the DataTables scrolling
                        // setup would hide the header, so we need to readd it on draw
                        $(this.s.dt.nTable).bind('draw.DTTT_Print', function () {
                            that._fnPrintScrollStart(oSetDT);
                        });
                    }

                    /* Remove the other DataTables feature nodes - but leave the table! and info div */
                    var anFeature = oSetDT.aanFeatures;
                    for (var cFeature in anFeature) {
                        if (cFeature != 'i' && cFeature != 't' && cFeature.length == 1) {
                            for (var i = 0, iLen = anFeature[cFeature].length; i < iLen; i++) {
                                this.dom.print.hidden.push({
                                    "node": anFeature[cFeature][i],
                                    "display": "block"
                                });
                                anFeature[cFeature][i].style.display = "none";
                            }
                        }
                    }

                    /* Print class can be used for styling */
                    $(document.body).addClass(this.classes.print.body);

                    /* Show information message to let the user know what is happening */
                    if (oConfig.sInfo !== "") {
                        this.fnInfo(oConfig.sInfo, 3000);
                    }

                    /* Add a message at the top of the page */
                    if (oConfig.sMessage) {
                        $('<div/>')
				.addClass(this.classes.print.message)
				.html(oConfig.sMessage)
				.prependTo('body');
                    }

                    /* Cache the scrolling and the jump to the top of the page */
                    this.s.print.saveScroll = $(window).scrollTop();
                    window.scrollTo(0, 0);

                    /* Bind a key event listener to the document for the escape key -
                    * it is removed in the callback
                    */
                    $(document).bind("keydown.DTTT", function (e) {
                        /* Only interested in the escape key */
                        if (e.keyCode == 27) {
                            e.preventDefault();
                            that._fnPrintEnd.call(that, e);
                        }
                    });
                },


                /**
                * Printing is finished, resume normal display
                *  @method  _fnPrintEnd
                *  @param   {Event} e Event object
                *  @returns void
                *  @private 
                */
                "_fnPrintEnd": function (e) {
                    var that = this;
                    var oSetDT = this.s.dt;
                    var oSetPrint = this.s.print;
                    var oDomPrint = this.dom.print;

                    /* Show all hidden nodes */
                    this._fnPrintShowNodes();

                    /* Restore DataTables' scrolling */
                    if (oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "") {
                        $(this.s.dt.nTable).unbind('draw.DTTT_Print');

                        this._fnPrintScrollEnd();
                    }

                    /* Restore the scroll */
                    window.scrollTo(0, oSetPrint.saveScroll);

                    /* Drop the print message */
                    $('div.' + this.classes.print.message).remove();

                    /* Styling class */
                    $(document.body).removeClass('DTTT_Print');

                    /* Restore the table length */
                    oSetDT._iDisplayStart = oSetPrint.saveStart;
                    oSetDT._iDisplayLength = oSetPrint.saveLength;
                    if (oSetDT.oApi._fnCalculateEnd) {
                        oSetDT.oApi._fnCalculateEnd(oSetDT);
                    }
                    oSetDT.oApi._fnDraw(oSetDT);

                    $(document).unbind("keydown.DTTT");
                },


                /**
                * Take account of scrolling in DataTables by showing the full table
                *  @returns void
                *  @private 
                */
                "_fnPrintScrollStart": function () {
                    var 
			oSetDT = this.s.dt,
			nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0],
			nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0],
			nScrollBody = oSetDT.nTable.parentNode,
			nTheadSize, nTfootSize;

                    /* Copy the header in the thead in the body table, this way we show one single table when
                    * in print view. Note that this section of code is more or less verbatim from DT 1.7.0
                    */
                    nTheadSize = oSetDT.nTable.getElementsByTagName('thead');
                    if (nTheadSize.length > 0) {
                        oSetDT.nTable.removeChild(nTheadSize[0]);
                    }

                    if (oSetDT.nTFoot !== null) {
                        nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot');
                        if (nTfootSize.length > 0) {
                            oSetDT.nTable.removeChild(nTfootSize[0]);
                        }
                    }

                    nTheadSize = oSetDT.nTHead.cloneNode(true);
                    oSetDT.nTable.insertBefore(nTheadSize, oSetDT.nTable.childNodes[0]);

                    if (oSetDT.nTFoot !== null) {
                        nTfootSize = oSetDT.nTFoot.cloneNode(true);
                        oSetDT.nTable.insertBefore(nTfootSize, oSetDT.nTable.childNodes[1]);
                    }

                    /* Now adjust the table's viewport so we can actually see it */
                    if (oSetDT.oScroll.sX !== "") {
                        oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth() + "px";
                        nScrollBody.style.width = $(oSetDT.nTable).outerWidth() + "px";
                        nScrollBody.style.overflow = "visible";
                    }

                    if (oSetDT.oScroll.sY !== "") {
                        nScrollBody.style.height = $(oSetDT.nTable).outerHeight() + "px";
                        nScrollBody.style.overflow = "visible";
                    }
                },


                /**
                * Take account of scrolling in DataTables by showing the full table. Note that the redraw of
                * the DataTable that we do will actually deal with the majority of the hard work here
                *  @returns void
                *  @private 
                */
                "_fnPrintScrollEnd": function () {
                    var 
			oSetDT = this.s.dt,
			nScrollBody = oSetDT.nTable.parentNode;

                    if (oSetDT.oScroll.sX !== "") {
                        nScrollBody.style.width = oSetDT.oApi._fnStringToCss(oSetDT.oScroll.sX);
                        nScrollBody.style.overflow = "auto";
                    }

                    if (oSetDT.oScroll.sY !== "") {
                        nScrollBody.style.height = oSetDT.oApi._fnStringToCss(oSetDT.oScroll.sY);
                        nScrollBody.style.overflow = "auto";
                    }
                },


                /**
                * Resume the display of all TableTools hidden nodes
                *  @method  _fnPrintShowNodes
                *  @returns void
                *  @private 
                */
                "_fnPrintShowNodes": function () {
                    var anHidden = this.dom.print.hidden;

                    for (var i = 0, iLen = anHidden.length; i < iLen; i++) {
                        anHidden[i].node.style.display = anHidden[i].display;
                    }
                    anHidden.splice(0, anHidden.length);
                },


                /**
                * Hide nodes which are not needed in order to display the table. Note that this function is
                * recursive
                *  @method  _fnPrintHideNodes
                *  @param   {Node} nNode Element which should be showing in a 'print' display
                *  @returns void
                *  @private 
                */
                "_fnPrintHideNodes": function (nNode) {
                    var anHidden = this.dom.print.hidden;

                    var nParent = nNode.parentNode;
                    var nChildren = nParent.childNodes;
                    for (var i = 0, iLen = nChildren.length; i < iLen; i++) {
                        if (nChildren[i] != nNode && nChildren[i].nodeType == 1) {
                            /* If our node is shown (don't want to show nodes which were previously hidden) */
                            var sDisplay = $(nChildren[i]).css("display");
                            if (sDisplay != "none") {
                                /* Cache the node and it's previous state so we can restore it */
                                anHidden.push({
                                    "node": nChildren[i],
                                    "display": sDisplay
                                });
                                nChildren[i].style.display = "none";
                            }
                        }
                    }

                    if (nParent.nodeName.toUpperCase() != "BODY") {
                        this._fnPrintHideNodes(nParent);
                    }
                }
            };



            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Static variables
            * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            /**
            * Store of all instances that have been created of TableTools, so one can look up other (when
            * there is need of a master)
            *  @property _aInstances
            *  @type	 Array
            *  @default  []
            *  @private
            */
            TableTools._aInstances = [];


            /**
            * Store of all listeners and their callback functions
            *  @property _aListeners
            *  @type	 Array
            *  @default  []
            */
            TableTools._aListeners = [];



            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Static methods
            * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            /**
            * Get an array of all the master instances
            *  @method  fnGetMasters
            *  @returns {Array} List of master TableTools instances
            *  @static
            */
            TableTools.fnGetMasters = function () {
                var a = [];
                for (var i = 0, iLen = TableTools._aInstances.length; i < iLen; i++) {
                    if (TableTools._aInstances[i].s.master) {
                        a.push(TableTools._aInstances[i]);
                    }
                }
                return a;
            };

            /**
            * Get the master instance for a table node (or id if a string is given)
            *  @method  fnGetInstance
            *  @returns {Object} ID of table OR table node, for which we want the TableTools instance
            *  @static
            */
            TableTools.fnGetInstance = function (node) {
                if (typeof node != 'object') {
                    node = document.getElementById(node);
                }

                for (var i = 0, iLen = TableTools._aInstances.length; i < iLen; i++) {
                    if (TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node) {
                        return TableTools._aInstances[i];
                    }
                }
                return null;
            };


            /**
            * Add a listener for a specific event
            *  @method  _fnEventListen
            *  @param   {Object} that Scope of the listening function (i.e. 'this' in the caller)
            *  @param   {String} type Event type
            *  @param   {Function} fn Function
            *  @returns void
            *  @private
            *  @static
            */
            TableTools._fnEventListen = function (that, type, fn) {
                TableTools._aListeners.push({
                    "that": that,
                    "type": type,
                    "fn": fn
                });
            };


            /**
            * An event has occurred - look up every listener and fire it off. We check that the event we are
            * going to fire is attached to the same table (using the table node as reference) before firing
            *  @method  _fnEventDispatch
            *  @param   {Object} that Scope of the listening function (i.e. 'this' in the caller)
            *  @param   {String} type Event type
            *  @param   {Node} node Element that the event occurred on (may be null)
            *  @param   {boolean} [selected] Indicate if the node was selected (true) or deselected (false)
            *  @returns void
            *  @private
            *  @static
            */
            TableTools._fnEventDispatch = function (that, type, node, selected) {
                var listeners = TableTools._aListeners;
                for (var i = 0, iLen = listeners.length; i < iLen; i++) {
                    if (that.dom.table == listeners[i].that.dom.table && listeners[i].type == type) {
                        listeners[i].fn(node, selected);
                    }
                }
            };






            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Constants
            * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */



            TableTools.buttonBase = {
                // Button base
                "sAction": "text",
                "sTag": "default",
                "sLinerTag": "default",
                "sButtonClass": "DTTT_button_text",
                "sButtonText": "Button text",
                "sTitle": "",
                "sToolTip": "",

                // Common button specific options
                "sCharSet": "utf8",
                "bBomInc": false,
                "sFileName": "*.csv",
                "sFieldBoundary": "",
                "sFieldSeperator": "\t",
                "sNewLine": "auto",
                "mColumns": "all", /* "all", "visible", "hidden" or array of column integers */
                "bHeader": true,
                "bFooter": true,
                "bOpenRows": false,
                "bSelectedOnly": false,
                "oSelectorOpts": undefined, // See http://datatables.net/docs/DataTables/1.9.4/#$ for full options

                // Callbacks
                "fnMouseover": null,
                "fnMouseout": null,
                "fnClick": null,
                "fnSelect": null,
                "fnComplete": null,
                "fnInit": null,
                "fnCellRender": null
            };


            /**
            * @namespace Default button configurations
            */
            TableTools.BUTTONS = {
                "csv": $.extend({}, TableTools.buttonBase, {
                    "sAction": "flash_save",
                    "sButtonClass": "DTTT_button_csv",
                    "sButtonText": "CSV",
                    "sFieldBoundary": '"',
                    "sFieldSeperator": ",",
                    "fnClick": function (nButton, oConfig, flash) {
                        this.fnSetText(flash, this.fnGetTableData(oConfig));
                    }
                }),

                "xls": $.extend({}, TableTools.buttonBase, {
                    "sAction": "flash_save",
                    "sCharSet": "utf16le",
                    "bBomInc": true,
                    "sButtonClass": "DTTT_button_xls",
                    "sButtonText": "Excel",
                    "fnClick": function (nButton, oConfig, flash) {
                        this.fnSetText(flash, this.fnGetTableData(oConfig));
                    }
                }),

                "copy": $.extend({}, TableTools.buttonBase, {
                    "sAction": "flash_copy",
                    "sButtonClass": "DTTT_button_copy",
                    "sButtonText": "Copy",
                    "fnClick": function (nButton, oConfig, flash) {
                        this.fnSetText(flash, this.fnGetTableData(oConfig));
                    },
                    "fnComplete": function (nButton, oConfig, flash, text) {
                        var 
				lines = text.split('\n').length,
				len = this.s.dt.nTFoot === null ? lines - 1 : lines - 2,
				plural = (len == 1) ? "" : "s";
                        this.fnInfo('<h6>Table copied</h6>' +
				'<p>Copied ' + len + ' row' + plural + ' to the clipboard.</p>',
				1500
			);
                    }
                }),

                "pdf": $.extend({}, TableTools.buttonBase, {
                    "sAction": "flash_pdf",
                    "sNewLine": "\n",
                    "sFileName": "*.pdf",
                    "sButtonClass": "DTTT_button_pdf",
                    "sButtonText": "PDF",
                    "sPdfOrientation": "portrait",
                    "sPdfSize": "A4",
                    "sPdfMessage": "",
                    "fnClick": function (nButton, oConfig, flash) {
                        this.fnSetText(flash,
				"title:" + this.fnGetTitle(oConfig) + "\n" +
				"message:" + oConfig.sPdfMessage + "\n" +
				"colWidth:" + this.fnCalcColRatios(oConfig) + "\n" +
				"orientation:" + oConfig.sPdfOrientation + "\n" +
				"size:" + oConfig.sPdfSize + "\n" +
				"--/TableToolsOpts--\n" +
				this.fnGetTableData(oConfig)
			);
                    }
                }),

                "print": $.extend({}, TableTools.buttonBase, {
                    "sInfo": "<h6>Print view</h6><p>Please use your browser's print function to " +
		  "print this table. Press escape when finished.</p>",
                    "sMessage": null,
                    "bShowAll": true,
                    "sToolTip": "View print view",
                    "sButtonClass": "DTTT_button_print",
                    "sButtonText": "Print",
                    "fnClick": function (nButton, oConfig) {
                        this.fnPrint(true, oConfig);
                    }
                }),

                "text": $.extend({}, TableTools.buttonBase),

                "select": $.extend({}, TableTools.buttonBase, {
                    "sButtonText": "Select button",
                    "fnSelect": function (nButton, oConfig) {
                        if (this.fnGetSelected().length !== 0) {
                            $(nButton).removeClass(this.classes.buttons.disabled);
                        } else {
                            $(nButton).addClass(this.classes.buttons.disabled);
                        }
                    },
                    "fnInit": function (nButton, oConfig) {
                        $(nButton).addClass(this.classes.buttons.disabled);
                    }
                }),

                "select_single": $.extend({}, TableTools.buttonBase, {
                    "sButtonText": "Select button",
                    "fnSelect": function (nButton, oConfig) {
                        var iSelected = this.fnGetSelected().length;
                        if (iSelected == 1) {
                            $(nButton).removeClass(this.classes.buttons.disabled);
                        } else {
                            $(nButton).addClass(this.classes.buttons.disabled);
                        }
                    },
                    "fnInit": function (nButton, oConfig) {
                        $(nButton).addClass(this.classes.buttons.disabled);
                    }
                }),

                "select_all": $.extend({}, TableTools.buttonBase, {
                    "sButtonText": "Select all",
                    "fnClick": function (nButton, oConfig) {
                        this.fnSelectAll();
                    },
                    "fnSelect": function (nButton, oConfig) {
                        if (this.fnGetSelected().length == this.s.dt.fnRecordsDisplay()) {
                            $(nButton).addClass(this.classes.buttons.disabled);
                        } else {
                            $(nButton).removeClass(this.classes.buttons.disabled);
                        }
                    }
                }),

                "select_none": $.extend({}, TableTools.buttonBase, {
                    "sButtonText": "Deselect all",
                    "fnClick": function (nButton, oConfig) {
                        this.fnSelectNone();
                    },
                    "fnSelect": function (nButton, oConfig) {
                        if (this.fnGetSelected().length !== 0) {
                            $(nButton).removeClass(this.classes.buttons.disabled);
                        } else {
                            $(nButton).addClass(this.classes.buttons.disabled);
                        }
                    },
                    "fnInit": function (nButton, oConfig) {
                        $(nButton).addClass(this.classes.buttons.disabled);
                    }
                }),

                "ajax": $.extend({}, TableTools.buttonBase, {
                    "sAjaxUrl": "/xhr.php",
                    "sButtonText": "Ajax button",
                    "fnClick": function (nButton, oConfig) {
                        var sData = this.fnGetTableData(oConfig);
                        $.ajax({
                            "url": oConfig.sAjaxUrl,
                            "data": [
					{ "name": "tableData", "value": sData }
				],
                            "success": oConfig.fnAjaxComplete,
                            "dataType": "json",
                            "type": "POST",
                            "cache": false,
                            "error": function () {
                                alert("Error detected when sending table data to server");
                            }
                        });
                    },
                    "fnAjaxComplete": function (json) {
                        alert('Ajax complete');
                    }
                }),

                "div": $.extend({}, TableTools.buttonBase, {
                    "sAction": "div",
                    "sTag": "div",
                    "sButtonClass": "DTTT_nonbutton",
                    "sButtonText": "Text button"
                }),

                "collection": $.extend({}, TableTools.buttonBase, {
                    "sAction": "collection",
                    "sButtonClass": "DTTT_button_collection",
                    "sButtonText": "Collection",
                    "fnClick": function (nButton, oConfig) {
                        this._fnCollectionShow(nButton, oConfig);
                    }
                })
            };
            /*
            *  on* callback parameters:
            *     1. node - button element
            *     2. object - configuration object for this button
            *     3. object - ZeroClipboard reference (flash button only)
            *     4. string - Returned string from Flash (flash button only - and only on 'complete')
            */

            // Alias to match the other plug-ins styling
            TableTools.buttons = TableTools.BUTTONS;


            /**
            * @namespace Classes used by TableTools - allows the styles to be override easily.
            *   Note that when TableTools initialises it will take a copy of the classes object
            *   and will use its internal copy for the remainder of its run time.
            */
            TableTools.classes = {
                "container": "DTTT_container",
                "buttons": {
                    "normal": "DTTT_button",
                    "disabled": "DTTT_disabled"
                },
                "collection": {
                    "container": "DTTT_collection",
                    "background": "DTTT_collection_background",
                    "buttons": {
                        "normal": "DTTT_button",
                        "disabled": "DTTT_disabled"
                    }
                },
                "select": {
                    "table": "DTTT_selectable",
                    "row": "DTTT_selected selected"
                },
                "print": {
                    "body": "DTTT_Print",
                    "info": "DTTT_print_info",
                    "message": "DTTT_PrintMessage"
                }
            };


            /**
            * @namespace ThemeRoller classes - built in for compatibility with DataTables' 
            *   bJQueryUI option.
            */
            TableTools.classes_themeroller = {
                "container": "DTTT_container ui-buttonset ui-buttonset-multi",
                "buttons": {
                    "normal": "DTTT_button ui-button ui-state-default"
                },
                "collection": {
                    "container": "DTTT_collection ui-buttonset ui-buttonset-multi"
                }
            };


            /**
            * @namespace TableTools default settings for initialisation
            */
            TableTools.DEFAULTS = {
                "sSwfPath": "../swf/copy_csv_xls_pdf.swf",
                "sRowSelect": "none",
                "sRowSelector": "tr",
                "sSelectedClass": null,
                "fnPreRowSelect": null,
                "fnRowSelected": null,
                "fnRowDeselected": null,
                "aButtons": ["copy", "csv", "xls", "pdf", "print"],
                "oTags": {
                    "container": "div",
                    "button": "a", // We really want to use buttons here, but Firefox and IE ignore the
                    // click on the Flash element in the button (but not mouse[in|out]).
                    "liner": "span",
                    "collection": {
                        "container": "div",
                        "button": "a",
                        "liner": "span"
                    }
                }
            };

            // Alias to match the other plug-ins
            TableTools.defaults = TableTools.DEFAULTS;


            /**
            * Name of this class
            *  @constant CLASS
            *  @type	 String
            *  @default  TableTools
            */
            TableTools.prototype.CLASS = "TableTools";


            /**
            * TableTools version
            *  @constant  VERSION
            *  @type	  String
            *  @default   See code
            */
            TableTools.version = "2.2.1";



            // DataTables 1.10 API
            // 
            // This will be extended in a big way in in TableTools 3 to provide API methods
            // such as rows().select() and rows.selected() etc, but for the moment the
            // tabletools() method simply returns the instance.

            if ($.fn.dataTable.Api) {
                $.fn.dataTable.Api.register('tabletools()', function () {
                    var tt = null;

                    if (this.context.length > 0) {
                        tt = TableTools.fnGetInstance(this.context[0].nTable);
                    }

                    return tt;
                });
            }




            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Initialisation
            * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            /*
            * Register a new feature with DataTables
            */
            if (typeof $.fn.dataTable == "function" &&
	 typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
	 $.fn.dataTableExt.fnVersionCheck('1.9.0')) {
                $.fn.dataTableExt.aoFeatures.push({
                    "fnInit": function (oDTSettings) {
                        var init = oDTSettings.oInit;
                        var opts = init ?
				init.tableTools || init.oTableTools || {} :
				{};

                        var oTT = new TableTools(oDTSettings.oInstance, opts);
                        TableTools._aInstances.push(oTT);

                        return oTT.dom.container;
                    },
                    "cFeature": "T",
                    "sFeature": "TableTools"
                });
            }
            else {
                alert("Warning: TableTools requires DataTables 1.9.0 or newer - www.datatables.net/download");
            }

            $.fn.DataTable.TableTools = TableTools;

        })(jQuery, window, document);

        /*
        * Register a new feature with DataTables
        */
        if (typeof $.fn.dataTable == "function" &&
	 typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
	 $.fn.dataTableExt.fnVersionCheck('1.9.0')) {
            $.fn.dataTableExt.aoFeatures.push({
                "fnInit": function (oDTSettings) {
                    var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ?
				oDTSettings.oInit.oTableTools : {};

                    var oTT = new TableTools(oDTSettings.oInstance, oOpts);
                    TableTools._aInstances.push(oTT);

                    return oTT.dom.container;
                },
                "cFeature": "T",
                "sFeature": "TableTools"
            });
        }
        else {
            alert("Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download");
        }


        $.fn.dataTable.TableTools = TableTools;
        $.fn.DataTable.TableTools = TableTools;


        return TableTools;
    }; // /factory


    // Define as an AMD module if possible
    if (typeof define === 'function' && define.amd) {
        define('datatables-tabletools', ['jquery', 'datatables'], factory);
    }
    else if (jQuery && !jQuery.fn.dataTable.TableTools) {
        // Otherwise simply initialise as normal, stopping multiple evaluation
        factory(jQuery, jQuery.fn.dataTable);
    }


})(window, document);


/*
 * File:        ColumnFilterWidgets.js
 * Version:     1.0.2
 * Description: Controls for filtering based on unique column values in DataTables
 * Author:      Dylan Kuhn (www.cyberhobo.net)
 * Language:    Javascript
 * License:     GPL v2 or BSD 3 point style
 * Contact:     cyberhobo@cyberhobo.net
 * 
 * Copyright 2011 Dylan Kuhn (except fnGetColumnData by Benedikt Forchhammer), all rights reserved.
 *
 * This source file is free software, under either the GPL v2 license or a
 * BSD style license, available at:
 *   http://datatables.net/license_gpl2
 *   http://datatables.net/license_bsd
 */

(function ($) {
    /*
    * Function: fnGetColumnData
    * Purpose:  Return an array of table values from a particular column.
    * Returns:  array string: 1d data array 
    * Inputs:   object:oSettings - dataTable settings object. This is always the last argument past to the function
    *           int:iColumn - the id of the column to extract the data from
    *           bool:bUnique - optional - if set to false duplicated values are not filtered out
    *           bool:bFiltered - optional - if set to false all the table data is used (not only the filtered)
    *           bool:bIgnoreEmpty - optional - if set to false empty values are not filtered from the result array
    * Author:   Benedikt Forchhammer <b.forchhammer /AT\ mind2.de>
    */

    $.fn.dataTableExt.oApi.fnGetColumnData = function (oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty) {
        // check that we have a column id

        if (typeof iColumn == "undefined") return new Array();

        // by default we only wany unique data
        if (typeof bUnique == "undefined") bUnique = true;

        // by default we do want to only look at filtered data
        if (typeof bFiltered == "undefined") bFiltered = true;

        // by default we do not wany to include empty values
        if (typeof bIgnoreEmpty == "undefined") bIgnoreEmpty = true;

        // list of rows which we're going to loop through
        var aiRows;

        // use only filtered rows
        if (bFiltered == true) aiRows = oSettings.aiDisplay;
        // use all rows
        else aiRows = oSettings.aiDisplayMaster; // all row numbers

        // set up data array	
        var asResultData = new Array();

        for (var i = 0, c = aiRows.length; i < c; i++) {
            iRow = aiRows[i];
            var aData = this.fnGetData(iRow);
            //modif Nerium
            var sValue = (aData[iColumn] == "" ? "(Vide)" : aData[iColumn]);

            // ignore empty values?
            if (bIgnoreEmpty == true && sValue.length == 0) continue;

            // ignore unique values?
            else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;

            // else push the value onto the result data array
            else asResultData.push(sValue);
        }

        return asResultData;
    };

    /**
    * Add backslashes to regular expression symbols in a string.
    * 
    * Allows a regular expression to be constructed to search for 
    * variable text.
    * 
    * @param string sText The text to escape.
    * @return string The escaped string.
    */
    var fnRegExpEscape = function (sText) {
        return sText.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    };

    /**
    * Menu-based filter widgets based on distinct column values for a table.
    *
    * @class ColumnFilterWidgets 
    * @constructor
    * @param {object} oDataTableSettings Settings for the target table.
    */
    var premierAppel = false;
    var ColumnFilterWidgets = function (oDataTableSettings) {

        var me = this;
        var sExcludeList = '';
        trueData = '';
        me.$WidgetContainer = $('<div class="column-filter-widgets"></div>');
        me.$MenuContainer = me.$WidgetContainer;
        me.$TermContainer = null;
        me.aoWidgets = [];
        me.sSeparator = '';
        var bTrueData = false;
        if ('oColumnFilterWidgets' in oDataTableSettings.oInit) {
            if ('aiExclude' in oDataTableSettings.oInit.oColumnFilterWidgets) {
                sExcludeList = '|' + oDataTableSettings.oInit.oColumnFilterWidgets.aiExclude.join('|') + '|';
            }
            if ('bGroupTerms' in oDataTableSettings.oInit.oColumnFilterWidgets && oDataTableSettings.oInit.oColumnFilterWidgets.bGroupTerms) {
                me.$MenuContainer = $('<div class="column-filter-widget-menus"></div>');
                me.$TermContainer = $('<div class="column-filter-widget-selected-terms"></div>').hide();
            }
            if ('trueData' in oDataTableSettings.oInit.oColumnFilterWidgets) {
                trueData = oDataTableSettings.oInit.oColumnFilterWidgets.trueData;
                bTrueData = true;
            }
        }

        // Add a widget for each visible and filtered column
        var counttrueData = 0; // truedata added
        $.each(oDataTableSettings.aoColumns, function (i, oColumn) {
            var $columnTh = $(oColumn.nTh);
            var $WidgetElem = $('<div class="column-filter-widget"></div>');
            if (sExcludeList.indexOf('|' + i + '|') < 0) {

                if (bTrueData == true) {
                    me.aoWidgets.push(new ColumnFilterWidget($WidgetElem, oDataTableSettings, i, me, 'trueData')); // truedata added

                    counttrueData++; // truedata added


                } else {
                    me.aoWidgets.push(new ColumnFilterWidget($WidgetElem, oDataTableSettings, i, me, ""));

                }


            }
            me.$MenuContainer.append($WidgetElem);

        });
        if (me.$TermContainer) {
            me.$WidgetContainer.append(me.$MenuContainer);
            me.$WidgetContainer.append(me.$TermContainer);
        }
        oDataTableSettings.aoDrawCallback.push({
            name: 'ColumnFilterWidgets',
            fn: function () {
                if (premierAppel == false) {

                    $.each(me.aoWidgets, function (i, oWidget) {
                        oWidget.fnDraw();
                    });
                    premierAppel = true;
                }
            }
        });

        return me;
    };

    /**
    * Get the container node of the column filter widgets.
    * 
    * @method
    * @return {Node} The container node.
    */
    ColumnFilterWidgets.prototype.getContainer = function () {
        return this.$WidgetContainer.get(0);
    }

    /**
    * A filter widget based on data in a table column.
    * 
    * @class ColumnFilterWidget
    * @constructor
    * @param {object} $Container The jQuery object that should contain the widget.
    * @param {object} oSettings The target table's settings.
    * @param {number} i The numeric index of the target table column.
    * @param {object} widgets The ColumnFilterWidgets instance the widget is a member of.
    */
    var ColumnFilterWidget = function ($Container, oDataTableSettings, i, widgets, trueData) { // truedata added
        var widget = this, sTargetList;
        widget.trueData = trueData; // truedata added
        widget.iColumn = i;
        widget.oColumn = oDataTableSettings.aoColumns[i];
        widget.$Container = $Container;
        widget.oDataTable = oDataTableSettings.oInstance;
        widget.asFilters = [];
        widget.sSeparator = '';
        widget.bSort = true;
        widget.iMaxSelections = -1;

        if ('oColumnFilterWidgets' in oDataTableSettings.oInit) {
            if ('sSeparator' in oDataTableSettings.oInit.oColumnFilterWidgets) {
                widget.sSeparator = oDataTableSettings.oInit.oColumnFilterWidgets.sSeparator;
            }
            if ('iMaxSelections' in oDataTableSettings.oInit.oColumnFilterWidgets) {
                widget.iMaxSelections = oDataTableSettings.oInit.oColumnFilterWidgets.iMaxSelections;
            }
            if ('aoColumnDefs' in oDataTableSettings.oInit.oColumnFilterWidgets) {
                $.each(oDataTableSettings.oInit.oColumnFilterWidgets.aoColumnDefs, function (iIndex, oColumnDef) {
                    var sTargetList = '|' + oColumnDef.aiTargets.join('|') + '|';
                    if (sTargetList.indexOf('|' + i + '|') >= 0) {
                        $.each(oColumnDef, function (sDef, oDef) {
                            widget[sDef] = oDef;
                        });
                    }
                });
            }
        }
        widget.$Select = $('<select></select>').change(function () {
            var sSelected = widget.$Select.val(), sText, $TermLink, $SelectedOption;

            if ('' === sSelected) {
                // The blank option is a default, not a filter, and is re-selected after filtering
                return;
            }

            var sText2 = sSelected;
            sText = $('<div>' + sSelected + '</div>').text();


            $TermLink = $('<a class="filter-term" href="#"></a>')
                    .addClass('filter-term-' + sText.toLowerCase().replace(/\W/g, ''))
                    .text(sText2)
                    .click(function () {
                        // Remove from current filters array
                        widget.asFilters = $.grep(widget.asFilters, function (sFilter) {
                            return sFilter != sSelected;
                        });
                        $TermLink.remove();
                        if (widgets.$TermContainer && 0 === widgets.$TermContainer.find('.filter-term').length) {
                            widgets.$TermContainer.hide();
                        }
                        // Add it back to the select
                        widget.$Select.append($('<option></option>').attr('value', sSelected).text(sSelected));
                        if (widget.iMaxSelections > 0 && widget.iMaxSelections > widget.asFilters.length) {
                            widget.$Select.attr('disabled', false);
                        }
                        
                        widget.fnFilter();
                        
                        return false;
                    });
            widget.asFilters.push(sSelected);
            if (widgets.$TermContainer) {
                widgets.$TermContainer.show();
                widgets.$TermContainer.prepend($TermLink);
            } else {
                widget.$Select.after($TermLink);
            }
            $SelectedOption = widget.$Select.children('option:selected');
            widget.$Select.val('');
            $SelectedOption.remove();
            if (widget.iMaxSelections > 0 && widget.iMaxSelections <= widget.asFilters.length) {
                widget.$Select.attr('disabled', true);
            }
            
            widget.fnFilter();
            


        });
        widget.$Container.append(widget.$Select);
        widget.fnDraw();
    };
    /**
    * Perform filtering on the target column.
    * 
    * @method fnFilter
    */
    ColumnFilterWidget.prototype.fnFilter = function () {

        var widget = this;
        var asEscapedFilters = [];
        var sFilterStart, sFilterEnd;
        if (widget.asFilters.length > 0) {
            //Ajout Nerium pour icone alerte
            $('#' + widget.oDataTable.DataTable().settings()[0].sInstance).find(".iconeParametrage").addClass("avecAlert");

            // Filters must have RegExp symbols escaped
            $.each(widget.asFilters, function (i, sFilter) {
                asEscapedFilters.push(fnRegExpEscape(sFilter));
            });
            // This regular expression filters by either whole column values or an item in a comma list
            sFilterStart = widget.sSeparator ? '(^|' + widget.sSeparator + ')(' : '^(';
            sFilterEnd = widget.sSeparator ? ')(' + widget.sSeparator + '|$)' : ')$';
            var dataTablePrevSearch = widget.oDataTable.DataTable().settings()[0].aoPreSearchCols[widget.iColumn].sSearch;
            var prevSearch = (dataTablePrevSearch.indexOf('[') >= 0 && dataTablePrevSearch.indexOf(']') >= 0 ? dataTablePrevSearch.substring(dataTablePrevSearch.indexOf('['), dataTablePrevSearch.indexOf(']') + 1) : "");
            widget.oDataTable.DataTable().columns(widget.iColumn).search(sFilterStart + asEscapedFilters.join('|') + sFilterEnd + prevSearch, true, false);
            if (etatTest) {
                widget.oDataTable.DataTable().draw();
            }
            //widget.oDataTable.fnFilter(sFilterStart + asEscapedFilters.join('|') + sFilterEnd, widget.iColumn, true, false);
        } else {
            //Ajout Nerium pour icone alerte
            $('#' + widget.oDataTable.DataTable().settings()[0].sInstance).find(".iconeParametrage").removeClass("avecAlert");
            // Clear any filters for this column
            var dataTablePrevSearch = widget.oDataTable.DataTable().settings()[0].aoPreSearchCols[widget.iColumn].sSearch;
            var prevSearch = (dataTablePrevSearch.indexOf('[') >= 0 && dataTablePrevSearch.indexOf(']') >= 0 ? dataTablePrevSearch.substring(dataTablePrevSearch.indexOf('['), dataTablePrevSearch.indexOf(']') + 1) : "");
            widget.oDataTable.DataTable().columns(widget.iColumn).search('' + prevSearch, true, false);
            if (etatTest) {
                widget.oDataTable.DataTable().draw();
            }

        }
    };

    /**
    * On each table draw, update filter menu items as needed. This allows any process to
    * update the table's column visiblity and menus will still be accurate.
    * 
    * @method fnDraw
    */
    ColumnFilterWidget.prototype.fnDraw = function () {

        var widget = this;
        var oDistinctOptions = {};
        var aDistinctOptions = [];
        var aData;
        if (widget.asFilters.length === 0) {
            // Find distinct column values

            if (widget.trueData != "") {

                widget.$Select.empty().append($('<option></option>').attr('value', '').text(widget.oColumn.sTitle));
            }
            else {
                aData = widget.oDataTable.fnGetColumnData(widget.iColumn, true, true, false);
                $.each(aData, function (i, sValue) {
                    var asValues = widget.sSeparator ? sValue.split(new RegExp(widget.sSeparator)) : [sValue];
                    $.each(asValues, function (j, sOption) {
                        if (!oDistinctOptions.hasOwnProperty(sOption)) {
                            oDistinctOptions[sOption] = true;
                            aDistinctOptions.push(sOption);
                        }
                    });
                });

                widget.$Select.empty().append($('<option></option>').attr('value', '').text(widget.oColumn.sTitle));

                // Build the menu
                //
                // ### changed the <a href="/ref#sTitle">sTitle</a> filled in the dropdown base to the <a href="/ref#sName">sName</a>            widget.$Select.empty().append( $( '<option></option>' ).attr( 'value', '' ).text( widget.oColumn.sTitle ) );
                //
                //widget.$Select.empty().append( $( '<option></option>' ).attr( 'value', '' ).text( widget.oColumn.sName ) );
                if (widget.bSort) {
                    if (widget.hasOwnProperty('fnSort')) {
                        aDistinctOptions.sort(widget.fnSort);
                    } else {
                        //ajout nerium pour le tri par type
                        var typeContenu = widget.oDataTable.fnSettings().aoColumns[widget.iColumn].sClass;
                        if (typeContenu.indexOf("numeriqueTri") >= 0) {
                            aDistinctOptions = aDistinctOptions.map(Number);
                            aDistinctOptions.sort(function (a, b) { return a - b });
                            aDistinctOptions = aDistinctOptions.map(String);
                        } else {
                            if (typeContenu.indexOf("dateHeureTri") >= 0) {

                                aDistinctOptions = aDistinctOptions.map(function (val, idx) {
                                    val = (val == "(Vide)" ? "01/01/1900 00:00:00" : val);
                                    var partDateHeure = val.split(' ');
                                    var partsDate = partDateHeure[0].split('/');
                                    var partsHeure = partDateHeure[1].split(':');
                                    return new Date(partsDate[2], partsDate[1] - 1, partsDate[0], partsHeure[0], partsHeure[1], partsHeure[2]);
                                });

                                aDistinctOptions.sort(function (date1, date2) {
                                    // ordre DESCENDANT.
                                    if (date1 > date2) return -1;
                                    if (date1 < date2) return 1;
                                    return 0;
                                });

                                aDistinctOptions = aDistinctOptions.map(function (val, idx) {
                                    return (val.getDate().toString().length < 2 ? "0" + val.getDate() : val.getDate())
                                    + "/" + ((val.getMonth() + 1).toString().length < 2 ? "0" + (val.getMonth() + 1) : (val.getMonth() + 1))
                                    + "/" + val.getFullYear() + " " + (val.getHours().toString().length < 2 ? "0" + val.getHours() : val.getHours())
                                    + ":" + (val.getMinutes().toString().length < 2 ? "0" + val.getMinutes() : val.getMinutes())
                                    + ":" + (val.getSeconds().toString().length < 2 ? "0" + val.getSeconds() : val.getSeconds())
                                });

                            } else {
                                if (typeContenu.indexOf("dateTri") >= 0) {
                                    aDistinctOptions = aDistinctOptions.map(function (val, idx) {
                                        var parts = val.split('/');
                                        var dtest = new Date(parts[2], parts[1] - 1, parts[0]);

                                        return dtest;
                                    });

                                    aDistinctOptions.sort(function (date1, date2) {
                                        // ordre DESCENDANT.
                                        if (date1 > date2) return -1;
                                        if (date1 < date2) return 1;
                                        return 0;
                                    });

                                    aDistinctOptions = aDistinctOptions.map(function (val, idx) {

                                        return (val.getDate().toString().length < 2 ? "0" + val.getDate() : val.getDate())
                                    + "/" + ((val.getMonth() + 1).toString().length < 2 ? "0" + (val.getMonth() + 1) : (val.getMonth() + 1))
                                    + "/" + val.getFullYear()
                                    });

                                } else {
                                    aDistinctOptions.sort();
                                }

                            }
                        }
                    }
                }
                $.each(aDistinctOptions, function (i, sOption) {
                    var sText;
                    sText = $('<div>' + sOption + '</div>').text();
                    sText = (sText == "01/01/1900 00:00:00" ? "(Vide)" : sText);
                    sOption = sOption.replace('&lt;', '<').replace('&gt;', '>');
                    widget.$Select.append($('<option></option>').attr('value', sOption).text(sText));
                });
                if (aDistinctOptions.length > 0) {
                    // Enable the menu
                    widget.$Select.attr('disabled', false);
                } else {
                    // 0 option is not a useful menu, disable it
                    widget.$Select.attr('disabled', true);
                }
            }



        }
    };

    /*
    * Register a new feature with DataTables
    */
    if (typeof $.fn.dataTable === 'function' && typeof $.fn.dataTableExt.fnVersionCheck === 'function' && $.fn.dataTableExt.fnVersionCheck('1.7.0')) {

        $.fn.dataTableExt.aoFeatures.push({
            'fnInit': function (oDTSettings) {
                var oWidgets = new ColumnFilterWidgets(oDTSettings);
                return oWidgets.getContainer();
            },
            'cFeature': 'W',
            'sFeature': 'ColumnFilterWidgets'
        });

    } else {
        throw 'Warning: ColumnFilterWidgets requires DataTables 1.7 or greater - www.datatables.net/download';
    }


} (jQuery));

/*! ColReorder 1.1.2
* ©2010-2014 SpryMedia Ltd - datatables.net/license
*/

/**
* @summary     ColReorder
* @description Provide the ability to reorder columns in a DataTable
* @version     1.1.2
* @file        dataTables.colReorder.js
* @author      SpryMedia Ltd (www.sprymedia.co.uk)
* @contact     www.sprymedia.co.uk/contact
* @copyright   Copyright 2010-2014 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
*   MIT license - http://datatables.net/license/mit
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.datatables.net
*/

(function (window, document, undefined) {


    /**
    * Switch the key value pairing of an index array to be value key (i.e. the old value is now the
    * key). For example consider [ 2, 0, 1 ] this would be returned as [ 1, 2, 0 ].
    *  @method  fnInvertKeyValues
    *  @param   array aIn Array to switch around
    *  @returns array
    */
    function fnInvertKeyValues(aIn) {
        var aRet = [];
        for (var i = 0, iLen = aIn.length; i < iLen; i++) {
            aRet[aIn[i]] = i;
        }
        return aRet;
    }


    /**
    * Modify an array by switching the position of two elements
    *  @method  fnArraySwitch
    *  @param   array aArray Array to consider, will be modified by reference (i.e. no return)
    *  @param   int iFrom From point
    *  @param   int iTo Insert point
    *  @returns void
    */
    function fnArraySwitch(aArray, iFrom, iTo) {
        var mStore = aArray.splice(iFrom, 1)[0];
        aArray.splice(iTo, 0, mStore);
    }


    /**
    * Switch the positions of nodes in a parent node (note this is specifically designed for
    * table rows). Note this function considers all element nodes under the parent!
    *  @method  fnDomSwitch
    *  @param   string sTag Tag to consider
    *  @param   int iFrom Element to move
    *  @param   int Point to element the element to (before this point), can be null for append
    *  @returns void
    */
    function fnDomSwitch(nParent, iFrom, iTo) {
        var anTags = [];
        //console.log("ordering " + iFrom + " to " + iTo);
        for (var i = 0, iLen = nParent.childNodes.length; i < iLen; i++) {
            if (nParent.childNodes[i].nodeType == 1) {
                anTags.push(nParent.childNodes[i]);
            }
        }
        var nStore = anTags[iFrom];

        if (iTo !== null) {
            nParent.insertBefore(nStore, anTags[iTo]);
        }
        else {
            nParent.appendChild(nStore);
        }
    }



    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    * DataTables plug-in API functions
    *
    * This are required by ColReorder in order to perform the tasks required, and also keep this
    * code portable, to be used for other column reordering projects with DataTables, if needed.
    * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


    /**
    * Plug-in for DataTables which will reorder the internal column structure by taking the column
    * from one position (iFrom) and insert it into a given point (iTo).
    *  @method  $.fn.dataTableExt.oApi.fnColReorder
    *  @param   object oSettings DataTables settings object - automatically added by DataTables!
    *  @param   int iFrom Take the column to be repositioned from this point
    *  @param   int iTo and insert it into this point
    *  @returns void
    */
    $.fn.dataTableExt.oApi.fnColReorder = function (oSettings, iFrom, iTo) {
        //console.log("yep")
        var v110 = $.fn.dataTable.Api ? true : false;
        var i, iLen, j, jLen, iCols = oSettings.aoColumns.length, nTrs, oCol;
        var attrMap = function (obj, prop, mapping) {
            if (!obj[prop]) {
                return;
            }

            var a = obj[prop].split('.');
            var num = a.shift();

            if (isNaN(num * 1)) {
                return;
            }

            obj[prop] = mapping[num * 1] + '.' + a.join('.');
        };

        /* Sanity check in the input */
        if (iFrom == iTo) {
            /* Pointless reorder */
            return;
        }

        if (iFrom < 0 || iFrom >= iCols) {
            this.oApi._fnLog(oSettings, 1, "ColReorder 'from' index is out of bounds: " + iFrom);
            return;
        }

        if (iTo < 0 || iTo >= iCols) {
            this.oApi._fnLog(oSettings, 1, "ColReorder 'to' index is out of bounds: " + iTo);
            return;
        }

        /*
        * Calculate the new column array index, so we have a mapping between the old and new
        */
        var aiMapping = [];
        for (i = 0, iLen = iCols; i < iLen; i++) {
            aiMapping[i] = i;
        }
        fnArraySwitch(aiMapping, iFrom, iTo);
        var aiInvertMapping = fnInvertKeyValues(aiMapping);


        /*
        * Convert all internal indexing to the new column order indexes
        */
        /* Sorting */
        for (i = 0, iLen = oSettings.aaSorting.length; i < iLen; i++) {
            oSettings.aaSorting[i][0] = aiInvertMapping[oSettings.aaSorting[i][0]];
        }

        /* Fixed sorting */
        if (oSettings.aaSortingFixed !== null) {
            for (i = 0, iLen = oSettings.aaSortingFixed.length; i < iLen; i++) {
                oSettings.aaSortingFixed[i][0] = aiInvertMapping[oSettings.aaSortingFixed[i][0]];
            }
        }

        /* Data column sorting (the column which the sort for a given column should take place on) */
        for (i = 0, iLen = iCols; i < iLen; i++) {
            oCol = oSettings.aoColumns[i];
            for (j = 0, jLen = oCol.aDataSort.length; j < jLen; j++) {
                oCol.aDataSort[j] = aiInvertMapping[oCol.aDataSort[j]];
            }

            // Update the column indexes
            if (v110) {
                oCol.idx = aiInvertMapping[oCol.idx];
            }
        }

        if (v110) {
            // Update 1.10 optimised sort class removal variable
            $.each(oSettings.aLastSort, function (i, val) {
                oSettings.aLastSort[i].src = aiInvertMapping[val.src];
            });
        }

        /* Update the Get and Set functions for each column */
        for (i = 0, iLen = iCols; i < iLen; i++) {
            oCol = oSettings.aoColumns[i];

            if (typeof oCol.mData == 'number') {
                oCol.mData = aiInvertMapping[oCol.mData];

                // regenerate the get / set functions
                oSettings.oApi._fnColumnOptions(oSettings, i, {});
            }
            else if ($.isPlainObject(oCol.mData)) {
                // HTML5 data sourced
                attrMap(oCol.mData, '_', aiInvertMapping);
                attrMap(oCol.mData, 'filter', aiInvertMapping);
                attrMap(oCol.mData, 'sort', aiInvertMapping);
                attrMap(oCol.mData, 'type', aiInvertMapping);

                // regenerate the get / set functions
                oSettings.oApi._fnColumnOptions(oSettings, i, {});
            }
        }


        /*
        * Move the DOM elements
        */
        if (oSettings.aoColumns[iFrom].bVisible) {
            /* Calculate the current visible index and the point to insert the node before. The insert
            * before needs to take into account that there might not be an element to insert before,
            * in which case it will be null, and an appendChild should be used
            */
            var iVisibleIndex = this.oApi._fnColumnIndexToVisible(oSettings, iFrom);
            var iInsertBeforeIndex = null;

            i = iTo < iFrom ? iTo : iTo + 1;
            while (iInsertBeforeIndex === null && i < iCols) {
                iInsertBeforeIndex = this.oApi._fnColumnIndexToVisible(oSettings, i);
                i++;
            }

            /* Header */
            nTrs = oSettings.nTHead.getElementsByTagName('tr');
            for (i = 0, iLen = nTrs.length; i < iLen; i++) {
                fnDomSwitch(nTrs[i], iVisibleIndex, iInsertBeforeIndex);
            }

            /* Footer */
            if (oSettings.nTFoot !== null) {
                nTrs = oSettings.nTFoot.getElementsByTagName('tr');
                for (i = 0, iLen = nTrs.length; i < iLen; i++) {
                    fnDomSwitch(nTrs[i], iVisibleIndex, iInsertBeforeIndex);
                }
            }

            /* Body */
            for (i = 0, iLen = oSettings.aoData.length; i < iLen; i++) {
                if (oSettings.aoData[i].nTr !== null) {
                    fnDomSwitch(oSettings.aoData[i].nTr, iVisibleIndex, iInsertBeforeIndex);
                }
            }
        }

        /*
        * Move the internal array elements
        */
        /* Columns */
        fnArraySwitch(oSettings.aoColumns, iFrom, iTo);

        /* Search columns */
        // fnArraySwitch(oSettings.aoPreSearchCols, iFrom, iTo);

        /* Array array - internal data anodes cache */
        for (i = 0, iLen = oSettings.aoData.length; i < iLen; i++) {
            var data = oSettings.aoData[i];

            if (v110) {
                // DataTables 1.10+
                if (data.anCells) {
                    fnArraySwitch(data.anCells, iFrom, iTo);
                }

                // For DOM sourced data, the invalidate will reread the cell into
                // the data array, but for data sources as an array, they need to
                // be flipped
                if (data.src !== 'dom' && $.isArray(data._aData)) {
                    fnArraySwitch(data._aData, iFrom, iTo);
                }
            }
            else {
                // DataTables 1.9-
                if ($.isArray(data._aData)) {
                    fnArraySwitch(data._aData, iFrom, iTo);
                }
                fnArraySwitch(data._anHidden, iFrom, iTo);
            }
        }

        /* Reposition the header elements in the header layout array */
        for (i = 0, iLen = oSettings.aoHeader.length; i < iLen; i++) {
            fnArraySwitch(oSettings.aoHeader[i], iFrom, iTo);
        }

        if (oSettings.aoFooter !== null) {
            for (i = 0, iLen = oSettings.aoFooter.length; i < iLen; i++) {
                fnArraySwitch(oSettings.aoFooter[i], iFrom, iTo);
            }
        }

        // In 1.10 we need to invalidate row cached data for sorting, filtering etc
        if (v110) {
            //            var api = new $.fn.dataTable.Api(oSettings);
            //            api.rows().invalidate();
        }

        /*
        * Update DataTables' event handlers
        */

        /* Sort listener */
        for (i = 0, iLen = iCols; i < iLen; i++) {
            $(oSettings.aoColumns[i].nTh).off('click.DT');
            this.oApi._fnSortAttachListener(oSettings, oSettings.aoColumns[i].nTh, i);
        }


        /* Fire an event so other plug-ins can update */
        $(oSettings.oInstance).trigger('column-reorder', [oSettings, {
            "iFrom": iFrom,
            "iTo": iTo,
            "aiInvertMapping": aiInvertMapping
        }]);
    };



    var factory = function ($, DataTable) {
        "use strict";

        /**
        * ColReorder provides column visibility control for DataTables
        * @class ColReorder
        * @constructor
        * @param {object} dt DataTables settings object
        * @param {object} opts ColReorder options
        */
        var ColReorder = function (dt, opts) {
            var oDTSettings;

            if ($.fn.dataTable.Api) {
                oDTSettings = new $.fn.dataTable.Api(dt).settings()[0];
            }
            // 1.9 compatibility
            else if (dt.fnSettings) {
                // DataTables object, convert to the settings object
                oDTSettings = dt.fnSettings();
            }
            else if (typeof dt === 'string') {
                // jQuery selector
                if ($.fn.dataTable.fnIsDataTable($(dt)[0])) {
                    oDTSettings = $(dt).eq(0).dataTable().fnSettings();
                }
            }
            else if (dt.nodeName && dt.nodeName.toLowerCase() === 'table') {
                // Table node
                if ($.fn.dataTable.fnIsDataTable(dt.nodeName)) {
                    oDTSettings = $(dt.nodeName).dataTable().fnSettings();
                }
            }
            else if (dt instanceof jQuery) {
                // jQuery object
                if ($.fn.dataTable.fnIsDataTable(dt[0])) {
                    oDTSettings = dt.eq(0).dataTable().fnSettings();
                }
            }
            else {
                // DataTables settings object
                oDTSettings = dt;
            }

            // Convert from camelCase to Hungarian, just as DataTables does
            var camelToHungarian = $.fn.dataTable.camelToHungarian;
            if (camelToHungarian) {
                camelToHungarian(ColReorder.defaults, ColReorder.defaults, true);
                camelToHungarian(ColReorder.defaults, opts || {});
            }


            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Public class variables
            * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            /**
            * @namespace Settings object which contains customisable information for ColReorder instance
            */
            this.s = {
                /**
                * DataTables settings object
                *  @property dt
                *  @type     Object
                *  @default  null
                */
                "dt": null,

                /**
                * Initialisation object used for this instance
                *  @property init
                *  @type     object
                *  @default  {}
                */
                "init": $.extend(true, {}, ColReorder.defaults, opts),

                /**
                * Number of columns to fix (not allow to be reordered)
                *  @property fixed
                *  @type     int
                *  @default  0
                */
                "fixed": 0,

                /**
                * Number of columns to fix counting from right (not allow to be reordered)
                *  @property fixedRight
                *  @type     int
                *  @default  0
                */
                "fixedRight": 0,

                /**
                * Callback function for once the reorder has been done
                *  @property dropcallback
                *  @type     function
                *  @default  null
                */
                "dropCallback": null,

                /**
                * @namespace Information used for the mouse drag
                */
                "mouse": {
                    "startX": -1,
                    "startY": -1,
                    "offsetX": -1,
                    "offsetY": -1,
                    "target": -1,
                    "targetIndex": -1,
                    "fromIndex": -1
                },

                /**
                * Information which is used for positioning the insert cusor and knowing where to do the
                * insert. Array of objects with the properties:
                *   x: x-axis position
                *   to: insert point
                *  @property aoTargets
                *  @type     array
                *  @default  []
                */
                "aoTargets": []
            };


            /**
            * @namespace Common and useful DOM elements for the class instance
            */
            this.dom = {
                /**
                * Dragging element (the one the mouse is moving)
                *  @property drag
                *  @type     element
                *  @default  null
                */
                "drag": null,

                /**
                * The insert cursor
                *  @property pointer
                *  @type     element
                *  @default  null
                */
                "pointer": null
            };


            /* Constructor logic */
            this.s.dt = oDTSettings.oInstance.fnSettings();
            this.s.dt._colReorder = this;
            this._fnConstruct();

            /* Add destroy callback */
            oDTSettings.oApi._fnCallbackReg(oDTSettings, 'aoDestroyCallback', $.proxy(this._fnDestroy, this), 'ColReorder');

            return this;
        };



        ColReorder.prototype = {
            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Public methods
            * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            /**
            * Reset the column ordering to the original ordering that was detected on
            * start up.
            *  @return {this} Returns `this` for chaining.
            *
            *  @example
            *    // DataTables initialisation with ColReorder
            *    var table = $('#example').dataTable( {
            *        "sDom": 'Rlfrtip'
            *    } );
            *
            *    // Add click event to a button to reset the ordering
            *    $('#resetOrdering').click( function (e) {
            *        e.preventDefault();
            *        $.fn.dataTable.ColReorder( table ).fnReset();
            *    } );
            */
            "fnReset": function () {
                var a = [];
                for (var i = 0, iLen = this.s.dt.aoColumns.length; i < iLen; i++) {
                    a.push(this.s.dt.aoColumns[i]._ColReorder_iOrigCol);
                }

                this._fnOrderColumns(a);

                return this;
            },

            /**
            * `Deprecated` - Get the current order of the columns, as an array.
            *  @return {array} Array of column identifiers
            *  @deprecated `fnOrder` should be used in preference to this method.
            *      `fnOrder` acts as a getter/setter.
            */
            "fnGetCurrentOrder": function () {
                return this.fnOrder();
            },

            /**
            * Get the current order of the columns, as an array. Note that the values
            * given in the array are unique identifiers for each column. Currently
            * these are the original ordering of the columns that was detected on
            * start up, but this could potentially change in future.
            *  @return {array} Array of column identifiers
            *
            *  @example
            *    // Get column ordering for the table
            *    var order = $.fn.dataTable.ColReorder( dataTable ).fnOrder();
            */
            /**
            * Set the order of the columns, from the positions identified in the
            * ordering array given. Note that ColReorder takes a brute force approach
            * to reordering, so it is possible multiple reordering events will occur
            * before the final order is settled upon.
            *  @param {array} [set] Array of column identifiers in the new order. Note
            *    that every column must be included, uniquely, in this array.
            *  @return {this} Returns `this` for chaining.
            *
            *  @example
            *    // Swap the first and second columns
            *    $.fn.dataTable.ColReorder( dataTable ).fnOrder( [1, 0, 2, 3, 4] );
            *
            *  @example
            *    // Move the first column to the end for the table `#example`
            *    var curr = $.fn.dataTable.ColReorder( '#example' ).fnOrder();
            *    var first = curr.shift();
            *    curr.push( first );
            *    $.fn.dataTable.ColReorder( '#example' ).fnOrder( curr );
            *
            *  @example
            *    // Reverse the table's order
            *    $.fn.dataTable.ColReorder( '#example' ).fnOrder(
            *      $.fn.dataTable.ColReorder( '#example' ).fnOrder().reverse()
            *    );
            */
            "fnOrder": function (set) {

                if (set === undefined) {
                    var a = [];
                    for (var i = 0, iLen = this.s.dt.aoColumns.length; i < iLen; i++) {
                        a.push(this.s.dt.aoColumns[i]._ColReorder_iOrigCol);
                    }
                    return a;
                }

                this._fnOrderColumns(fnInvertKeyValues(set));

                return this;
            },


            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Private methods (they are of course public in JS, but recommended as private)
            * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

            /**
            * Constructor logic
            *  @method  _fnConstruct
            *  @returns void
            *  @private
            */
            "_fnConstruct": function () {
                var that = this;
                var iLen = this.s.dt.aoColumns.length;
                var i;

                /* Columns discounted from reordering - counting left to right */
                if (this.s.init.iFixedColumns) {
                    this.s.fixed = this.s.init.iFixedColumns;
                }

                /* Columns discounted from reordering - counting right to left */
                this.s.fixedRight = this.s.init.iFixedColumnsRight ?
			this.s.init.iFixedColumnsRight :
			0;

                /* Drop callback initialisation option */
                if (this.s.init.fnReorderCallback) {
                    this.s.dropCallback = this.s.init.fnReorderCallback;
                }

                /* Add event handlers for the drag and drop, and also mark the original column order */
                for (i = 0; i < iLen; i++) {
                    if (i > this.s.fixed - 1 && i < iLen - this.s.fixedRight) {
                        this._fnMouseListener(i, this.s.dt.aoColumns[i].nTh);
                    }

                    /* Mark the original column order for later reference */
                    this.s.dt.aoColumns[i]._ColReorder_iOrigCol = i;
                }

                /* State saving */
                this.s.dt.oApi._fnCallbackReg(this.s.dt, 'aoStateSaveParams', function (oS, oData) {
                    that._fnStateSave.call(that, oData);
                }, "ColReorder_State");

                /* An initial column order has been specified */
                var aiOrder = null;
                if (this.s.init.aiOrder) {
                    aiOrder = this.s.init.aiOrder.slice();
                }

                /* State loading, overrides the column order given */
                if (this.s.dt.oLoadedState && typeof this.s.dt.oLoadedState.ColReorder != 'undefined' &&
		  this.s.dt.oLoadedState.ColReorder.length == this.s.dt.aoColumns.length) {
                    aiOrder = this.s.dt.oLoadedState.ColReorder;
                }

                /* If we have an order to apply - do so */
                if (aiOrder) {
                    /* We might be called during or after the DataTables initialisation. If before, then we need
                    * to wait until the draw is done, if after, then do what we need to do right away
                    */
                    if (!that.s.dt._bInitComplete) {
                        var bDone = false;
                        this.s.dt.aoDrawCallback.push({
                            "fn": function () {
                                if (!that.s.dt._bInitComplete && !bDone) {
                                    bDone = true;
                                    var resort = fnInvertKeyValues(aiOrder);
                                    that._fnOrderColumns.call(that, resort);
                                }
                            },
                            "sName": "ColReorder_Pre"
                        });
                    }
                    else {
                        var resort = fnInvertKeyValues(aiOrder);
                        that._fnOrderColumns.call(that, resort);
                    }
                }
                else {
                    this._fnSetColumnIndexes();
                }
            },


            /**
            * Set the column order from an array
            *  @method  _fnOrderColumns
            *  @param   array a An array of integers which dictate the column order that should be applied
            *  @returns void
            *  @private
            */
            "_fnOrderColumns": function (a) {
                if (a.length != this.s.dt.aoColumns.length) {
                    this.s.dt.oInstance.oApi._fnLog(this.s.dt, 1, "ColReorder - array reorder does not " +
				"match known number of columns. Skipping.");
                    return;
                }

                for (var i = 0, iLen = a.length; i < iLen; i++) {
                    var currIndex = $.inArray(i, a);
                    if (i != currIndex) {
                        //                        /* Reorder our switching array */
                        fnArraySwitch(a, currIndex, i);

                        /* Do the column reorder in the table */
                        this.s.dt.oInstance.fnColReorder(currIndex, i);
                    }
                }

                /* When scrolling we need to recalculate the column sizes to allow for the shift */
                if (this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "") {
                    this.s.dt.oInstance.fnAdjustColumnSizing();
                }

                /* Save the state */
                this.s.dt.oInstance.oApi._fnSaveState(this.s.dt);

                this._fnSetColumnIndexes();
            },


            /**
            * Because we change the indexes of columns in the table, relative to their starting point
            * we need to reorder the state columns to what they are at the starting point so we can
            * then rearrange them again on state load!
            *  @method  _fnStateSave
            *  @param   object oState DataTables state
            *  @returns string JSON encoded cookie string for DataTables
            *  @private
            */
            "_fnStateSave": function (oState) {
                var i, iLen, aCopy, iOrigColumn;
                var oSettings = this.s.dt;
                var columns = oSettings.aoColumns;

                oState.ColReorder = [];

                /* Sorting */
                if (oState.aaSorting) {
                    // 1.10.0-
                    for (i = 0; i < oState.aaSorting.length; i++) {
                        oState.aaSorting[i][0] = columns[oState.aaSorting[i][0]]._ColReorder_iOrigCol;
                    }

                    var aSearchCopy = $.extend(true, [], oState.aoSearchCols);

                    for (i = 0, iLen = columns.length; i < iLen; i++) {
                        iOrigColumn = columns[i]._ColReorder_iOrigCol;

                        /* Column filter */
                        oState.aoSearchCols[iOrigColumn] = aSearchCopy[i];

                        /* Visibility */
                        oState.abVisCols[iOrigColumn] = columns[i].bVisible;

                        /* Column reordering */
                        oState.ColReorder.push(iOrigColumn);
                    }
                }
                else if (oState.order) {
                    // 1.10.1+
                    for (i = 0; i < oState.order.length; i++) {
                        oState.order[i][0] = columns[oState.order[i][0]]._ColReorder_iOrigCol;
                    }

                    var stateColumnsCopy = $.extend(true, [], oState.columns);

                    for (i = 0, iLen = columns.length; i < iLen; i++) {
                        iOrigColumn = columns[i]._ColReorder_iOrigCol;

                        /* Columns */
                        oState.columns[iOrigColumn] = stateColumnsCopy[i];

                        /* Column reordering */
                        oState.ColReorder.push(iOrigColumn);
                    }
                }
            },


            /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
            * Mouse drop and drag
            */

            /**
            * Add a mouse down listener to a particluar TH element
            *  @method  _fnMouseListener
            *  @param   int i Column index
            *  @param   element nTh TH element clicked on
            *  @returns void
            *  @private
            */
            "_fnMouseListener": function (i, nTh) {
                var that = this;
                $(nTh).on('mousedown.ColReorder', function (e) {
                    e.preventDefault();
                    that._fnMouseDown.call(that, e, nTh);
                });
            },


            /**
            * Mouse down on a TH element in the table header
            *  @method  _fnMouseDown
            *  @param   event e Mouse event
            *  @param   element nTh TH element to be dragged
            *  @returns void
            *  @private
            */
            "_fnMouseDown": function (e, nTh) {
                var that = this;
                /* Store information about the mouse position */
                var target = $(e.target).closest('th, td');
                var offset = target.offset();
                var idx = parseInt($(nTh).attr('data-column-index'), 10);

                if (idx === undefined) {
                    return;
                }

                this.s.mouse.startX = e.pageX;
                this.s.mouse.startY = e.pageY;
                this.s.mouse.offsetX = e.pageX - offset.left;
                this.s.mouse.offsetY = e.pageY - offset.top;
                this.s.mouse.target = this.s.dt.aoColumns[idx].nTh; //target[0];
                this.s.mouse.targetIndex = idx;
                this.s.mouse.fromIndex = idx;

                this._fnRegions();

                /* Add event handlers to the document */
                $(document)
			.on('mousemove.ColReorder', function (e) {
			    that._fnMouseMove.call(that, e);
			})
			.on('mouseup.ColReorder', function (e) {
			    that._fnMouseUp.call(that, e);
			});
            },


            /**
            * Deal with a mouse move event while dragging a node
            *  @method  _fnMouseMove
            *  @param   event e Mouse event
            *  @returns void
            *  @private
            */
            "_fnMouseMove": function (e) {
                var that = this;

                if (this.dom.drag === null) {
                    /* Only create the drag element if the mouse has moved a specific distance from the start
                    * point - this allows the user to make small mouse movements when sorting and not have a
                    * possibly confusing drag element showing up
                    */
                    if (Math.pow(
				Math.pow(e.pageX - this.s.mouse.startX, 2) +
				Math.pow(e.pageY - this.s.mouse.startY, 2), 0.5) < 5) {
                        return;
                    }
                    this._fnCreateDragNode();
                }

                /* Position the element - we respect where in the element the click occured */
                this.dom.drag.css({
                    left: e.pageX - this.s.mouse.offsetX,
                    top: e.pageY - this.s.mouse.offsetY
                });

                /* Based on the current mouse position, calculate where the insert should go */
                var bSet = false;
                var lastToIndex = this.s.mouse.toIndex;

                for (var i = 1, iLen = this.s.aoTargets.length; i < iLen; i++) {
                    if (e.pageX < this.s.aoTargets[i - 1].x + ((this.s.aoTargets[i].x - this.s.aoTargets[i - 1].x) / 2)) {
                        this.dom.pointer.css('left', this.s.aoTargets[i - 1].x);
                        this.s.mouse.toIndex = this.s.aoTargets[i - 1].to;
                        bSet = true;
                        break;
                    }
                }

                // The insert element wasn't positioned in the array (less than
                // operator), so we put it at the end
                if (!bSet) {
                    this.dom.pointer.css('left', this.s.aoTargets[this.s.aoTargets.length - 1].x);
                    this.s.mouse.toIndex = this.s.aoTargets[this.s.aoTargets.length - 1].to;
                }

                // Perform reordering if realtime updating is on and the column has moved
                if (this.s.init.bRealtime && lastToIndex !== this.s.mouse.toIndex) {
                    this.s.dt.oInstance.fnColReorder(this.s.mouse.fromIndex, this.s.mouse.toIndex);
                    this.s.mouse.fromIndex = this.s.mouse.toIndex;
                    this._fnRegions();
                }
            },


            /**
            * Finish off the mouse drag and insert the column where needed
            *  @method  _fnMouseUp
            *  @param   event e Mouse event
            *  @returns void
            *  @private
            */
            "_fnMouseUp": function (e) {
                var that = this;

                $(document).off('mousemove.ColReorder mouseup.ColReorder');

                if (this.dom.drag !== null) {
                    /* Remove the guide elements */
                    this.dom.drag.remove();
                    this.dom.pointer.remove();
                    this.dom.drag = null;
                    this.dom.pointer = null;

                    /* Actually do the reorder */
                    this.s.dt.oInstance.fnColReorder(this.s.mouse.fromIndex, this.s.mouse.toIndex);
                    this._fnSetColumnIndexes();

                    /* When scrolling we need to recalculate the column sizes to allow for the shift */
                    if (this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "") {
                        this.s.dt.oInstance.fnAdjustColumnSizing();
                    }

                    if (this.s.dropCallback !== null) {
                        this.s.dropCallback.call(this);
                    }

                    /* Save the state */
                    this.s.dt.oInstance.oApi._fnSaveState(this.s.dt);
                }
            },


            /**
            * Calculate a cached array with the points of the column inserts, and the
            * 'to' points
            *  @method  _fnRegions
            *  @returns void
            *  @private
            */
            "_fnRegions": function () {
                var aoColumns = this.s.dt.aoColumns;

                this.s.aoTargets.splice(0, this.s.aoTargets.length);

                this.s.aoTargets.push({
                    "x": $(this.s.dt.nTable).offset().left,
                    "to": 0
                });

                var iToPoint = 0;
                for (var i = 0, iLen = aoColumns.length; i < iLen; i++) {
                    /* For the column / header in question, we want it's position to remain the same if the
                    * position is just to it's immediate left or right, so we only incremement the counter for
                    * other columns
                    */
                    if (i != this.s.mouse.fromIndex) {
                        iToPoint++;
                    }

                    if (aoColumns[i].bVisible) {
                        this.s.aoTargets.push({
                            "x": $(aoColumns[i].nTh).offset().left + $(aoColumns[i].nTh).outerWidth(),
                            "to": iToPoint
                        });
                    }
                }

                /* Disallow columns for being reordered by drag and drop, counting right to left */
                if (this.s.fixedRight !== 0) {
                    this.s.aoTargets.splice(this.s.aoTargets.length - this.s.fixedRight);
                }

                /* Disallow columns for being reordered by drag and drop, counting left to right */
                if (this.s.fixed !== 0) {
                    this.s.aoTargets.splice(0, this.s.fixed);
                }
            },


            /**
            * Copy the TH element that is being drags so the user has the idea that they are actually
            * moving it around the page.
            *  @method  _fnCreateDragNode
            *  @returns void
            *  @private
            */
            "_fnCreateDragNode": function () {
                var scrolling = this.s.dt.oScroll.sX !== "" || this.s.dt.oScroll.sY !== "";

                var origCell = this.s.dt.aoColumns[this.s.mouse.targetIndex].nTh;
                var origTr = origCell.parentNode;
                var origThead = origTr.parentNode;
                var origTable = origThead.parentNode;
                var cloneCell = $(origCell).clone();

                // This is a slightly odd combination of jQuery and DOM, but it is the
                // fastest and least resource intensive way I could think of cloning
                // the table with just a single header cell in it.
                this.dom.drag = $(origTable.cloneNode(false))
			.addClass('DTCR_clonedTable')
			.append(
				origThead.cloneNode(false).appendChild(
					origTr.cloneNode(false).appendChild(
						cloneCell[0]
					)
				)
			)
			.css({
			    position: 'absolute',
			    top: 0,
			    left: 0,
			    width: $(origCell).outerWidth(),
			    height: $(origCell).outerHeight()
			})
			.appendTo('body');

                this.dom.pointer = $('<div></div>')
			.addClass('DTCR_pointer')
			.css({
			    position: 'absolute',
			    top: scrolling ?
					$('div.dataTables_scroll', this.s.dt.nTableWrapper).offset().top :
					$(this.s.dt.nTable).offset().top,
			    height: scrolling ?
					$('div.dataTables_scroll', this.s.dt.nTableWrapper).height() :
					$(this.s.dt.nTable).height()
			})
			.appendTo('body');
            },

            /**
            * Clean up ColReorder memory references and event handlers
            *  @method  _fnDestroy
            *  @returns void
            *  @private
            */
            "_fnDestroy": function () {
                var i, iLen;

                for (i = 0, iLen = this.s.dt.aoDrawCallback.length; i < iLen; i++) {
                    if (this.s.dt.aoDrawCallback[i].sName === 'ColReorder_Pre') {
                        this.s.dt.aoDrawCallback.splice(i, 1);
                        break;
                    }
                }

                $(this.s.dt.nTHead).find('*').off('.ColReorder');

                $.each(this.s.dt.aoColumns, function (i, column) {
                    $(column.nTh).removeAttr('data-column-index');
                });

                this.s.dt._colReorder = null;
                this.s = null;
            },


            /**
            * Add a data attribute to the column headers, so we know the index of
            * the row to be reordered. This allows fast detection of the index, and
            * for this plug-in to work with FixedHeader which clones the nodes.
            *  @private
            */
            "_fnSetColumnIndexes": function () {
                $.each(this.s.dt.aoColumns, function (i, column) {
                    $(column.nTh).attr('data-column-index', i);
                });
            }
        };





        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        * Static parameters
        * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */


        /**
        * ColReorder default settings for initialisation
        *  @namespace
        *  @static
        */
        ColReorder.defaults = {
            /**
            * Predefined ordering for the columns that will be applied automatically
            * on initialisation. If not specified then the order that the columns are
            * found to be in the HTML is the order used.
            *  @type array
            *  @default null
            *  @static
            *  @example
            *      // Using the `oColReorder` option in the DataTables options object
            *      $('#example').dataTable( {
            *          "sDom": 'Rlfrtip',
            *          "oColReorder": {
            *              "aiOrder": [ 4, 3, 2, 1, 0 ]
            *          }
            *      } );
            *
            *  @example
            *      // Using `new` constructor
            *      $('#example').dataTable()
            *
            *      new $.fn.dataTable.ColReorder( '#example', {
            *          "aiOrder": [ 4, 3, 2, 1, 0 ]
            *      } );
            */
            aiOrder: null,

            /**
            * Redraw the table's column ordering as the end user draws the column
            * (`true`) or wait until the mouse is released (`false` - default). Note
            * that this will perform a redraw on each reordering, which involves an
            * Ajax request each time if you are using server-side processing in
            * DataTables.
            *  @type boolean
            *  @default false
            *  @static
            *  @example
            *      // Using the `oColReorder` option in the DataTables options object
            *      $('#example').dataTable( {
            *          "sDom": 'Rlfrtip',
            *          "oColReorder": {
            *              "bRealtime": true
            *          }
            *      } );
            *
            *  @example
            *      // Using `new` constructor
            *      $('#example').dataTable()
            *
            *      new $.fn.dataTable.ColReorder( '#example', {
            *          "bRealtime": true
            *      } );
            */
            bRealtime: false,

            /**
            * Indicate how many columns should be fixed in position (counting from the
            * left). This will typically be 1 if used, but can be as high as you like.
            *  @type int
            *  @default 0
            *  @static
            *  @example
            *      // Using the `oColReorder` option in the DataTables options object
            *      $('#example').dataTable( {
            *          "sDom": 'Rlfrtip',
            *          "oColReorder": {
            *              "iFixedColumns": 1
            *          }
            *      } );
            *
            *  @example
            *      // Using `new` constructor
            *      $('#example').dataTable()
            *
            *      new $.fn.dataTable.ColReorder( '#example', {
            *          "iFixedColumns": 1
            *      } );
            */
            iFixedColumns: 0,

            /**
            * As `iFixedColumnsRight` but counting from the right.
            *  @type int
            *  @default 0
            *  @static
            *  @example
            *      // Using the `oColReorder` option in the DataTables options object
            *      $('#example').dataTable( {
            *          "sDom": 'Rlfrtip',
            *          "oColReorder": {
            *              "iFixedColumnsRight": 1
            *          }
            *      } );
            *
            *  @example
            *      // Using `new` constructor
            *      $('#example').dataTable()
            *
            *      new $.fn.dataTable.ColReorder( '#example', {
            *          "iFixedColumnsRight": 1
            *      } );
            */
            iFixedColumnsRight: 0,

            /**
            * Callback function that is fired when columns are reordered
            *  @type function():void
            *  @default null
            *  @static
            *  @example
            *      // Using the `oColReorder` option in the DataTables options object
            *      $('#example').dataTable( {
            *          "sDom": 'Rlfrtip',
            *          "oColReorder": {
            *              "fnReorderCallback": function () {
            *                  alert( 'Columns reordered' );
            *              }
            *          }
            *      } );
            *
            *  @example
            *      // Using `new` constructor
            *      $('#example').dataTable()
            *
            *      new $.fn.dataTable.ColReorder( '#example', {
            *          "fnReorderCallback": function () {
            *              alert( 'Columns reordered' );
            *          }
            *      } );
            */
            fnReorderCallback: null
        };



        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        * Constants
        * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

        /**
        * ColReorder version
        *  @constant  version
        *  @type      String
        *  @default   As code
        */
        ColReorder.version = "1.1.2";



        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        * DataTables interfaces
        * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

        // Expose
        $.fn.dataTable.ColReorder = ColReorder;
        $.fn.DataTable.ColReorder = ColReorder;


        // Register a new feature with DataTables
        if (typeof $.fn.dataTable == "function" &&
     typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
     $.fn.dataTableExt.fnVersionCheck('1.9.3')) {
            $.fn.dataTableExt.aoFeatures.push({
                "fnInit": function (settings) {
                    var table = settings.oInstance;

                    if (!settings._colReorder) {
                        var dtInit = settings.oInit;
                        var opts = dtInit.colReorder || dtInit.oColReorder || {};

                        new ColReorder(settings, opts);
                    }
                    else {
                        table.oApi._fnLog(settings, 1, "ColReorder attempted to initialise twice. Ignoring second");
                    }

                    return null; /* No node for DataTables to insert */
                },
                "cFeature": "R",
                "sFeature": "ColReorder"
            });
        }
        else {
            alert("Warning: ColReorder requires DataTables 1.9.3 or greater - www.datatables.net/download");
        }


        // API augmentation
        if ($.fn.dataTable.Api) {
            $.fn.dataTable.Api.register('colReorder.reset()', function () {
                return this.iterator('table', function (ctx) {
                    ctx._colReorder.fnReset();
                });
            });

            $.fn.dataTable.Api.register('colReorder.order()', function (set) {
                if (set) {
                    return this.iterator('table', function (ctx) {
                        ctx._colReorder.fnOrder(set);
                    });
                }

                return this.context.length ?
			this.context[0]._colReorder.fnOrder() :
			null;
            });
        }

        return ColReorder;
    }; // /factory


    // Define as an AMD module if possible
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'datatables'], factory);
    }
    else if (typeof exports === 'object') {
        // Node/CommonJS
        factory(require('jquery'), require('datatables'));
    }
    else if (jQuery && !jQuery.fn.dataTable.ColReorder) {
        // Otherwise simply initialise as normal, stopping multiple evaluation
        factory(jQuery, jQuery.fn.dataTable);
    }


})(window, document);

/*!
 ColVis 1.1.0
 ©2010-2014 SpryMedia Ltd - datatables.net/license
*/
(function(j,i,k){j=function(d){var e=function(a,b){(!this.CLASS||"ColVis"!=this.CLASS)&&alert("Warning: ColVis must be initialised with the keyword 'new'");"undefined"==typeof b&&(b={});d.fn.dataTable.camelToHungarian&&d.fn.dataTable.camelToHungarian(e.defaults,b);this.s={dt:null,oInit:b,hidden:!0,abOriginal:[]};this.dom={wrapper:null,button:null,collection:null,background:null,catcher:null,buttons:[],groupButtons:[],restore:null};e.aInstances.push(this);this.s.dt=d.fn.dataTable.Api?(new d.fn.dataTable.Api(a)).settings()[0]:
a;this._fnConstruct(b);return this};e.prototype={button:function(){return this.dom.wrapper},fnRebuild:function(){this.rebuild()},rebuild:function(){for(var a=this.dom.buttons.length-1;0<=a;a--)this.dom.collection.removeChild(this.dom.buttons[a]);this.dom.buttons.splice(0,this.dom.buttons.length);this.dom.restore&&this.dom.restore.parentNode(this.dom.restore);this._fnAddGroups();this._fnAddButtons();this._fnDrawCallback()},_fnConstruct:function(a){this._fnApplyCustomisation(a);var b=this,c,f;this.dom.wrapper=
i.createElement("div");this.dom.wrapper.className="ColVis";this.dom.button=d("<button />",{"class":!this.s.dt.bJUI?"ColVis_Button ColVis_MasterButton":"ColVis_Button ColVis_MasterButton ui-button ui-state-default"}).append("<span>"+this.s.buttonText+"</span>").bind("mouseover"==this.s.activate?"mouseover":"click",function(a){a.preventDefault();b._fnCollectionShow()}).appendTo(this.dom.wrapper)[0];this.dom.catcher=this._fnDomCatcher();this.dom.collection=this._fnDomCollection();this.dom.background=
this._fnDomBackground();this._fnAddGroups();this._fnAddButtons();c=0;for(f=this.s.dt.aoColumns.length;c<f;c++)this.s.abOriginal.push(this.s.dt.aoColumns[c].bVisible);this.s.dt.aoDrawCallback.push({fn:function(){b._fnDrawCallback.call(b)},sName:"ColVis"});d(this.s.dt.oInstance).bind("column-reorder",function(a,d,e){c=0;for(f=b.s.aiExclude.length;c<f;c++)b.s.aiExclude[c]=e.aiInvertMapping[b.s.aiExclude[c]];a=b.s.abOriginal.splice(e.iFrom,1)[0];b.s.abOriginal.splice(e.iTo,0,a);b.fnRebuild()});this._fnDrawCallback()},
_fnApplyCustomisation:function(a){d.extend(!0,this.s,e.defaults,a);!this.s.showAll&&this.s.bShowAll&&(this.s.showAll=this.s.sShowAll);!this.s.restore&&this.s.bRestore&&(this.s.restore=this.s.sRestore);var a=this.s.groups,b=this.s.aoGroups;if(a)for(var c=0,f=a.length;c<f;c++)if(a[c].title&&(b[c].sTitle=a[c].title),a[c].columns)b[c].aiColumns=a[c].columns},_fnDrawCallback:function(){for(var a=this.s.dt.aoColumns,b=this.dom.buttons,c=this.s.aoGroups,f,g=0,h=b.length;g<h;g++)f=b[g],f.__columnIdx!==k&&
d("input",f).prop("checked",a[f.__columnIdx].bVisible);b=0;for(f=c.length;b<f;b++){a:{for(var g=c[b].aiColumns,h=0,e=g.length;h<e;h++)if(!1===a[g[h]].bVisible){g=!1;break a}g=!0}if(g)d("input",this.dom.groupButtons[b]).prop("checked",!0),d("input",this.dom.groupButtons[b]).prop("indeterminate",!1);else{a:{g=c[b].aiColumns;h=0;for(e=g.length;h<e;h++)if(!0===a[g[h]].bVisible){g=!1;break a}g=!0}g?(d("input",this.dom.groupButtons[b]).prop("checked",!1),d("input",this.dom.groupButtons[b]).prop("indeterminate",
!1)):d("input",this.dom.groupButtons[b]).prop("indeterminate",!0)}}},_fnAddGroups:function(){var a;if("undefined"!=typeof this.s.aoGroups)for(var b=0,c=this.s.aoGroups.length;b<c;b++)a=this._fnDomGroupButton(b),this.dom.groupButtons.push(a),this.dom.buttons.push(a),this.dom.collection.appendChild(a)},_fnAddButtons:function(){var a,b=this.s.dt.aoColumns;if(-1===d.inArray("all",this.s.aiExclude))for(var c=0,f=b.length;c<f;c++)-1===d.inArray(c,this.s.aiExclude)&&(a=this._fnDomColumnButton(c),a.__columnIdx=
c,this.dom.buttons.push(a));"alpha"===this.s.order&&this.dom.buttons.sort(function(a,c){var d=b[a.__columnIdx].sTitle,f=b[c.__columnIdx].sTitle;return d===f?0:d<f?-1:1});this.s.restore&&(a=this._fnDomRestoreButton(),a.className+=" ColVis_Restore",this.dom.buttons.push(a));this.s.showAll&&(a=this._fnDomShowAllButton(),a.className+=" ColVis_ShowAll",this.dom.buttons.push(a));d(this.dom.collection).append(this.dom.buttons)},_fnDomRestoreButton:function(){var a=this;return d('<li class="ColVis_Special '+
(this.s.dt.bJUI?"ui-button ui-state-default":"")+'">'+this.s.restore+"</li>").click(function(){for(var b=0,c=a.s.abOriginal.length;b<c;b++)a.s.dt.oInstance.fnSetColumnVis(b,a.s.abOriginal[b],!1);a._fnAdjustOpenRows();a.s.dt.oInstance.fnAdjustColumnSizing(!1);a.s.dt.oInstance.fnDraw(!1)})[0]},_fnDomShowAllButton:function(){var a=this;return d('<li class="ColVis_Special '+(this.s.dt.bJUI?"ui-button ui-state-default":"")+'">'+this.s.showAll+"</li>").click(function(){for(var b=0,c=a.s.abOriginal.length;b<
c;b++)-1===a.s.aiExclude.indexOf(b)&&a.s.dt.oInstance.fnSetColumnVis(b,!0,!1);a._fnAdjustOpenRows();a.s.dt.oInstance.fnAdjustColumnSizing(!1);a.s.dt.oInstance.fnDraw(!1)})[0]},_fnDomGroupButton:function(a){var b=this,c=this.s.aoGroups[a];return d('<li class="ColVis_Special '+(this.s.dt.bJUI?"ui-button ui-state-default":"")+'"><label><input type="checkbox" /><span>'+c.sTitle+"</span></label></li>").click(function(a){var g=!d("input",this).is(":checked");"li"!==a.target.nodeName.toLowerCase()&&(g=!g);
for(a=0;a<c.aiColumns.length;a++)b.s.dt.oInstance.fnSetColumnVis(c.aiColumns[a],g)})[0]},_fnDomColumnButton:function(a){var b=this,c=this.s.dt.aoColumns[a],f=this.s.dt,c=null===this.s.fnLabel?c.sTitle:this.s.fnLabel(a,c.sTitle,c.nTh);return d("<li "+(f.bJUI?'class="ui-button ui-state-default"':"")+'><label><input type="checkbox" /><span>'+c+"</span></label></li>").click(function(c){var e=!d("input",this).is(":checked");"li"!==c.target.nodeName.toLowerCase()&&(e=!e);c=d.fn.dataTableExt.iApiIndex;d.fn.dataTableExt.iApiIndex=
b._fnDataTablesApiIndex.call(b);f.oFeatures.bServerSide?(b.s.dt.oInstance.fnSetColumnVis(a,e,!1),b.s.dt.oInstance.fnAdjustColumnSizing(!1),(""!==f.oScroll.sX||""!==f.oScroll.sY)&&b.s.dt.oInstance.oApi._fnScrollDraw(b.s.dt),b._fnDrawCallback()):b.s.dt.oInstance.fnSetColumnVis(a,e);d.fn.dataTableExt.iApiIndex=c;null!==b.s.fnStateChange&&b.s.fnStateChange.call(b,a,e)})[0]},_fnDataTablesApiIndex:function(){for(var a=0,b=this.s.dt.oInstance.length;a<b;a++)if(this.s.dt.oInstance[a]==this.s.dt.nTable)return a;
return 0},_fnDomCollection:function(){return d("<ul />",{"class":!this.s.dt.bJUI?"ColVis_collection":"ColVis_collection ui-buttonset ui-buttonset-multi"}).css({display:"none",opacity:0,position:!this.s.bCssPosition?"absolute":""})[0]},_fnDomCatcher:function(){var a=this,b=i.createElement("div");b.className="ColVis_catcher";d(b).click(function(){a._fnCollectionHide.call(a,null,null)});return b},_fnDomBackground:function(){var a=this,b=d("<div></div>").addClass("ColVis_collectionBackground").css("opacity",
0).click(function(){a._fnCollectionHide.call(a,null,null)});"mouseover"==this.s.activate&&b.mouseover(function(){a.s.overcollection=!1;a._fnCollectionHide.call(a,null,null)});return b[0]},_fnCollectionShow:function(){var a=this,b;b=d(this.dom.button).offset();var c=this.dom.collection,f=this.dom.background,e=parseInt(b.left,10),h=parseInt(b.top+d(this.dom.button).outerHeight(),10);this.s.bCssPosition||(c.style.top=h+"px",c.style.left=e+"px");d(c).css({display:"block",opacity:0});f.style.bottom="0px";
f.style.right="0px";h=this.dom.catcher.style;h.height=d(this.dom.button).outerHeight()+"px";h.width=d(this.dom.button).outerWidth()+"px";h.top=b.top+"px";h.left=e+"px";i.body.appendChild(f);i.body.appendChild(c);i.body.appendChild(this.dom.catcher);d(c).animate({opacity:1},a.s.iOverlayFade);d(f).animate({opacity:0.1},a.s.iOverlayFade,"linear",function(){d.browser&&(d.browser.msie&&d.browser.version=="6.0")&&a._fnDrawCallback()});this.s.bCssPosition||(b="left"==this.s.sAlign?e:e-d(c).outerWidth()+
d(this.dom.button).outerWidth(),c.style.left=b+"px",f=d(c).outerWidth(),d(c).outerHeight(),e=d(i).width(),b+f>e&&(c.style.left=e-f+"px"));this.s.hidden=!1},_fnCollectionHide:function(){var a=this;!this.s.hidden&&null!==this.dom.collection&&(this.s.hidden=!0,d(this.dom.collection).animate({opacity:0},a.s.iOverlayFade,function(){this.style.display="none"}),d(this.dom.background).animate({opacity:0},a.s.iOverlayFade,function(){i.body.removeChild(a.dom.background);i.body.removeChild(a.dom.catcher)}))},
_fnAdjustOpenRows:function(){for(var a=this.s.dt.aoOpenRows,b=this.s.dt.oApi._fnVisbleColumns(this.s.dt),c=0,d=a.length;c<d;c++)a[c].nTr.getElementsByTagName("td")[0].colSpan=b}};e.fnRebuild=function(a){var b=null;"undefined"!=typeof a&&(b=a.fnSettings().nTable);for(var c=0,d=e.aInstances.length;c<d;c++)("undefined"==typeof a||b==e.aInstances[c].s.dt.nTable)&&e.aInstances[c].fnRebuild()};e.defaults={active:"click",buttonText:"Show / hide columns",aiExclude:[],bRestore:!1,sRestore:"Restore original",
bShowAll:!1,sShowAll:"Show All",sAlign:"left",fnStateChange:null,iOverlayFade:500,fnLabel:null,bCssPosition:!1,aoGroups:[],order:"column"};e.aInstances=[];e.prototype.CLASS="ColVis";e.VERSION="1.1.0";e.prototype.VERSION=e.VERSION;"function"==typeof d.fn.dataTable&&"function"==typeof d.fn.dataTableExt.fnVersionCheck&&d.fn.dataTableExt.fnVersionCheck("1.7.0")?d.fn.dataTableExt.aoFeatures.push({fnInit:function(a){var b=a.oInit;return(new e(a,b.colVis||b.oColVis||{})).button()},cFeature:"C",sFeature:"ColVis"}):
alert("Warning: ColVis requires DataTables 1.7 or greater - www.datatables.net/download");d.fn.dataTable.ColVis=e;return d.fn.DataTable.ColVis=e};"function"===typeof define&&define.amd?define("datatables-colvis",["jquery","datatables"],j):jQuery&&!jQuery.fn.dataTable.ColVis&&j(jQuery,jQuery.fn.dataTable)})(window,document);

jQuery.fn.dataTableExt.oApi.fnDisplayStart = function (datatable, iStart, bRedraw) {
    if (datatable === null) return false;
    oSettings = datatable.settings()[0];
    if (typeof bRedraw == 'undefined') {
        bRedraw = true;
    }

    oSettings._iDisplayStart = iStart;
    if (oSettings.oApi._fnCalculateEnd) {
        oSettings.oApi._fnCalculateEnd(oSettings);
    }

    if (bRedraw) {
        oSettings.oApi._fnDraw(oSettings);
    }
};


// Ici sont rajoutés les fonctions trouvées sur le net pour dataTables

/*
* Function: fnLengthChange
* Purpose:  Change the number of records on display
* Returns:  array:
* Inputs:   object:oSettings - DataTables settings object
*           int:iDisplay - New display length
*/
$.fn.dataTableExt.oApi.fnLengthChange = function (oSettings, iDisplay) {
    oSettings._iDisplayLength = iDisplay;
    oSettings.oApi._fnCalculateEnd(oSettings);

    /* If we have space to show extra rows (backing up from the end point - then do so */
    if (oSettings._iDisplayEnd == oSettings.aiDisplay.length) {
        oSettings._iDisplayStart = oSettings._iDisplayEnd - oSettings._iDisplayLength;
        if (oSettings._iDisplayStart < 0) {
            oSettings._iDisplayStart = 0;
        }
    }

    if (oSettings._iDisplayLength == -1) {
        oSettings._iDisplayStart = 0;
    }

    oSettings.oApi._fnDraw(oSettings);

    $('select', oSettings.aanFeatures.l).val(iDisplay);
}

/*   
* Function: fnGetColumnIndex   
* Purpose:  Return an integer matching the column index of passed in string representing <a href="/ref#sTitle">sTitle</a>     
* Returns:  int:x - column index, or -1 if not found   
* Inputs:   object:oSettings - automatically added by DataTables   
*           string:sCol - required - string matching the <a href="/ref#sTitle">sTitle</a> value of a table column   
*/
$.fn.dataTableExt.oApi.fnGetColumnIndex = function (oSettings, sName) {
    var cols = oSettings.aoColumns;
    for (var x = 0, xLen = cols.length; x < xLen; x++) {
        if (cols[x].sName == sName) {
            return x;
        };
    }
    return -1;
}

/*   
* Inspiré de la fct précédente, permet de récupérer le mData  
*/
$.fn.dataTableExt.oApi.fnGetMData = function (oSettings, mData) {
    var cols = oSettings.aoColumns;
    for (var x = 0, xLen = cols.length; x < xLen; x++) {
        if (cols[x].mData == mData) {
            return x;
        };
    }
    return -1;
}

/*   
* Function: fnGetColumnTitle   
* Purpose:  retourne l'index du titre d'une colonne si trouvé si non -1 
* Inputs:   object:oSettings - automatiquement ajouté par DataTables   
*           string:sCol - required - une chaîne qui correspond au titre d'une colonne 
*/
$.fn.dataTableExt.oApi.fnGetColumnTitle = function (oSettings, sTitle) {
    var cols = oSettings.aoColumns;
    for (var x = 0, xLen = cols.length; x < xLen; x++) {
        if (cols[x].sTitle == sTitle) {
            return x;
        };
    }
    return -1;
}



$.fn.dataTableExt.oApi.fnFilterClear = function (oSettings) {
    /* Remove global filter */oSettings.oPreviousSearch.sSearch = "";
    /* Remove the text of the global filter in the input boxes */
    if (typeof oSettings.aanFeatures.f != 'undefined') {
        var n = oSettings.aanFeatures.f; for (var i = 0, iLen = n.length; i < iLen; i++) {
            $('input', n[i]).val('');
        }
    }
    /* Remove the search text for the column filters - NOTE - if you have input boxes for these
    * filters, these will need to be reset     */
    for (var i = 0, iLen = oSettings.aoPreSearchCols.length; i < iLen; i++) { oSettings.aoPreSearchCols[i].sSearch = ""; }
    /* Redraw */
    oSettings.oApi._fnReDraw(oSettings);
}


/*
Fonction permettant d'effacer les filtres dataTables sauvegardé en cookie
A appeller après cablage d'un tableau
*/
var etatTest = true;
$.fn.dataTableExt.oApi.fnResetAllFilters = function (datatable, bDraw/*default true*/, idInputEnCours, etat, modePage, sansFiltresDeRecherche) {

    if (datatable === null) return false;
    oSettings = datatable.settings();

    for (iCol = 0; iCol < oSettings[0].aoPreSearchCols.length; iCol++) {
        oSettings[0].aoPreSearchCols[iCol].sSearch = '';

    }

    if (etat != '""' && etat != null) {
        etat = etat.split("\\").join("");
        etat = etat.split("^(").join("");
        etat = etat.split(")$").join("");
    }
    recherche = "";
    var oState = JSON.parse(etat);
    if (modePage == null || modePage == "" || typeof modePage === 'undefined') {
        idInputEnCours = 'recherche_' + idInputEnCours;
        if ($('#rechercheLignes').length > 0 && $('#rechercheLignes').is(":visible") && datatable.settings()[0].sInstance == "tableauListeDesProduits") {
            idInputEnCours = "rechercheLignes";
        }
        if (etat != '""' && etat != null) {
            oSettings[0].oPreviousSearch.sSearch = oState.oSearch.sSearch;
            recherche = oSettings[0].oPreviousSearch.sSearch;
        }
    }

    //test si filterWidget est actif
    calculerHauteur = false;
    if (etat != '""' && etat != null) {
        filtresActifs = false;
        etatTest = false;
        nbFiltresExistants = 0;

        //visibilité des parametres
        if (oState.paramVis == "1" && $('#' + datatable.settings()[0].sInstance).find(".iconeParametrage").is(':visible')) {
            $('#' + datatable.settings()[0].sInstance).find(".iconeParametrage").trigger("click");
        } else {
            // L'instruction suivante ne peut pas avoir lieu ici car le processus DT n'est pas fini : $('.contenuPage table thead').offset().top; donnera un résultat différent si on attend un peu
            //calculerHauteurTableau();
            calculerHauteur = true;
        }

        if (typeof sansFiltresDeRecherche === 'undefined') {
            sansFiltresDeRecherche = false;
        }
        if (typeof visualisation2Fenetre !== 'undefined' && oState.modeVisualisation == visualisation2Fenetre) {
            //console.log('ss ' + oState.modeVisualisation);
            $('#' + datatable.settings()[0].sInstance).find(".iconeModeVisualisation").attr('title', ACTIVER_MODE_VISUALISATION_DEUX_FENETRES);
            $('#' + datatable.settings()[0].sInstance).find(".iconeModeVisualisation").trigger("click");
            //modeVisualisationMode2 = oState.modeVisualisation;
        }


        for (i = 0, iLen = oState.aoSearchCols.length; i < iLen; i++) {

            if (oState.aoSearchCols[i].sSearch.length > 0) {

                rechercheColonne = (oState.aoSearchCols[i].sSearch.indexOf('[') >= 0 && oState.aoSearchCols[i].sSearch.indexOf(']') >= 0
                ? oState.aoSearchCols[i].sSearch.substring(oState.aoSearchCols[i].sSearch.indexOf('['), oState.aoSearchCols[i].sSearch.indexOf(']') + 1) : "");
                if (datatable.settings()[0].sDom.indexOf('W') >= 0
                    && datatable.settings()[0].sInstance.indexOf('moduleDescriptif_') == -1 // provisoire, à supprimer une fois le taf de dépolluage fait 
                    && datatable.settings()[0].sInstance.indexOf('moduleConseilAssocieDescriptif_') == -1
                ) {
                    rechercheWidget = oState.aoSearchCols[i].sSearch.replace(rechercheColonne, "");

                    if (rechercheWidget != "") {
                        tableauDesFiltres = rechercheWidget.split("|");
                        // verifier si les filtres existent toujours dans la base pour pouvoir determiner la visibilité de la partie paramètres
                        for (j = 0, jLen = tableauDesFiltres.length; j < jLen; j++) {
                            if ($('#' + datatable.settings()[0].sInstance + '_wrapper').find('.column-filter-widget:eq(' + i + ') option[value="' + tableauDesFiltres[j] + '"]').length > 0) {
                                $('#' + datatable.settings()[0].sInstance + '_wrapper').find('.column-filter-widget:eq(' + i + ') option[value="' + tableauDesFiltres[j] + '"]').attr('selected', 'selected').change();
                                nbFiltresExistants = nbFiltresExistants + 1;
                            }

                        }
                    }

                }
                if (rechercheColonne != "") {
                    var oInputCol = $('#' + datatable.settings()[0].sInstance).find("[data-orig-col='" + i + "']").find("input");
                    if (oInputCol.length > 0 && sansFiltresDeRecherche == false) {
                        oInputCol.val(rechercheColonne.replace('[', '').replace(']', ''));
                        if (oInputCol.val().trim() != '' && !oInputCol.next().is('img')) {
                            oInputCol.after('<img class="viderSaisieColonne" src="/ressource/image/commun/' + BOUTON_SUPPRIMER_FILTRE + '" onclick="$(this).prev().val(\'\'); $(this).prev().change(); " alt="" />');
                        } else if (oInputCol.val().trim() == '' && oInputCol.next().is('img')) {
                            oInputCol.next().remove();
                        }
                    }
                }

                if (sansFiltresDeRecherche) {
                    datatable.settings()[0].aoPreSearchCols[i].sSearch = "";
                    nbFiltresExistants = 0;
                } else {
                    datatable.settings()[0].aoPreSearchCols[i].sSearch = datatable.settings()[0].aoPreSearchCols[i].sSearch + rechercheColonne;
                }
            }

            //filtrage par intervalle
            if (oState.aoSearchCols[i].hasOwnProperty('pSearch') && typeof oState.aoSearchCols[i].pSearch !== 'undefined' && oState.aoSearchCols[i].pSearch.length == 2) {

                if ($('#dateDebut' + i).length > 0 && $('#dateFin' + i).length > 0) {
                    $('#dateDebut' + i).val(oState.aoSearchCols[i].pSearch[0]);
                    $('#dateFin' + i).val(oState.aoSearchCols[i].pSearch[1]);
                    $('#dateFin' + i).parent().find('.annulerRechercheDate').show();

                }
            }

        }

        if (nbFiltresExistants > 0 && !filtresActifs && $('#' + datatable.settings()[0].sInstance).find(".iconeParametrage").is(':visible')) {
            var iconeParametre = $('#' + datatable.settings()[0].sInstance).find(".iconeParametrage");
            if (iconeParametre.attr('title') == AFFICHER_LE_PARAMETRAGE_DU_TABLEAU) {
                iconeParametre.attr('src', '/ressource/image/commun/parametrageAlerte.png');
            }
            $('#' + datatable.settings()[0].sInstance).find(".iconeParametrage").addClass("avecAlert");
            filtresActifs = true;
        }


    } else {
        calculerHauteur = true;
    }
    // $('#' + datatable.settings()[0].sInstance).find(".iconeModeVisualisation").trigger("click");
    
    if (recherche.trim() != RECHERCHER + ' ...' && recherche != '' && (typeof sansFiltresDeRecherche === 'undefined' || sansFiltresDeRecherche == false)) {

        $('#' + idInputEnCours).val(recherche);
        oSettings[0].oPreviousSearch.sSearch = recherche;

        if (idInputEnCours != "rechercheLignes") {
            $('#' + idInputEnCours).after('<img class="viderSaisie ' + classeExplorer + '" src="/ressource/image/commun/ic_supprimer_noir.png" onclick="$(this).prev().val(\'\'); $(this).remove(); viderRecherche(\'' + datatable.settings()[0].sInstance + '\');" alt="" />');
        }
    } else {
        oSettings[0].oPreviousSearch.sSearch = '';

        if (idInputEnCours != "rechercheLignes") {
            $('#' + idInputEnCours).val(RECHERCHER + ' ...');
            if ($('#' + idInputEnCours).next().is('img')) {
                $('#' + idInputEnCours).next().remove();
            }
        } /* else {
            $('#' + idInputEnCours).val("");
        }*/

    }

    /* $("#" + datatable.settings()[0].sInstance + "_wrapper").find(".contenuCaption").appendTo($("#" + datatable.settings()[0].sInstance + "_wrapper").find(".top"));*/
    $("#" + datatable.settings()[0].sInstance + "_filter").appendTo($("#" + datatable.settings()[0].sInstance + "_wrapper").find(".contenuCaption"));
    //$('#divDesFiltresParIntervalles').appendTo($("#" + datatable.settings()[0].sInstance + "_wrapper").find(".top"));

    if (!datatable.settings()[0].oFeatures.bServerSide) {
        etatTest = true;
        setTimeout(function () { datatable.draw(); }, 0);
    } else {

        etatTest = true;
    }

    if (calculerHauteur && !$('#' + datatable.settings()[0].sInstance).hasClass('nonScrollable')) {
       
        calculerHauteurTableau();
    }
}
function extraireLesIntervalles(etat) {
    var rechercheIntervalles = "";
    if (etat != '""' && etat != null) {
        etat = etat.split("\\").join("");
        etat = etat.split("^(").join("");
        etat = etat.split(")$").join("");
        var oState = JSON.parse(etat);
        
        for (i = 0, iLen = oState.aoSearchCols.length; i < iLen; i++) {
            //filtrage par intervalle
            if (oState.aoSearchCols[i].hasOwnProperty('pSearch') && typeof oState.aoSearchCols[i].pSearch !== 'undefined' && oState.aoSearchCols[i].pSearch.length == 2) {
                if ($('#dateDebut' + i).length > 0 && $('#dateFin' + i).length > 0) {
                    rechercheIntervalles = rechercheIntervalles + "_" + i + ";" + oState.aoSearchCols[i].pSearch[0] + ";" + oState.aoSearchCols[i].pSearch[1];
                }
            }
        }
    }
    return rechercheIntervalles;
}
function gestionDesFiltresParColonneEtVisibilite(iColumn, bVisible, oSettings) {
    // test sur le réordonnement des colonnes
   
    iCol = (oSettings.sDom.indexOf('R') >= 0 ? oSettings.aoColumns[iColumn]._ColReorder_iOrigCol : iColumn);
    if (bVisible) {

        rechercheColonne = (oSettings.aoPreSearchCols[iCol].sSearch.indexOf('[') >= 0 && oSettings.aoPreSearchCols[iCol].sSearch.indexOf(']') >= 0
        ? oSettings.aoPreSearchCols[iCol].sSearch.substring(oSettings.aoPreSearchCols[iCol].sSearch.indexOf('['), oSettings.aoPreSearchCols[iCol].sSearch.indexOf(']') + 1) : "");

        if (rechercheColonne != "") {
            var oInputCol = $('#' + oSettings.sInstance).find("[data-orig-col='" + iCol + "']").find("input");
            if (oInputCol.length > 0) {
                oInputCol.val(rechercheColonne.replace('[', '').replace(']', ''));
                if (oInputCol.val().trim() != '' && !oInputCol.next().is('img')) {
                    oInputCol.after('<img class="viderSaisieColonne" src="/ressource/image/commun/' + BOUTON_SUPPRIMER_FILTRE + '" onclick="$(this).prev().val(\'\'); $(this).prev().change(); " alt="" />');
                } else if (oInputCol.val().trim() == '' && oInputCol.next().is('img')) {
                    oInputCol.next().remove();
                }
            }
        }

    }
}

// Trier IP ou version
// http://www.datatables.net/plug-ins/sorting
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "ip-address-pre": function (a) {
        var m = a.split("."), x = "";

        for (var i = 0; i < m.length; i++) {
            var item = m[i];
            if (item.length == 1) {
                x += "00" + item;
            } else if (item.length == 2) {
                x += "0" + item;
            } else {
                x += item;
            }
        }

        return x;
    },

    "ip-address-asc": function (a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "ip-address-desc": function (a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});

// Trier date euro ou version
// http://www.datatables.net/plug-ins/sorting
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "date-euro-pre": function (a) {
        if ($.trim(a) != '') {
            var frDatea = $.trim(a).split(' ');
            var frTimea = frDatea[1].split(':');
            var frDatea2 = frDatea[0].split('/');
            // certaines dates ne contiennent pas de millisecondes et dans ce cas ça bug
            // l'instruction suivante permet de couvrir les 2 cas de figure : milliseconde présentent ou non
            milliSecondes = (typeof frTimea[2] != 'undefined') ? frTimea[2] : 0;
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + milliSecondes) * 1;
        } else {
            var x = 10000000000000; // = l'an 1000 ...
        }

        return x;
    },

    "date-euro-asc": function (a, b) {
        return a - b;
    },

    "date-euro-desc": function (a, b) {
        return b - a;
    }
});

// Trier valeurs entières 
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "num-html-pre": function (a) {
        var x = String(a).replace(/<[\s\S]*?>/g, "");
        return parseFloat(x);
    },

    "num-html-asc": function (a, b) {
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    },

    "num-html-desc": function (a, b) {
        return ((a < b) ? 1 : ((a > b) ? -1 : 0));
    }
});


$.fn.dataTableExt.oApi.fnReloadAjax = function (oSettings, sNewSource, fnCallback, bStandingRedraw) {
    if (typeof sNewSource != 'undefined' && sNewSource != null) {
        oSettings.sAjaxSource = sNewSource;
    }
    this.oApi._fnProcessingDisplay(oSettings, true);
    var that = this;
    var iStart = oSettings._iDisplayStart;

    oSettings.fnServerData(oSettings.sAjaxSource, [], function (json) {
        /* Clear the old information from the table */
        that.oApi._fnClearTable(oSettings);

        /* Got the data - add it to the table */
        for (var i = 0; i < json.aaData.length; i++) {
            that.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        that.fnDraw();

        if (typeof bStandingRedraw != 'undefined' && bStandingRedraw === true) {
            oSettings._iDisplayStart = iStart;
            that.fnDraw(false);
        }

        that.oApi._fnProcessingDisplay(oSettings, false);

        /* Callback user function - for event handlers etc */
        if (typeof fnCallback == 'function' && fnCallback != null) {
            fnCallback(oSettings);
        }
    }, oSettings);
}

$.fn.dataTableExt.oApi.fnStandingRedraw = function (oSettings) {
    //redraw to account for filtering and sorting
    // concept here is that (for client side) there is a row got inserted at the end (for an add)
    // or when a record was modified it could be in the middle of the table
    // that is probably not supposed to be there - due to filtering / sorting
    // so we need to re process filtering and sorting
    // BUT - if it is server side - then this should be handled by the server - so skip this step
    if (oSettings.oFeatures.bServerSide === false) {
        var before = oSettings._iDisplayStart;
        oSettings.oApi._fnReDraw(oSettings);
        //iDisplayStart has been reset to zero - so lets change it back
        oSettings._iDisplayStart = before;
        oSettings.oApi._fnCalculateEnd(oSettings);
    }

    //draw the 'current' page
    oSettings.oApi._fnDraw(oSettings);
};



$.fn.dataTableExt.oApi.fnReinitiateDataTable = function (idTableau, indiceCheckBox) {
    var oTable = $('#' + idTableau).DataTable();
    //vider les filtres
    etatTest = false;
    //recherche globale
    oTable.settings()[0].oPreviousSearch.sSearch = "";

    //icone parametre
    var iconeParametre = $('#' + oTable.settings()[0].sInstance).find(".iconeParametrage");
    if (iconeParametre.attr('title') == AFFICHER_LE_PARAMETRAGE_DU_TABLEAU) {
        iconeParametre.attr('src', '/ressource/image/commun/parametrage.png');
    }
    if (iconeParametre.hasClass("avecAlert")) {
        iconeParametre.removeClass("avecAlert");
    }
    //icone ModeVisualisation

    var iconeModeVisualisation = $('#' + oTable.settings()[0].sInstance).find(".iconeModeVisualisation");
    if (typeof iconeModeVisualisation.attr('title') !== 'undefined') {
        inisialiserModeVisualisation(iconeModeVisualisation);
    }
    var label = $('#' + idTableau + '_filter label');
    label.find(".viderSaisie").trigger("click");
    var inputTecherche = $('#' + idTableau + '_filter label input');
    inputTecherche.trigger("blur");
    for (i = 0, iLen = oTable.settings()[0].aoPreSearchCols.length; i < iLen; i++) {

        oTable.settings()[0].aoPreSearchCols[i].sSearch = "";
    }
    $('#' + oTable.settings()[0].sInstance).find(".recherchable").find("input").val("");
    // pour la recherche globale coté liste des produit webshop 
    if (typeof zoneDeRecherche !== 'undefined') {
        zoneDeRecherche = "";
        $('#rechercheLignes').val(zoneDeRecherche);
        $('.annulerRechercheWebshop').hide(); 
    }
    $('.viderSaisieColonne').remove();
    // reinitialise les filtres
    var oFilterTerms = $('#' + idTableau + '_wrapper .top .column-filter-widgets .column-filter-widget .filter-term')
    oFilterTerms.trigger("click");
    //reinitialise la visibilitée des colonnes
    //reste l'indice des colonnes
    var panneauCheckBoxesColonnesVis = $('#ColVis_collection_' + idTableau);

    if (panneauCheckBoxesColonnesVis.length > 0) {

        panneauCheckBoxesColonnesVis.find('li input:checkbox:not(:checked)').each(function () {
            $(this).trigger("click");
        });
        $.fn.DataTable.ColVis.fnRebuild();
    }
    //reinitialise l'ordre des colonnes
    if (oTable.settings()[0]._colReorder) {
        oTable.colReorder.reset();
    }
    colonnesOrdonnees = [];
    colonnesVisibilite = [];
    if (typeof indiceCheckBox !== 'undefined' && oTable.settings()[0].sDom.indexOf('R') >= 0) {
        iLen = oTable.settings()[0].aoColumns.length;
        for (i = 0; i < iLen; i++) {
            // abVisCols
            colonnesVisibilite.push(oTable.settings()[0].aoColumns[i].bVisible);
            // ColReorder
            origCol = oTable.settings()[0].aoColumns[i]._ColReorder_iOrigCol;
            colonnesOrdonnees.push(origCol);
        }
        if (oTable.settings()[0].aoColumns[indiceCheckBox]._ColReorder_iOrigCol == indiceCheckBox) {
            valeurColonne = colonnesOrdonnees[indiceCheckBox];
            colonnesOrdonnees.splice(indiceCheckBox, 1);
            colonnesOrdonnees.unshift(valeurColonne);
            visibiliteColonne = colonnesVisibilite[indiceCheckBox];
            colonnesVisibilite.splice(indiceCheckBox, 1);
            colonnesVisibilite.unshift(visibiliteColonne);
            var settings = oTable.settings();
            for (var i = 0; i < iLen; i++) {
                fnAfficherCacherColonne(idTableau, i, colonnesVisibilite[i]);
            }
            oTable.colReorder.reset();
            oTable.colReorder.order(colonnesOrdonnees);
        }

    }
    recherchesParIntervalles = "";
    $('[id^=dateDebut]').each(function () {
        $(this).val("");
    });
    $('[id^=dateFin]').each(function () {
        $(this).val("");
        $(this).parent().find('.annulerRechercheDate').hide();
    });
    if ($('#' + idTableau).find(".colonneDeTriParDefault").length > 0) {

        $('#' + idTableau).find(".sorting_asc:not(.colonneDeTriParDefault)").removeClass("sorting_asc");
        $('#' + idTableau).find(".sorting_desc:not(.colonneDeTriParDefault)").removeClass("sorting_desc");
        if (!$('#' + idTableau).find(".colonneDeTriParDefault").first().hasClass("sorting_asc")) {

            $('#' + idTableau).find('.colonneDeTriParDefault').first().trigger('click');
        }
    } else {


        colonneParDefaut = $('#' + idTableau).find('.colonneDeTriParDefaultDesc');

        $('#' + idTableau).find(".sorting_asc:not(.colonneDeTriParDefaultDesc)").removeClass("sorting_asc");
        $('#' + idTableau).find(".sorting_desc:not(.colonneDeTriParDefaultDesc)").removeClass("sorting_desc");

        if (!$('#' + idTableau).find(".colonneDeTriParDefaultDesc").first().hasClass("sorting_desc")) {

            if ($('#' + idTableau).find(".colonneDeTriParDefaultDesc").first().hasClass("sorting") == true) {

                setTimeout(function () { $('#' + idTableau).find(".colonneDeTriParDefaultDesc").first().trigger('click'); }, 1000);
            }

            $('#' + idTableau).find(".colonneDeTriParDefaultDesc").first().trigger('click');
        }


    }
    if (idTableau == 'moduleDescriptif_tableauListeDesBDDVegetalesEnPreselection'
    || idTableau == 'moduleDescriptif_tableauListeDesBDDVegetalesEnRattachement'
    || idTableau == 'moduleDescriptif_tableauListeDesBDDVegetales'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifsEnRattachement'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifsEnPreselection'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifs') {
        tableauDesLargeuresEtIndicesDescriptif = "reinitialisé";
    } else if (idTableau == 'moduleValeur_tableauListeDeValeurs'
    || idTableau == 'moduleValeur_tableauListeDeValeursVlv'
    || idTableau == 'moduleValeur_tableauListeDeValeursReferentes') {
        tableauDesLargeuresEtIndicesValeurs = "reinitialisé";
    } else if (idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesVlv'
    || idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategories'
    || idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesReferentes') {
        tableauDesLargeuresEtIndicesCriteresCategories = "reinitialisé";
    } else if (idTableau == 'tableauListeDesCategoriesDescriptifs') {
        tableauDesLargeuresEtIndicesCategorieDescriptifs = "reinitialisé";
    } else if (idTableau == 'moduleMediaCategorie_tableauListeDesCategoriesMedias'
    || idTableau == 'moduleMediaCategorie_tableauListeDesCategoriesMediasVlv') {
        tableauDesLargeuresEtIndicesCategorieMedias = "reinitialisé";
    } else if (idTableau == 'tableauListeDesTypesDeConseils') {
        tableauDesLargeuresEtIndicesConseilsTypes = "reinitialisé";
    } else if (idTableau == 'tableauListeDesTypesInfoComplementaireConseil') {
        tableauDesLargeuresEtIndicesConseilInfoComplementaireTypes = "reinitialisé";
    } else if (idTableau == 'tableauListeDesInfosComplementaireConseil') {
        tableauDesLargeuresEtIndicesConseilInfoComplementaires = "reinitialisé";
    } else if (idTableau == 'copyrights') {
        tableauDesLargeuresEtIndicesCopyrights = "reinitialisé";
    } else if (idTableau == 'moduleCritere_tableauListeDeCriteres'
    || idTableau == 'moduleCritere_tableauListeDeCriteresVlv'
    || idTableau == 'moduleCritere_tableauListeDeCriteresReferentes'

    || idTableau == 'moduleCritere_tableauListeDeCriteresAppShop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresAppShopVlv'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitAppShop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitAppShopVlv'

    || idTableau == 'moduleCritere_tableauListeDeCriteresWebshop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresWebshopVlv'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitWebshop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitWebshopVlv') {
        tableauDesLargeuresEtIndicesCritere = "reinitialisé";
    } else if (idTableau == 'lieux') {
        tableauDesLargeuresEtIndicesLieux = "reinitialisé";
    } else if (idTableau == 'moduleMedia_tableauListeDeMedias'
    || idTableau == 'moduleConseil_tableauListeDesMedias'
    || idTableau == 'moduleDescriptif_tableauListeDeMedias'
    || idTableau == 'moduleMedia_tableauListeDeMediasVlv'
    || idTableau == 'moduleMedia_tableauListeDeMediasReferente') {
        tableauDesLargeuresEtIndicesMedia = "reinitialisé";
    } else if (idTableau == 'moduleLangue_tableauListeDesLangues') {
        tableauDesLargeuresEtIndicesTraduction = "reinitialisé";
    } else if (idTableau == 'moduleLangue_tableauListeDesEntitees') {
        tableauDesLargeuresEtIndicesEntiteesTraduction = "reinitialisé";
    } else if (idTableau == 'moduleLangue_tableauEditerTraduction') {
        tableauDesLargeuresEtIndicesEditerTraduction = "reinitialisé";
    } else if (idTableau == 'tableauListeDesConseils'
    || idTableau == 'moduleConseilAssocieDescriptif_tableauListeDesConseils') {
        tableauDesLargeuresEtIndicesConseil = "reinitialisé";
    } else if (idTableau == 'tableauListeDesCatalogues') {
        tableauDesLargeuresEtIndicesCatalogues = "reinitialisé";
    } else if (idTableau == 'tableauLignesDeCatalogue') {
        tableauDesLargeuresEtIndicesLignesCatalogue = "reinitialisé";
    } else if (idTableau == 'tableauListeDesComptesBancaires') {
        tableauDesLargeuresEtIndicesComptesBancaires = "reinitialisé";
    } else if (idTableau == 'tableauListeDesDemandesServices'
    || idTableau == 'tableauActualise_tableauListeDesDemandesServices') {
        tableauDesLargeuresEtIndicesDemandesServices = "reinitialisé";
    } else if (idTableau == 'natureDemandeService') {
        tableauDesLargeuresEtIndicesNatureDemandeService = "reinitialisé";
    } else if (idTableau == 'tableauListeDesProduitsDemandeService') {
        tableauDesLargeuresEtIndicesProduitDemandeService = "reinitialisé";
    } else if (idTableau == 'tableauListeDesCategoriesDemandeService') {
        tableauDesLargeuresEtIndicesCategorieDemandeService = "reinitialisé";
    } else if (idTableau == 'tableauListeDesSousCategoriesDemandeService') {
        tableauDesLargeuresEtIndicesSousCategorieDemandeService = "reinitialisé";
    } else if (idTableau == 'tableauListeDesAdressesDeLivraison') {
        tableauDesLargeuresEtIndicesAdresseLivraison = "reinitialisé";
    } else if (idTableau == 'tableauListeTypeUniteVente'
    || idTableau == 'tableauListePresentations'
    || idTableau == "tableauListeMillesimes") {
        tableauDesLargeuresEtIndicesDictionnaire = "reinitialisé";
    } else if (idTableau == 'tableauEletter') {
        tableauDesLargeuresEtIndicesEletter = "reinitialisé";
    } else if (idTableau == 'tableauListeDEmailsConseilsEnvoyes') {
        tableauDesLargeuresEtIndicesEmailsConseilsEnvoyes = "reinitialisé";
    } else if (idTableau == 'tableauGroupes'
    || idTableau == 'tableauGroupes_detailSociete') {
        tableauDesLargeuresEtIndicesGroupe = "reinitialisé";
    } else if (idTableau == 'tableauListeDesArticles') {
        tableauDesLargeuresEtIndicesArticles = "reinitialisé";
    } else if (idTableau == 'tableauServices') {
        tableauDesLargeuresEtIndicesServices = "reinitialisé";
    } else if (idTableau == 'tableauMesServices') {
        tableauDesLargeuresEtIndicesMesServices = "reinitialisé";
    } else if (idTableau == 'tableauListeDesOperationsEnvoyees') {
        tableauDesLargeuresEtIndicesOperations = "reinitialisé";
    } else if (idTableau == 'tableauListeTaille'
    || idTableau == 'tableauListeUniteVente') {
        tableauDesLargeuresEtIndicesTypeUniteVente = "reinitialisé";
    } else if (idTableau == 'moduleClients_tableauClients'
    || idTableau == 'moduleDemandeService_tableauClients'
    || idTableau == 'moduleAjoutGroupe_tableauClients'
    || idTableau == 'moduleAjoutGroupe_tableauClientsModifierGroupe'
    || idTableau == 'moduleConsulterGroupe_tableauClients') {
        tableauDesLargeuresEtIndicesMesClients = "reinitialisé";
    } else if (idTableau == 'tableauListeClientsWebshop') {
        tableauDesLargeuresEtIndicesClientWebshop = "reinitialisé";
    } else if (idTableau == 'moduleComptesSecondaires_tableauListeDesComptes'
    || idTableau == 'moduleDemandeService_tableauListeDesComptes') {
        tableauDesLargeuresEtIndicesComptes = "reinitialisé";
    } else if (idTableau == 'tableauListeDeAuthentifications') {
        tableauDesLargeuresEtIndicesAuthentifications = "reinitialisé";
    } else if (idTableau == 'tableauListeDEmaislEnvoyes') {
        tableauDesLargeuresEtIndicesEmailsEnvoyes = "reinitialisé";
    } else if (idTableau == 'moduleHistoriqueConsultation_tableauListeDetailsHistoriqueConsultation') {
        tableauDesLargeuresEtIndicesHistoriqueConsultation = "reinitialisé";
    } else if (idTableau == 'tableauListeDHistoriqueDImport') {
        tableauDesLargeuresEtIndicesHistoriqueImport = "reinitialisé";
    } else if (idTableau == 'tableauDeLogsBase') {
        tableauDesLargeuresEtIndicesLogsDeLaBase = "reinitialisé";
    } else if (idTableau == 'tableauListeParametresApplication') {
        tableauDesLargeuresEtIndicesParametresDeLApplication = "reinitialisé";
    } else if (idTableau == 'tableauListeDesProduits') {
        tableauDesLargeuresEtIndicesProduits = "reinitialisé";
    } else if (idTableau == 'tableauListePanier' 
    || idTableau == 'tableauListeRecapPanier') {
        tableauDesLargeuresEtIndicesPanier = "reinitialisé";
    } else if (idTableau == 'tableauListeClientsWebshop') {
        tableauDesLargeuresEtIndicesClientWebshop = "reinitialisé";
    } else if (idTableau == 'tableauListeDesComptesAAdministrer'
    || idTableau == 'tableauComptesConnectes') {
        tableauDesLargeuresEtIndicesCompteAAdministrer = "reinitialisé";
    } else if (idTableau == 'tableauListeDesVersionsCode') {
        tableauDesLargeuresEtIndicesVersionsCode = "reinitialisé";
    } else if (idTableau == 'tableauListeDesConsommateurs') {
        tableauDesLargeuresEtIndicesConsommateurs = "reinitialisé";
    } else if (idTableau == 'tableauListeModesExpeditions') {
        tableauDesLargeuresEtIndicesModesExpeditions = "reinitialisé";
    } else if (idTableau == 'tableauListeBoutiques') {
        tableauDesLargeuresEtIndicesBoutiques = "reinitialisé";
    } else if (idTableau == 'tableauListeDesPaiements') {
        tableauDesLargeuresEtIndicesPaiements = "reinitialisé";
    } else if (idTableau == 'tableauListeCumulsEmballages') {
        tableauDesLargeuresEtIndicesCumulsEmballages = "reinitialisé";
    } else if (idTableau == 'tableauListeDesOperationsWebshop') {
        tableauDesLargeuresEtIndicesOperationsWebshop = "reinitialisé";
    } else if (idTableau == 'tableauListeDesAdressesDeLivraisonWebshop') {
        tableauDesLargeuresEtIndicesAdresseLivraison = "reinitialisé";
    } else if (idTableau == 'tableauListeDesModelesEmails') {
        tableauDesLargeuresEtIndicesDesModelesEmails = "reinitialisé";
    }
    etatTest = true;
    if (oTable != null) {
        oTable.draw();

    }
}

// affiche une colonne cachée et masque une colonne visible
function fnAfficherCacherColonne(idTableau, iCol, visible) {
    /* Get the DataTables object again - this is not a recreation, just a get of the object */
    var oTable = $('#' + idTableau).DataTable();

    if (oTable.settings()[0].aoColumns[iCol] !== null) {
        setTimeout(function () { oTable.column(iCol).visible(visible); }, 0);
    }



}
// affiche une colonne cachée et masque une colonne visible
function fnAfficherCacherColonneDansBoucle(idTableau, iCol, visible) {
    /* Get the DataTables object again - this is not a recreation, just a get of the object */
    var oTable = $('#' + idTableau).DataTable();
 
    if (oTable.settings()[0].aoColumns[iCol] !== null) {
        oTable.column(iCol).visible(visible); 
    }



}

// affiche une colonne cachée et masque une colonne visible
function fnAfficherCacherColonneOrigCol(idTableau, iOrigCol, visible) {
    /* Get the DataTables object again - this is not a recreation, just a get of the object */
    var oTable = $('#' + idTableau).DataTable();
    var oSettings = oTable.settings();
    //
    var iLen = oTable.column()[0].length;
    var i = 0, trouv = false;

    while ( i < iLen && !trouv) {
        if (oSettings[0].aoColumns[i] != null && oSettings[0].aoColumns[i]._ColReorder_iOrigCol == iOrigCol) {
            iOrigCol = i;
            trouv = true;
        }
        i++;
    }

    fnAfficherCacherColonne(idTableau, iOrigCol, visible);
    
}
function fnNombreLignesAAfficher(etatTableau, nombreParDefaut) {
    nombreLignes = (nombreParDefaut != null ? nombreParDefaut : 10);
    if ((etatTableau != '""') && (etatTableau != null)) {

        etatTableau = etatTableau.split("\\").join("");
        etatTableau = etatTableau.split("^(").join("");
        etatTableau = etatTableau.split(")$").join("");

        etat = JSON.parse(etatTableau);
        nombreLignes = etat.iLength;
    }
    return nombreLignes;
}

//placer les CheckBoxs au début sans tomber dans le bug de la première colonne masquée
function fnOrdonnerColonnes(idTableau, etatTableau, indiceCheckBox) {
    
    var oTable = $('#' + idTableau).DataTable();
    var settings = oTable.settings();
    if ((etatTableau != '""') && (etatTableau!=null)){
        /* Get the DataTables object again - this is not a recreation, just a get of the object */
        
        etatTableau = etatTableau.split("\\").join("");
        etatTableau = etatTableau.split("^(").join("");
        etatTableau = etatTableau.split(")$").join("");
        
        var etat = JSON.parse(etatTableau);
        var iLen = etat.abVisCols.length;
        //        //cas ajout colonne à la fin
        //        if (oTable.settings()[0].aoColumns.length > etat.ColReorder.length) {
        //            etat.ColReorder.push(oTable.settings()[0].aoColumns.length);
        //            etat.abVisCols.push(oTable.settings()[0].aoColumns[oTable.settings()[0].aoColumns.length-1].bVisible);
        //        }

        //code de dépannage
        //        if (idTableau == "tableauListePanier") {
        //            iLen = 26;
        //            y = jQuery.grep(y, function (value) {
        //                return value != removeItem;
        //            });
        //        }
        

        for (var i = 0; i < iLen; i++) {
            if (etat.abVisCols[i] == false) {
                fnAfficherCacherColonne(idTableau, i, etat.abVisCols[i]);
            }
        }
        
        if (etatTableau == '""' || etatTableau == null || etatTableau == '') {
         

        } else {
            //test si colReorder est actif
            if (oTable.settings()[0].sDom.indexOf('R') >= 0) {
                oTable.colReorder.reset();
                oTable.colReorder.order(JSON.parse(etatTableau).ColReorder);
                colonnesOrdonnees = [];
                if (typeof indiceCheckBox !== 'undefined' && oTable.settings()[0].sDom.indexOf('R') >= 0) {
                    //                    tableauAvecCheckBoxAuDebut = JSON.parse(etatTableau).ColReorder;
                    //                    visibiliteTableauAvecCheckBoxAuDebut = etat.abVisCols;
                    //                    if (oTable.settings()[0].aoColumns[indiceCheckBox]._ColReorder_iOrigCol == indiceCheckBox) {
                    //                        valeurColonne = tableauAvecCheckBoxAuDebut[indiceCheckBox];
                    //                        tableauAvecCheckBoxAuDebut.splice(indiceCheckBox, 1);
                    //                        tableauAvecCheckBoxAuDebut.unshift(valeurColonne);
                    //                        colonnesOrdonnees = tableauAvecCheckBoxAuDebut;
                    //                        visibiliteColonne = visibiliteTableauAvecCheckBoxAuDebut[indiceCheckBox];
                    //                        visibiliteTableauAvecCheckBoxAuDebut.splice(indiceCheckBox, 1);
                    //                        visibiliteTableauAvecCheckBoxAuDebut.unshift(visibiliteColonne);
                    //                        etat.abVisCols = visibiliteTableauAvecCheckBoxAuDebut;
                    //                        for (var i = 0; i < iLen; i++) {
                    //                            fnAfficherCacherColonne(idTableau, i, etat.abVisCols[i]);
                    //                        }
                    //                        oTable.colReorder.reset();
                    //                        oTable.colReorder.order(colonnesOrdonnees);
                    //                    } 
                    
                }
            
            
            }
            
            if (etat.aaSorting.length > 0) {
                oTable.order(etat.aaSorting);
                if (oTable.settings()[0].oFeatures.bServerSide) {
                    $('#' + oTable.settings()[0].sInstance).find("thead th").not(".sorting_disabled").removeClass('sorting_desc').removeClass('sorting_asc').addClass('sorting');
                }
                for (i = 0; i < etat.aaSorting.length; i++) {
                    iCol = (oTable.settings()[0].sDom.indexOf('R') >= 0 ? oTable.settings()[0].aoColumns[etat.aaSorting[i][0]]._ColReorder_iOrigCol : i);
                     nthChild = $('#' + oTable.settings()[0].sInstance).find('[data-orig-col="' + iCol + '"]').index()+1;
                     $('#' + oTable.settings()[0].sInstance).find("thead th:nth-child(" + nthChild + ")").removeClass('sorting').addClass('sorting_' + etat.aaSorting[i][1]);
                }
             }

            if ($("select[name='" + idTableau + "_length']").length && idTableau != 'tableauListePanier' ) {
                $("select[name='" + idTableau + "_length']").val(etat.iLength);
                oTable.settings()[0]._iDisplayLength = etat.iLength; 
            }
            
       }

    }

    

    setTimeout(function () { $("#" + oTable.settings()[0].sInstance).css('visibility', 'visible'); }, 0);
    masquerChargement();
    $('.contenuPage').show();
   

}
// liste des colonnes visibles 
function colonnesVisibles(dTable) {
    dTable = dTable.dataTable();
    vCols = new Array();

    $.each(dTable.fnSettings().aoColumns, function (c) {
        if (dTable.fnSettings().aoColumns[c].bVisible == true) {
            vCols = vCols.concat((dTable.fnSettings().sDom.indexOf('R') >= 0 ? dTable.fnSettings().aoColumns[c]._ColReorder_iOrigCol : c))
        }
    });

    return vCols;
}

jQuery.fn.DataTable.ext.type.search.string = function (data) {
    return !data ?
        '' :
        typeof data === 'string' ?
            enleverAccents(data) : data;
           
};

function redimentionnerTableau() {
    var $table = $('.dataTable'),
    $bodyCells = $table.find('thead tr:first').children(),
    colWidth;
    // Adjust the width of thead cells when window resizes
    $(window).resize(function () {
        // Get the tbody columns width array
        colWidth = $bodyCells.map(function () {
            return $(this).width();
        }).get();

        // Set the width of thead columns
        $table.find('tfoot tr').children().each(function (i, v) {
            $(v).width(colWidth[i]);
        });
        $table.find('tbody tr').children().each(function (i, v) {
            $(v).width(colWidth[i]);
        });
        $table.find('tbody').width($table.find('tbody').width() + 10);
    }).resize(); // Trigger resize handler
}


function colonnesVisiblesOuPas(etatTableau, tableauDesColonnes, idTableau) {
    var oTable = $('#' + idTableau).DataTable();
    var oSettings = oTable.settings();
    var iLen = oSettings[0].aoColumns.length;
    if (tableauDesColonnes.length < iLen) {
       

        for (i = 0; i < iLen; i++) {
            if (tableauDesColonnes.length <= i) {
                tableauDesColonnes.splice(i, 0, ";" + i + ";0;0;0")
            } else {
                uneColonne = tableauDesColonnes[i].split(";");
                if (uneColonne[1].ltrim().rtrim() != i) {
                    tableauDesColonnes.splice(i, 0, ";" + i + ";0;0;0")
                }
            }
        }
    }
    

    if ((etatTableau == '""') || (etatTableau == null) ) {
        
        for (i = 0; i < tableauDesColonnes.length; i++) {
            tableauDesColonnes[i] += ";1";
        }

    } else {
        etatTableau = etatTableau.split("\\").join("");
        etatTableau = etatTableau.split("^(").join("");
        etatTableau = etatTableau.split(")$").join("");
        etat = JSON.parse(etatTableau);
        //test si colReorder est actif
        if (oTable.settings()[0].sDom.indexOf('R') >= 0) {
            len = etat.ColReorder.length;
            for (i = 0; i < tableauDesColonnes.length; i++) {
                j = 0;
                trouverColonne = false;
                while (j < len && !trouverColonne) {
                    if (etat.ColReorder[j] == i) {
                        trouverColonne = true;
                        tableauDesColonnes[i] += ";" + (etat.abVisCols[j] == true ? 1 : 0);
                    }
                    j++;
                }
            }
        } else {
            len = etat.abVisCols.length;
            for (i = 0; i < tableauDesColonnes.length; i++) {
               
                trouverColonne = true;
                tableauDesColonnes[i] += ";" + (etat.abVisCols[i] == true ? 1 : 0);
                 
            }
            
        }
    }

    return tableauDesColonnes;
}


function largeurActuel(idTableau, etatTableau, indiceOrigine, largeurParDefaut) {
    largeurActuelle = largeurParDefaut;
    var oTable = $('#' + idTableau).DataTable();
    if ((etatTableau != "") && (etatTableau != '""') && (etatTableau != null)) {
        etatTableau = etatTableau.split("\\").join("");
        etatTableau = etatTableau.split("^(").join("");
        etatTableau = etatTableau.split(")$").join("");
        etat = JSON.parse(etatTableau);
        if (etat.hasOwnProperty('ColWidth') && typeof etat.ColWidth !== 'undefined' && etat.ColWidth.length) {
            if (oTable.settings()[0].sDom.indexOf('R') >= 0 && etat.ColWidth.length > 0) {
                len = etat.ColReorder.length;
                trouverColonne = false;
                j = 0;
                while (j < len && !trouverColonne) {
                    if (etat.ColReorder[j] == indiceOrigine) {
                        trouverColonne = true;
                        largeurActuelle = etat.ColWidth[j];
                    }
                    j++;
                }
            } else {
                largeurActuelle = etat.ColWidth[indiceOrigine];
            }
        }

    }
    return largeurActuelle;
}


function indiceColonneReordonnee(indiceOrigine, oTable) {
    iLen = oTable.column()[0].length;
    oSettings = oTable.settings();
    i = 0, trouv = false;

    while (i < iLen && !trouv) {
        if (oSettings[0].aoColumns[i] != null && oSettings[0].aoColumns[i]._ColReorder_iOrigCol == indiceOrigine) {
            indiceOrigine = i;
            trouv = true;
        }
        i++;
    }
    return indiceOrigine;
}
/*! FixedHeader 2.1.1
 * ©2010-2014 SpryMedia Ltd - datatables.net/license
 */

/**
 * @summary     FixedHeader
 * @description Fix a table's header or footer, so it is always visible while
 *              Scrolling
 * @version     2.1.1
 * @file        dataTables.fixedHeader.js
 * @author      SpryMedia Ltd (www.sprymedia.co.uk)
 * @contact     www.sprymedia.co.uk/contact
 * @copyright   Copyright 2009-2014 SpryMedia Ltd.
 *
 * This source file is free software, available under the following license:
 *   MIT license - http://datatables.net/license/mit
 *
 * This source file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
 *
 * For details please refer to: http://www.datatables.net
 */

/* Global scope for FixedColumns for backwards compatibility - will be removed
 * in future. Not documented in 1.1.x.
 */

/* Global scope for FixedColumns */
var FixedHeader;

(function(window, document, undefined) {


var factory = function( $, DataTable ) {
"use strict";

/*
 * Function: FixedHeader
 * Purpose:  Provide 'fixed' header, footer and columns for a DataTable
 * Returns:  object:FixedHeader - must be called with 'new'
 * Inputs:   mixed:mTable - target table
 *  @param {object} dt DataTables instance or HTML table node. With DataTables
 *    1.10 this can also be a jQuery collection (with just a single table in its
 *    result set), a jQuery selector, DataTables API instance or settings
 *    object.
 *  @param {object} [oInit] initialisation settings, with the following
 *    properties (each optional)
 *    * bool:top -    fix the header (default true)
 *    * bool:bottom - fix the footer (default false)
 *    * int:left -    fix the left column(s) (default 0)
 *    * int:right -   fix the right column(s) (default 0)
 *    * int:zTop -    fixed header zIndex
 *    * int:zBottom - fixed footer zIndex
 *    * int:zLeft -   fixed left zIndex
 *    * int:zRight -  fixed right zIndex
 */
FixedHeader = function ( mTable, oInit ) {
	/* Sanity check - you just know it will happen */
	if ( ! this instanceof FixedHeader )
	{
		alert( "FixedHeader warning: FixedHeader must be initialised with the 'new' keyword." );
		return;
	}

	var that = this;
	var oSettings = {
		"aoCache": [],
		"oSides": {
			"top": true,
			"bottom": false,
			"left": 0,
			"right": 0
		},
		"oZIndexes": {
			"top": 104,
			"bottom": 103,
			"left": 102,
			"right": 101
		},
		"oCloneOnDraw": {
			"top": false,
			"bottom": false,
			"left": true,
			"right": true
		},
		"oMes": {
			"iTableWidth": 0,
			"iTableHeight": 0,
			"iTableLeft": 0,
			"iTableRight": 0, /* note this is left+width, not actually "right" */
			"iTableTop": 0,
			"iTableBottom": 0 /* note this is top+height, not actually "bottom" */
		},
		"oOffset": {
			"top": 0
		},
		"nTable": null,
		"bFooter": false,
		"bInitComplete": false
	};

	/*
	 * Function: fnGetSettings
	 * Purpose:  Get the settings for this object
	 * Returns:  object: - settings object
	 * Inputs:   -
	 */
	this.fnGetSettings = function () {
		return oSettings;
	};

	/*
	 * Function: fnUpdate
	 * Purpose:  Update the positioning and copies of the fixed elements
	 * Returns:  -
	 * Inputs:   -
	 */
	this.fnUpdate = function () {
		this._fnUpdateClones();
		this._fnUpdatePositions();
	};

	/*
	 * Function: fnPosition
	 * Purpose:  Update the positioning of the fixed elements
	 * Returns:  -
	 * Inputs:   -
	 */
	this.fnPosition = function () {
		this._fnUpdatePositions();
	};


	var dt = $.fn.dataTable.Api ?
		new $.fn.dataTable.Api( mTable ).settings()[0] :
		mTable.fnSettings();

	dt._oPluginFixedHeader = this;

	/* Let's do it */
	this.fnInit( dt, oInit );

};


/*
 * Variable: FixedHeader
 * Purpose:  Prototype for FixedHeader
 * Scope:    global
 */
FixedHeader.prototype = {
	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Initialisation
	 */

	/*
	 * Function: fnInit
	 * Purpose:  The "constructor"
	 * Returns:  -
	 * Inputs:   {as FixedHeader function}
	 */
	fnInit: function ( oDtSettings, oInit )
	{
		var s = this.fnGetSettings();
		var that = this;

		/* Record the user definable settings */
		this.fnInitSettings( s, oInit );

		if ( oDtSettings.oScroll.sX !== "" || oDtSettings.oScroll.sY !== "" )
		{
			alert( "FixedHeader 2 is not supported with DataTables' scrolling mode at this time" );
			return;
		}

		s.nTable = oDtSettings.nTable;
		oDtSettings.aoDrawCallback.unshift( {
			"fn": function () {
				FixedHeader.fnMeasure();
				that._fnUpdateClones.call(that);
				that._fnUpdatePositions.call(that);
			},
			"sName": "FixedHeader"
		} );

		s.bFooter = ($('>tfoot', s.nTable).length > 0) ? true : false;

		/* Add the 'sides' that are fixed */
		if ( s.oSides.top )
		{
			s.aoCache.push( that._fnCloneTable( "fixedHeader", "FixedHeader_Header", that._fnCloneThead ) );
		}
		if ( s.oSides.bottom )
		{
			s.aoCache.push( that._fnCloneTable( "fixedFooter", "FixedHeader_Footer", that._fnCloneTfoot ) );
		}
		if ( s.oSides.left )
		{
			s.aoCache.push( that._fnCloneTable( "fixedLeft", "FixedHeader_Left", that._fnCloneTLeft, s.oSides.left ) );
		}
		if ( s.oSides.right )
		{
			s.aoCache.push( that._fnCloneTable( "fixedRight", "FixedHeader_Right", that._fnCloneTRight, s.oSides.right ) );
		}

		/* Event listeners for window movement */
		FixedHeader.afnScroll.push( function () {
			that._fnUpdatePositions.call(that);
		} );

		$(window).resize( function () {
			FixedHeader.fnMeasure();
			that._fnUpdateClones.call(that);
			that._fnUpdatePositions.call(that);
		} );

		$(s.nTable)
			.on('column-reorder.dt', function () {
				FixedHeader.fnMeasure();
				that._fnUpdateClones( true );
				that._fnUpdatePositions();
			} )
			.on('column-visibility.dt', function () {
				FixedHeader.fnMeasure();
				that._fnUpdateClones( true );
				that._fnUpdatePositions();
			} );

		/* Get things right to start with */
		FixedHeader.fnMeasure();
		that._fnUpdateClones();
		that._fnUpdatePositions();

		s.bInitComplete = true;
	},


	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Support functions
	 */

	/*
	 * Function: fnInitSettings
	 * Purpose:  Take the user's settings and copy them to our local store
	 * Returns:  -
	 * Inputs:   object:s - the local settings object
	 *           object:oInit - the user's settings object
	 */
	fnInitSettings: function ( s, oInit )
	{
		if ( oInit !== undefined )
		{
			if ( oInit.top !== undefined ) {
				s.oSides.top = oInit.top;
			}
			if ( oInit.bottom !== undefined ) {
				s.oSides.bottom = oInit.bottom;
			}
			if ( typeof oInit.left == 'boolean' ) {
				s.oSides.left = oInit.left ? 1 : 0;
			}
			else if ( oInit.left !== undefined ) {
				s.oSides.left = oInit.left;
			}
			if ( typeof oInit.right == 'boolean' ) {
				s.oSides.right = oInit.right ? 1 : 0;
			}
			else if ( oInit.right !== undefined ) {
				s.oSides.right = oInit.right;
			}

			if ( oInit.zTop !== undefined ) {
				s.oZIndexes.top = oInit.zTop;
			}
			if ( oInit.zBottom !== undefined ) {
				s.oZIndexes.bottom = oInit.zBottom;
			}
			if ( oInit.zLeft !== undefined ) {
				s.oZIndexes.left = oInit.zLeft;
			}
			if ( oInit.zRight !== undefined ) {
				s.oZIndexes.right = oInit.zRight;
			}

			if ( oInit.offsetTop !== undefined ) {
				s.oOffset.top = oInit.offsetTop;
			}
			if ( oInit.alwaysCloneTop !== undefined ) {
				s.oCloneOnDraw.top = oInit.alwaysCloneTop;
			}
			if ( oInit.alwaysCloneBottom !== undefined ) {
				s.oCloneOnDraw.bottom = oInit.alwaysCloneBottom;
			}
			if ( oInit.alwaysCloneLeft !== undefined ) {
				s.oCloneOnDraw.left = oInit.alwaysCloneLeft;
			}
			if ( oInit.alwaysCloneRight !== undefined ) {
				s.oCloneOnDraw.right = oInit.alwaysCloneRight;
			}
		}
	},

	/*
	 * Function: _fnCloneTable
	 * Purpose:  Clone the table node and do basic initialisation
	 * Returns:  -
	 * Inputs:   -
	 */
	_fnCloneTable: function ( sType, sClass, fnClone, iCells )
	{
		var s = this.fnGetSettings();
		var nCTable;

		/* We know that the table _MUST_ has a DIV wrapped around it, because this is simply how
		 * DataTables works. Therefore, we can set this to be relatively position (if it is not
		 * alreadu absolute, and use this as the base point for the cloned header
		 */
		if ( $(s.nTable.parentNode).css('position') != "absolute" )
		{
			s.nTable.parentNode.style.position = "relative";
		}

		/* Just a shallow clone will do - we only want the table node */
		nCTable = s.nTable.cloneNode( false );
		nCTable.removeAttribute( 'id' );

		var nDiv = document.createElement( 'div' );
		nDiv.style.position = "absolute";
		nDiv.style.top = "0px";
		nDiv.style.left = "0px";
		nDiv.className += " FixedHeader_Cloned "+sType+" "+sClass;

		/* Set the zIndexes */
		if ( sType == "fixedHeader" )
		{
			nDiv.style.zIndex = s.oZIndexes.top;
		}
		if ( sType == "fixedFooter" )
		{
			nDiv.style.zIndex = s.oZIndexes.bottom;
		}
		if ( sType == "fixedLeft" )
		{
			nDiv.style.zIndex = s.oZIndexes.left;
		}
		else if ( sType == "fixedRight" )
		{
			nDiv.style.zIndex = s.oZIndexes.right;
		}

		/* remove margins since we are going to position it absolutely */
		nCTable.style.margin = "0";

		/* Insert the newly cloned table into the DOM, on top of the "real" header */
		nDiv.appendChild( nCTable );
		document.body.appendChild( nDiv );

		return {
			"nNode": nCTable,
			"nWrapper": nDiv,
			"sType": sType,
			"sPosition": "",
			"sTop": "",
			"sLeft": "",
			"fnClone": fnClone,
			"iCells": iCells
		};
	},

	/*
	 * Function: _fnMeasure
	 * Purpose:  Get the current positioning of the table in the DOM
	 * Returns:  -
	 * Inputs:   -
	 */
	_fnMeasure: function ()
	{
		var
			s = this.fnGetSettings(),
			m = s.oMes,
			jqTable = $(s.nTable),
			oOffset = jqTable.offset(),
			iParentScrollTop = this._fnSumScroll( s.nTable.parentNode, 'scrollTop' ),
			iParentScrollLeft = this._fnSumScroll( s.nTable.parentNode, 'scrollLeft' );

		m.iTableWidth = jqTable.outerWidth();
		m.iTableHeight = jqTable.outerHeight();
		m.iTableLeft = oOffset.left + s.nTable.parentNode.scrollLeft;
		m.iTableTop = oOffset.top + iParentScrollTop;
		m.iTableRight = m.iTableLeft + m.iTableWidth;
		m.iTableRight = FixedHeader.oDoc.iWidth - m.iTableLeft - m.iTableWidth;
		m.iTableBottom = FixedHeader.oDoc.iHeight - m.iTableTop - m.iTableHeight;
	},

	/*
	 * Function: _fnSumScroll
	 * Purpose:  Sum node parameters all the way to the top
	 * Returns:  int: sum
	 * Inputs:   node:n - node to consider
	 *           string:side - scrollTop or scrollLeft
	 */
	_fnSumScroll: function ( n, side )
	{
		var i = n[side];
		while ( n = n.parentNode )
		{
			if ( n.nodeName == 'HTML' || n.nodeName == 'BODY' )
			{
				break;
			}
			i = n[side];
		}
		return i;
	},

	/*
	 * Function: _fnUpdatePositions
	 * Purpose:  Loop over the fixed elements for this table and update their positions
	 * Returns:  -
	 * Inputs:   -
	 */
	_fnUpdatePositions: function ()
	{
		var s = this.fnGetSettings();
		this._fnMeasure();

		for ( var i=0, iLen=s.aoCache.length ; i<iLen ; i++ )
		{
			if ( s.aoCache[i].sType == "fixedHeader" )
			{
				this._fnScrollFixedHeader( s.aoCache[i] );
			}
			else if ( s.aoCache[i].sType == "fixedFooter" )
			{
				this._fnScrollFixedFooter( s.aoCache[i] );
			}
			else if ( s.aoCache[i].sType == "fixedLeft" )
			{
				this._fnScrollHorizontalLeft( s.aoCache[i] );
			}
			else
			{
				this._fnScrollHorizontalRight( s.aoCache[i] );
			}
		}
	},

	/*
	 * Function: _fnUpdateClones
	 * Purpose:  Loop over the fixed elements for this table and call their cloning functions
	 * Returns:  -
	 * Inputs:   -
	 */
	_fnUpdateClones: function ( full )
	{
		var s = this.fnGetSettings();

		if ( full ) {
			// This is a little bit of a hack to force a full clone draw. When
			// `full` is set to true, we want to reclone the source elements,
			// regardless of the clone-on-draw settings
			s.bInitComplete = false;
		}

		for ( var i=0, iLen=s.aoCache.length ; i<iLen ; i++ )
		{
			s.aoCache[i].fnClone.call( this, s.aoCache[i] );
		}

		if ( full ) {
			s.bInitComplete = true;
		}
	},


	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Scrolling functions
	 */

	/*
	 * Function: _fnScrollHorizontalLeft
	 * Purpose:  Update the positioning of the scrolling elements
	 * Returns:  -
	 * Inputs:   object:oCache - the cached values for this fixed element
	 */
	_fnScrollHorizontalRight: function ( oCache )
	{
		var
			s = this.fnGetSettings(),
			oMes = s.oMes,
			oWin = FixedHeader.oWin,
			oDoc = FixedHeader.oDoc,
			nTable = oCache.nWrapper,
			iFixedWidth = $(nTable).outerWidth();

		if ( oWin.iScrollRight < oMes.iTableRight )
		{
			/* Fully right aligned */
			this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft+oMes.iTableWidth-iFixedWidth)+"px", 'left', nTable.style );
		}
		else if ( oMes.iTableLeft < oDoc.iWidth-oWin.iScrollRight-iFixedWidth )
		{
			/* Middle */
			this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop-oWin.iScrollTop)+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', (oWin.iWidth-iFixedWidth)+"px", 'left', nTable.style );
		}
		else
		{
			/* Fully left aligned */
			this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
		}
	},

	/*
	 * Function: _fnScrollHorizontalLeft
	 * Purpose:  Update the positioning of the scrolling elements
	 * Returns:  -
	 * Inputs:   object:oCache - the cached values for this fixed element
	 */
	_fnScrollHorizontalLeft: function ( oCache )
	{
		var
			s = this.fnGetSettings(),
			oMes = s.oMes,
			oWin = FixedHeader.oWin,
			oDoc = FixedHeader.oDoc,
			nTable = oCache.nWrapper,
			iCellWidth = $(nTable).outerWidth();

		if ( oWin.iScrollLeft < oMes.iTableLeft )
		{
			/* Fully left align */
			this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
		}
		else if ( oWin.iScrollLeft < oMes.iTableLeft+oMes.iTableWidth-iCellWidth )
		{
			this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop-oWin.iScrollTop)+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', "0px", 'left', nTable.style );
		}
		else
		{
			/* Fully right align */
			this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft+oMes.iTableWidth-iCellWidth)+"px", 'left', nTable.style );
		}
	},

	/*
	 * Function: _fnScrollFixedFooter
	 * Purpose:  Update the positioning of the scrolling elements
	 * Returns:  -
	 * Inputs:   object:oCache - the cached values for this fixed element
	 */
	_fnScrollFixedFooter: function ( oCache )
	{
		var
			s = this.fnGetSettings(),
			oMes = s.oMes,
			oWin = FixedHeader.oWin,
			oDoc = FixedHeader.oDoc,
			nTable = oCache.nWrapper,
			iTheadHeight = $("thead", s.nTable).outerHeight(),
			iCellHeight = $(nTable).outerHeight();

		if ( oWin.iScrollBottom < oMes.iTableBottom )
		{
			/* Below */
			this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+oMes.iTableHeight-iCellHeight)+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
		}
		else if ( oWin.iScrollBottom < oMes.iTableBottom+oMes.iTableHeight-iCellHeight-iTheadHeight )
		{
			this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', (oWin.iHeight-iCellHeight)+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft-oWin.iScrollLeft)+"px", 'left', nTable.style );
		}
		else
		{
			/* Above */
			this._fnUpdateCache( oCache, 'sPosition', 'absolute', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+iCellHeight)+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
		}
	},

	/*
	 * Function: _fnScrollFixedHeader
	 * Purpose:  Update the positioning of the scrolling elements
	 * Returns:  -
	 * Inputs:   object:oCache - the cached values for this fixed element
	 */
	_fnScrollFixedHeader: function ( oCache )
	{
		var
			s = this.fnGetSettings(),
			oMes = s.oMes,
			oWin = FixedHeader.oWin,
			oDoc = FixedHeader.oDoc,
			nTable = oCache.nWrapper,
			iTbodyHeight = 0,
			anTbodies = s.nTable.getElementsByTagName('tbody');

		for (var i = 0; i < anTbodies.length; ++i) {
			iTbodyHeight += anTbodies[i].offsetHeight;
		}

		if ( oMes.iTableTop > oWin.iScrollTop + s.oOffset.top )
		{
			/* Above the table */
			this._fnUpdateCache( oCache, 'sPosition', "absolute", 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', oMes.iTableTop+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
		}
		else if ( oWin.iScrollTop + s.oOffset.top > oMes.iTableTop+iTbodyHeight )
		{
			/* At the bottom of the table */
			this._fnUpdateCache( oCache, 'sPosition', "absolute", 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', (oMes.iTableTop+iTbodyHeight)+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', oMes.iTableLeft+"px", 'left', nTable.style );
		}
		else
		{
			/* In the middle of the table */
			this._fnUpdateCache( oCache, 'sPosition', 'fixed', 'position', nTable.style );
			this._fnUpdateCache( oCache, 'sTop', s.oOffset.top+"px", 'top', nTable.style );
			this._fnUpdateCache( oCache, 'sLeft', (oMes.iTableLeft-oWin.iScrollLeft)+"px", 'left', nTable.style );
		}
	},

	/*
	 * Function: _fnUpdateCache
	 * Purpose:  Check the cache and update cache and value if needed
	 * Returns:  -
	 * Inputs:   object:oCache - local cache object
	 *           string:sCache - cache property
	 *           string:sSet - value to set
	 *           string:sProperty - object property to set
	 *           object:oObj - object to update
	 */
	_fnUpdateCache: function ( oCache, sCache, sSet, sProperty, oObj )
	{
		if ( oCache[sCache] != sSet )
		{
			oObj[sProperty] = sSet;
			oCache[sCache] = sSet;
		}
	},



	/**
	 * Copy the classes of all child nodes from one element to another. This implies
	 * that the two have identical structure - no error checking is performed to that
	 * fact.
	 *  @param {element} source Node to copy classes from
	 *  @param {element} dest Node to copy classes too
	 */
	_fnClassUpdate: function ( source, dest )
	{
		var that = this;

		if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" ||
			 source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" )
		{
			dest.className = source.className;
		}

		$(source).children().each( function (i) {
			that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] );
		} );
	},


	/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	 * Cloning functions
	 */

	/*
	 * Function: _fnCloneThead
	 * Purpose:  Clone the thead element
	 * Returns:  -
	 * Inputs:   object:oCache - the cached values for this fixed element
	 */
	_fnCloneThead: function ( oCache )
	{
		var s = this.fnGetSettings();
		var nTable = oCache.nNode;

		if ( s.bInitComplete && !s.oCloneOnDraw.top )
		{
			this._fnClassUpdate( $('thead', s.nTable)[0], $('thead', nTable)[0] );
			return;
		}

		/* Set the wrapper width to match that of the cloned table */
		var iDtWidth = $(s.nTable).outerWidth();
		oCache.nWrapper.style.width = iDtWidth+"px";
		nTable.style.width = iDtWidth+"px";

		/* Remove any children the cloned table has */
		while ( nTable.childNodes.length > 0 )
		{
			$('thead th', nTable).unbind( 'click' );
			nTable.removeChild( nTable.childNodes[0] );
		}

		/* Clone the DataTables header */
		var nThead = $('thead', s.nTable).clone(true)[0];
		nTable.appendChild( nThead );

		/* Copy the widths across - apparently a clone isn't good enough for this */
		var a = [];
		var b = [];

		$("thead>tr th", s.nTable).each( function (i) {
			a.push( $(this).width() );
		} );

		$("thead>tr td", s.nTable).each( function (i) {
			b.push( $(this).width() );
		} );

		$("thead>tr th", s.nTable).each( function (i) {
			$("thead>tr th:eq("+i+")", nTable).width( a[i] );
			$(this).width( a[i] );
		} );

		$("thead>tr td", s.nTable).each( function (i) {
			$("thead>tr td:eq("+i+")", nTable).width( b[i] );
			$(this).width( b[i] );
		} );

		// Stop DataTables 1.9 from putting a focus ring on the headers when
		// clicked to sort
		$('th.sorting, th.sorting_desc, th.sorting_asc', nTable).bind( 'click', function () {
			this.blur();
		} );
	},

	/*
	 * Function: _fnCloneTfoot
	 * Purpose:  Clone the tfoot element
	 * Returns:  -
	 * Inputs:   object:oCache - the cached values for this fixed element
	 */
	_fnCloneTfoot: function ( oCache )
	{
		var s = this.fnGetSettings();
		var nTable = oCache.nNode;

		/* Set the wrapper width to match that of the cloned table */
		oCache.nWrapper.style.width = $(s.nTable).outerWidth()+"px";

		/* Remove any children the cloned table has */
		while ( nTable.childNodes.length > 0 )
		{
			nTable.removeChild( nTable.childNodes[0] );
		}

		/* Clone the DataTables footer */
		var nTfoot = $('tfoot', s.nTable).clone(true)[0];
		nTable.appendChild( nTfoot );

		/* Copy the widths across - apparently a clone isn't good enough for this */
		$("tfoot:eq(0)>tr th", s.nTable).each( function (i) {
			$("tfoot:eq(0)>tr th:eq("+i+")", nTable).width( $(this).width() );
		} );

		$("tfoot:eq(0)>tr td", s.nTable).each( function (i) {
			$("tfoot:eq(0)>tr td:eq("+i+")", nTable).width( $(this).width() );
		} );
	},

	/*
	 * Function: _fnCloneTLeft
	 * Purpose:  Clone the left column(s)
	 * Returns:  -
	 * Inputs:   object:oCache - the cached values for this fixed element
	 */
	_fnCloneTLeft: function ( oCache )
	{
		var s = this.fnGetSettings();
		var nTable = oCache.nNode;
		var nBody = $('tbody', s.nTable)[0];

		/* Remove any children the cloned table has */
		while ( nTable.childNodes.length > 0 )
		{
			nTable.removeChild( nTable.childNodes[0] );
		}

		/* Is this the most efficient way to do this - it looks horrible... */
		nTable.appendChild( $("thead", s.nTable).clone(true)[0] );
		nTable.appendChild( $("tbody", s.nTable).clone(true)[0] );
		if ( s.bFooter )
		{
			nTable.appendChild( $("tfoot", s.nTable).clone(true)[0] );
		}

		/* Remove unneeded cells */
		var sSelector = 'gt(' + (oCache.iCells - 1) + ')';
		$('thead tr', nTable).each( function (k) {
			$('th:' + sSelector, this).remove();
		} );

		$('tfoot tr', nTable).each( function (k) {
			$('th:' + sSelector, this).remove();
		} );

		$('tbody tr', nTable).each( function (k) {
			$('td:' + sSelector, this).remove();
		} );

		this.fnEqualiseHeights( 'thead', nBody.parentNode, nTable );
		this.fnEqualiseHeights( 'tbody', nBody.parentNode, nTable );
		this.fnEqualiseHeights( 'tfoot', nBody.parentNode, nTable );

		var iWidth = 0;
		for (var i = 0; i < oCache.iCells; i++) {
			iWidth += $('thead tr th:eq(' + i + ')', s.nTable).outerWidth();
		}
		nTable.style.width = iWidth+"px";
		oCache.nWrapper.style.width = iWidth+"px";
	},

	/*
	 * Function: _fnCloneTRight
	 * Purpose:  Clone the right most column(s)
	 * Returns:  -
	 * Inputs:   object:oCache - the cached values for this fixed element
	 */
	_fnCloneTRight: function ( oCache )
	{
		var s = this.fnGetSettings();
		var nBody = $('tbody', s.nTable)[0];
		var nTable = oCache.nNode;
		var iCols = $('tbody tr:eq(0) td', s.nTable).length;

		/* Remove any children the cloned table has */
		while ( nTable.childNodes.length > 0 )
		{
			nTable.removeChild( nTable.childNodes[0] );
		}

		/* Is this the most efficient way to do this - it looks horrible... */
		nTable.appendChild( $("thead", s.nTable).clone(true)[0] );
		nTable.appendChild( $("tbody", s.nTable).clone(true)[0] );
		if ( s.bFooter )
		{
			nTable.appendChild( $("tfoot", s.nTable).clone(true)[0] );
		}
		$('thead tr th:lt('+(iCols-oCache.iCells)+')', nTable).remove();
		$('tfoot tr th:lt('+(iCols-oCache.iCells)+')', nTable).remove();

		/* Remove unneeded cells */
		$('tbody tr', nTable).each( function (k) {
			$('td:lt('+(iCols-oCache.iCells)+')', this).remove();
		} );

		this.fnEqualiseHeights( 'thead', nBody.parentNode, nTable );
		this.fnEqualiseHeights( 'tbody', nBody.parentNode, nTable );
		this.fnEqualiseHeights( 'tfoot', nBody.parentNode, nTable );

		var iWidth = 0;
		for (var i = 0; i < oCache.iCells; i++) {
			iWidth += $('thead tr th:eq('+(iCols-1-i)+')', s.nTable).outerWidth();
		}
		nTable.style.width = iWidth+"px";
		oCache.nWrapper.style.width = iWidth+"px";
	},


	/**
	 * Equalise the heights of the rows in a given table node in a cross browser way. Note that this
	 * is more or less lifted as is from FixedColumns
	 *  @method  fnEqualiseHeights
	 *  @returns void
	 *  @param   {string} parent Node type - thead, tbody or tfoot
	 *  @param   {element} original Original node to take the heights from
	 *  @param   {element} clone Copy the heights to
	 *  @private
	 */
	"fnEqualiseHeights": function ( parent, original, clone )
	{
		var that = this;
		var originals = $(parent +' tr', original);
		var height;

		$(parent+' tr', clone).each( function (k) {
			height = originals.eq( k ).css('height');

			// This is nasty :-(. IE has a sub-pixel error even when setting
			// the height below (the Firefox fix) which causes the fixed column
			// to go out of alignment. Need to add a pixel before the assignment
			// Can this be feature detected? Not sure how...
			if ( navigator.appName == 'Microsoft Internet Explorer' ) {
				height = parseInt( height, 10 ) + 1;
			}

			$(this).css( 'height', height );

			// For Firefox to work, we need to also set the height of the
			// original row, to the value that we read from it! Otherwise there
			// is a sub-pixel rounding error
			originals.eq( k ).css( 'height', height );
		} );
	}
};


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Static properties and methods
 *   We use these for speed! This information is common to all instances of FixedHeader, so no
 * point if having them calculated and stored for each different instance.
 */

/*
 * Variable: oWin
 * Purpose:  Store information about the window positioning
 * Scope:    FixedHeader
 */
FixedHeader.oWin = {
	"iScrollTop": 0,
	"iScrollRight": 0,
	"iScrollBottom": 0,
	"iScrollLeft": 0,
	"iHeight": 0,
	"iWidth": 0
};

/*
 * Variable: oDoc
 * Purpose:  Store information about the document size
 * Scope:    FixedHeader
 */
FixedHeader.oDoc = {
	"iHeight": 0,
	"iWidth": 0
};

/*
 * Variable: afnScroll
 * Purpose:  Array of functions that are to be used for the scrolling components
 * Scope:    FixedHeader
 */
FixedHeader.afnScroll = [];

/*
 * Function: fnMeasure
 * Purpose:  Update the measurements for the window and document
 * Returns:  -
 * Inputs:   -
 */
FixedHeader.fnMeasure = function ()
{
	var
		jqWin = $(window),
		jqDoc = $(document),
		oWin = FixedHeader.oWin,
		oDoc = FixedHeader.oDoc;

	oDoc.iHeight = jqDoc.height();
	oDoc.iWidth = jqDoc.width();

	oWin.iHeight = jqWin.height();
	oWin.iWidth = jqWin.width();
	oWin.iScrollTop = jqWin.scrollTop();
	oWin.iScrollLeft = jqWin.scrollLeft();
	oWin.iScrollRight = oDoc.iWidth - oWin.iScrollLeft - oWin.iWidth;
	oWin.iScrollBottom = oDoc.iHeight - oWin.iScrollTop - oWin.iHeight;
};


FixedHeader.version = "2.1.1";


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * Global processing
 */

/*
 * Just one 'scroll' event handler in FixedHeader, which calls the required components. This is
 * done as an optimisation, to reduce calculation and proagation time
 */
$(window).scroll( function () {
	FixedHeader.fnMeasure();

	for ( var i=0, iLen=FixedHeader.afnScroll.length ; i<iLen ; i++ ) {
		FixedHeader.afnScroll[i]();
	}
} );


$.fn.dataTable.FixedHeader = FixedHeader;
$.fn.DataTable.FixedHeader = FixedHeader;


return FixedHeader;
}; // /factory


// Define as an AMD module if possible
if ( typeof define === 'function' && define.amd ) {
	define( 'datatables-fixedheader', ['jquery', 'datatables'], factory );
}
else if ( jQuery && !jQuery.fn.dataTable.FixedHeader ) {
	// Otherwise simply initialise as normal, stopping multiple evaluation
	factory( jQuery, jQuery.fn.dataTable );
}


})(window, document);


var tableauLargeurColonneListe;
var tableauDesLargeuresEtIndicesLocal;

function initialisationPageLargeurColonneListe(idTableauParent) {
    $('.contenuPage').hide();
    nommagesColonnes = "";
    renommage = false;
    if (idTableauParent == 'moduleDescriptif_tableauListeDesBDDVegetalesEnPreselection'
    || idTableauParent == 'moduleDescriptif_tableauListeDesBDDVegetalesEnRattachement'
    || idTableauParent == 'moduleDescriptif_tableauListeDesBDDVegetales'
    || idTableauParent == 'moduleDescriptif_tableauListeDesDescriptifsEnRattachement'
    || idTableauParent == 'moduleDescriptif_tableauListeDesDescriptifsEnPreselection'
    || idTableauParent == 'moduleDescriptif_tableauListeDesDescriptifs') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesDescriptif;
    } else if (idTableauParent == 'moduleValeur_tableauListeDeValeurs'
    || idTableauParent == 'moduleValeur_tableauListeDeValeursVlv'
    || idTableauParent == 'moduleValeur_tableauListeDeValeursReferentes') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesValeurs;
    } else if (idTableauParent == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesVlv'
    || idTableauParent == 'moduleCritereCategorie_tableauListeDesCriteresCategories'
    || idTableauParent == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesReferentes') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCriteresCategories;
    } else if (idTableauParent == 'tableauListeDesCategoriesDescriptifs') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCategorieDescriptifs;
    } else if (idTableauParent == 'moduleMediaCategorie_tableauListeDesCategoriesMedias'
    || idTableauParent == 'moduleMediaCategorie_tableauListeDesCategoriesMediasVlv') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCategorieMedias;
    } else if (idTableauParent == 'tableauListeDesTypesDeConseils') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesConseilsTypes;
    } else if (idTableauParent == 'tableauListeDesTypesInfoComplementaireConseil') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesConseilInfoComplementaireTypes;
    } else if (idTableauParent == 'tableauListeDesInfosComplementaireConseil') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesInfosComplementaireConseils;
    } else if (idTableauParent == 'copyrights') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCopyrights;
    } else if (idTableauParent == 'moduleCritere_tableauListeDeCriteres'
    || idTableauParent == 'moduleCritere_tableauListeDeCriteresVlv'
    || idTableauParent == 'moduleCritere_tableauListeDeCriteresReferentes'

    || idTableauParent == 'moduleCritere_tableauListeDeCriteresWebshop'
    || idTableauParent == 'moduleCritere_tableauListeDeCriteresWebshopVlv'
    || idTableauParent == 'moduleCritere_tableauListeDeCriteresProduitWebshop'
        || idTableauParent == 'moduleCritere_tableauListeDeCriteresProduitWebshopVlv'

    || idTableauParent == 'moduleCritere_tableauListeDeCriteresWebshop'
    || idTableauParent == 'moduleCritere_tableauListeDeCriteresWebshopVlv'
    || idTableauParent == 'moduleCritere_tableauListeDeCriteresProduitWebshop'
    || idTableauParent == 'moduleCritere_tableauListeDeCriteresProduitWebshopVlv') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCritere;
    } else if (idTableauParent == 'lieux') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesLieux;
    } else if (idTableauParent == 'moduleMedia_tableauListeDeMedias'
    || idTableauParent == 'moduleConseil_tableauListeDesMedias'
    || idTableauParent == 'moduleDescriptif_tableauListeDeMedias'
    || idTableauParent == 'moduleMedia_tableauListeDeMediasVlv'
    || idTableauParent == 'moduleMedia_tableauListeDeMediasReferente') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesMedia;
    } else if (idTableauParent == 'moduleLangue_tableauListeDesLangues') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesTraduction;
    } else if (idTableauParent == 'moduleLangue_tableauListeDesEntitees') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesEntiteesTraduction;
    } else if (idTableauParent == 'moduleLangue_tableauEditerTraduction') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesEditerTraduction;
    } else if (idTableauParent == 'tableauListeDesConseils'
    || idTableauParent == 'moduleConseilAssocieDescriptif_tableauListeDesConseils') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesConseil;
    } else if (idTableauParent == 'tableauListeDesCatalogues') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCatalogues;
    } else if (idTableauParent == 'tableauLignesDeCatalogue') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesLignesCatalogue;
    } else if (idTableauParent == 'tableauListeDesComptesBancaires') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesComptesBancaires;
    } else if (idTableauParent == 'tableauListeDesDemandesServices'
    || idTableauParent == 'tableauActualise_tableauListeDesDemandesServices') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesDemandesServices;
    } else if (idTableauParent == 'natureDemandeService') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesNatureDemandeService;
    } else if (idTableauParent == 'tableauListeDesProduitsDemandeService') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesProduitDemandeService;
    } else if (idTableauParent == 'tableauListeDesCategoriesDemandeService') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCategorieDemandeService;
    } else if (idTableauParent == 'tableauListeDesSousCategoriesDemandeService') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesSousCategorieDemandeService;
    } else if (idTableauParent == 'tableauListeDesAdressesDeLivraison') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesAdresseLivraison;
    }else if (idTableauParent == 'tableauListeTypeUniteVente'
    || idTableauParent == 'tableauListePresentations'
    || idTableauParent == "tableauListeMillesimes") {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesDictionnaire;
    } else if (idTableauParent == 'tableauEletter') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesEletter;
    } else if (idTableauParent == 'tableauListeDEmailsConseilsEnvoyes') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesEmailsConseilsEnvoyes;
    } else if (idTableauParent == 'tableauGroupes'
    || idTableauParent == 'tableauGroupes_detailSociete') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesGroupe;
    } else if (idTableauParent == 'tableauListeDesArticles') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesArticles;
    } else if (idTableauParent == 'tableauServices') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesServices;
    } else if (idTableauParent == 'tableauMesServices') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesMesServices;
    } else if (idTableauParent == 'tableauListeDesOperationsEnvoyees') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesOperations;
    } else if (idTableauParent == 'tableauListeTaille'
    || idTableauParent == 'tableauListeUniteVente') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesTypeUniteVente;
    } else if (idTableauParent == 'moduleClients_tableauClients'
    || idTableauParent == 'moduleDemandeService_tableauClients'
    || idTableauParent == 'moduleAjoutGroupe_tableauClients'
    || idTableauParent == 'moduleAjoutGroupe_tableauClientsModifierGroupe'
    || idTableauParent == 'moduleConsulterGroupe_tableauClients') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesMesClients;
    } else if (idTableauParent == 'tableauListeClientsWebshop') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesClientWebshop;
    } else if (idTableauParent == 'moduleComptesSecondaires_tableauListeDesComptes'
    || idTableauParent == 'moduleDemandeService_tableauListeDesComptes') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesComptes;
    } else if (idTableauParent == 'tableauListeDeAuthentifications') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesAuthentifications;
    } else if (idTableauParent == 'tableauListeDEmaislEnvoyes') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesEmailsEnvoyes;
    } else if (idTableauParent == 'moduleHistoriqueConsultation_tableauListeDetailsHistoriqueConsultation') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesHistoriqueConsultation;
    } else if (idTableauParent == 'tableauListeDHistoriqueDImport') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesHistoriqueImport;
    } else if (idTableauParent == 'tableauDeLogsBase') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesLogsDeLaBase;
    } else if (idTableauParent == 'tableauListeParametresApplication') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesParametresDeLApplication;
    } else if (idTableauParent == 'tableauListeDesProduits') {
        renommage = true;
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesProduits;
    } else if (idTableauParent == 'tableauListePanier' || idTableauParent == 'tableauListeRecapPanier') {
        renommage = true;
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesPanier; 
    } else if (idTableauParent == 'tableauListeClientsWebshop') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesClientWebshop;
    } else if (idTableauParent == 'tableauListeDesComptesAAdministrer'
    || idTableauParent == 'tableauComptesConnectes') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCompteAAdministrer;
    } else if (idTableauParent == 'tableauListeDesVersionsCode') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesVersionsCode;
    } else if (idTableauParent == 'tableauListeDesConsommateurs') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesConsommateurs;
    } else if (idTableauParent == 'tableauListeModesExpeditions') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesModesExpeditions;
    } else if (idTableauParent == 'tableauListeBoutiques') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesBoutiques;
    } else if (idTableauParent == 'tableauListeDesPaiements') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesPaiements;
    } else if (idTableauParent == 'tableauListeCumulsEmballages') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesCumulsEmballages;
    } else if (idTableauParent == 'tableauListeDesOperationsWebshop') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesOperationsWebshop;
    } else if (idTableauParent == 'tableauListeDesAdressesDeLivraisonWebshop') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesAdresseLivraison;
    } else if (idTableauParent == 'tableauListeDesDureesDemandesServices') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesDureeDemandesServices;
    } else if (idTableauParent == 'tableauListeDesModelesEmails') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesDesModelesEmails;
    }



    $('#listeDesLargeursColonnes').attr("data-tableauattache", idTableauParent);
    $(".listeLargeursColonnes").find('.messagePopup').remove();
    tableauindice = retournerIndiceTableau('listeDesLargeursColonnes');

    pageSelectionnee = retournerdebutPage(tableauindice);
    // Cabler la librairie dataTables sur le tableau
    tableauLargeurColonneListe = $('#listeDesLargeursColonnes').DataTable({
        // Activer la sauvegarde d'état du tableau
        //'stateSave': true,
        // Chargement état tableau
        //        'stateLoadParams': function (oSettings, data) {
        //            return JSON.parse(lieux);
        //        },
        'order': [],
        // Options sur les colonnes
        // sName pour le nommage interne (à dataTables) des colonnes. bSortable pour le trie. bVisible pour la visibilité
        'columns': [
            { 'className': 'width40' },
            { 'name': 'libelle', 'className': 'width135' },
            { 'name': 'largeur', 'className': 'width135' },
            { 'name': 'largeurParDefaut', 'className': 'width135', 'visible': true },
            { 'name': 'renommage', 'className': 'width135', 'visible': (idTableauParent == 'tableauListeDesProduits' || idTableauParent == 'tableauListePanier' ? true : false) },
            { 'name': 'modifier', 'orderable': false, 'className': 'width60' },
            { 'name': 'indiceColonne', 'visible': false }


        ],
        // W<"clear"> pour activer les filtres
        // T          pour activer l'export
        // l          pour choisir nombre de lignes affichées dans tableau via un combobox
        // f          pour activer le champ de recherche textuelle
        // t          "pour tableau HTML", veut dire quoi ??? préciser la réelle utilité
        // i          pour afficher les informations sur la pagination (Ex : Affichage 5 à 10 sur 47)
        // p          pour activer la pagination
        // R          pour activer le déplacement des colonnes
        // C          pour activer la visibilité des colonnes
        'dom': '<"top"Tlftip>rt',
        // Pour décider du nombre de boutons concernant la pagination. Valeurs possible : 'two_button' or 'full_numbers'
        'paginationType': 'full_numbers',
        // Export de Datatable sous plusieurs format
        'tableTools': {
            // Attribuer les évènements aux bouttons d'export (csv, pdf, Excel)
            'sSwfPath': '/ressource/js/librairie/DataTables-1.10.0/extras/TableTools-2.2.1/swf/copy_csv_xls_pdf.swf',
            'aButtons': [
            // Definir les colonnes qu'on souhaite exporter
                {'sExtends': 'copy', 'sButtonText': '', 'mColumns': [0, 1, 2, 3], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'csv', 'sButtonText': '', 'sFileName': 'test' + '.csv', 'sTitle': 'test', 'mColumns': [0, 1, 2, 3], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'xls', 'sButtonText': '', 'sFileName': 'test' + '.xls', 'sTitle': 'test', 'mColumns': [0, 1, 2, 3], 'oSelectorOpts': { filter: 'applied', order: 'current'} },
                { 'sExtends': 'pdf', 'sButtonText': '', 'sFileName': 'test' + '.pdf', 'sTitle': 'test', 'mColumns': [0, 1, 2, 3], 'oSelectorOpts': { filter: 'applied', order: 'current'} }
            ]
        },
        // Spécifier le fichier de langue pour dataTables
        'language': { 'url': fichierLangue },
        // Spécifier la première page d'affichage
        'displayStart': parseInt(pageSelectionnee),
        'initComplete': function (settings, data) {
            fnOrdonnerColonnes('listeDesLargeursColonnes', null);
            //$(this).css('visibility', 'visible');
            materialiserChampsDeRecherche('listeDesLargeursColonnes');

            initialiserCoVis('listeDesLargeursColonnes');
            // Ne pas tenir compte des filtres dans la sauvegarde d'état du tableau
            // Je n'ai pas l'explication mais si l'appel à la méthode se fait en dehors d'un setTimeout alors exception JS
            setTimeout(function () { $.fn.dataTableExt.oApi.fnResetAllFilters(tableauLargeurColonneListe, true, 'listeDesLargeursColonnes', null); }, 0);
        },

        'drawCallback': function (settings) {
            //cette fonction prend en charge de masquer le loader de chargement et affiche la table après sa création

            // $('.contenuCaption').css('width', $('.dataTables_wrapper').width() - 20);
            forcerCablagePagination('listeDesLargeursColonnes');
           

        },
        'preDrawCallback': function (settings) {
            //tableauLieux.settings()[0].oPreviousSearch.sSearch = enleverAccents(tableauLieux.settings()[0].oPreviousSearch.sSearch);
            //alert(tableauLieux.settings()[0].oPreviousSearch.sSearch);

        }
    });

    $('.enTeteColonneCliquable').attr('title', CLIQUER_POUR_TRIER_SUR_LA_COLONNE_OU_MAINTENIR_POUR_DEPLACER_LA_COLONNE);

    // Gestion modification par clic sur icones
    gestionDeCLiqueSurIcones('listeDesLargeursColonnes', renommage);
    // Gestion modification par clic sur td
    gestionDeCliquesurElementTD('listeDesLargeursColonnes', renommage);
    ancienneLigneCliquee = null;
}





function modifierLigne_PageLargeursColonnes(mode) {
    
    if (typeof mode !== 'undefined') {

        if (mode == "global") {
            indexColonneValeurParametre = tableauLargeurColonneListe.column('largeur:name').index();
            indexColonneValeurRenommageParametre = tableauLargeurColonneListe.column('renommage:name').index();
            indexColonneModifier = tableauLargeurColonneListe.column('modifier:name').index();
            if (ligneCliquee != null) {
                donneesDeLaLigne = tableauLargeurColonneListe.row(ligneCliquee).data();
                colonnes = $('>td', ligneCliquee);
                colonnes[indexColonneValeurParametre].innerHTML = '<input id="inputModification" type="text" value="' + donneesDeLaLigne[indexColonneValeurParametre].replaceAll('"', '&#34;') + '" onkeypress="evenementToucheEntreeOuEchap(event.keyCode, \'tableauLargeurColonneListe\', \'global\')">';
                colonnes[indexColonneValeurRenommageParametre].innerHTML = '<input id="inputRenommage" type="text" value="' + donneesDeLaLigne[indexColonneValeurRenommageParametre].replaceAll('"', '&#34;') + '" onkeypress="evenementToucheEntreeOuEchap(event.keyCode, \'tableauLargeurColonneListe\', \'global\')">';
                colonnes[indexColonneModifier].innerHTML = '<img id="enregistrer" class="cursorPointer" alt="" title="' + ENREGISTRER + '" src="' + ICONE_ENREGISTRER_PETITE + '" />'
                + '<img id="annuler" class="cursorPointer" alt="" title="' + ANNULER + '" src="' + ICONE_ANNULER_PETITE + '" />';
                // Placer le focus à la fin de la chaine dans l'input
                valeur = $('#inputRenommage').val();
                $('#inputRenommage').val('');
                $('#inputRenommage').focus();
                $('#inputRenommage').val(valeur);
                valeur = $('#inputModification').val();
                $('#inputModification').val('');
                $('#inputModification').focus();
                $('#inputModification').val(valeur);
            }
        }

    } else {
        indexColonneValeurParametre = tableauLargeurColonneListe.column('largeur:name').index();
        indexColonneModifier = tableauLargeurColonneListe.column('modifier:name').index() - 1;
        if (ligneCliquee != null) {
            donneesDeLaLigne = tableauLargeurColonneListe.row(ligneCliquee).data();
            colonnes = $('>td', ligneCliquee);
            colonnes[indexColonneValeurParametre].innerHTML = '<input id="inputModification" type="text" value="' + donneesDeLaLigne[indexColonneValeurParametre].replaceAll('"', '&#34;') + '" onkeypress="evenementToucheEntreeOuEchap(event.keyCode, \'tableauLargeurColonneListe\')">';
            colonnes[indexColonneModifier].innerHTML = '<img id="enregistrer" class="cursorPointer" alt="" title="' + ENREGISTRER + '" src="' + ICONE_ENREGISTRER_PETITE + '" />'
            + '<img id="annuler" class="cursorPointer" alt="" title="' + ANNULER + '" src="' + ICONE_ANNULER_PETITE + '" />';
            // Placer le focus à la fin de la chaine dans l'input
            valeur = $('#inputModification').val();
            $('#inputModification').val('');
            $('#inputModification').focus();
            $('#inputModification').val(valeur);
        }
    }
    
}




function enregistrerModificationLigne_PageLargeursColonnes(mode) {

    modificationsColonnes = true;

    oTable = $('#listeDesLargeursColonnes').DataTable({ 'retrieve': true });
    oSetting = oTable.settings()[0];
    tableauindice = retournerIndiceTableau("listeDesLargeursColonnes");
    pageSelectionnee = retournerdebutPage(tableauindice);
    oSetting.iInitDisplayStart = pageSelectionnee;

    indexColonneValeurParametre = tableauLargeurColonneListe.column('largeur:name').index();
    indexColonneIndice = tableauLargeurColonneListe.column('indiceColonne:name').index();
    indexColonneLargeurParDefaut = tableauLargeurColonneListe.column('largeurParDefaut:name').index();
    indexColonneLibelleParDefaut = tableauLargeurColonneListe.column('libelle:name').index();
    indexColonneValeurRenommageParametre = tableauLargeurColonneListe.column('renommage:name').index();
    champsDeSaisiesModification = $('#inputModification ', ligneCliquee);
    
    iPos = $('#listeDesLargeursColonnes tbody tr').index(ligneCliquee);
    

    // Champs obligatoires
    formulaireValide = true;
    messageErreur = '';

    $('.erreurSaisie').each(function () {
        $(this).removeClass('erreurSaisie');
    });

    donneesDeLaLigne = tableauLargeurColonneListe.row(ligneCliquee).data();
    if (typeof mode !== 'undefined' ) {
        if (mode == "global") {
            if ($('#inputModification').val() == '' && $('#inputModification').parent().hasClass('obligatoire')) {

                formulaireValide = false;
                messageErreur += LA_LARGEUR_COLONNE_EST_OBLIGATOIRE + '.<br/>';
                $('#inputModification').addClass('erreurSaisie');
            } else {
                largeurParDefaut = donneesDeLaLigne[indexColonneLargeurParDefaut];
                tableauParentAttache = $('#listeDesLargeursColonnes').data("tableauattache");
                dtTableauParentAttache = $('#' + tableauParentAttache).DataTable();
                reordonneeCol = indiceColonneReordonnee(tableauLargeurColonneListe.row(iPos).data()[6], dtTableauParentAttache) + 1;

                if (isNaN($('#inputModification').val())) {
                    formulaireValide = false;
                    messageErreur += LA_LARGEUR_EST_UN_ENTIER + '.<br/>';
                    $('#inputModification').addClass('erreurSaisie');
                } else if ($('table#' + tableauParentAttache + ' thead th[data-orig-col-header="' + tableauLargeurColonneListe.row(iPos).data()[6] + '"]').hasClass('colonneAvecLargeurSpecifique') && parseInt(largeurParDefaut.replaceAll('"', '')) > parseInt($('#inputModification').val())) {
                    formulaireValide = false;
                    messageErreur += LARGEUR_MINIMALE_INSUFFISANTE_MEDIA + largeurParDefaut.replaceAll('"', '') + ' pixels.<br/>';
                    $('#inputModification').addClass('erreurSaisie');
                } else if (parseInt($('#inputModification').val()) < 40) { //if (parseInt(largeurParDefaut.replaceAll('"', '')) > parseInt($('#inputModification').val())) {
                    formulaireValide = false;
                    messageErreur += LARGEUR_MINIMALE_INSUFFISANTE + '.<br/>';
                    $('#inputModification').addClass('erreurSaisie');
                }


            }

            if ($('#inputRenommage').val() == '' && $('#inputRenommage').parent().hasClass('obligatoire')) {

                formulaireValide = false;
                messageErreur += CHAMP_OBLIGATOIRE + '.<br/>';
                $('#inputRenommage').addClass('erreurSaisie');
            } else {
                nomParDefaut = donneesDeLaLigne[indexColonneLibelleParDefaut];
                tableauParentAttache = $('#listeDesLargeursColonnes').data("tableauattache");
                dtTableauParentAttache = $('#' + tableauParentAttache).DataTable();
                reordonneeCol = indiceColonneReordonnee(tableauLargeurColonneListe.row(iPos).data()[6], dtTableauParentAttache) + 1;
                
                //                if ($('#inputRenommage').val() == nomParDefaut) {
                //                    modificationsColonnes = false;
                //                } 

            }
        }
    } else {
        if ($('#inputModification').val() == '' && $('#inputModification').parent().hasClass('obligatoire')) {

            formulaireValide = false;
            messageErreur += LA_LARGEUR_COLONNE_EST_OBLIGATOIRE + '.<br/>';
            $('#inputModification').addClass('erreurSaisie');
        } else {
           
            largeurParDefaut = donneesDeLaLigne[indexColonneLargeurParDefaut];
            tableauParentAttache = $('#listeDesLargeursColonnes').data("tableauattache");
            dtTableauParentAttache = $('#' + tableauParentAttache).DataTable();
            reordonneeCol = indiceColonneReordonnee(tableauLargeurColonneListe.row(iPos).data()[6], dtTableauParentAttache) + 1;

            if (isNaN($('#inputModification').val())) {
                formulaireValide = false;
                messageErreur += LA_LARGEUR_EST_UN_ENTIER + '.<br/>';
                $('#inputModification').addClass('erreurSaisie');
            } else if ($('table#' + tableauParentAttache + ' thead th[data-orig-col-header="' + tableauLargeurColonneListe.row(iPos).data()[6] + '"]').hasClass('colonneAvecLargeurSpecifique') && parseInt(largeurParDefaut.replaceAll('"', '')) > parseInt($('#inputModification').val())) {
                formulaireValide = false;
                messageErreur += LARGEUR_MINIMALE_INSUFFISANTE_MEDIA + largeurParDefaut.replaceAll('"', '') + ' pixels.<br/>';
                $('#inputModification').addClass('erreurSaisie');
            } else if (parseInt($('#inputModification').val()) < 40) { //if (parseInt(largeurParDefaut.replaceAll('"', '')) > parseInt($('#inputModification').val())) {
                formulaireValide = false;
                messageErreur += LARGEUR_MINIMALE_INSUFFISANTE + '.<br/>';
                $('#inputModification').addClass('erreurSaisie');
            }


        }

    }


    if (formulaireValide) {
        if (typeof mode !== 'undefined') {
            if (mode == "global") {
                champsDeSaisiesRenommage = $('#inputRenommage ', ligneCliquee);

                indexColonneModifier = tableauLargeurColonneListe.column('modifier:name').index();
                tableauLargeurColonneListe.cell(ligneCliquee, indexColonneValeurParametre).data(champsDeSaisiesModification[0].value.replace('<', '&lt;').replace('>', '&gt;'));
                // A FAIRE --> détailler les paramètres de la fonction

                tableauLargeurColonneListe.settings()[0].iInitDisplayStart = tableauLargeurColonneListe.settings()[0]._iDisplayStart;
                tableauLargeurColonneListe.cell(ligneCliquee, indexColonneModifier).data('<img id="modifier" class="cursorPointer" alt="" title="' + MODIFIER + '" src="/ressource/image/commun/modifier32.png"/>').draw();
                
                colonneDOrigine = donneesDeLaLigne[indexColonneIndice];
                trouveColonne = false;
                colonnes = tableauDesLargeuresEtIndicesLocal.split("|");
                detailColonnes = [];
                j = 0;
                while (j < colonnes.length && !trouveColonne) {
                    detailColonnes = colonnes[j].split(";");
                    if (detailColonnes[0].ltrim().rtrim() == colonneDOrigine.ltrim().rtrim()) {
                        detailColonnes[1] = donneesDeLaLigne[indexColonneValeurParametre].replaceAll('"', '');
                        colonnes[j] = detailColonnes[0].ltrim().rtrim() + ";" + detailColonnes[1].ltrim().rtrim();
                        trouveColonne = true;
                    }
                    j++;
                } 
                tableauDesLargeuresEtIndicesLocal = colonnes.join('|');
                tableauLargeurColonneListe.cell(ligneCliquee, indexColonneValeurRenommageParametre).data(champsDeSaisiesRenommage[0].value.replace('<', '&lt;').replace('>', '&gt;'));
                colonnesRenommees = nommagesColonnes.split("|");
                j = 0;
                trouveColonne = false;
                while (j < colonnesRenommees.length && !trouveColonne) {
                    if (colonnesRenommees[j].indexOf("_" + donneesDeLaLigne[indexColonneIndice] + "_") >= 0) {
                        colonnesRenommees.splice(j, 1); 
                        trouveColonne = true;
                    }
                    j++;
                }
                nommagesColonnes = (colonnesRenommees.length > 0 ? colonnesRenommees.join("|") : "");
                if (modificationsColonnes == true) {
                    nommagesColonnes = nommagesColonnes + donneesDeLaLigne[indexColonneValeurRenommageParametre] + ";_" + donneesDeLaLigne[indexColonneIndice] + "_|";
                }
               
            }
        } else {
            indexColonneModifier = tableauLargeurColonneListe.column('modifier:name').index() - 1;
            tableauLargeurColonneListe.cell(ligneCliquee, indexColonneValeurParametre).data(champsDeSaisiesModification[0].value.replace('<', '&lt;').replace('>', '&gt;'));
            // A FAIRE --> détailler les paramètres de la fonction
            tableauLargeurColonneListe.settings()[0].iInitDisplayStart = tableauLargeurColonneListe.settings()[0]._iDisplayStart;
            tableauLargeurColonneListe.cell(ligneCliquee, indexColonneModifier).data('<img id="modifier" class="cursorPointer" alt="" title="' + MODIFIER + '" src="/ressource/image/commun/modifier32.png"/>').draw();

            colonneDOrigine = donneesDeLaLigne[indexColonneIndice];
            trouveColonne = false;
            colonnes = tableauDesLargeuresEtIndicesLocal.split("|");
            detailColonnes = [];
            j = 0;
            while (j < colonnes.length && !trouveColonne) {
                detailColonnes = colonnes[j].split(";");
                if (detailColonnes[0].ltrim().rtrim() == colonneDOrigine.ltrim().rtrim()) {
                    detailColonnes[1] = donneesDeLaLigne[indexColonneValeurParametre].replaceAll('"', '');
                    colonnes[j] = detailColonnes[0].ltrim().rtrim() + ";" + detailColonnes[1].ltrim().rtrim();
                    trouveColonne = true;
                }
                j++;
            }
            tableauDesLargeuresEtIndicesLocal = colonnes.join('|');
        }
    } else {
        alerte(messageErreur, 'erreur');
    }
}

function validerEtAppliquerModifications(idTableau) {
    //console.log(idTableau);
    if (idTableau == 'moduleDescriptif_tableauListeDesBDDVegetalesEnPreselection'
    || idTableau == 'moduleDescriptif_tableauListeDesBDDVegetalesEnRattachement'
    || idTableau == 'moduleDescriptif_tableauListeDesBDDVegetales'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifsEnRattachement'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifsEnPreselection'
    || idTableau == 'moduleDescriptif_tableauListeDesDescriptifs') {
        tableauDesLargeuresEtIndicesDescriptif = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleValeur_tableauListeDeValeurs'
    || idTableau == 'moduleValeur_tableauListeDeValeursVlv'
    || idTableau == 'moduleValeur_tableauListeDeValeursReferentes') {
        tableauDesLargeuresEtIndicesValeurs = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesVlv'
    || idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategories'
    || idTableau == 'moduleCritereCategorie_tableauListeDesCriteresCategoriesReferentes') {
        tableauDesLargeuresEtIndicesCriteresCategories = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesCategoriesDescriptifs') {
        tableauDesLargeuresEtIndicesCategorieDescriptifs = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleMediaCategorie_tableauListeDesCategoriesMedias'
    || idTableau == 'moduleMediaCategorie_tableauListeDesCategoriesMediasVlv') {
        tableauDesLargeuresEtIndicesCategorieMedias = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesTypesDeConseils') {
        tableauDesLargeuresEtIndicesConseilsTypes = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesTypesInfoComplementaireConseil') {
        tableauDesLargeuresEtIndicesConseilInfoComplementaireTypes = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesInfosComplementaireConseil') {
        tableauDesLargeuresEtIndicesInfosComplementaireConseils = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'copyrights') {
        tableauDesLargeuresEtIndicesCopyrights = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleCritere_tableauListeDeCriteres'
    || idTableau == 'moduleCritere_tableauListeDeCriteresVlv'
    || idTableau == 'moduleCritere_tableauListeDeCriteresReferentes'
    || idTableau == 'moduleCritere_tableauListeDeCriteresWebshop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresWebshopVlv'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitWebshop'
    || idTableau == 'moduleCritere_tableauListeDeCriteresProduitWebshopVlv') {
        tableauDesLargeuresEtIndicesCritere = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'lieux') {
        tableauDesLargeuresEtIndicesLieux = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleMedia_tableauListeDeMedias'
    || idTableau == 'moduleConseil_tableauListeDesMedias'
    || idTableau == 'moduleDescriptif_tableauListeDeMedias'
    || idTableau == 'moduleMedia_tableauListeDeMediasVlv'
    || idTableau == 'moduleMedia_tableauListeDeMediasReferente') {
        tableauDesLargeuresEtIndicesMedia = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleLangue_tableauListeDesLangues') {
        tableauDesLargeuresEtIndicesTraduction = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleLangue_tableauListeDesEntitees') {
        tableauDesLargeuresEtIndicesEntiteesTraduction = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleLangue_tableauEditerTraduction') {
        tableauDesLargeuresEtIndicesEditerTraduction = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesConseils'
    || idTableau == 'moduleConseilAssocieDescriptif_tableauListeDesConseils') {
        tableauDesLargeuresEtIndicesConseil = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesCatalogues') {
        tableauDesLargeuresEtIndicesCatalogues = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauLignesDeCatalogue') {
        tableauDesLargeuresEtIndicesLignesCatalogue = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesComptesBancaires') {
        tableauDesLargeuresEtIndicesComptesBancaires = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesDemandesServices'
    || idTableau == 'tableauActualise_tableauListeDesDemandesServices') {
        tableauDesLargeuresEtIndicesDemandesServices = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'natureDemandeService') {
        tableauDesLargeuresEtIndicesNatureDemandeService = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesProduitsDemandeService') {
        tableauDesLargeuresEtIndicesProduitDemandeService = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesCategoriesDemandeService') {
        tableauDesLargeuresEtIndicesCategorieDemandeService = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesSousCategoriesDemandeService') {
        tableauDesLargeuresEtIndicesSousCategorieDemandeService = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesAdressesDeLivraison') {
        tableauDesLargeuresEtIndicesAdresseLivraison = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeTypeUniteVente'
    || idTableau == 'tableauListePresentations'
    || idTableau == "tableauListeMillesimes") {
        tableauDesLargeuresEtIndicesDictionnaire = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauEletter') {
        tableauDesLargeuresEtIndicesEletter = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDEmailsConseilsEnvoyes') {
        tableauDesLargeuresEtIndicesEmailsConseilsEnvoyes = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauGroupes'
    || idTableau == 'tableauGroupes_detailSociete') {
        tableauDesLargeuresEtIndicesGroupe = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesArticles') {
        tableauDesLargeuresEtIndicesArticles = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauServices') {
        tableauDesLargeuresEtIndicesServices = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauMesServices') {
        tableauDesLargeuresEtIndicesMesServices = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesOperationsEnvoyees') {
        tableauDesLargeuresEtIndicesOperations = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeTaille'
    || idTableau == 'tableauListeUniteVente') {
        tableauDesLargeuresEtIndicesTypeUniteVente = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleClients_tableauClients'
    || idTableau == 'moduleDemandeService_tableauClients'
    || idTableau == 'moduleAjoutGroupe_tableauClients'
    || idTableau == 'moduleAjoutGroupe_tableauClientsModifierGroupe'
    || idTableau == 'moduleConsulterGroupe_tableauClients') {
        tableauDesLargeuresEtIndicesMesClients = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeClientsWebshop') {
        tableauDesLargeuresEtIndicesClientWebshop = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleComptesSecondaires_tableauListeDesComptes'
    || idTableau == 'moduleDemandeService_tableauListeDesComptes') {
        tableauDesLargeuresEtIndicesComptes = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDeAuthentifications') {
        tableauDesLargeuresEtIndicesAuthentifications = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDEmaislEnvoyes') {
        tableauDesLargeuresEtIndicesEmailsEnvoyes = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'moduleHistoriqueConsultation_tableauListeDetailsHistoriqueConsultation') {
        tableauDesLargeuresEtIndicesHistoriqueConsultation = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDHistoriqueDImport') {
        tableauDesLargeuresEtIndicesHistoriqueImport = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauDeLogsBase') {
        tableauDesLargeuresEtIndicesLogsDeLaBase = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeParametresApplication') {
        tableauDesLargeuresEtIndicesParametresDeLApplication = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesProduits') {
        tableauDesLargeuresEtIndicesProduits = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListePanier' || idTableau == 'tableauListeRecapPanier') {
        tableauDesLargeuresEtIndicesPanier = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeClientsWebshop') {
        tableauDesLargeuresEtIndicesClientWebshop = tableauDesLargeuresEtIndicesLocal
    } else if (idTableau == 'tableauListeDesComptesAAdministrer'
    || idTableau == 'tableauComptesConnectes') {
        tableauDesLargeuresEtIndicesCompteAAdministrer = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesVersionsCode') {
        tableauDesLargeuresEtIndicesVersionsCode = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesConsommateurs') {
        tableauDesLargeuresEtIndicesConsommateurs = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeModesExpeditions') {
        tableauDesLargeuresEtIndicesModesExpeditions = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeBoutiques') {
        tableauDesLargeuresEtIndicesBoutiques = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesPaiements') {
        tableauDesLargeuresEtIndicesLocal = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeCumulsEmballages') {
        tableauDesLargeuresEtIndicesCumulsEmballages = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesOperationsWebshop') {
        tableauDesLargeuresEtIndicesOperationsWebshop = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesAdressesDeLivraisonWebshop') {
        tableauDesLargeuresEtIndicesAdresseLivraison = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesDureesDemandesServices') {
        tableauDesLargeuresEtIndicesDureeDemandesServices = tableauDesLargeuresEtIndicesLocal;
    } else if (idTableau == 'tableauListeDesModelesEmails') {
        tableauDesLargeuresEtIndicesDesModelesEmails = tableauDesLargeuresEtIndicesLocal;
    }
    //console.log(tableauDesLargeuresEtIndicesLocal);
    //console.log(idTableau);
    appliquerLesLargeurs(idTableau, tableauDesLargeuresEtIndicesLocal, nommagesColonnes);
    
    fermerPopup();
    alerte(LARGEURS_MISENT_A_JOUR, 'confirmation');

}


/*! http://responsiveslides.com v1.54 by @viljamis */
(function(c,I,B){c.fn.responsiveSlides=function(l){var a=c.extend({auto:!0,speed:500,timeout:4E3,pager:!1,nav:!1,random:!1,pause:!1,pauseControls:!0,prevText:"Previous",nextText:"Next",maxwidth:"",navContainer:"",manualControls:"",namespace:"rslides",before:c.noop,after:c.noop},l);return this.each(function(){B++;var f=c(this),s,r,t,m,p,q,n=0,e=f.children(),C=e.size(),h=parseFloat(a.speed),D=parseFloat(a.timeout),u=parseFloat(a.maxwidth),g=a.namespace,d=g+B,E=g+"_nav "+d+"_nav",v=g+"_here",j=d+"_on",
w=d+"_s",k=c("<ul class='"+g+"_tabs "+d+"_tabs' />"),x={"float":"left",position:"relative",opacity:1,zIndex:2},y={"float":"none",position:"absolute",opacity:0,zIndex:1},F=function(){var b=(document.body||document.documentElement).style,a="transition";if("string"===typeof b[a])return!0;s=["Moz","Webkit","Khtml","O","ms"];var a=a.charAt(0).toUpperCase()+a.substr(1),c;for(c=0;c<s.length;c++)if("string"===typeof b[s[c]+a])return!0;return!1}(),z=function(b){a.before(b);F?(e.removeClass(j).css(y).eq(b).addClass(j).css(x),
n=b,setTimeout(function(){a.after(b)},h)):e.stop().fadeOut(h,function(){c(this).removeClass(j).css(y).css("opacity",1)}).eq(b).fadeIn(h,function(){c(this).addClass(j).css(x);a.after(b);n=b})};a.random&&(e.sort(function(){return Math.round(Math.random())-0.5}),f.empty().append(e));e.each(function(a){this.id=w+a});f.addClass(g+" "+d);l&&l.maxwidth&&f.css("max-width",u);e.hide().css(y).eq(0).addClass(j).css(x).show();F&&e.show().css({"-webkit-transition":"opacity "+h+"ms ease-in-out","-moz-transition":"opacity "+
h+"ms ease-in-out","-o-transition":"opacity "+h+"ms ease-in-out",transition:"opacity "+h+"ms ease-in-out"});if(1<e.size()){if(D<h+100)return;if(a.pager&&!a.manualControls){var A=[];e.each(function(a){a+=1;A+="<li><a href='#' class='"+w+a+"'>"+a+"</a></li>"});k.append(A);l.navContainer?c(a.navContainer).append(k):f.after(k)}a.manualControls&&(k=c(a.manualControls),k.addClass(g+"_tabs "+d+"_tabs"));(a.pager||a.manualControls)&&k.find("li").each(function(a){c(this).addClass(w+(a+1))});if(a.pager||a.manualControls)q=
k.find("a"),r=function(a){q.closest("li").removeClass(v).eq(a).addClass(v)};a.auto&&(t=function(){p=setInterval(function(){e.stop(!0,!0);var b=n+1<C?n+1:0;(a.pager||a.manualControls)&&r(b);z(b)},D)},t());m=function(){a.auto&&(clearInterval(p),t())};a.pause&&f.hover(function(){clearInterval(p)},function(){m()});if(a.pager||a.manualControls)q.bind("click",function(b){b.preventDefault();a.pauseControls||m();b=q.index(this);n===b||c("."+j).queue("fx").length||(r(b),z(b))}).eq(0).closest("li").addClass(v),
a.pauseControls&&q.hover(function(){clearInterval(p)},function(){m()});if(a.nav){g="<a href='#' class='"+E+" prev'>"+a.prevText+"</a><a href='#' class='"+E+" next'>"+a.nextText+"</a>";l.navContainer?c(a.navContainer).append(g):f.after(g);var d=c("."+d+"_nav"),G=d.filter(".prev");d.bind("click",function(b){b.preventDefault();b=c("."+j);if(!b.queue("fx").length){var d=e.index(b);b=d-1;d=d+1<C?n+1:0;z(c(this)[0]===G[0]?b:d);if(a.pager||a.manualControls)r(c(this)[0]===G[0]?b:d);a.pauseControls||m()}});
a.pauseControls&&d.hover(function(){clearInterval(p)},function(){m()})}}if("undefined"===typeof document.body.style.maxWidth&&l.maxwidth){var H=function(){f.css("width","100%");f.width()>u&&f.css("width",u)};H();c(I).bind("resize",function(){H()})}})}})(jQuery,this,0);

function initialisationLightBox() {
    // Rendre déplaçable le lightbox
    $('#contenuLightBox').draggable({
        handle: '#imageLightBox',
        containment: 'body' // Pour empêcher la sortie de l'élément hors de la page
    });

    $('#layoutLightBox').on('click', function () {
        fermerLightBox();
    });

    $(document).on('keyup', function (evt) {
        if (evt.keyCode == 27) {
            fermerLightBox();
        }
    });

}

function afficherLightBox(sourceImage) {
    if (typeof($('.contenuPageDetailProduitMobile').html()) == 'undefined') {
        afficherChargement();
    }
    $('#imageLightBox').attr('src', sourceImage);
    $('#imageLightBox').load(function () {
        $('#layoutLightBox').show(200);
        $('#contenuLightBox').show(200);
        img = new Image();
        img.src = sourceImage;
        widthImage = img.width;
        heightImage = img.height;
        largeurMax = $(window).width() * 0.8;
        hauteurMax = $(window).height() * 0.8;

        pourcentageRedimensionnementSurLargeur = largeurMax / widthImage;
        nouvelleHauteur = parseInt(pourcentageRedimensionnementSurLargeur * heightImage);
        // Redimensionnement sur largeurMax
        if (nouvelleHauteur < hauteurMax && pourcentageRedimensionnementSurLargeur < 1.00) {
            nouvelleLargeur = parseInt(pourcentageRedimensionnementSurLargeur * widthImage);
            if (typeof ($('.contenuPageDetailProduitMobile').html()) == 'undefined') {
                $('#contenuLightBox').css('top', '20px');
                $('#imageLightBox').css('margin-left', -(widthImage / 2) + 'px'); //centrer l'image cas normal
            } else {
                $('#contenuLightBox').css('left', '10%');
            }
            $('#imageLightBox').css('width', nouvelleLargeur + 'px'); // changer le largeur de l'image
            // Redimensionnement sur hauteurMax
        } else {
            pourcentageRedimensionnementSurHauteur = hauteurMax / heightImage;
            if (pourcentageRedimensionnementSurHauteur < 1.00) {
                nouvelleLargeur = parseInt(pourcentageRedimensionnementSurHauteur * widthImage);
                nouvelleHauteur = parseInt(pourcentageRedimensionnementSurHauteur * heightImage);
                if (typeof ($('.contenuPageDetailProduitMobile').html()) == 'undefined') {
                    $('#contenuLightBox').css('top', '20px');
                    $('#imageLightBox').css('margin-left', -(nouvelleLargeur / 2) + 'px'); //centrer l'image
                } else {
                    $('#contenuLightBox').css('left', '10%');
                }
                $('#imageLightBox').css('width', nouvelleLargeur + 'px'); // changer le largeur de l'image
                $('#imageLightBox').css('height', nouvelleHauteur + 'px'); // changer le hauteur de l'image
                // Redimensionnement plus grand que l'image d'origine, alors pas de redimensionnement, on conserve la taille
            } else {
                nouvelleLargeur = widthImage;
                nouvelleHauteur = heightImage;
                if (typeof ($('.contenuPageDetailProduitMobile').html()) == 'undefined') {
                    $('#contenuLightBox').css('top', '15%');
                    $('#imageLightBox').css('margin-left', -(widthImage / 2) + 'px'); //centrer l'image cas normal
                } else {
                    $('#contenuLightBox').css('left', '10%');
                }
                $('#imageLightBox').css('width', nouvelleLargeur + 'px'); // changer le largeur de l'image
                $('#imageLightBox').css('height', nouvelleHauteur + 'px'); // changer le hauteur de l'image
            }
        }

        //            if (widthImage >= ($(window).width())) {
        //                $('#contenuLightBox').css('top', '20px');
        //                $('#imageLightBox').css('margin-left', -(($(window).width() * 0.8) / 2) + 'px'); //centrer l'image
        //                $('#imageLightBox').css('width', $(window).width() * 0.8 + 'px'); // changer le largeur de l'image
        //            } else {
        //                $('#contenuLightBox').css('top', '15px');
        //                $('#imageLightBox').css('height', $(window).height() * 0.8 + 'px'); // changer le hauteur de l'image
        //                $('#imageLightBox').css('margin-left', -($('#imageLightBox').width() / 2) + 'px'); //centrer l'image
        //            }
        if (typeof ($('.contenuPageDetailProduitMobile').html()) == 'undefined') {
            masquerChargement();
        }
    });

}

function fermerLightBox() {
    $('#layoutLightBox').fadeOut(200);
    $('#contenuLightBox').fadeOut(200);
    $('#imageLightBox').removeAttr('src');
    $('#imageLightBox').removeAttr('style');
}

;(function(factory) {
    if(typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
    }
    else if(typeof exports === 'object') {
        module.exports = factory(require('jquery'));
    }
    else {
        factory(jQuery);
    }
}
(function($) {
    var pluginName = "tinycarousel"
    ,   defaults   =
        {
            start: 0
        ,   axis: "x"
        ,   buttons: true
        ,   bullets: false
        ,   interval: false
        ,   intervalTime: 3000
        ,   animation: true
        ,   animationTime: 1000
        ,   infinite: true
        }
    ;

    function Plugin($container, options) {
        /**
         * The options of the carousel extend with the defaults.
         *
         * @property options
         * @type Object
         * @default defaults
         */
        this.options = $.extend({}, defaults, options);

        /**
         * @property _defaults
         * @type Object
         * @private
         * @default defaults
         */
        this._defaults = defaults;

        /**
         * @property _name
         * @type String
         * @private
         * @final
         * @default 'tinycarousel'
         */
        this._name = pluginName;

        var self = this
        ,   $viewport = $container.find(".viewport:first")
        ,   $overview = $container.find(".overview:first")
        ,   $slides = null
        ,   $next = $container.find(".next:first")
        ,   $prev = $container.find(".prev:first")
        ,   $bullets = $container.find(".bullet")

        ,   viewportSize = 0
        ,   contentStyle = {}
        ,   slidesVisible = 0
        ,   slideSize = 0
        ,   slideIndex = 0

        ,   isHorizontal = this.options.axis === 'x'
        ,   sizeLabel = isHorizontal ? "Width" : "Height"
        ,   posiLabel = isHorizontal ? "left" : "top"
        ,   intervalTimer = null
        ;

        /**
         * The index of the current slide.
         *
         * @property slideCurrent
         * @type Number
         * @default 0
         */
        this.slideCurrent = 0;

        /**
         * The number of slides the carousel is currently aware of.
         *
         * @property slidesTotal
         * @type Number
         * @default 0
         */
        this.slidesTotal = 0;

        /**
         * If the interval is running the value will be true.
         *
         * @property intervalActive
         * @type Boolean
         * @default false
         */
        this.intervalActive = false;

        /**
         * @method _initialize
         * @private
         */
        function _initialize() {
            self.update();
            self.move(self.slideCurrent);

            _setEvents();

            return self;
        }

        /**
         * You can use this method to add new slides on the fly. Or to let the carousel recalculate itself.
         *
         * @method update
         * @chainable
         */
        this.update = function() {
            $overview.find(".mirrored").remove();

            $slides = $overview.children();
            viewportSize = $viewport[0]["offset" + sizeLabel];
            slideSize = $slides.first()["outer" + sizeLabel](true);
            self.slidesTotal = $slides.length;
            self.slideCurrent = self.options.start || 0;
            slidesVisible = Math.ceil(viewportSize / slideSize);

            $overview.append($slides.slice(0, slidesVisible).clone().addClass("mirrored"));
            $overview.css(sizeLabel.toLowerCase(), slideSize * (self.slidesTotal + slidesVisible));

            _setButtons();

            return self;
        };

        /**
         * @method _setEvents
         * @private
         */
        function _setEvents() {
            if(self.options.buttons) {
                $prev.click(function() {
                    self.move(--slideIndex);

                    return false;
                });

                $next.click(function() {
                    self.move(++slideIndex);

                    return false;
                });
            }

            $(window).resize(self.update);

            if(self.options.bullets) {
                $container.on("click", ".bullet", function() {
                    self.move(slideIndex = +$(this).attr("data-slide"));

                    return false;
                });
            }
        }


        /**
         * If the interval is stoped start it.
         *
         * @method start
         * @chainable
         */
        this.start = function() {
            if(self.options.interval) {
                clearTimeout(intervalTimer);

                self.intervalActive = true;

                intervalTimer = setTimeout(function() {
                    self.move(++slideIndex);

                }, self.options.intervalTime);
            }

            return self;
        };

        /**
         * If the interval is running stop it.
         *
         * @method start
         * @chainable
         */
        this.stop = function() {
            clearTimeout(intervalTimer);

            self.intervalActive = false;

            return self;
        };

        /**
         * Move to a specific slide.
         *
         * @method move
         * @chainable
         * @param {Number}  [index] The slide to move to.
         */
        this.move = function(index) {
            slideIndex = isNaN(index) ? self.slideCurrent : index;
            self.slideCurrent = slideIndex % self.slidesTotal;

            if(slideIndex < 0) {
                self.slideCurrent = slideIndex = self.slidesTotal - 1;
                $overview.css(posiLabel, -(self.slidesTotal) * slideSize);
            }

            if(slideIndex > self.slidesTotal) {
                self.slideCurrent = slideIndex = 1;
                $overview.css(posiLabel, 0);
            }
            contentStyle[posiLabel] = -slideIndex * slideSize;

            $overview.animate(
                contentStyle
            ,   {
                    queue : false
                ,   duration : self.options.animation ? self.options.animationTime : 0
                ,   always : function() {
                       /**
                        * The move event will trigger when the carousel slides to a new slide.
                        *
                        * @event move
                        */
                        $container.trigger("move", [$slides[self.slideCurrent], self.slideCurrent]);
                    }
                });

            _setButtons();
            self.start();

            return self;
        };

        /**
         * @method _setButtons
         * @private
         */
        function _setButtons() {
            if(self.options.buttons && !self.options.infinite) {
                $prev.toggleClass("disable", self.slideCurrent <= 0);
                $next.toggleClass("disable", self.slideCurrent >= self.slidesTotal - slidesVisible);
            }

            if(self.options.bullets) {
                $bullets.removeClass("active");
                $($bullets[self.slideCurrent]).addClass("active");
            }
        }

        return _initialize();
    }

    /**
    * @class tinycarousel
    * @constructor
    * @param {Object} options
        @param {Number}  [options.start=0] The slide to start with.
        @param {String}  [options.axis=x] Vertical or horizontal scroller? ( x || y ).
        @param {Boolean} [options.buttons=true] Show previous and next navigation buttons.
        @param {Boolean} [options.bullets=false] Is there a page number navigation present?
        @param {Boolean} [options.interval=false] Move to another block on intervals.
        @param {Number}  [options.intervalTime=3000] Interval time in milliseconds.
        @param {Boolean} [options.animate=true] False is instant, true is animate.
        @param {Number}  [options.animationTime=1000] How fast must the animation move in ms?
        @param {Boolean} [options.infinite=true] Infinite carousel.
    */
    $.fn[pluginName] = function(options) {
        return this.each(function() {
            if(!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Plugin($(this), options));
            }
        });
    };
}));

// Copyright 2018 - ScientiaMobile, Inc., Reston, VA
// WURFL Device Detection
// Terms of service:
// http://web.wurfl.io/license

eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('8 7={"6":5,"4":"3 2","1":"0"};',9,9,'Desktop|form_factor|Chrome|Google|complete_device_name|false|is_mobile|WURFL|var'.split('|'),0,{}))

