/* Minification failed. Returning unminified contents.
(47957,15-16): run-time error JS1010: Expected identifier: .
(47957,15-16): run-time error JS1195: Expected expression: .
 */
/*! jQuery v2.1.4 | (c) 2005, 2015 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.4",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)+1>=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="length"in a&&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"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N=M.replace("w","w#"),O="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+N+"))|)"+L+"*\\]",P=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+O+")*)|.*)\\)|)",Q=new RegExp(L+"+","g"),R=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),S=new RegExp("^"+L+"*,"+L+"*"),T=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),U=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),V=new RegExp(P),W=new RegExp("^"+N+"$"),X={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+O),PSEUDO:new RegExp("^"+P),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,aa=/[+~]/,ba=/'|\\/g,ca=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),da=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)},ea=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(fa){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(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||[],k=b.nodeType,"string"!=typeof a||!a||1!==k&&9!==k&&11!==k)return d;if(!e&&p){if(11!==k&&(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 H.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName)return H.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=1!==k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(ba,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+ra(o[l]);w=aa.test(a)&&pa(b.parentNode)||b,x=o.join(",")}if(x)try{return H.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return ia(function(b){return b=+b,ia(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 pa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=g.documentElement,e=g.defaultView,e&&e!==e.top&&(e.addEventListener?e.addEventListener("unload",ea,!1):e.attachEvent&&e.attachEvent("onunload",ea)),p=!f(g),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(g.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(g.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!g.getElementsByName||!g.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ca,da);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(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 p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(g.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\f]' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),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))&&ja(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),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===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return la(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?la(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.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 ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.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},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.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=ga.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=ga.selectors={cacheLength:50,createPseudo:ia,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(ca,da),a[3]=(a[3]||a[4]||a[5]||"").replace(ca,da),"~="===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]||ga.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]&&ga.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(ca,da).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("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.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.replace(Q," ")+" ").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()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ia(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),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(ca,da),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return W.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(ca,da).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:oa(function(){return[0]}),last:oa(function(a,b){return[b-1]}),eq:oa(function(a,b,c){return[0>c?c+b:c]}),even:oa(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:oa(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:oa(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:oa(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]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function qa(){}qa.prototype=d.filters=d.pseudos,d.setFilters=new qa,g=ga.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?ga.error(a):z(a,i).slice(0)};function ra(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function sa(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 ta(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 ua(a,b,c){for(var d=0,e=b.length;e>d;d++)ga(a,b[d],c);return c}function va(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 wa(a,b,c,d,e,f){return d&&!d[u]&&(d=wa(d)),e&&!e[u]&&(e=wa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ua(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:va(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=va(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?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=va(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sa(function(a){return a===b},h,!0),l=sa(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sa(ta(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 wa(i>1&&ta(m),i>1&&ra(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xa(a.slice(i,e)),f>e&&xa(a=a.slice(e)),f>e&&ra(a))}m.push(c)}return ta(m)}function ya(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]=F.call(i));s=va(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&ga.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,ya(e,d)),f.selector=a}return f},i=ga.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(ca,da),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(ca,da),aa.test(j[0].type)&&pa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&ra(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,aa.test(a)&&pa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(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+K.uid++}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 aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ia={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,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(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 ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(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 oa(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 pa(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=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(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(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$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=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.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=ja(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=ja(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(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(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(oa(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&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(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(oa(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&&ea.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(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}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 qa,ra={};function sa(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 ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qa[0].contentDocument,b.write(),b.close(),c=sa(a,b),qa.detach()),ra[a]=c),c}var ua=/^margin/,va=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wa=function(b){return b.ownerDocument.defaultView.opener?b.ownerDocument.defaultView.getComputedStyle(b,null):a.getComputedStyle(b,null)};function xa(a,b,c){var d,e,f,g,h=a.style;return c=c||wa(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),va.test(g)&&ua.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 ya(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),f.removeChild(c),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 za=/^(none|table(?!-c[ea]).+)/,Aa=new RegExp("^("+Q+")(.*)$","i"),Ba=new RegExp("^([+-])=("+Q+")","i"),Ca={position:"absolute",visibility:"hidden",display:"block"},Da={letterSpacing:"0",fontWeight:"400"},Ea=["Webkit","O","Moz","ms"];function Fa(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Ea.length;while(e--)if(b=Ea[e]+c,b in a)return b;return d}function Ga(a,b,c){var d=Aa.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Ha(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 Ia(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wa(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xa(a,b,f),(0>e||null==e)&&(e=a.style[b]),va.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Ha(a,b,c||(g?"border":"content"),d,f)+"px"}function Ja(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",ta(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=xa(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]=Fa(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=Ba.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]=Fa(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xa(a,b,d)),"normal"===e&&b in Da&&(e=Da[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?za.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Ca,function(){return Ia(a,b,d)}):Ia(a,b,d):void 0},set:function(a,c,d){var e=d&&wa(a);return Ga(a,c,d?Ha(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=ya(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xa,[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}},ua.test(a)||(n.cssHooks[a+b].set=Ga)}),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=wa(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 Ja(this,!0)},hide:function(){return Ja(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 Ka(a,b,c,d,e){return new Ka.prototype.init(a,b,c,d,e)}n.Tween=Ka,Ka.prototype={constructor:Ka,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=Ka.propHooks[this.prop];return a&&a.get?a.get(this):Ka.propHooks._default.get(this)},run:function(a){var b,c=Ka.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=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):Ka.propHooks._default.set(this),this}},Ka.prototype.init.prototype=Ka.prototype,Ka.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}}},Ka.propHooks.scrollTop=Ka.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=Ka.prototype.init,n.fx.step={};var La,Ma,Na=/^(?:toggle|show|hide)$/,Oa=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pa=/queueHooks$/,Qa=[Va],Ra={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Oa.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Oa.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 Sa(){return setTimeout(function(){La=void 0}),La=n.now()}function Ta(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 Ua(a,b,c){for(var d,e=(Ra[b]||[]).concat(Ra["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Va(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")||ta(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],Na.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?ta(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=Ua(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 Wa(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 Xa(a,b,c){var d,e,f=0,g=Qa.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=La||Sa(),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:La||Sa(),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(Wa(k,j.opts.specialEasing);g>f;f++)if(d=Qa[f].call(j,a,k,j.opts))return d;return n.map(k,Ua,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(Xa,{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],Ra[c]=Ra[c]||[],Ra[c].unshift(b)},prefilter:function(a,b){b?Qa.unshift(a):Qa.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=Xa(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&&Pa.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(Ta(b,!0),a,d,e)}}),n.each({slideDown:Ta("show"),slideUp:Ta("hide"),slideToggle:Ta("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(La=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),La=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(){Ma||(Ma=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Ma),Ma=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 Ya,Za,$a=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)?Za:Ya)),
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}}}}}),Za={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=$a[b]||n.find.attr;$a[b]=function(a,b,d){var e,f;return d||(f=$a[b],$a[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$a[b]=f),e}});var _a=/^(?: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")||_a.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 ab=/[\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(ab," "):" ")){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(ab," "):"")){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(ab," ").indexOf(b)>=0)return!0;return!1}});var bb=/\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(bb,""):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 cb=n.now(),db=/\?/;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 eb=/#.*$/,fb=/([?&])_=[^&]*/,gb=/^(.*?):[ \t]*([^\r\n]*)$/gm,hb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,ib=/^(?:GET|HEAD)$/,jb=/^\/\//,kb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,lb={},mb={},nb="*/".concat("*"),ob=a.location.href,pb=kb.exec(ob.toLowerCase())||[];function qb(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 rb(a,b,c,d){var e={},f=a===mb;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 sb(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 tb(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 ub(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:ob,type:"GET",isLocal:hb.test(pb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":nb,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?sb(sb(a,n.ajaxSettings),b):sb(n.ajaxSettings,a)},ajaxPrefilter:qb(lb),ajaxTransport:qb(mb),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=gb.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||ob)+"").replace(eb,"").replace(jb,pb[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=kb.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===pb[1]&&h[2]===pb[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(pb[3]||("http:"===pb[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),rb(lb,k,b,v),2===t)return v;i=n.event&&k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!ib.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(db.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=fb.test(d)?d.replace(fb,"$1_="+cb++):d+(db.test(d)?"&":"?")+"_="+cb++)),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]?", "+nb+"; 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=rb(mb,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=tb(k,v,f)),u=ub(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._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 vb=/%20/g,wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Ab(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)Ab(c,a[c],b,e);return d.join("&").replace(vb,"+")},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")&&zb.test(this.nodeName)&&!yb.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(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Bb=0,Cb={},Db={0:200,1223:204},Eb=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in Cb)Cb[a]()}),k.cors=!!Eb&&"withCredentials"in Eb,k.ajax=Eb=!!Eb,n.ajaxTransport(function(a){var b;return k.cors||Eb&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Bb;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 Cb[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Db[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=Cb[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 Fb=[],Gb=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Fb.pop()||n.expando+"_"+cb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Gb.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gb.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(Gb,"$1"+e):b.jsonp!==!1&&(b.url+=(db.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,Fb.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 Hb=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Hb)return Hb.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.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Ib=a.document.documentElement;function Jb(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=Jb(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||Ib;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Ib})}}),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=Jb(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]=ya(k.pixelPosition,function(a,c){return c?(c=xa(a,b),va.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 Kb=a.jQuery,Lb=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Lb),b&&a.jQuery===n&&(a.jQuery=Kb),n},typeof b===U&&(a.jQuery=a.$=n),n});
//# sourceMappingURL=jquery.min.map;
/*! 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(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,s){var n,a,o,r=t.nodeName.toLowerCase();return"area"===r?(n=t.parentNode,a=n.name,t.href&&a&&"map"===n.nodeName.toLowerCase()?(o=e("img[usemap='#"+a+"']")[0],!!o&&i(o)):!1):(/^(input|select|textarea|button|object)$/.test(r)?!t.disabled:"a"===r?t.href||s:s)&&i(t)}function i(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}function s(e){for(var t,i;e.length&&e[0]!==document;){if(t=e.css("position"),("absolute"===t||"relative"===t||"fixed"===t)&&(i=parseInt(e.css("zIndex"),10),!isNaN(i)&&0!==i))return i;e=e.parent()}return 0}function n(){this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},e.extend(this._defaults,this.regional[""]),this.regional.en=e.extend(!0,{},this.regional[""]),this.regional["en-US"]=e.extend(!0,{},this.regional.en),this.dpDiv=a(e("<div id='"+this._mainDivId+"' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"))}function a(t){var i="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return t.delegate(i,"mouseout",function(){e(this).removeClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).removeClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).removeClass("ui-datepicker-next-hover")}).delegate(i,"mouseover",o)}function o(){e.datepicker._isDisabledDatepicker(v.inline?v.dpDiv.parent()[0]:v.input[0])||(e(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),e(this).addClass("ui-state-hover"),-1!==this.className.indexOf("ui-datepicker-prev")&&e(this).addClass("ui-datepicker-prev-hover"),-1!==this.className.indexOf("ui-datepicker-next")&&e(this).addClass("ui-datepicker-next-hover"))}function r(t,i){e.extend(t,i);for(var s in i)null==i[s]&&(t[s]=i[s]);return t}function h(e){return function(){var t=this.element.val();e.apply(this,arguments),this._refresh(),t!==this.element.val()&&this._trigger("change")}}e.ui=e.ui||{},e.extend(e.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}}),e.fn.extend({scrollParent:function(t){var i=this.css("position"),s="absolute"===i,n=t?/(auto|scroll|hidden)/:/(auto|scroll)/,a=this.parents().filter(function(){var t=e(this);return s&&"static"===t.css("position")?!1:n.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==i&&a.length?a:e(this[0].ownerDocument||document)},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.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(i){return t(i,!isNaN(e.attr(i,"tabindex")))},tabbable:function(i){var s=e.attr(i,"tabindex"),n=isNaN(s);return(n||s>=0)&&t(i,!n)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(t,i){function s(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"===i?["Left","Right"]:["Top","Bottom"],a=i.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+i]=function(t){return void 0===t?o["inner"+i].call(this):this.each(function(){e(this).css(a,s(this,t)+"px")})},e.fn["outer"+i]=function(t,n){return"number"!=typeof t?o["outer"+i].call(this,t):this.each(function(){e(this).css(a,s(this,t,!0,n)+"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.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),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(void 0!==t)return this.css("zIndex",t);if(this.length)for(var i,s,n=e(this[0]);n.length&&n[0]!==document;){if(i=n.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(n.css("zIndex"),10),!isNaN(s)&&0!==s))return s;n=n.parent()}return 0}}),e.ui.plugin={add:function(t,i,s){var n,a=e.ui[t].prototype;for(n in s)a.plugins[n]=a.plugins[n]||[],a.plugins[n].push([i,s[n]])},call:function(e,t,i,s){var n,a=e.plugins[t];if(a&&(s||e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType))for(n=0;a.length>n;n++)e.options[a[n][0]]&&a[n][1].apply(e.element,i)}};var l=0,u=Array.prototype.slice;e.cleanData=function(t){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=e._data(n,"events"),s&&s.remove&&e(n).triggerHandler("remove")}catch(o){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var n,a,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],n=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[l]=e[l]||{},a=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,a,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},n=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,a=this._superApply;return this._super=e,this._superApply=n,t=s.apply(this,arguments),this._super=i,this._superApply=a,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:a?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:n}),a?(e.each(a._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete a._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var i,s,n=u.call(arguments,1),a=0,o=n.length;o>a;a++)for(i in n[a])s=n[a][i],n[a].hasOwnProperty(i)&&void 0!==s&&(t[i]=e.isPlainObject(s)?e.isPlainObject(t[i])?e.widget.extend({},t[i],s):e.widget.extend({},s):s);return t},e.widget.bridge=function(t,i){var s=i.prototype.widgetFullName||t;e.fn[t]=function(n){var a="string"==typeof n,o=u.call(arguments,1),r=this;return a?this.each(function(){var i,a=e.data(this,s);return"instance"===n?(r=a,!1):a?e.isFunction(a[n])&&"_"!==n.charAt(0)?(i=a[n].apply(a,o),i!==a&&void 0!==i?(r=i&&i.jquery?r.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+n+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+n+"'")}):(o.length&&(n=e.widget.extend.apply(null,[n].concat(o))),this.each(function(){var t=e.data(this,s);t?(t.option(n||{}),t._init&&t._init()):e.data(this,s,new i(n,this))})),r}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,i){i=e(i||this.defaultElement||this)[0],this.element=e(i),this.uuid=l++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),i!==this&&(e.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===i&&this.destroy()}}),this.document=e(i.style?i.ownerDocument:i.document||i),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),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.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(t,i){var s,n,a,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(n=o[t]=e.widget.extend({},this.options[t]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(t=s.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}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",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var n,a=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=n=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),e.each(s,function(s,o){function r(){return t||a.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.delegate(u,l,r):i.bind(l,r)})},_off:function(t,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(i).undelegate(i),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_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,o=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(o)&&o.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 o,r=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),o=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&e.effects&&e.effects.effect[r]?s[t](n):r!==t&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}}),e.widget;var d=!1;e(document).mouseup(function(){d=!1}),e.widget("ui.mouse",{version:"1.11.4",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):void 0}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!d){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var i=this,s=1===t.which,n="string"==typeof this.options.cancel&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(t)!==!1,!this._mouseStarted)?(t.preventDefault(),!0):(!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return i._mouseMove(e)},this._mouseUpDelegate=function(e){return i._mouseUp(e)},this.document.bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),d=!0,!0)):!0}},_mouseMove:function(t){if(this._mouseMoved){if(e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button)return this._mouseUp(t);if(!t.which)return this._mouseUp(t)}return(t.which||t.button)&&(this._mouseMoved=!0),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 this.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)),d=!1,!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}}),function(){function t(e,t,i){return[parseFloat(e[0])*(p.test(e[0])?t/100:1),parseFloat(e[1])*(p.test(e[1])?i/100:1)]}function i(t,i){return parseInt(e.css(t,i),10)||0}function s(t){var i=t[0];return 9===i.nodeType?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(i)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:i.preventDefault?{width:0,height:0,offset:{top:i.pageY,left:i.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var n,a,o=Math.max,r=Math.abs,h=Math.round,l=/left|center|right/,u=/top|center|bottom/,d=/[\+\-]\d+(\.[\d]+)?%?/,c=/^\w+/,p=/%$/,f=e.fn.position;e.position={scrollbarWidth:function(){if(void 0!==n)return n;var t,i,s=e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),a=s.children()[0];return e("body").append(s),t=a.offsetWidth,s.css("overflow","scroll"),i=a.offsetWidth,t===i&&(i=s[0].clientWidth),s.remove(),n=t-i},getScrollInfo:function(t){var i=t.isWindow||t.isDocument?"":t.element.css("overflow-x"),s=t.isWindow||t.isDocument?"":t.element.css("overflow-y"),n="scroll"===i||"auto"===i&&t.width<t.element[0].scrollWidth,a="scroll"===s||"auto"===s&&t.height<t.element[0].scrollHeight;return{width:a?e.position.scrollbarWidth():0,height:n?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var i=e(t||window),s=e.isWindow(i[0]),n=!!i[0]&&9===i[0].nodeType;return{element:i,isWindow:s,isDocument:n,offset:i.offset()||{left:0,top:0},scrollLeft:i.scrollLeft(),scrollTop:i.scrollTop(),width:s||n?i.width():i.outerWidth(),height:s||n?i.height():i.outerHeight()}}},e.fn.position=function(n){if(!n||!n.of)return f.apply(this,arguments);n=e.extend({},n);var p,m,g,v,y,b,_=e(n.of),x=e.position.getWithinInfo(n.within),w=e.position.getScrollInfo(x),k=(n.collision||"flip").split(" "),T={};return b=s(_),_[0].preventDefault&&(n.at="left top"),m=b.width,g=b.height,v=b.offset,y=e.extend({},v),e.each(["my","at"],function(){var e,t,i=(n[this]||"").split(" ");1===i.length&&(i=l.test(i[0])?i.concat(["center"]):u.test(i[0])?["center"].concat(i):["center","center"]),i[0]=l.test(i[0])?i[0]:"center",i[1]=u.test(i[1])?i[1]:"center",e=d.exec(i[0]),t=d.exec(i[1]),T[this]=[e?e[0]:0,t?t[0]:0],n[this]=[c.exec(i[0])[0],c.exec(i[1])[0]]}),1===k.length&&(k[1]=k[0]),"right"===n.at[0]?y.left+=m:"center"===n.at[0]&&(y.left+=m/2),"bottom"===n.at[1]?y.top+=g:"center"===n.at[1]&&(y.top+=g/2),p=t(T.at,m,g),y.left+=p[0],y.top+=p[1],this.each(function(){var s,l,u=e(this),d=u.outerWidth(),c=u.outerHeight(),f=i(this,"marginLeft"),b=i(this,"marginTop"),D=d+f+i(this,"marginRight")+w.width,S=c+b+i(this,"marginBottom")+w.height,M=e.extend({},y),C=t(T.my,u.outerWidth(),u.outerHeight());"right"===n.my[0]?M.left-=d:"center"===n.my[0]&&(M.left-=d/2),"bottom"===n.my[1]?M.top-=c:"center"===n.my[1]&&(M.top-=c/2),M.left+=C[0],M.top+=C[1],a||(M.left=h(M.left),M.top=h(M.top)),s={marginLeft:f,marginTop:b},e.each(["left","top"],function(t,i){e.ui.position[k[t]]&&e.ui.position[k[t]][i](M,{targetWidth:m,targetHeight:g,elemWidth:d,elemHeight:c,collisionPosition:s,collisionWidth:D,collisionHeight:S,offset:[p[0]+C[0],p[1]+C[1]],my:n.my,at:n.at,within:x,elem:u})}),n.using&&(l=function(e){var t=v.left-M.left,i=t+m-d,s=v.top-M.top,a=s+g-c,h={target:{element:_,left:v.left,top:v.top,width:m,height:g},element:{element:u,left:M.left,top:M.top,width:d,height:c},horizontal:0>i?"left":t>0?"right":"center",vertical:0>a?"top":s>0?"bottom":"middle"};d>m&&m>r(t+i)&&(h.horizontal="center"),c>g&&g>r(s+a)&&(h.vertical="middle"),h.important=o(r(t),r(i))>o(r(s),r(a))?"horizontal":"vertical",n.using.call(this,e,h)}),u.offset(e.extend(M,{using:l}))})},e.ui.position={fit:{left:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollLeft:s.offset.left,a=s.width,r=e.left-t.collisionPosition.marginLeft,h=n-r,l=r+t.collisionWidth-a-n;t.collisionWidth>a?h>0&&0>=l?(i=e.left+h+t.collisionWidth-a-n,e.left+=h-i):e.left=l>0&&0>=h?n:h>l?n+a-t.collisionWidth:n:h>0?e.left+=h:l>0?e.left-=l:e.left=o(e.left-r,e.left)},top:function(e,t){var i,s=t.within,n=s.isWindow?s.scrollTop:s.offset.top,a=t.within.height,r=e.top-t.collisionPosition.marginTop,h=n-r,l=r+t.collisionHeight-a-n;t.collisionHeight>a?h>0&&0>=l?(i=e.top+h+t.collisionHeight-a-n,e.top+=h-i):e.top=l>0&&0>=h?n:h>l?n+a-t.collisionHeight:n:h>0?e.top+=h:l>0?e.top-=l:e.top=o(e.top-r,e.top)}},flip:{left:function(e,t){var i,s,n=t.within,a=n.offset.left+n.scrollLeft,o=n.width,h=n.isWindow?n.scrollLeft:n.offset.left,l=e.left-t.collisionPosition.marginLeft,u=l-h,d=l+t.collisionWidth-o-h,c="left"===t.my[0]?-t.elemWidth:"right"===t.my[0]?t.elemWidth:0,p="left"===t.at[0]?t.targetWidth:"right"===t.at[0]?-t.targetWidth:0,f=-2*t.offset[0];0>u?(i=e.left+c+p+f+t.collisionWidth-o-a,(0>i||r(u)>i)&&(e.left+=c+p+f)):d>0&&(s=e.left-t.collisionPosition.marginLeft+c+p+f-h,(s>0||d>r(s))&&(e.left+=c+p+f))},top:function(e,t){var i,s,n=t.within,a=n.offset.top+n.scrollTop,o=n.height,h=n.isWindow?n.scrollTop:n.offset.top,l=e.top-t.collisionPosition.marginTop,u=l-h,d=l+t.collisionHeight-o-h,c="top"===t.my[1],p=c?-t.elemHeight:"bottom"===t.my[1]?t.elemHeight:0,f="top"===t.at[1]?t.targetHeight:"bottom"===t.at[1]?-t.targetHeight:0,m=-2*t.offset[1];0>u?(s=e.top+p+f+m+t.collisionHeight-o-a,(0>s||r(u)>s)&&(e.top+=p+f+m)):d>0&&(i=e.top-t.collisionPosition.marginTop+p+f+m-h,(i>0||d>r(i))&&(e.top+=p+f+m))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,i,s,n,o,r=document.getElementsByTagName("body")[0],h=document.createElement("div");t=document.createElement(r?"div":"body"),s={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},r&&e.extend(s,{position:"absolute",left:"-1000px",top:"-1000px"});for(o in s)t.style[o]=s[o];t.appendChild(h),i=r||document.documentElement,i.insertBefore(t,i.firstChild),h.style.cssText="position: absolute; left: 10.7432222px;",n=e(h).offset().left,a=n>10&&11>n,t.innerHTML="",i.removeChild(t)}()}(),e.ui.position,e.widget("ui.accordion",{version:"1.11.4",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},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 t=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset").attr("role","tablist"),t.collapsible||t.active!==!1&&null!=t.active||(t.active=0),this._processPanels(),0>t.active&&(t.active+=this.headers.length),this._refresh()},_getCreateEventData:function(){return{header:this.active,panel:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&&(e("<span>").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),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(),e=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(),"content"!==this.options.heightStyle&&e.css("height","")},_setOption:function(e,t){return"active"===e?(this._activate(t),void 0):("event"===e&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),"collapsible"!==e||t||this.options.active!==!1||this._activate(0),"icons"===e&&(this._destroyIcons(),t&&this._createIcons()),"disabled"===e&&(this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t)),void 0)},_keydown:function(t){if(!t.altKey&&!t.ctrlKey){var i=e.ui.keyCode,s=this.headers.length,n=this.headers.index(t.target),a=!1;switch(t.keyCode){case i.RIGHT:case i.DOWN:a=this.headers[(n+1)%s];break;case i.LEFT:case i.UP:a=this.headers[(n-1+s)%s];break;case i.SPACE:case i.ENTER:this._eventHandler(t);break;case i.HOME:a=this.headers[0];break;case i.END:a=this.headers[s-1]}a&&(e(t.target).attr("tabIndex",-1),e(a).attr("tabIndex",0),a.focus(),t.preventDefault())}},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&&t.ctrlKey&&e(t.currentTarget).prev().focus()},refresh:function(){var t=this.options;this._processPanels(),t.active===!1&&t.collapsible===!0||!this.headers.length?(t.active=!1,this.active=e()):t.active===!1?this._activate(0):this.active.length&&!e.contains(this.element[0],this.active[0])?this.headers.length===this.headers.find(".ui-state-disabled").length?(t.active=!1,this.active=e()):this._activate(Math.max(0,t.active-1)):t.active=this.headers.index(this.active),this._destroyIcons(),this._refresh()},_processPanels:function(){var e=this.headers,t=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(),t&&(this._off(e.not(this.headers)),this._off(t.not(this.panels)))},_refresh:function(){var t,i=this.options,s=i.heightStyle,n=this.element.parent();this.active=this._findActive(i.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 t=e(this),i=t.uniqueId().attr("id"),s=t.next(),n=s.uniqueId().attr("id");t.attr("aria-controls",n),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false","aria-expanded":"false",tabIndex:-1}).next().attr({"aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0}).next().attr({"aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._createIcons(),this._setupEvents(i.event),"fill"===s?(t=n.height(),this.element.siblings(":visible").each(function(){var i=e(this),s=i.css("position");"absolute"!==s&&"fixed"!==s&&(t-=i.outerHeight(!0))}),this.headers.each(function(){t-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,t-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):"auto"===s&&(t=0,this.headers.next().each(function(){t=Math.max(t,e(this).css("height","").height())}).height(t))},_activate:function(t){var i=this._findActive(t)[0];i!==this.active[0]&&(i=i||this.active[0],this._eventHandler({target:i,currentTarget:i,preventDefault:e.noop}))},_findActive:function(t){return"number"==typeof t?this.headers.eq(t):e()},_setupEvents:function(t){var i={keydown:"_keydown"};t&&e.each(t.split(" "),function(e,t){i[t]="_eventHandler"}),this._off(this.headers.add(this.headers.next())),this._on(this.headers,i),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._hoverable(this.headers),this._focusable(this.headers)},_eventHandler:function(t){var i=this.options,s=this.active,n=e(t.currentTarget),a=n[0]===s[0],o=a&&i.collapsible,r=o?e():n.next(),h=s.next(),l={oldHeader:s,oldPanel:h,newHeader:o?e():n,newPanel:r};t.preventDefault(),a&&!i.collapsible||this._trigger("beforeActivate",t,l)===!1||(i.active=o?!1:this.headers.index(n),this.active=a?e():n,this._toggle(l),s.removeClass("ui-accordion-header-active ui-state-active"),i.icons&&s.children(".ui-accordion-header-icon").removeClass(i.icons.activeHeader).addClass(i.icons.header),a||(n.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),i.icons&&n.children(".ui-accordion-header-icon").removeClass(i.icons.header).addClass(i.icons.activeHeader),n.next().addClass("ui-accordion-content-active")))},_toggle:function(t){var i=t.newPanel,s=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=i,this.prevHide=s,this.options.animate?this._animate(i,s,t):(s.hide(),i.show(),this._toggleComplete(t)),s.attr({"aria-hidden":"true"}),s.prev().attr({"aria-selected":"false","aria-expanded":"false"}),i.length&&s.length?s.prev().attr({tabIndex:-1,"aria-expanded":"false"}):i.length&&this.headers.filter(function(){return 0===parseInt(e(this).attr("tabIndex"),10)}).attr("tabIndex",-1),i.attr("aria-hidden","false").prev().attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_animate:function(e,t,i){var s,n,a,o=this,r=0,h=e.css("box-sizing"),l=e.length&&(!t.length||e.index()<t.index()),u=this.options.animate||{},d=l&&u.down||u,c=function(){o._toggleComplete(i)};return"number"==typeof d&&(a=d),"string"==typeof d&&(n=d),n=n||d.easing||u.easing,a=a||d.duration||u.duration,t.length?e.length?(s=e.show().outerHeight(),t.animate(this.hideProps,{duration:a,easing:n,step:function(e,t){t.now=Math.round(e)}}),e.hide().animate(this.showProps,{duration:a,easing:n,complete:c,step:function(e,i){i.now=Math.round(e),"height"!==i.prop?"content-box"===h&&(r+=i.now):"content"!==o.options.heightStyle&&(i.now=Math.round(s-t.outerHeight()-r),r=0)}}),void 0):t.animate(this.hideProps,a,n,c):e.animate(this.showProps,a,n,c)},_toggleComplete:function(e){var t=e.oldPanel;t.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),t.length&&(t.parent()[0].className=t.parent()[0].className),this._trigger("activate",null,e)}}),e.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",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.mouseHandled=!1,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}),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item":function(e){e.preventDefault()},"click .ui-menu-item":function(t){var i=e(t.target);!this.mouseHandled&&i.not(".ui-state-disabled").length&&(this.select(t),t.isPropagationStopped()||(this.mouseHandled=!0),i.has(".ui-menu").length?this.expand(t):!this.element.is(":focus")&&e(this.document[0].activeElement).closest(".ui-menu").length&&(this.element.trigger("focus",[!0]),this.active&&1===this.active.parents(".ui-menu").length&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){if(!this.previousFilter){var i=e(t.currentTarget);
i.siblings(".ui-state-active").removeClass("ui-state-active"),this.focus(t,i)}},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var i=this.active||this.element.find(this.options.items).eq(0);t||this.focus(e,i)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(e){this._closeOnDocumentClick(e)&&this.collapseAll(e),this.mouseHandled=!1}})},_destroy:function(){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(),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 t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){var i,s,n,a,o=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:o=!1,s=this.previousFilter||"",n=String.fromCharCode(t.keyCode),a=!1,clearTimeout(this.filterTimer),n===s?a=!0:n=s+n,i=this._filterMenuItems(n),i=a&&-1!==i.index(this.active.next())?this.active.nextAll(".ui-menu-item"):i,i.length||(n=String.fromCharCode(t.keyCode),i=this._filterMenuItems(n)),i.length?(this.focus(t,i),this.previousFilter=n,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter}o&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.is("[aria-haspopup='true']")?this.expand(e):this.select(e))},refresh:function(){var t,i,s=this,n=this.options.icons.submenu,a=this.element.find(this.options.menus);this.element.toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length),a.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 t=e(this),i=t.parent(),s=e("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);i.attr("aria-haspopup","true").prepend(s),t.attr("aria-labelledby",i.attr("id"))}),t=a.add(this.element),i=t.find(this.options.items),i.not(".ui-menu-item").each(function(){var t=e(this);s._isDivider(t)&&t.addClass("ui-widget-content ui-menu-divider")}),i.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({tabIndex:-1,role:this._itemRole()}),i.filter(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},_setOption:function(e,t){"icons"===e&&this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu),"disabled"===e&&this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this._super(e,t)},focus:function(e,t){var i,s;this.blur(e,e&&"focus"===e.type),this._scrollIntoView(t),this.active=t.first(),s=this.active.addClass("ui-state-focus").removeClass("ui-state-active"),this.options.role&&this.element.attr("aria-activedescendant",s.attr("id")),this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"),e&&"keydown"===e.type?this._close():this.timer=this._delay(function(){this._close()},this.delay),i=t.children(".ui-menu"),i.length&&e&&/^mouse/.test(e.type)&&this._startOpening(i),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var i,s,n,a,o,r;this._hasScroll()&&(i=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,s=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,n=t.offset().top-this.activeMenu.offset().top-i-s,a=this.activeMenu.scrollTop(),o=this.activeMenu.height(),r=t.outerHeight(),0>n?this.activeMenu.scrollTop(a+n):n+r>o&&this.activeMenu.scrollTop(a+n-o+r))},blur:function(e,t){t||clearTimeout(this.timer),this.active&&(this.active.removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active}))},_startOpening:function(e){clearTimeout(this.timer),"true"===e.attr("aria-hidden")&&(this.timer=this._delay(function(){this._close(),this._open(e)},this.delay))},_open:function(t){var i=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(i)},collapseAll:function(t,i){clearTimeout(this.timer),this.timer=this._delay(function(){var s=i?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));s.length||(s=this.element),this._close(s),this.blur(t),this.activeMenu=s},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.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(t){return!e(t.target).closest(".ui-menu").length},_isDivider:function(e){return!/[^\-\u2014\u2013\s]/.test(e.text())},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").find(this.options.items).first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},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(e,t,i){var s;this.active&&(s="first"===e||"last"===e?this.active["first"===e?"prevAll":"nextAll"](".ui-menu-item").eq(-1):this.active[e+"All"](".ui-menu-item").eq(0)),s&&s.length&&this.active||(s=this.activeMenu.find(this.options.items)[t]()),this.focus(i,s)},nextPage:function(t){var i,s,n;return this.active?(this.isLastItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return i=e(this),0>i.offset().top-s-n}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items)[this.active?"last":"first"]())),void 0):(this.next(t),void 0)},previousPage:function(t){var i,s,n;return this.active?(this.isFirstItem()||(this._hasScroll()?(s=this.active.offset().top,n=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return i=e(this),i.offset().top-s+n>0}),this.focus(t,i)):this.focus(t,this.activeMenu.find(this.options.items).first())),void 0):(this.next(t),void 0)},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var i={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,i)},_filterMenuItems:function(t){var i=t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&"),s=RegExp("^"+i,"i");return this.activeMenu.find(this.options.items).filter(".ui-menu-item").filter(function(){return s.test(e.trim(e(this).text()))})}}),e.widget("ui.autocomplete",{version:"1.11.4",defaultElement:"<input>",options:{appendTo:null,autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},requestIndex:0,pending:0,_create:function(){var t,i,s,n=this.element[0].nodeName.toLowerCase(),a="textarea"===n,o="input"===n;this.isMultiLine=a?!0:o?!1:this.element.prop("isContentEditable"),this.valueMethod=this.element[a||o?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(n){if(this.element.prop("readOnly"))return t=!0,s=!0,i=!0,void 0;t=!1,s=!1,i=!1;var a=e.ui.keyCode;switch(n.keyCode){case a.PAGE_UP:t=!0,this._move("previousPage",n);break;case a.PAGE_DOWN:t=!0,this._move("nextPage",n);break;case a.UP:t=!0,this._keyEvent("previous",n);break;case a.DOWN:t=!0,this._keyEvent("next",n);break;case a.ENTER:this.menu.active&&(t=!0,n.preventDefault(),this.menu.select(n));break;case a.TAB:this.menu.active&&this.menu.select(n);break;case a.ESCAPE:this.menu.element.is(":visible")&&(this.isMultiLine||this._value(this.term),this.close(n),n.preventDefault());break;default:i=!0,this._searchTimeout(n)}},keypress:function(s){if(t)return t=!1,(!this.isMultiLine||this.menu.element.is(":visible"))&&s.preventDefault(),void 0;if(!i){var n=e.ui.keyCode;switch(s.keyCode){case n.PAGE_UP:this._move("previousPage",s);break;case n.PAGE_DOWN:this._move("nextPage",s);break;case n.UP:this._keyEvent("previous",s);break;case n.DOWN:this._keyEvent("next",s)}}},input:function(e){return s?(s=!1,e.preventDefault(),void 0):(this._searchTimeout(e),void 0)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,void 0):(clearTimeout(this.searching),this.close(e),this._change(e),void 0)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({role:null}).hide().menu("instance"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var i=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(s){s.target===t.element[0]||s.target===i||e.contains(i,s.target)||t.close()})})},menufocus:function(t,i){var s,n;return this.isNewMenu&&(this.isNewMenu=!1,t.originalEvent&&/^mouse/.test(t.originalEvent.type))?(this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)}),void 0):(n=i.item.data("ui-autocomplete-item"),!1!==this._trigger("focus",t,{item:n})&&t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(n.value),s=i.item.attr("aria-label")||n.value,s&&e.trim(s).length&&(this.liveRegion.children().hide(),e("<div>").text(s).appendTo(this.liveRegion)),void 0)},menuselect:function(e,t){var i=t.item.data("ui-autocomplete-item"),s=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s,this.selectedItem=i})),!1!==this._trigger("select",e,{item:i})&&this._value(i.value),this.term=this._value(),this.close(e),this.selectedItem=i}}),this.liveRegion=e("<span>",{role:"status","aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body),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(e,t){this._super(e,t),"source"===e&&this._initSource(),"appendTo"===e&&this.menu.element.appendTo(this._appendTo()),"disabled"===e&&t&&this.xhr&&this.xhr.abort()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t&&t[0]||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_initSource:function(){var t,i,s=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(i,s){s(e.ui.autocomplete.filter(t,i.term))}):"string"==typeof this.options.source?(i=this.options.source,this.source=function(t,n){s.xhr&&s.xhr.abort(),s.xhr=e.ajax({url:i,data:t,dataType:"json",success:function(e){n(e)},error:function(){n([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){var t=this.term===this._value(),i=this.menu.element.is(":visible"),s=e.altKey||e.ctrlKey||e.metaKey||e.shiftKey;(!t||t&&!i&&!s)&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){return e=null!=e?e:this._value(),this.term=this._value(),e.length<this.options.minLength?this.close(t):this._trigger("search",t)!==!1?this._search(e):void 0},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var t=++this.requestIndex;return e.proxy(function(e){t===this.requestIndex&&this.__response(e),this.pending--,this.pending||this.element.removeClass("ui-autocomplete-loading")},this)},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return"string"==typeof t?{label:t,value:t}:e.extend({},t,{label:t.label||t.value,value:t.value||t.label})})},_suggest:function(t){var i=this.menu.element.empty();this._renderMenu(i,t),this.isNewMenu=!0,this.menu.refresh(),i.show(),this._resizeMenu(),i.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,i){var s=this;e.each(i,function(e,i){s._renderItemData(t,i)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,i){return e("<li>").text(i.label).appendTo(t)},_move:function(e,t){return this.menu.element.is(":visible")?this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)?(this.isMultiLine||this._value(this.term),this.menu.blur(),void 0):(this.menu[e](t),void 0):(this.search(null,t),void 0)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){(!this.isMultiLine||this.menu.element.is(":visible"))&&(this._move(e,t),t.preventDefault())}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,i){var s=RegExp(e.ui.autocomplete.escapeRegex(i),"i");return e.grep(t,function(e){return s.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(t){var i;this._superApply(arguments),this.options.disabled||this.cancelSearch||(i=t&&t.length?this.options.messages.results(t.length):this.options.messages.noResults,this.liveRegion.children().hide(),e("<div>").text(i).appendTo(this.liveRegion))}}),e.ui.autocomplete;var c,p="ui-button ui-widget ui-state-default ui-corner-all",f="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",m=function(){var t=e(this);setTimeout(function(){t.find(":ui-button").button("refresh")},1)},g=function(t){var i=t.name,s=t.form,n=e([]);return i&&(i=i.replace(/'/g,"\\'"),n=s?e(s).find("[name='"+i+"'][type=radio]"):e("[name='"+i+"'][type=radio]",t.ownerDocument).filter(function(){return!this.form})),n};e.widget("ui.button",{version:"1.11.4",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,m),"boolean"!=typeof this.options.disabled?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var t=this,i=this.options,s="checkbox"===this.type||"radio"===this.type,n=s?"":"ui-state-active";null===i.label&&(i.label="input"===this.type?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(p).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){i.disabled||this===c&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){i.disabled||e(this).removeClass(n)}).bind("click"+this.eventNamespace,function(e){i.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this._on({focus:function(){this.buttonElement.addClass("ui-state-focus")},blur:function(){this.buttonElement.removeClass("ui-state-focus")}}),s&&this.element.bind("change"+this.eventNamespace,function(){t.refresh()}),"checkbox"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){return i.disabled?!1:void 0}):"radio"===this.type?this.buttonElement.bind("click"+this.eventNamespace,function(){if(i.disabled)return!1;e(this).addClass("ui-state-active"),t.buttonElement.attr("aria-pressed","true");var s=t.element[0];g(s).not(s).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){return i.disabled?!1:(e(this).addClass("ui-state-active"),c=this,t.document.one("mouseup",function(){c=null}),void 0)}).bind("mouseup"+this.eventNamespace,function(){return i.disabled?!1:(e(this).removeClass("ui-state-active"),void 0)}).bind("keydown"+this.eventNamespace,function(t){return i.disabled?!1:((t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active"),void 0)}).bind("keyup"+this.eventNamespace+" blur"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",i.disabled),this._resetButton()},_determineButtonType:function(){var e,t,i;this.type=this.element.is("[type=checkbox]")?"checkbox":this.element.is("[type=radio]")?"radio":this.element.is("input")?"input":"button","checkbox"===this.type||"radio"===this.type?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),i=this.element.is(":checked"),i&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",i)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(p+" ui-state-active "+f).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){return this._super(e,t),"disabled"===e?(this.widget().toggleClass("ui-state-disabled",!!t),this.element.prop("disabled",!!t),t&&("checkbox"===this.type||"radio"===this.type?this.buttonElement.removeClass("ui-state-focus"):this.buttonElement.removeClass("ui-state-focus ui-state-active")),void 0):(this._resetButton(),void 0)},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),"radio"===this.type?g(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):"checkbox"===this.type&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if("input"===this.type)return this.options.label&&this.element.val(this.options.label),void 0;var t=this.buttonElement.removeClass(f),i=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),s=this.options.icons,n=s.primary&&s.secondary,a=[];s.primary||s.secondary?(this.options.text&&a.push("ui-button-text-icon"+(n?"s":s.primary?"-primary":"-secondary")),s.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+s.primary+"'></span>"),s.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+s.secondary+"'></span>"),this.options.text||(a.push(n?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(i)))):a.push("ui-button-text-only"),t.addClass(a.join(" "))}}),e.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(e,t){"disabled"===e&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t="rtl"===this.element.css("direction"),i=this.element.find(this.options.items),s=i.filter(":ui-button");i.not(":ui-button").button(),s.button("refresh"),this.buttons=i.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}}),e.ui.button,e.extend(e.ui,{datepicker:{version:"1.11.4"}});var v;e.extend(n.prototype,{markerClassName:"hasDatepicker",maxRows:4,_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return r(this._defaults,e||{}),this},_attachDatepicker:function(t,i){var s,n,a;s=t.nodeName.toLowerCase(),n="div"===s||"span"===s,t.id||(this.uuid+=1,t.id="dp"+this.uuid),a=this._newInst(e(t),n),a.settings=e.extend({},i||{}),"input"===s?this._connectDatepicker(t,a):n&&this._inlineDatepicker(t,a)},_newInst:function(t,i){var s=t[0].id.replace(/([^A-Za-z0-9_\-])/g,"\\\\$1");return{id:s,input:t,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:i,dpDiv:i?a(e("<div class='"+this._inlineClass+" ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")):this.dpDiv}},_connectDatepicker:function(t,i){var s=e(t);i.append=e([]),i.trigger=e([]),s.hasClass(this.markerClassName)||(this._attachments(s,i),s.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp),this._autoSize(i),e.data(t,"datepicker",i),i.settings.disabled&&this._disableDatepicker(t))},_attachments:function(t,i){var s,n,a,o=this._get(i,"appendText"),r=this._get(i,"isRTL");i.append&&i.append.remove(),o&&(i.append=e("<span class='"+this._appendClass+"'>"+o+"</span>"),t[r?"before":"after"](i.append)),t.unbind("focus",this._showDatepicker),i.trigger&&i.trigger.remove(),s=this._get(i,"showOn"),("focus"===s||"both"===s)&&t.focus(this._showDatepicker),("button"===s||"both"===s)&&(n=this._get(i,"buttonText"),a=this._get(i,"buttonImage"),i.trigger=e(this._get(i,"buttonImageOnly")?e("<img/>").addClass(this._triggerClass).attr({src:a,alt:n,title:n}):e("<button type='button'></button>").addClass(this._triggerClass).html(a?e("<img/>").attr({src:a,alt:n,title:n}):n)),t[r?"before":"after"](i.trigger),i.trigger.click(function(){return e.datepicker._datepickerShowing&&e.datepicker._lastInput===t[0]?e.datepicker._hideDatepicker():e.datepicker._datepickerShowing&&e.datepicker._lastInput!==t[0]?(e.datepicker._hideDatepicker(),e.datepicker._showDatepicker(t[0])):e.datepicker._showDatepicker(t[0]),!1}))},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t,i,s,n,a=new Date(2009,11,20),o=this._get(e,"dateFormat");o.match(/[DM]/)&&(t=function(e){for(i=0,s=0,n=0;e.length>n;n++)e[n].length>i&&(i=e[n].length,s=n);return s},a.setMonth(t(this._get(e,o.match(/MM/)?"monthNames":"monthNamesShort"))),a.setDate(t(this._get(e,o.match(/DD/)?"dayNames":"dayNamesShort"))+20-a.getDay())),e.input.attr("size",this._formatDate(e,a).length)}},_inlineDatepicker:function(t,i){var s=e(t);s.hasClass(this.markerClassName)||(s.addClass(this.markerClassName).append(i.dpDiv),e.data(t,"datepicker",i),this._setDate(i,this._getDefaultDate(i),!0),this._updateDatepicker(i),this._updateAlternate(i),i.settings.disabled&&this._disableDatepicker(t),i.dpDiv.css("display","block"))},_dialogDatepicker:function(t,i,s,n,a){var o,h,l,u,d,c=this._dialogInst;return c||(this.uuid+=1,o="dp"+this.uuid,this._dialogInput=e("<input type='text' id='"+o+"' style='position: absolute; top: -100px; width: 0px;'/>"),this._dialogInput.keydown(this._doKeyDown),e("body").append(this._dialogInput),c=this._dialogInst=this._newInst(this._dialogInput,!1),c.settings={},e.data(this._dialogInput[0],"datepicker",c)),r(c.settings,n||{}),i=i&&i.constructor===Date?this._formatDate(c,i):i,this._dialogInput.val(i),this._pos=a?a.length?a:[a.pageX,a.pageY]:null,this._pos||(h=document.documentElement.clientWidth,l=document.documentElement.clientHeight,u=document.documentElement.scrollLeft||document.body.scrollLeft,d=document.documentElement.scrollTop||document.body.scrollTop,this._pos=[h/2-100+u,l/2-150+d]),this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),c.settings.onSelect=s,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),e.blockUI&&e.blockUI(this.dpDiv),e.data(this._dialogInput[0],"datepicker",c),this},_destroyDatepicker:function(t){var i,s=e(t),n=e.data(t,"datepicker");s.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),e.removeData(t,"datepicker"),"input"===i?(n.append.remove(),n.trigger.remove(),s.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):("div"===i||"span"===i)&&s.removeClass(this.markerClassName).empty(),v===n&&(v=null))},_enableDatepicker:function(t){var i,s,n=e(t),a=e.data(t,"datepicker");n.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!1,a.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().removeClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}))},_disableDatepicker:function(t){var i,s,n=e(t),a=e.data(t,"datepicker");n.hasClass(this.markerClassName)&&(i=t.nodeName.toLowerCase(),"input"===i?(t.disabled=!0,a.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"})):("div"===i||"span"===i)&&(s=n.children("."+this._inlineClass),s.children().addClass("ui-state-disabled"),s.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)),this._disabledInputs=e.map(this._disabledInputs,function(e){return e===t?null:e}),this._disabledInputs[this._disabledInputs.length]=t)},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;this._disabledInputs.length>t;t++)if(this._disabledInputs[t]===e)return!0;return!1},_getInst:function(t){try{return e.data(t,"datepicker")}catch(i){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(t,i,s){var n,a,o,h,l=this._getInst(t);return 2===arguments.length&&"string"==typeof i?"defaults"===i?e.extend({},e.datepicker._defaults):l?"all"===i?e.extend({},l.settings):this._get(l,i):null:(n=i||{},"string"==typeof i&&(n={},n[i]=s),l&&(this._curInst===l&&this._hideDatepicker(),a=this._getDateDatepicker(t,!0),o=this._getMinMaxDate(l,"min"),h=this._getMinMaxDate(l,"max"),r(l.settings,n),null!==o&&void 0!==n.dateFormat&&void 0===n.minDate&&(l.settings.minDate=this._formatDate(l,o)),null!==h&&void 0!==n.dateFormat&&void 0===n.maxDate&&(l.settings.maxDate=this._formatDate(l,h)),"disabled"in n&&(n.disabled?this._disableDatepicker(t):this._enableDatepicker(t)),this._attachments(e(t),l),this._autoSize(l),this._setDate(l,a),this._updateAlternate(l),this._updateDatepicker(l)),void 0)},_changeDatepicker:function(e,t,i){this._optionDatepicker(e,t,i)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var i=this._getInst(e);i&&(this._setDate(i,t),this._updateDatepicker(i),this._updateAlternate(i))},_getDateDatepicker:function(e,t){var i=this._getInst(e);return i&&!i.inline&&this._setDateFromField(i,t),i?this._getDate(i):null},_doKeyDown:function(t){var i,s,n,a=e.datepicker._getInst(t.target),o=!0,r=a.dpDiv.is(".ui-datepicker-rtl");if(a._keyEvent=!0,e.datepicker._datepickerShowing)switch(t.keyCode){case 9:e.datepicker._hideDatepicker(),o=!1;break;case 13:return n=e("td."+e.datepicker._dayOverClass+":not(."+e.datepicker._currentClass+")",a.dpDiv),n[0]&&e.datepicker._selectDay(t.target,a.selectedMonth,a.selectedYear,n[0]),i=e.datepicker._get(a,"onSelect"),i?(s=e.datepicker._formatDate(a),i.apply(a.input?a.input[0]:null,[s,a])):e.datepicker._hideDatepicker(),!1;case 27:e.datepicker._hideDatepicker();break;case 33:e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(a,"stepBigMonths"):-e.datepicker._get(a,"stepMonths"),"M");break;case 34:e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(a,"stepBigMonths"):+e.datepicker._get(a,"stepMonths"),"M");break;case 35:(t.ctrlKey||t.metaKey)&&e.datepicker._clearDate(t.target),o=t.ctrlKey||t.metaKey;break;case 36:(t.ctrlKey||t.metaKey)&&e.datepicker._gotoToday(t.target),o=t.ctrlKey||t.metaKey;break;case 37:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,r?1:-1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?-e.datepicker._get(a,"stepBigMonths"):-e.datepicker._get(a,"stepMonths"),"M");break;case 38:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,-7,"D"),o=t.ctrlKey||t.metaKey;break;case 39:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,r?-1:1,"D"),o=t.ctrlKey||t.metaKey,t.originalEvent.altKey&&e.datepicker._adjustDate(t.target,t.ctrlKey?+e.datepicker._get(a,"stepBigMonths"):+e.datepicker._get(a,"stepMonths"),"M");break;case 40:(t.ctrlKey||t.metaKey)&&e.datepicker._adjustDate(t.target,7,"D"),o=t.ctrlKey||t.metaKey;break;default:o=!1}else 36===t.keyCode&&t.ctrlKey?e.datepicker._showDatepicker(this):o=!1;o&&(t.preventDefault(),t.stopPropagation())},_doKeyPress:function(t){var i,s,n=e.datepicker._getInst(t.target);
return e.datepicker._get(n,"constrainInput")?(i=e.datepicker._possibleChars(e.datepicker._get(n,"dateFormat")),s=String.fromCharCode(null==t.charCode?t.keyCode:t.charCode),t.ctrlKey||t.metaKey||" ">s||!i||i.indexOf(s)>-1):void 0},_doKeyUp:function(t){var i,s=e.datepicker._getInst(t.target);if(s.input.val()!==s.lastVal)try{i=e.datepicker.parseDate(e.datepicker._get(s,"dateFormat"),s.input?s.input.val():null,e.datepicker._getFormatConfig(s)),i&&(e.datepicker._setDateFromField(s),e.datepicker._updateAlternate(s),e.datepicker._updateDatepicker(s))}catch(n){}return!0},_showDatepicker:function(t){if(t=t.target||t,"input"!==t.nodeName.toLowerCase()&&(t=e("input",t.parentNode)[0]),!e.datepicker._isDisabledDatepicker(t)&&e.datepicker._lastInput!==t){var i,n,a,o,h,l,u;i=e.datepicker._getInst(t),e.datepicker._curInst&&e.datepicker._curInst!==i&&(e.datepicker._curInst.dpDiv.stop(!0,!0),i&&e.datepicker._datepickerShowing&&e.datepicker._hideDatepicker(e.datepicker._curInst.input[0])),n=e.datepicker._get(i,"beforeShow"),a=n?n.apply(t,[t,i]):{},a!==!1&&(r(i.settings,a),i.lastVal=null,e.datepicker._lastInput=t,e.datepicker._setDateFromField(i),e.datepicker._inDialog&&(t.value=""),e.datepicker._pos||(e.datepicker._pos=e.datepicker._findPos(t),e.datepicker._pos[1]+=t.offsetHeight),o=!1,e(t).parents().each(function(){return o|="fixed"===e(this).css("position"),!o}),h={left:e.datepicker._pos[0],top:e.datepicker._pos[1]},e.datepicker._pos=null,i.dpDiv.empty(),i.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),e.datepicker._updateDatepicker(i),h=e.datepicker._checkOffset(i,h,o),i.dpDiv.css({position:e.datepicker._inDialog&&e.blockUI?"static":o?"fixed":"absolute",display:"none",left:h.left+"px",top:h.top+"px"}),i.inline||(l=e.datepicker._get(i,"showAnim"),u=e.datepicker._get(i,"duration"),i.dpDiv.css("z-index",s(e(t))+1),e.datepicker._datepickerShowing=!0,e.effects&&e.effects.effect[l]?i.dpDiv.show(l,e.datepicker._get(i,"showOptions"),u):i.dpDiv[l||"show"](l?u:null),e.datepicker._shouldFocusInput(i)&&i.input.focus(),e.datepicker._curInst=i))}},_updateDatepicker:function(t){this.maxRows=4,v=t,t.dpDiv.empty().append(this._generateHTML(t)),this._attachHandlers(t);var i,s=this._getNumberOfMonths(t),n=s[1],a=17,r=t.dpDiv.find("."+this._dayOverClass+" a");r.length>0&&o.apply(r.get(0)),t.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),n>1&&t.dpDiv.addClass("ui-datepicker-multi-"+n).css("width",a*n+"em"),t.dpDiv[(1!==s[0]||1!==s[1]?"add":"remove")+"Class"]("ui-datepicker-multi"),t.dpDiv[(this._get(t,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),t===e.datepicker._curInst&&e.datepicker._datepickerShowing&&e.datepicker._shouldFocusInput(t)&&t.input.focus(),t.yearshtml&&(i=t.yearshtml,setTimeout(function(){i===t.yearshtml&&t.yearshtml&&t.dpDiv.find("select.ui-datepicker-year:first").replaceWith(t.yearshtml),i=t.yearshtml=null},0))},_shouldFocusInput:function(e){return e.input&&e.input.is(":visible")&&!e.input.is(":disabled")&&!e.input.is(":focus")},_checkOffset:function(t,i,s){var n=t.dpDiv.outerWidth(),a=t.dpDiv.outerHeight(),o=t.input?t.input.outerWidth():0,r=t.input?t.input.outerHeight():0,h=document.documentElement.clientWidth+(s?0:e(document).scrollLeft()),l=document.documentElement.clientHeight+(s?0:e(document).scrollTop());return i.left-=this._get(t,"isRTL")?n-o:0,i.left-=s&&i.left===t.input.offset().left?e(document).scrollLeft():0,i.top-=s&&i.top===t.input.offset().top+r?e(document).scrollTop():0,i.left-=Math.min(i.left,i.left+n>h&&h>n?Math.abs(i.left+n-h):0),i.top-=Math.min(i.top,i.top+a>l&&l>a?Math.abs(a+r):0),i},_findPos:function(t){for(var i,s=this._getInst(t),n=this._get(s,"isRTL");t&&("hidden"===t.type||1!==t.nodeType||e.expr.filters.hidden(t));)t=t[n?"previousSibling":"nextSibling"];return i=e(t).offset(),[i.left,i.top]},_hideDatepicker:function(t){var i,s,n,a,o=this._curInst;!o||t&&o!==e.data(t,"datepicker")||this._datepickerShowing&&(i=this._get(o,"showAnim"),s=this._get(o,"duration"),n=function(){e.datepicker._tidyDialog(o)},e.effects&&(e.effects.effect[i]||e.effects[i])?o.dpDiv.hide(i,e.datepicker._get(o,"showOptions"),s,n):o.dpDiv["slideDown"===i?"slideUp":"fadeIn"===i?"fadeOut":"hide"](i?s:null,n),i||n(),this._datepickerShowing=!1,a=this._get(o,"onClose"),a&&a.apply(o.input?o.input[0]:null,[o.input?o.input.val():"",o]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),e.blockUI&&(e.unblockUI(),e("body").append(this.dpDiv))),this._inDialog=!1)},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(t){if(e.datepicker._curInst){var i=e(t.target),s=e.datepicker._getInst(i[0]);(i[0].id!==e.datepicker._mainDivId&&0===i.parents("#"+e.datepicker._mainDivId).length&&!i.hasClass(e.datepicker.markerClassName)&&!i.closest("."+e.datepicker._triggerClass).length&&e.datepicker._datepickerShowing&&(!e.datepicker._inDialog||!e.blockUI)||i.hasClass(e.datepicker.markerClassName)&&e.datepicker._curInst!==s)&&e.datepicker._hideDatepicker()}},_adjustDate:function(t,i,s){var n=e(t),a=this._getInst(n[0]);this._isDisabledDatepicker(n[0])||(this._adjustInstDate(a,i+("M"===s?this._get(a,"showCurrentAtPos"):0),s),this._updateDatepicker(a))},_gotoToday:function(t){var i,s=e(t),n=this._getInst(s[0]);this._get(n,"gotoCurrent")&&n.currentDay?(n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear):(i=new Date,n.selectedDay=i.getDate(),n.drawMonth=n.selectedMonth=i.getMonth(),n.drawYear=n.selectedYear=i.getFullYear()),this._notifyChange(n),this._adjustDate(s)},_selectMonthYear:function(t,i,s){var n=e(t),a=this._getInst(n[0]);a["selected"+("M"===s?"Month":"Year")]=a["draw"+("M"===s?"Month":"Year")]=parseInt(i.options[i.selectedIndex].value,10),this._notifyChange(a),this._adjustDate(n)},_selectDay:function(t,i,s,n){var a,o=e(t);e(n).hasClass(this._unselectableClass)||this._isDisabledDatepicker(o[0])||(a=this._getInst(o[0]),a.selectedDay=a.currentDay=e("a",n).html(),a.selectedMonth=a.currentMonth=i,a.selectedYear=a.currentYear=s,this._selectDate(t,this._formatDate(a,a.currentDay,a.currentMonth,a.currentYear)))},_clearDate:function(t){var i=e(t);this._selectDate(i,"")},_selectDate:function(t,i){var s,n=e(t),a=this._getInst(n[0]);i=null!=i?i:this._formatDate(a),a.input&&a.input.val(i),this._updateAlternate(a),s=this._get(a,"onSelect"),s?s.apply(a.input?a.input[0]:null,[i,a]):a.input&&a.input.trigger("change"),a.inline?this._updateDatepicker(a):(this._hideDatepicker(),this._lastInput=a.input[0],"object"!=typeof a.input[0]&&a.input.focus(),this._lastInput=null)},_updateAlternate:function(t){var i,s,n,a=this._get(t,"altField");a&&(i=this._get(t,"altFormat")||this._get(t,"dateFormat"),s=this._getDate(t),n=this.formatDate(i,s,this._getFormatConfig(t)),e(a).each(function(){e(this).val(n)}))},noWeekends:function(e){var t=e.getDay();return[t>0&&6>t,""]},iso8601Week:function(e){var t,i=new Date(e.getTime());return i.setDate(i.getDate()+4-(i.getDay()||7)),t=i.getTime(),i.setMonth(0),i.setDate(1),Math.floor(Math.round((t-i)/864e5)/7)+1},parseDate:function(t,i,s){if(null==t||null==i)throw"Invalid arguments";if(i="object"==typeof i?""+i:i+"",""===i)return null;var n,a,o,r,h=0,l=(s?s.shortYearCutoff:null)||this._defaults.shortYearCutoff,u="string"!=typeof l?l:(new Date).getFullYear()%100+parseInt(l,10),d=(s?s.dayNamesShort:null)||this._defaults.dayNamesShort,c=(s?s.dayNames:null)||this._defaults.dayNames,p=(s?s.monthNamesShort:null)||this._defaults.monthNamesShort,f=(s?s.monthNames:null)||this._defaults.monthNames,m=-1,g=-1,v=-1,y=-1,b=!1,_=function(e){var i=t.length>n+1&&t.charAt(n+1)===e;return i&&n++,i},x=function(e){var t=_(e),s="@"===e?14:"!"===e?20:"y"===e&&t?4:"o"===e?3:2,n="y"===e?s:1,a=RegExp("^\\d{"+n+","+s+"}"),o=i.substring(h).match(a);if(!o)throw"Missing number at position "+h;return h+=o[0].length,parseInt(o[0],10)},w=function(t,s,n){var a=-1,o=e.map(_(t)?n:s,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)});if(e.each(o,function(e,t){var s=t[1];return i.substr(h,s.length).toLowerCase()===s.toLowerCase()?(a=t[0],h+=s.length,!1):void 0}),-1!==a)return a+1;throw"Unknown name at position "+h},k=function(){if(i.charAt(h)!==t.charAt(n))throw"Unexpected literal at position "+h;h++};for(n=0;t.length>n;n++)if(b)"'"!==t.charAt(n)||_("'")?k():b=!1;else switch(t.charAt(n)){case"d":v=x("d");break;case"D":w("D",d,c);break;case"o":y=x("o");break;case"m":g=x("m");break;case"M":g=w("M",p,f);break;case"y":m=x("y");break;case"@":r=new Date(x("@")),m=r.getFullYear(),g=r.getMonth()+1,v=r.getDate();break;case"!":r=new Date((x("!")-this._ticksTo1970)/1e4),m=r.getFullYear(),g=r.getMonth()+1,v=r.getDate();break;case"'":_("'")?k():b=!0;break;default:k()}if(i.length>h&&(o=i.substr(h),!/^\s+/.test(o)))throw"Extra/unparsed characters found in date: "+o;if(-1===m?m=(new Date).getFullYear():100>m&&(m+=(new Date).getFullYear()-(new Date).getFullYear()%100+(u>=m?0:-100)),y>-1)for(g=1,v=y;;){if(a=this._getDaysInMonth(m,g-1),a>=v)break;g++,v-=a}if(r=this._daylightSavingAdjust(new Date(m,g-1,v)),r.getFullYear()!==m||r.getMonth()+1!==g||r.getDate()!==v)throw"Invalid date";return r},ATOM:"yy-mm-dd",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",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:1e7*60*60*24*(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925)),formatDate:function(e,t,i){if(!t)return"";var s,n=(i?i.dayNamesShort:null)||this._defaults.dayNamesShort,a=(i?i.dayNames:null)||this._defaults.dayNames,o=(i?i.monthNamesShort:null)||this._defaults.monthNamesShort,r=(i?i.monthNames:null)||this._defaults.monthNames,h=function(t){var i=e.length>s+1&&e.charAt(s+1)===t;return i&&s++,i},l=function(e,t,i){var s=""+t;if(h(e))for(;i>s.length;)s="0"+s;return s},u=function(e,t,i,s){return h(e)?s[t]:i[t]},d="",c=!1;if(t)for(s=0;e.length>s;s++)if(c)"'"!==e.charAt(s)||h("'")?d+=e.charAt(s):c=!1;else switch(e.charAt(s)){case"d":d+=l("d",t.getDate(),2);break;case"D":d+=u("D",t.getDay(),n,a);break;case"o":d+=l("o",Math.round((new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime()-new Date(t.getFullYear(),0,0).getTime())/864e5),3);break;case"m":d+=l("m",t.getMonth()+1,2);break;case"M":d+=u("M",t.getMonth(),o,r);break;case"y":d+=h("y")?t.getFullYear():(10>t.getYear()%100?"0":"")+t.getYear()%100;break;case"@":d+=t.getTime();break;case"!":d+=1e4*t.getTime()+this._ticksTo1970;break;case"'":h("'")?d+="'":c=!0;break;default:d+=e.charAt(s)}return d},_possibleChars:function(e){var t,i="",s=!1,n=function(i){var s=e.length>t+1&&e.charAt(t+1)===i;return s&&t++,s};for(t=0;e.length>t;t++)if(s)"'"!==e.charAt(t)||n("'")?i+=e.charAt(t):s=!1;else switch(e.charAt(t)){case"d":case"m":case"y":case"@":i+="0123456789";break;case"D":case"M":return null;case"'":n("'")?i+="'":s=!0;break;default:i+=e.charAt(t)}return i},_get:function(e,t){return void 0!==e.settings[t]?e.settings[t]:this._defaults[t]},_setDateFromField:function(e,t){if(e.input.val()!==e.lastVal){var i=this._get(e,"dateFormat"),s=e.lastVal=e.input?e.input.val():null,n=this._getDefaultDate(e),a=n,o=this._getFormatConfig(e);try{a=this.parseDate(i,s,o)||n}catch(r){s=t?"":s}e.selectedDay=a.getDate(),e.drawMonth=e.selectedMonth=a.getMonth(),e.drawYear=e.selectedYear=a.getFullYear(),e.currentDay=s?a.getDate():0,e.currentMonth=s?a.getMonth():0,e.currentYear=s?a.getFullYear():0,this._adjustInstDate(e)}},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(t,i,s){var n=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},a=function(i){try{return e.datepicker.parseDate(e.datepicker._get(t,"dateFormat"),i,e.datepicker._getFormatConfig(t))}catch(s){}for(var n=(i.toLowerCase().match(/^c/)?e.datepicker._getDate(t):null)||new Date,a=n.getFullYear(),o=n.getMonth(),r=n.getDate(),h=/([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,l=h.exec(i);l;){switch(l[2]||"d"){case"d":case"D":r+=parseInt(l[1],10);break;case"w":case"W":r+=7*parseInt(l[1],10);break;case"m":case"M":o+=parseInt(l[1],10),r=Math.min(r,e.datepicker._getDaysInMonth(a,o));break;case"y":case"Y":a+=parseInt(l[1],10),r=Math.min(r,e.datepicker._getDaysInMonth(a,o))}l=h.exec(i)}return new Date(a,o,r)},o=null==i||""===i?s:"string"==typeof i?a(i):"number"==typeof i?isNaN(i)?s:n(i):new Date(i.getTime());return o=o&&"Invalid Date"==""+o?s:o,o&&(o.setHours(0),o.setMinutes(0),o.setSeconds(0),o.setMilliseconds(0)),this._daylightSavingAdjust(o)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,i){var s=!t,n=e.selectedMonth,a=e.selectedYear,o=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=o.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=o.getMonth(),e.drawYear=e.selectedYear=e.currentYear=o.getFullYear(),n===e.selectedMonth&&a===e.selectedYear||i||this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(s?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&""===e.input.val()?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(t){var i=this._get(t,"stepMonths"),s="#"+t.id.replace(/\\\\/g,"\\");t.dpDiv.find("[data-handler]").map(function(){var t={prev:function(){e.datepicker._adjustDate(s,-i,"M")},next:function(){e.datepicker._adjustDate(s,+i,"M")},hide:function(){e.datepicker._hideDatepicker()},today:function(){e.datepicker._gotoToday(s)},selectDay:function(){return e.datepicker._selectDay(s,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return e.datepicker._selectMonthYear(s,this,"M"),!1},selectYear:function(){return e.datepicker._selectMonthYear(s,this,"Y"),!1}};e(this).bind(this.getAttribute("data-event"),t[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t,i,s,n,a,o,r,h,l,u,d,c,p,f,m,g,v,y,b,_,x,w,k,T,D,S,M,C,N,A,P,I,H,z,F,E,O,j,W,L=new Date,R=this._daylightSavingAdjust(new Date(L.getFullYear(),L.getMonth(),L.getDate())),Y=this._get(e,"isRTL"),B=this._get(e,"showButtonPanel"),J=this._get(e,"hideIfNoPrevNext"),q=this._get(e,"navigationAsDateFormat"),K=this._getNumberOfMonths(e),V=this._get(e,"showCurrentAtPos"),U=this._get(e,"stepMonths"),Q=1!==K[0]||1!==K[1],G=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),X=this._getMinMaxDate(e,"min"),$=this._getMinMaxDate(e,"max"),Z=e.drawMonth-V,et=e.drawYear;if(0>Z&&(Z+=12,et--),$)for(t=this._daylightSavingAdjust(new Date($.getFullYear(),$.getMonth()-K[0]*K[1]+1,$.getDate())),t=X&&X>t?X:t;this._daylightSavingAdjust(new Date(et,Z,1))>t;)Z--,0>Z&&(Z=11,et--);for(e.drawMonth=Z,e.drawYear=et,i=this._get(e,"prevText"),i=q?this.formatDate(i,this._daylightSavingAdjust(new Date(et,Z-U,1)),this._getFormatConfig(e)):i,s=this._canAdjustMonth(e,-1,et,Z)?"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>":J?"":"<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+i+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"e":"w")+"'>"+i+"</span></a>",n=this._get(e,"nextText"),n=q?this.formatDate(n,this._daylightSavingAdjust(new Date(et,Z+U,1)),this._getFormatConfig(e)):n,a=this._canAdjustMonth(e,1,et,Z)?"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>":J?"":"<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+n+"'><span class='ui-icon ui-icon-circle-triangle-"+(Y?"w":"e")+"'>"+n+"</span></a>",o=this._get(e,"currentText"),r=this._get(e,"gotoCurrent")&&e.currentDay?G:R,o=q?this.formatDate(o,r,this._getFormatConfig(e)):o,h=e.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(e,"closeText")+"</button>",l=B?"<div class='ui-datepicker-buttonpane ui-widget-content'>"+(Y?h:"")+(this._isInRange(e,r)?"<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'>"+o+"</button>":"")+(Y?"":h)+"</div>":"",u=parseInt(this._get(e,"firstDay"),10),u=isNaN(u)?0:u,d=this._get(e,"showWeek"),c=this._get(e,"dayNames"),p=this._get(e,"dayNamesMin"),f=this._get(e,"monthNames"),m=this._get(e,"monthNamesShort"),g=this._get(e,"beforeShowDay"),v=this._get(e,"showOtherMonths"),y=this._get(e,"selectOtherMonths"),b=this._getDefaultDate(e),_="",w=0;K[0]>w;w++){for(k="",this.maxRows=4,T=0;K[1]>T;T++){if(D=this._daylightSavingAdjust(new Date(et,Z,e.selectedDay)),S=" ui-corner-all",M="",Q){if(M+="<div class='ui-datepicker-group",K[1]>1)switch(T){case 0:M+=" ui-datepicker-group-first",S=" ui-corner-"+(Y?"right":"left");break;case K[1]-1:M+=" ui-datepicker-group-last",S=" ui-corner-"+(Y?"left":"right");break;default:M+=" ui-datepicker-group-middle",S=""}M+="'>"}for(M+="<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix"+S+"'>"+(/all|left/.test(S)&&0===w?Y?a:s:"")+(/all|right/.test(S)&&0===w?Y?s:a:"")+this._generateMonthYearHeader(e,Z,et,X,$,w>0||T>0,f,m)+"</div><table class='ui-datepicker-calendar'><thead>"+"<tr>",C=d?"<th class='ui-datepicker-week-col'>"+this._get(e,"weekHeader")+"</th>":"",x=0;7>x;x++)N=(x+u)%7,C+="<th scope='col'"+((x+u+6)%7>=5?" class='ui-datepicker-week-end'":"")+">"+"<span title='"+c[N]+"'>"+p[N]+"</span></th>";for(M+=C+"</tr></thead><tbody>",A=this._getDaysInMonth(et,Z),et===e.selectedYear&&Z===e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,A)),P=(this._getFirstDayOfMonth(et,Z)-u+7)%7,I=Math.ceil((P+A)/7),H=Q?this.maxRows>I?this.maxRows:I:I,this.maxRows=H,z=this._daylightSavingAdjust(new Date(et,Z,1-P)),F=0;H>F;F++){for(M+="<tr>",E=d?"<td class='ui-datepicker-week-col'>"+this._get(e,"calculateWeek")(z)+"</td>":"",x=0;7>x;x++)O=g?g.apply(e.input?e.input[0]:null,[z]):[!0,""],j=z.getMonth()!==Z,W=j&&!y||!O[0]||X&&X>z||$&&z>$,E+="<td class='"+((x+u+6)%7>=5?" ui-datepicker-week-end":"")+(j?" ui-datepicker-other-month":"")+(z.getTime()===D.getTime()&&Z===e.selectedMonth&&e._keyEvent||b.getTime()===z.getTime()&&b.getTime()===D.getTime()?" "+this._dayOverClass:"")+(W?" "+this._unselectableClass+" ui-state-disabled":"")+(j&&!v?"":" "+O[1]+(z.getTime()===G.getTime()?" "+this._currentClass:"")+(z.getTime()===R.getTime()?" ui-datepicker-today":""))+"'"+(j&&!v||!O[2]?"":" title='"+O[2].replace(/'/g,"&#39;")+"'")+(W?"":" data-handler='selectDay' data-event='click' data-month='"+z.getMonth()+"' data-year='"+z.getFullYear()+"'")+">"+(j&&!v?"&#xa0;":W?"<span class='ui-state-default'>"+z.getDate()+"</span>":"<a class='ui-state-default"+(z.getTime()===R.getTime()?" ui-state-highlight":"")+(z.getTime()===G.getTime()?" ui-state-active":"")+(j?" ui-priority-secondary":"")+"' href='#'>"+z.getDate()+"</a>")+"</td>",z.setDate(z.getDate()+1),z=this._daylightSavingAdjust(z);M+=E+"</tr>"}Z++,Z>11&&(Z=0,et++),M+="</tbody></table>"+(Q?"</div>"+(K[0]>0&&T===K[1]-1?"<div class='ui-datepicker-row-break'></div>":""):""),k+=M}_+=k}return _+=l,e._keyEvent=!1,_},_generateMonthYearHeader:function(e,t,i,s,n,a,o,r){var h,l,u,d,c,p,f,m,g=this._get(e,"changeMonth"),v=this._get(e,"changeYear"),y=this._get(e,"showMonthAfterYear"),b="<div class='ui-datepicker-title'>",_="";if(a||!g)_+="<span class='ui-datepicker-month'>"+o[t]+"</span>";else{for(h=s&&s.getFullYear()===i,l=n&&n.getFullYear()===i,_+="<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>",u=0;12>u;u++)(!h||u>=s.getMonth())&&(!l||n.getMonth()>=u)&&(_+="<option value='"+u+"'"+(u===t?" selected='selected'":"")+">"+r[u]+"</option>");_+="</select>"}if(y||(b+=_+(!a&&g&&v?"":"&#xa0;")),!e.yearshtml)if(e.yearshtml="",a||!v)b+="<span class='ui-datepicker-year'>"+i+"</span>";else{for(d=this._get(e,"yearRange").split(":"),c=(new Date).getFullYear(),p=function(e){var t=e.match(/c[+\-].*/)?i+parseInt(e.substring(1),10):e.match(/[+\-].*/)?c+parseInt(e,10):parseInt(e,10);return isNaN(t)?c:t},f=p(d[0]),m=Math.max(f,p(d[1]||"")),f=s?Math.max(f,s.getFullYear()):f,m=n?Math.min(m,n.getFullYear()):m,e.yearshtml+="<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";m>=f;f++)e.yearshtml+="<option value='"+f+"'"+(f===i?" selected='selected'":"")+">"+f+"</option>";e.yearshtml+="</select>",b+=e.yearshtml,e.yearshtml=null}return b+=this._get(e,"yearSuffix"),y&&(b+=(!a&&g&&v?"":"&#xa0;")+_),b+="</div>"},_adjustInstDate:function(e,t,i){var s=e.drawYear+("Y"===i?t:0),n=e.drawMonth+("M"===i?t:0),a=Math.min(e.selectedDay,this._getDaysInMonth(s,n))+("D"===i?t:0),o=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(s,n,a)));e.selectedDay=o.getDate(),e.drawMonth=e.selectedMonth=o.getMonth(),e.drawYear=e.selectedYear=o.getFullYear(),("M"===i||"Y"===i)&&this._notifyChange(e)},_restrictMinMax:function(e,t){var i=this._getMinMaxDate(e,"min"),s=this._getMinMaxDate(e,"max"),n=i&&i>t?i:t;return s&&n>s?s:n},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return null==t?[1,1]:"number"==typeof t?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return new Date(e,t,1).getDay()},_canAdjustMonth:function(e,t,i,s){var n=this._getNumberOfMonths(e),a=this._daylightSavingAdjust(new Date(i,s+(0>t?t:n[0]*n[1]),1));return 0>t&&a.setDate(this._getDaysInMonth(a.getFullYear(),a.getMonth())),this._isInRange(e,a)},_isInRange:function(e,t){var i,s,n=this._getMinMaxDate(e,"min"),a=this._getMinMaxDate(e,"max"),o=null,r=null,h=this._get(e,"yearRange");return h&&(i=h.split(":"),s=(new Date).getFullYear(),o=parseInt(i[0],10),r=parseInt(i[1],10),i[0].match(/[+\-].*/)&&(o+=s),i[1].match(/[+\-].*/)&&(r+=s)),(!n||t.getTime()>=n.getTime())&&(!a||t.getTime()<=a.getTime())&&(!o||t.getFullYear()>=o)&&(!r||r>=t.getFullYear())},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t="string"!=typeof t?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,i,s){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var n=t?"object"==typeof t?t:this._daylightSavingAdjust(new Date(s,i,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),n,this._getFormatConfig(e))}}),e.fn.datepicker=function(t){if(!this.length)return this;e.datepicker.initialized||(e(document).mousedown(e.datepicker._checkExternalClick),e.datepicker.initialized=!0),0===e("#"+e.datepicker._mainDivId).length&&e("body").append(e.datepicker.dpDiv);var i=Array.prototype.slice.call(arguments,1);return"string"!=typeof t||"isDisabled"!==t&&"getDate"!==t&&"widget"!==t?"option"===t&&2===arguments.length&&"string"==typeof arguments[1]?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i)):this.each(function(){"string"==typeof t?e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this].concat(i)):e.datepicker._attachDatepicker(this,t)}):e.datepicker["_"+t+"Datepicker"].apply(e.datepicker,[this[0]].concat(i))},e.datepicker=new n,e.datepicker.initialized=!1,e.datepicker.uuid=(new Date).getTime(),e.datepicker.version="1.11.4",e.datepicker,e.widget("ui.draggable",e.ui.mouse,{version:"1.11.4",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&&this._setPositionRelative(),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._setHandleClassName(),this._mouseInit()},_setOption:function(e,t){this._super(e,t),"handle"===e&&(this._removeHandleClassName(),this._setHandleClassName())},_destroy:function(){return(this.helper||this.element).is(".ui-draggable-dragging")?(this.destroyOnClear=!0,void 0):(this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._removeHandleClassName(),this._mouseDestroy(),void 0)},_mouseCapture:function(t){var i=this.options;return this._blurActiveElement(t),this.helper||i.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(this._blockFrames(i.iframeFix===!0?"iframe":i.iframeFix),!0):!1)},_blockFrames:function(t){this.iframeBlocks=this.document.find(t).map(function(){var t=e(this);return e("<div>").css("position","absolute").appendTo(t.parent()).outerWidth(t.outerWidth()).outerHeight(t.outerHeight()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_blurActiveElement:function(t){var i=this.document[0];if(this.handleElement.is(t.target))try{i.activeElement&&"body"!==i.activeElement.nodeName.toLowerCase()&&e(i.activeElement).blur()}catch(s){}},_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(!0),this.offsetParent=this.helper.offsetParent(),this.hasFixedAncestor=this.helper.parents().filter(function(){return"fixed"===e(this).css("position")}).length>0,this.positionAbs=this.element.offset(),this._refreshOffsets(t),this.originalPosition=this.position=this._generatePosition(t,!1),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._normalizeRightBottom(),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_refreshOffsets:function(e){this.offset={top:this.positionAbs.top-this.margins.top,left:this.positionAbs.left-this.margins.left,scroll:!1,parent:this._getParentOffset(),relative:this._getRelativeOffset()},this.offset.click={left:e.pageX-this.offset.left,top:e.pageY-this.offset.top}},_mouseDrag:function(t,i){if(this.hasFixedAncestor&&(this.offset.parent=this._getParentOffset()),this.position=this._generatePosition(t,!0),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.helper[0].style.left=this.position.left+"px",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),"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},_mouseUp:function(t){return this._unblockFrames(),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),this.handleElement.is(t.target)&&this.element.focus(),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},_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(t){var i=this.options,s=e.isFunction(i.helper),n=s?e(i.helper.apply(this.element[0],[t])):"clone"===i.helper?this.element.clone().removeAttr("id"):this.element;return n.parents("body").length||n.appendTo("parent"===i.appendTo?this.element[0].parentNode:i.appendTo),s&&n[0]===this.element[0]&&this._setPositionRelative(),n[0]===this.element[0]||/(fixed|absolute)/.test(n.css("position"))||n.css("position","absolute"),n},_setPositionRelative:function(){/^(?:r|a|f)/.test(this.element.css("position"))||(this.element[0].style.position="relative")},_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)},_isRootNode:function(e){return/(html|body)/i.test(e.tagName)||e===this.document[0]},_getParentOffset:function(){var t=this.offsetParent.offset(),i=this.document[0];return"absolute"===this.cssPosition&&this.scrollParent[0]!==i&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),this._isRootNode(this.offsetParent[0])&&(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)return{top:0,left:0};var e=this.element.position(),t=this._isRootNode(this.scrollParent[0]);return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+(t?0:this.scrollParent.scrollTop()),left:e.left-(parseInt(this.helper.css("left"),10)||0)+(t?0:this.scrollParent.scrollLeft())}},_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,a=this.document[0];return this.relativeContainer=null,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()||a.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):"document"===n.containment?(this.containment=[0,0,e(a).width()-this.helperProportions.width-this.margins.left,(e(a).height()||a.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top],void 0):n.containment.constructor===Array?(this.containment=n.containment,void 0):("parent"===n.containment&&(n.containment=this.helper[0].parentNode),i=e(n.containment),s=i[0],s&&(t=/(scroll|auto)/.test(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.relativeContainer=i),void 0):(this.containment=null,void 0)
},_convertPositionTo:function(e,t){t||(t=this.position);var i="absolute"===e?1:-1,s=this._isRootNode(this.scrollParent[0]);return{top:t.top+this.offset.relative.top*i+this.offset.parent.top*i-("fixed"===this.cssPosition?-this.offset.scroll.top:s?0:this.offset.scroll.top)*i,left:t.left+this.offset.relative.left*i+this.offset.parent.left*i-("fixed"===this.cssPosition?-this.offset.scroll.left:s?0:this.offset.scroll.left)*i}},_generatePosition:function(e,t){var i,s,n,a,o=this.options,r=this._isRootNode(this.scrollParent[0]),h=e.pageX,l=e.pageY;return r&&this.offset.scroll||(this.offset.scroll={top:this.scrollParent.scrollTop(),left:this.scrollParent.scrollLeft()}),t&&(this.containment&&(this.relativeContainer?(s=this.relativeContainer.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,e.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),e.pageY-this.offset.click.top<i[1]&&(l=i[1]+this.offset.click.top),e.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),e.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),"y"===o.axis&&(h=this.originalPageX),"x"===o.axis&&(l=this.originalPageY)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.offset.scroll.top:r?0:this.offset.scroll.top),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.offset.scroll.left:r?0: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,this.destroyOnClear&&this.destroy()},_normalizeRightBottom:function(){"y"!==this.options.axis&&"auto"!==this.helper.css("right")&&(this.helper.width(this.helper.width()),this.helper.css("right","auto")),"x"!==this.options.axis&&"auto"!==this.helper.css("bottom")&&(this.helper.height(this.helper.height()),this.helper.css("bottom","auto"))},_trigger:function(t,i,s){return s=s||this._uiHash(),e.ui.plugin.call(this,t,[i,s,this],!0),/^(drag|start|stop)/.test(t)&&(this.positionAbs=this._convertPositionTo("absolute"),s.offset=this.positionAbs),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,s){var n=e.extend({},i,{item:s.element});s.sortables=[],e(s.options.connectToSortable).each(function(){var i=e(this).sortable("instance");i&&!i.options.disabled&&(s.sortables.push(i),i.refreshPositions(),i._trigger("activate",t,n))})},stop:function(t,i,s){var n=e.extend({},i,{item:s.element});s.cancelHelperRemoval=!1,e.each(s.sortables,function(){var e=this;e.isOver?(e.isOver=0,s.cancelHelperRemoval=!0,e.cancelHelperRemoval=!1,e._storedCSS={position:e.placeholder.css("position"),top:e.placeholder.css("top"),left:e.placeholder.css("left")},e._mouseStop(t),e.options.helper=e.options._helper):(e.cancelHelperRemoval=!0,e._trigger("deactivate",t,n))})},drag:function(t,i,s){e.each(s.sortables,function(){var n=!1,a=this;a.positionAbs=s.positionAbs,a.helperProportions=s.helperProportions,a.offset.click=s.offset.click,a._intersectsWith(a.containerCache)&&(n=!0,e.each(s.sortables,function(){return this.positionAbs=s.positionAbs,this.helperProportions=s.helperProportions,this.offset.click=s.offset.click,this!==a&&this._intersectsWith(this.containerCache)&&e.contains(a.element[0],this.element[0])&&(n=!1),n})),n?(a.isOver||(a.isOver=1,s._parent=i.helper.parent(),a.currentItem=i.helper.appendTo(a.element).data("ui-sortable-item",!0),a.options._helper=a.options.helper,a.options.helper=function(){return i.helper[0]},t.target=a.currentItem[0],a._mouseCapture(t,!0),a._mouseStart(t,!0,!0),a.offset.click.top=s.offset.click.top,a.offset.click.left=s.offset.click.left,a.offset.parent.left-=s.offset.parent.left-a.offset.parent.left,a.offset.parent.top-=s.offset.parent.top-a.offset.parent.top,s._trigger("toSortable",t),s.dropped=a.element,e.each(s.sortables,function(){this.refreshPositions()}),s.currentItem=s.element,a.fromOutside=s),a.currentItem&&(a._mouseDrag(t),i.position=a.position)):a.isOver&&(a.isOver=0,a.cancelHelperRemoval=!0,a.options._revert=a.options.revert,a.options.revert=!1,a._trigger("out",t,a._uiHash(a)),a._mouseStop(t,!0),a.options.revert=a.options._revert,a.options.helper=a.options._helper,a.placeholder&&a.placeholder.remove(),i.helper.appendTo(s._parent),s._refreshOffsets(t),i.position=s._generatePosition(t,!0),s._trigger("fromSortable",t),s.dropped=!1,e.each(s.sortables,function(){this.refreshPositions()}))})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,i,s){var n=e("body"),a=s.options;n.css("cursor")&&(a._cursor=n.css("cursor")),n.css("cursor",a.cursor)},stop:function(t,i,s){var n=s.options;n._cursor&&e("body").css("cursor",n._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,i,s){var n=e(i.helper),a=s.options;n.css("opacity")&&(a._opacity=n.css("opacity")),n.css("opacity",a.opacity)},stop:function(t,i,s){var n=s.options;n._opacity&&e(i.helper).css("opacity",n._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(e,t,i){i.scrollParentNotHidden||(i.scrollParentNotHidden=i.helper.scrollParent(!1)),i.scrollParentNotHidden[0]!==i.document[0]&&"HTML"!==i.scrollParentNotHidden[0].tagName&&(i.overflowOffset=i.scrollParentNotHidden.offset())},drag:function(t,i,s){var n=s.options,a=!1,o=s.scrollParentNotHidden[0],r=s.document[0];o!==r&&"HTML"!==o.tagName?(n.axis&&"x"===n.axis||(s.overflowOffset.top+o.offsetHeight-t.pageY<n.scrollSensitivity?o.scrollTop=a=o.scrollTop+n.scrollSpeed:t.pageY-s.overflowOffset.top<n.scrollSensitivity&&(o.scrollTop=a=o.scrollTop-n.scrollSpeed)),n.axis&&"y"===n.axis||(s.overflowOffset.left+o.offsetWidth-t.pageX<n.scrollSensitivity?o.scrollLeft=a=o.scrollLeft+n.scrollSpeed:t.pageX-s.overflowOffset.left<n.scrollSensitivity&&(o.scrollLeft=a=o.scrollLeft-n.scrollSpeed))):(n.axis&&"x"===n.axis||(t.pageY-e(r).scrollTop()<n.scrollSensitivity?a=e(r).scrollTop(e(r).scrollTop()-n.scrollSpeed):e(window).height()-(t.pageY-e(r).scrollTop())<n.scrollSensitivity&&(a=e(r).scrollTop(e(r).scrollTop()+n.scrollSpeed))),n.axis&&"y"===n.axis||(t.pageX-e(r).scrollLeft()<n.scrollSensitivity?a=e(r).scrollLeft(e(r).scrollLeft()-n.scrollSpeed):e(window).width()-(t.pageX-e(r).scrollLeft())<n.scrollSensitivity&&(a=e(r).scrollLeft(e(r).scrollLeft()+n.scrollSpeed)))),a!==!1&&e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(s,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,i,s){var n=s.options;s.snapElements=[],e(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var t=e(this),i=t.offset();this!==s.element[0]&&s.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:i.top,left:i.left})})},drag:function(t,i,s){var n,a,o,r,h,l,u,d,c,p,f=s.options,m=f.snapTolerance,g=i.offset.left,v=g+s.helperProportions.width,y=i.offset.top,b=y+s.helperProportions.height;for(c=s.snapElements.length-1;c>=0;c--)h=s.snapElements[c].left-s.margins.left,l=h+s.snapElements[c].width,u=s.snapElements[c].top-s.margins.top,d=u+s.snapElements[c].height,h-m>v||g>l+m||u-m>b||y>d+m||!e.contains(s.snapElements[c].item.ownerDocument,s.snapElements[c].item)?(s.snapElements[c].snapping&&s.options.snap.release&&s.options.snap.release.call(s.element,t,e.extend(s._uiHash(),{snapItem:s.snapElements[c].item})),s.snapElements[c].snapping=!1):("inner"!==f.snapMode&&(n=m>=Math.abs(u-b),a=m>=Math.abs(d-y),o=m>=Math.abs(h-v),r=m>=Math.abs(l-g),n&&(i.position.top=s._convertPositionTo("relative",{top:u-s.helperProportions.height,left:0}).top),a&&(i.position.top=s._convertPositionTo("relative",{top:d,left:0}).top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h-s.helperProportions.width}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l}).left)),p=n||a||o||r,"outer"!==f.snapMode&&(n=m>=Math.abs(u-y),a=m>=Math.abs(d-b),o=m>=Math.abs(h-g),r=m>=Math.abs(l-v),n&&(i.position.top=s._convertPositionTo("relative",{top:u,left:0}).top),a&&(i.position.top=s._convertPositionTo("relative",{top:d-s.helperProportions.height,left:0}).top),o&&(i.position.left=s._convertPositionTo("relative",{top:0,left:h}).left),r&&(i.position.left=s._convertPositionTo("relative",{top:0,left:l-s.helperProportions.width}).left)),!s.snapElements[c].snapping&&(n||a||o||r||p)&&s.options.snap.snap&&s.options.snap.snap.call(s.element,t,e.extend(s._uiHash(),{snapItem:s.snapElements[c].item})),s.snapElements[c].snapping=n||a||o||r||p)}}),e.ui.plugin.add("draggable","stack",{start:function(t,i,s){var n,a=s.options,o=e.makeArray(e(a.stack)).sort(function(t,i){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(i).css("zIndex"),10)||0)});o.length&&(n=parseInt(e(o[0]).css("zIndex"),10)||0,e(o).each(function(t){e(this).css("zIndex",n+t)}),this.css("zIndex",n+o.length))}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,i,s){var n=e(i.helper),a=s.options;n.css("zIndex")&&(a._zIndex=n.css("zIndex")),n.css("zIndex",a.zIndex)},stop:function(t,i,s){var n=s.options;n._zIndex&&e(i.helper).css("zIndex",n._zIndex)}}),e.ui.draggable,e.widget("ui.resizable",e.ui.mouse,{version:"1.11.4",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_num:function(e){return parseInt(e,10)||0},_isNumber:function(e){return!isNaN(parseInt(e,10))},_hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",n=!1;return t[s]>0?!0:(t[s]=1,n=t[s]>0,t[s]=0,n)},_create:function(){var t,i,s,n,a,o=this,r=this.options;if(this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!r.aspectRatio,aspectRatio:r.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:r.helper||r.ghost||r.animate?r.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/^(canvas|textarea|input|select|button|img)$/i)&&(this.element.wrap(e("<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=!0,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}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=r.handles||(e(".ui-resizable-handle",this.element).length?{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"}:"e,s,se"),this._handles=e(),this.handles.constructor===String)for("all"===this.handles&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={},i=0;t.length>i;i++)s=e.trim(t[i]),a="ui-resizable-"+s,n=e("<div class='ui-resizable-handle "+a+"'></div>"),n.css({zIndex:r.zIndex}),"se"===s&&n.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(n);this._renderAxis=function(t){var i,s,n,a;t=t||this.element;for(i in this.handles)this.handles[i].constructor===String?this.handles[i]=this.element.children(this.handles[i]).first().show():(this.handles[i].jquery||this.handles[i].nodeType)&&(this.handles[i]=e(this.handles[i]),this._on(this.handles[i],{mousedown:o._mouseDown})),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/^(textarea|input|select|button)$/i)&&(s=e(this.handles[i],this.element),a=/sw|ne|nw|se|n|s/.test(i)?s.outerHeight():s.outerWidth(),n=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join(""),t.css(n,a),this._proportionallyResize()),this._handles=this._handles.add(this.handles[i])},this._renderAxis(this.element),this._handles=this._handles.add(this.element.find(".ui-resizable-handle")),this._handles.disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(n=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=n&&n[1]?n[1]:"se")}),r.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){r.disabled||(e(this).removeClass("ui-resizable-autohide"),o._handles.show())}).mouseleave(function(){r.disabled||o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,i=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(i(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),i(this.originalElement),this},_mouseCapture:function(t){var i,s,n=!1;for(i in this.handles)s=e(this.handles[i])[0],(s===t.target||e.contains(s,t.target))&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(t){var i,s,n,a=this.options,o=this.element;return this.resizing=!0,this._renderProxy(),i=this._num(this.helper.css("left")),s=this._num(this.helper.css("top")),a.containment&&(i+=e(a.containment).scrollLeft()||0,s+=e(a.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:i,top:s},this.size=this._helper?{width:this.helper.width(),height:this.helper.height()}:{width:o.width(),height:o.height()},this.originalSize=this._helper?{width:o.outerWidth(),height:o.outerHeight()}:{width:o.width(),height:o.height()},this.sizeDiff={width:o.outerWidth()-o.width(),height:o.outerHeight()-o.height()},this.originalPosition={left:i,top:s},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio="number"==typeof a.aspectRatio?a.aspectRatio:this.originalSize.width/this.originalSize.height||1,n=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor","auto"===n?this.axis+"-resize":n),o.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var i,s,n=this.originalMousePosition,a=this.axis,o=t.pageX-n.left||0,r=t.pageY-n.top||0,h=this._change[a];return this._updatePrevProperties(),h?(i=h.apply(this,[t,o,r]),this._updateVirtualBoundaries(t.shiftKey),(this._aspectRatio||t.shiftKey)&&(i=this._updateRatio(i,t)),i=this._respectSize(i,t),this._updateCache(i),this._propagate("resize",t),s=this._applyChanges(),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(s)||(this._updatePrevProperties(),this._trigger("resize",t,this.ui()),this._applyChanges()),!1):!1},_mouseStop:function(t){this.resizing=!1;var i,s,n,a,o,r,h,l=this.options,u=this;return this._helper&&(i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),n=s&&this._hasScroll(i[0],"left")?0:u.sizeDiff.height,a=s?0:u.sizeDiff.width,o={width:u.helper.width()-a,height:u.helper.height()-n},r=parseInt(u.element.css("left"),10)+(u.position.left-u.originalPosition.left)||null,h=parseInt(u.element.css("top"),10)+(u.position.top-u.originalPosition.top)||null,l.animate||this.element.css(e.extend(o,{top:h,left:r})),u.helper.height(u.size.height),u.helper.width(u.size.width),this._helper&&!l.animate&&this._proportionallyResize()),e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_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 e={};return this.position.top!==this.prevPosition.top&&(e.top=this.position.top+"px"),this.position.left!==this.prevPosition.left&&(e.left=this.position.left+"px"),this.size.width!==this.prevSize.width&&(e.width=this.size.width+"px"),this.size.height!==this.prevSize.height&&(e.height=this.size.height+"px"),this.helper.css(e),e},_updateVirtualBoundaries:function(e){var t,i,s,n,a,o=this.options;a={minWidth:this._isNumber(o.minWidth)?o.minWidth:0,maxWidth:this._isNumber(o.maxWidth)?o.maxWidth:1/0,minHeight:this._isNumber(o.minHeight)?o.minHeight:0,maxHeight:this._isNumber(o.maxHeight)?o.maxHeight:1/0},(this._aspectRatio||e)&&(t=a.minHeight*this.aspectRatio,s=a.minWidth/this.aspectRatio,i=a.maxHeight*this.aspectRatio,n=a.maxWidth/this.aspectRatio,t>a.minWidth&&(a.minWidth=t),s>a.minHeight&&(a.minHeight=s),a.maxWidth>i&&(a.maxWidth=i),a.maxHeight>n&&(a.maxHeight=n)),this._vBoundaries=a},_updateCache:function(e){this.offset=this.helper.offset(),this._isNumber(e.left)&&(this.position.left=e.left),this._isNumber(e.top)&&(this.position.top=e.top),this._isNumber(e.height)&&(this.size.height=e.height),this._isNumber(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,i=this.size,s=this.axis;return this._isNumber(e.height)?e.width=e.height*this.aspectRatio:this._isNumber(e.width)&&(e.height=e.width/this.aspectRatio),"sw"===s&&(e.left=t.left+(i.width-e.width),e.top=null),"nw"===s&&(e.top=t.top+(i.height-e.height),e.left=t.left+(i.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,i=this.axis,s=this._isNumber(e.width)&&t.maxWidth&&t.maxWidth<e.width,n=this._isNumber(e.height)&&t.maxHeight&&t.maxHeight<e.height,a=this._isNumber(e.width)&&t.minWidth&&t.minWidth>e.width,o=this._isNumber(e.height)&&t.minHeight&&t.minHeight>e.height,r=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,l=/sw|nw|w/.test(i),u=/nw|ne|n/.test(i);return a&&(e.width=t.minWidth),o&&(e.height=t.minHeight),s&&(e.width=t.maxWidth),n&&(e.height=t.maxHeight),a&&l&&(e.left=r-t.minWidth),s&&l&&(e.left=r-t.maxWidth),o&&u&&(e.top=h-t.minHeight),n&&u&&(e.top=h-t.maxHeight),e.width||e.height||e.left||!e.top?e.width||e.height||e.top||!e.left||(e.left=null):e.top=null,e},_getPaddingPlusBorderDimensions:function(e){for(var t=0,i=[],s=[e.css("borderTopWidth"),e.css("borderRightWidth"),e.css("borderBottomWidth"),e.css("borderLeftWidth")],n=[e.css("paddingTop"),e.css("paddingRight"),e.css("paddingBottom"),e.css("paddingLeft")];4>t;t++)i[t]=parseInt(s[t],10)||0,i[t]+=parseInt(n[t],10)||0;return{height:i[0]+i[2],width:i[1]+i[3]}},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var e,t=0,i=this.helper||this.element;this._proportionallyResizeElements.length>t;t++)e=this._proportionallyResizeElements[t],this.outerDimensions||(this.outerDimensions=this._getPaddingPlusBorderDimensions(e)),e.css({height:i.height()-this.outerDimensions.height||0,width:i.width()-this.outerDimensions.width||0})},_renderProxy:function(){var t=this.element,i=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<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:++i.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,i){var s=this.originalSize,n=this.originalPosition;return{top:n.top+i,height:s.height-i}},s:function(e,t,i){return{height:this.originalSize.height+i}},se:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},sw:function(t,i,s){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,i,s]))},ne:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,i,s]))},nw:function(t,i,s){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,i,s]))}},_propagate:function(t,i){e.ui.plugin.call(this,t,[i,this.ui()]),"resize"!==t&&this._trigger(t,i,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}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var i=e(this).resizable("instance"),s=i.options,n=i._proportionallyResizeElements,a=n.length&&/textarea/i.test(n[0].nodeName),o=a&&i._hasScroll(n[0],"left")?0:i.sizeDiff.height,r=a?0:i.sizeDiff.width,h={width:i.size.width-r,height:i.size.height-o},l=parseInt(i.element.css("left"),10)+(i.position.left-i.originalPosition.left)||null,u=parseInt(i.element.css("top"),10)+(i.position.top-i.originalPosition.top)||null;i.element.animate(e.extend(h,u&&l?{top:u,left:l}:{}),{duration:s.animateDuration,easing:s.animateEasing,step:function(){var s={width:parseInt(i.element.css("width"),10),height:parseInt(i.element.css("height"),10),top:parseInt(i.element.css("top"),10),left:parseInt(i.element.css("left"),10)};n&&n.length&&e(n[0]).css({width:s.width,height:s.height}),i._updateCache(s),i._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,i,s,n,a,o,r,h=e(this).resizable("instance"),l=h.options,u=h.element,d=l.containment,c=d instanceof e?d.get(0):/parent/.test(d)?u.parent().get(0):d;c&&(h.containerElement=e(c),/document/.test(d)||d===document?(h.containerOffset={left:0,top:0},h.containerPosition={left:0,top:0},h.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(c),i=[],e(["Top","Right","Left","Bottom"]).each(function(e,s){i[e]=h._num(t.css("padding"+s))}),h.containerOffset=t.offset(),h.containerPosition=t.position(),h.containerSize={height:t.innerHeight()-i[3],width:t.innerWidth()-i[1]},s=h.containerOffset,n=h.containerSize.height,a=h.containerSize.width,o=h._hasScroll(c,"left")?c.scrollWidth:a,r=h._hasScroll(c)?c.scrollHeight:n,h.parentData={element:c,left:s.left,top:s.top,width:o,height:r}))},resize:function(t){var i,s,n,a,o=e(this).resizable("instance"),r=o.options,h=o.containerOffset,l=o.position,u=o._aspectRatio||t.shiftKey,d={top:0,left:0},c=o.containerElement,p=!0;c[0]!==document&&/static/.test(c.css("position"))&&(d=h),l.left<(o._helper?h.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-h.left:o.position.left-d.left),u&&(o.size.height=o.size.width/o.aspectRatio,p=!1),o.position.left=r.helper?h.left:0),l.top<(o._helper?h.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-h.top:o.position.top),u&&(o.size.width=o.size.height*o.aspectRatio,p=!1),o.position.top=o._helper?h.top:0),n=o.containerElement.get(0)===o.element.parent().get(0),a=/relative|absolute/.test(o.containerElement.css("position")),n&&a?(o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top):(o.offset.left=o.element.offset().left,o.offset.top=o.element.offset().top),i=Math.abs(o.sizeDiff.width+(o._helper?o.offset.left-d.left:o.offset.left-h.left)),s=Math.abs(o.sizeDiff.height+(o._helper?o.offset.top-d.top:o.offset.top-h.top)),i+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-i,u&&(o.size.height=o.size.width/o.aspectRatio,p=!1)),s+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-s,u&&(o.size.width=o.size.height*o.aspectRatio,p=!1)),p||(o.position.left=o.prevPosition.left,o.position.top=o.prevPosition.top,o.size.width=o.prevSize.width,o.size.height=o.prevSize.height)},stop:function(){var t=e(this).resizable("instance"),i=t.options,s=t.containerOffset,n=t.containerPosition,a=t.containerElement,o=e(t.helper),r=o.offset(),h=o.outerWidth()-t.sizeDiff.width,l=o.outerHeight()-t.sizeDiff.height;t._helper&&!i.animate&&/relative/.test(a.css("position"))&&e(this).css({left:r.left-n.left-s.left,width:h,height:l}),t._helper&&!i.animate&&/static/.test(a.css("position"))&&e(this).css({left:r.left-n.left-s.left,width:h,height:l})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).resizable("instance"),i=t.options;e(i.alsoResize).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})},resize:function(t,i){var s=e(this).resizable("instance"),n=s.options,a=s.originalSize,o=s.originalPosition,r={height:s.size.height-a.height||0,width:s.size.width-a.width||0,top:s.position.top-o.top||0,left:s.position.left-o.left||0};e(n.alsoResize).each(function(){var t=e(this),s=e(this).data("ui-resizable-alsoresize"),n={},a=t.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(a,function(e,t){var i=(s[t]||0)+(r[t]||0);i&&i>=0&&(n[t]=i||null)}),t.css(n)})},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).resizable("instance"),i=t.options,s=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass("string"==typeof i.ghost?i.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).resizable("instance");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).resizable("instance");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t,i=e(this).resizable("instance"),s=i.options,n=i.size,a=i.originalSize,o=i.originalPosition,r=i.axis,h="number"==typeof s.grid?[s.grid,s.grid]:s.grid,l=h[0]||1,u=h[1]||1,d=Math.round((n.width-a.width)/l)*l,c=Math.round((n.height-a.height)/u)*u,p=a.width+d,f=a.height+c,m=s.maxWidth&&p>s.maxWidth,g=s.maxHeight&&f>s.maxHeight,v=s.minWidth&&s.minWidth>p,y=s.minHeight&&s.minHeight>f;s.grid=h,v&&(p+=l),y&&(f+=u),m&&(p-=l),g&&(f-=u),/^(se|s|e)$/.test(r)?(i.size.width=p,i.size.height=f):/^(ne)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.top=o.top-c):/^(sw)$/.test(r)?(i.size.width=p,i.size.height=f,i.position.left=o.left-d):((0>=f-u||0>=p-l)&&(t=i._getPaddingPlusBorderDimensions(this)),f-u>0?(i.size.height=f,i.position.top=o.top-c):(f=u-t.height,i.size.height=f,i.position.top=o.top+a.height-f),p-l>0?(i.size.width=p,i.position.left=o.left-d):(p=l-t.width,i.size.width=p,i.position.left=o.left+a.width-p))}}),e.ui.resizable,e.widget("ui.dialog",{version:"1.11.4",options:{appendTo:"body",autoOpen:!0,buttons:[],closeOnEscape:!0,closeText:"Close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:null,maxWidth:null,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var i=e(this).css(t).offset().top;0>i&&e(this).css("top",t.top-i)}},resizable:!0,show:null,title:null,width:300,beforeClose:null,close:null,drag:null,dragStart:null,dragStop:null,focus:null,open:null,resize:null,resizeStart:null,resizeStop:null},sizeRelatedOptions:{buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},resizableRelatedOptions:{maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},_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(),this.options.draggable&&e.fn.draggable&&this._makeDraggable(),this.options.resizable&&e.fn.resizable&&this._makeResizable(),this._isOpen=!1,this._trackFocus()},_init:function(){this.options.autoOpen&&this.open()},_appendTo:function(){var t=this.options.appendTo;return t&&(t.jquery||t.nodeType)?e(t):this.document.find(t||"body").eq(0)},_destroy:function(){var e,t=this.originalPosition;this._untrackInstance(),this._destroyOverlay(),this.element.removeUniqueId().removeClass("ui-dialog-content ui-widget-content").css(this.originalCss).detach(),this.uiDialog.stop(!0,!0).remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},disable:e.noop,enable:e.noop,close:function(t){var i,s=this;if(this._isOpen&&this._trigger("beforeClose",t)!==!1){if(this._isOpen=!1,this._focusedElement=null,this._destroyOverlay(),this._untrackInstance(),!this.opener.filter(":focusable").focus().length)try{i=this.document[0].activeElement,i&&"body"!==i.nodeName.toLowerCase()&&e(i).blur()}catch(n){}this._hide(this.uiDialog,this.options.hide,function(){s._trigger("close",t)})}},isOpen:function(){return this._isOpen},moveToTop:function(){this._moveToTop()},_moveToTop:function(t,i){var s=!1,n=this.uiDialog.siblings(".ui-front:visible").map(function(){return+e(this).css("z-index")}).get(),a=Math.max.apply(null,n);return a>=+this.uiDialog.css("z-index")&&(this.uiDialog.css("z-index",a+1),s=!0),s&&!i&&this._trigger("focus",t),s},open:function(){var t=this;return this._isOpen?(this._moveToTop()&&this._focusTabbable(),void 0):(this._isOpen=!0,this.opener=e(this.document[0].activeElement),this._size(),this._position(),this._createOverlay(),this._moveToTop(null,!0),this.overlay&&this.overlay.css("z-index",this.uiDialog.css("z-index")-1),this._show(this.uiDialog,this.options.show,function(){t._focusTabbable(),t._trigger("focus")}),this._makeFocusTarget(),this._trigger("open"),void 0)},_focusTabbable:function(){var e=this._focusedElement;e||(e=this.element.find("[autofocus]")),e.length||(e=this.element.find(":tabbable")),e.length||(e=this.uiDialogButtonPane.find(":tabbable")),e.length||(e=this.uiDialogTitlebarClose.filter(":tabbable")),e.length||(e=this.uiDialog),e.eq(0).focus()},_keepFocus:function(t){function i(){var t=this.document[0].activeElement,i=this.uiDialog[0]===t||e.contains(this.uiDialog[0],t);i||this._focusTabbable()}t.preventDefault(),i.call(this),this._delay(i)},_createWrapper:function(){this.uiDialog=e("<div>").addClass("ui-dialog ui-widget ui-widget-content ui-corner-all ui-front "+this.options.dialogClass).hide().attr({tabIndex:-1,role:"dialog"}).appendTo(this._appendTo()),this._on(this.uiDialog,{keydown:function(t){if(this.options.closeOnEscape&&!t.isDefaultPrevented()&&t.keyCode&&t.keyCode===e.ui.keyCode.ESCAPE)return t.preventDefault(),this.close(t),void 0;
if(t.keyCode===e.ui.keyCode.TAB&&!t.isDefaultPrevented()){var i=this.uiDialog.find(":tabbable"),s=i.filter(":first"),n=i.filter(":last");t.target!==n[0]&&t.target!==this.uiDialog[0]||t.shiftKey?t.target!==s[0]&&t.target!==this.uiDialog[0]||!t.shiftKey||(this._delay(function(){n.focus()}),t.preventDefault()):(this._delay(function(){s.focus()}),t.preventDefault())}},mousedown:function(e){this._moveToTop(e)&&this._focusTabbable()}}),this.element.find("[aria-describedby]").length||this.uiDialog.attr({"aria-describedby":this.element.uniqueId().attr("id")})},_createTitlebar:function(){var t;this.uiDialogTitlebar=e("<div>").addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(this.uiDialog),this._on(this.uiDialogTitlebar,{mousedown:function(t){e(t.target).closest(".ui-dialog-titlebar-close")||this.uiDialog.focus()}}),this.uiDialogTitlebarClose=e("<button type='button'></button>").button({label:this.options.closeText,icons:{primary:"ui-icon-closethick"},text:!1}).addClass("ui-dialog-titlebar-close").appendTo(this.uiDialogTitlebar),this._on(this.uiDialogTitlebarClose,{click:function(e){e.preventDefault(),this.close(e)}}),t=e("<span>").uniqueId().addClass("ui-dialog-title").prependTo(this.uiDialogTitlebar),this._title(t),this.uiDialog.attr({"aria-labelledby":t.attr("id")})},_title:function(e){this.options.title||e.html("&#160;"),e.text(this.options.title)},_createButtonPane:function(){this.uiDialogButtonPane=e("<div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),this.uiButtonSet=e("<div>").addClass("ui-dialog-buttonset").appendTo(this.uiDialogButtonPane),this._createButtons()},_createButtons:function(){var t=this,i=this.options.buttons;return this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),e.isEmptyObject(i)||e.isArray(i)&&!i.length?(this.uiDialog.removeClass("ui-dialog-buttons"),void 0):(e.each(i,function(i,s){var n,a;s=e.isFunction(s)?{click:s,text:i}:s,s=e.extend({type:"button"},s),n=s.click,s.click=function(){n.apply(t.element[0],arguments)},a={icons:s.icons,text:s.showText},delete s.icons,delete s.showText,e("<button></button>",s).button(a).appendTo(t.uiButtonSet)}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog),void 0)},_makeDraggable:function(){function t(e){return{position:e.position,offset:e.offset}}var i=this,s=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(s,n){e(this).addClass("ui-dialog-dragging"),i._blockFrames(),i._trigger("dragStart",s,t(n))},drag:function(e,s){i._trigger("drag",e,t(s))},stop:function(n,a){var o=a.offset.left-i.document.scrollLeft(),r=a.offset.top-i.document.scrollTop();s.position={my:"left top",at:"left"+(o>=0?"+":"")+o+" "+"top"+(r>=0?"+":"")+r,of:i.window},e(this).removeClass("ui-dialog-dragging"),i._unblockFrames(),i._trigger("dragStop",n,t(a))}})},_makeResizable:function(){function t(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}var i=this,s=this.options,n=s.resizable,a=this.uiDialog.css("position"),o="string"==typeof n?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:s.maxWidth,maxHeight:s.maxHeight,minWidth:s.minWidth,minHeight:this._minHeight(),handles:o,start:function(s,n){e(this).addClass("ui-dialog-resizing"),i._blockFrames(),i._trigger("resizeStart",s,t(n))},resize:function(e,s){i._trigger("resize",e,t(s))},stop:function(n,a){var o=i.uiDialog.offset(),r=o.left-i.document.scrollLeft(),h=o.top-i.document.scrollTop();s.height=i.uiDialog.height(),s.width=i.uiDialog.width(),s.position={my:"left top",at:"left"+(r>=0?"+":"")+r+" "+"top"+(h>=0?"+":"")+h,of:i.window},e(this).removeClass("ui-dialog-resizing"),i._unblockFrames(),i._trigger("resizeStop",n,t(a))}}).css("position",a)},_trackFocus:function(){this._on(this.widget(),{focusin:function(t){this._makeFocusTarget(),this._focusedElement=e(t.target)}})},_makeFocusTarget:function(){this._untrackInstance(),this._trackingInstances().unshift(this)},_untrackInstance:function(){var t=this._trackingInstances(),i=e.inArray(this,t);-1!==i&&t.splice(i,1)},_trackingInstances:function(){var e=this.document.data("ui-dialog-instances");return e||(e=[],this.document.data("ui-dialog-instances",e)),e},_minHeight:function(){var e=this.options;return"auto"===e.height?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(){var e=this.uiDialog.is(":visible");e||this.uiDialog.show(),this.uiDialog.position(this.options.position),e||this.uiDialog.hide()},_setOptions:function(t){var i=this,s=!1,n={};e.each(t,function(e,t){i._setOption(e,t),e in i.sizeRelatedOptions&&(s=!0),e in i.resizableRelatedOptions&&(n[e]=t)}),s&&(this._size(),this._position()),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option",n)},_setOption:function(e,t){var i,s,n=this.uiDialog;"dialogClass"===e&&n.removeClass(this.options.dialogClass).addClass(t),"disabled"!==e&&(this._super(e,t),"appendTo"===e&&this.uiDialog.appendTo(this._appendTo()),"buttons"===e&&this._createButtons(),"closeText"===e&&this.uiDialogTitlebarClose.button({label:""+t}),"draggable"===e&&(i=n.is(":data(ui-draggable)"),i&&!t&&n.draggable("destroy"),!i&&t&&this._makeDraggable()),"position"===e&&this._position(),"resizable"===e&&(s=n.is(":data(ui-resizable)"),s&&!t&&n.resizable("destroy"),s&&"string"==typeof t&&n.resizable("option","handles",t),s||t===!1||this._makeResizable()),"title"===e&&this._title(this.uiDialogTitlebar.find(".ui-dialog-title")))},_size:function(){var e,t,i,s=this.options;this.element.show().css({width:"auto",minHeight:0,maxHeight:"none",height:0}),s.minWidth>s.width&&(s.width=s.minWidth),e=this.uiDialog.css({height:"auto",width:s.width}).outerHeight(),t=Math.max(0,s.minHeight-e),i="number"==typeof s.maxHeight?Math.max(0,s.maxHeight-e):"none","auto"===s.height?this.element.css({minHeight:t,maxHeight:i,height:"auto"}):this.element.height(Math.max(0,s.height-e)),this.uiDialog.is(":data(ui-resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())},_blockFrames:function(){this.iframeBlocks=this.document.find("iframe").map(function(){var t=e(this);return e("<div>").css({position:"absolute",width:t.outerWidth(),height:t.outerHeight()}).appendTo(t.parent()).offset(t.offset())[0]})},_unblockFrames:function(){this.iframeBlocks&&(this.iframeBlocks.remove(),delete this.iframeBlocks)},_allowInteraction:function(t){return e(t.target).closest(".ui-dialog").length?!0:!!e(t.target).closest(".ui-datepicker").length},_createOverlay:function(){if(this.options.modal){var t=!0;this._delay(function(){t=!1}),this.document.data("ui-dialog-overlays")||this._on(this.document,{focusin:function(e){t||this._allowInteraction(e)||(e.preventDefault(),this._trackingInstances()[0]._focusTabbable())}}),this.overlay=e("<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&&this.overlay){var e=this.document.data("ui-dialog-overlays")-1;e?this.document.data("ui-dialog-overlays",e):this.document.unbind("focusin").removeData("ui-dialog-overlays"),this.overlay.remove(),this.overlay=null}}}),e.widget("ui.droppable",{version:"1.11.4",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,i=this.options,s=i.accept;this.isover=!1,this.isout=!0,this.accept=e.isFunction(s)?s:function(e){return e.is(s)},this.proportions=function(){return arguments.length?(t=arguments[0],void 0):t?t:t={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}},this._addToManager(i.scope),i.addClasses&&this.element.addClass("ui-droppable")},_addToManager:function(t){e.ui.ddmanager.droppables[t]=e.ui.ddmanager.droppables[t]||[],e.ui.ddmanager.droppables[t].push(this)},_splice:function(e){for(var t=0;e.length>t;t++)e[t]===this&&e.splice(t,1)},_destroy:function(){var t=e.ui.ddmanager.droppables[this.options.scope];this._splice(t),this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,i){if("accept"===t)this.accept=e.isFunction(i)?i:function(e){return e.is(i)};else if("scope"===t){var s=e.ui.ddmanager.droppables[this.options.scope];this._splice(s),this._addToManager(i)}this._super(t,i)},_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 i=e(this).droppable("instance");return i.options.greedy&&!i.options.disabled&&i.options.scope===s.options.scope&&i.accept.call(i.element[0],s.currentItem||s.element)&&e.ui.intersect(s,e.extend(i,{offset:i.element.offset()}),i.options.tolerance,t)?(n=!0,!1):void 0}),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(){function e(e,t,i){return e>=t&&t+i>e}return function(t,i,s,n){if(!i.offset)return!1;var a=(t.positionAbs||t.position.absolute).left+t.margins.left,o=(t.positionAbs||t.position.absolute).top+t.margins.top,r=a+t.helperProportions.width,h=o+t.helperProportions.height,l=i.offset.left,u=i.offset.top,d=l+i.proportions().width,c=u+i.proportions().height;switch(s){case"fit":return a>=l&&d>=r&&o>=u&&c>=h;case"intersect":return a+t.helperProportions.width/2>l&&d>r-t.helperProportions.width/2&&o+t.helperProportions.height/2>u&&c>h-t.helperProportions.height/2;case"pointer":return e(n.pageY,u,i.proportions().height)&&e(n.pageX,l,i.proportions().width);case"touch":return(o>=u&&c>=o||h>=u&&c>=h||u>o&&h>c)&&(a>=l&&d>=a||r>=l&&d>=r||l>a&&r>d);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,i)&&(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,i),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(this).droppable("instance").options.scope===n}),a.length&&(s=e(a[0]).droppable("instance"),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)}},e.ui.droppable;var y="ui-effects-",b=e;e.effects={effect:{}},function(e,t){function i(e,t,i){var s=d[t.type]||{};return null==e?i||!t.def?null:t.def:(e=s.floor?~~e:parseFloat(e),isNaN(e)?t.def:s.mod?(e+s.mod)%s.mod:0>e?0:e>s.max?s.max:e)}function s(i){var s=l(),n=s._rgba=[];return i=i.toLowerCase(),f(h,function(e,a){var o,r=a.re.exec(i),h=r&&a.parse(r),l=a.space||"rgba";return h?(o=s[l](h),s[u[l].cache]=o[u[l].cache],n=s._rgba=o._rgba,!1):t}),n.length?("0,0,0,0"===n.join()&&e.extend(n,a.transparent),s):a[i]}function n(e,t,i){return i=(i+1)%1,1>6*i?e+6*(t-e)*i:1>2*i?t:2>3*i?e+6*(t-e)*(2/3-i):e}var a,o="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",r=/^([\-+])=\s*(\d+\.?\d*)/,h=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1],e[2],e[3],e[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,parse:function(e){return[2.55*e[1],2.55*e[2],2.55*e[3],e[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(e){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(e){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(e){return[e[1],e[2]/100,e[3]/100,e[4]]}}],l=e.Color=function(t,i,s,n){return new e.Color.fn.parse(t,i,s,n)},u={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"}}}},d={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},c=l.support={},p=e("<p>")[0],f=e.each;p.style.cssText="background-color:rgba(1,1,1,.5)",c.rgba=p.style.backgroundColor.indexOf("rgba")>-1,f(u,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),l.fn=e.extend(l.prototype,{parse:function(n,o,r,h){if(n===t)return this._rgba=[null,null,null,null],this;(n.jquery||n.nodeType)&&(n=e(n).css(o),o=t);var d=this,c=e.type(n),p=this._rgba=[];return o!==t&&(n=[n,o,r,h],c="array"),"string"===c?this.parse(s(n)||a._default):"array"===c?(f(u.rgba.props,function(e,t){p[t.idx]=i(n[t.idx],t)}),this):"object"===c?(n instanceof l?f(u,function(e,t){n[t.cache]&&(d[t.cache]=n[t.cache].slice())}):f(u,function(t,s){var a=s.cache;f(s.props,function(e,t){if(!d[a]&&s.to){if("alpha"===e||null==n[e])return;d[a]=s.to(d._rgba)}d[a][t.idx]=i(n[e],t,!0)}),d[a]&&0>e.inArray(null,d[a].slice(0,3))&&(d[a][3]=1,s.from&&(d._rgba=s.from(d[a])))}),this):t},is:function(e){var i=l(e),s=!0,n=this;return f(u,function(e,a){var o,r=i[a.cache];return r&&(o=n[a.cache]||a.to&&a.to(n._rgba)||[],f(a.props,function(e,i){return null!=r[i.idx]?s=r[i.idx]===o[i.idx]:t})),s}),s},_space:function(){var e=[],t=this;return f(u,function(i,s){t[s.cache]&&e.push(i)}),e.pop()},transition:function(e,t){var s=l(e),n=s._space(),a=u[n],o=0===this.alpha()?l("transparent"):this,r=o[a.cache]||a.to(o._rgba),h=r.slice();return s=s[a.cache],f(a.props,function(e,n){var a=n.idx,o=r[a],l=s[a],u=d[n.type]||{};null!==l&&(null===o?h[a]=l:(u.mod&&(l-o>u.mod/2?o+=u.mod:o-l>u.mod/2&&(o-=u.mod)),h[a]=i((l-o)*t+o,n)))}),this[n](h)},blend:function(t){if(1===this._rgba[3])return this;var i=this._rgba.slice(),s=i.pop(),n=l(t)._rgba;return l(e.map(i,function(e,t){return(1-s)*n[t]+s*e}))},toRgbaString:function(){var t="rgba(",i=e.map(this._rgba,function(e,t){return null==e?t>2?1:0:e});return 1===i[3]&&(i.pop(),t="rgb("),t+i.join()+")"},toHslaString:function(){var t="hsla(",i=e.map(this.hsla(),function(e,t){return null==e&&(e=t>2?1:0),t&&3>t&&(e=Math.round(100*e)+"%"),e});return 1===i[3]&&(i.pop(),t="hsl("),t+i.join()+")"},toHexString:function(t){var i=this._rgba.slice(),s=i.pop();return t&&i.push(~~(255*s)),"#"+e.map(i,function(e){return e=(e||0).toString(16),1===e.length?"0"+e:e}).join("")},toString:function(){return 0===this._rgba[3]?"transparent":this.toRgbaString()}}),l.fn.parse.prototype=l.fn,u.hsla.to=function(e){if(null==e[0]||null==e[1]||null==e[2])return[null,null,null,e[3]];var t,i,s=e[0]/255,n=e[1]/255,a=e[2]/255,o=e[3],r=Math.max(s,n,a),h=Math.min(s,n,a),l=r-h,u=r+h,d=.5*u;return t=h===r?0:s===r?60*(n-a)/l+360:n===r?60*(a-s)/l+120:60*(s-n)/l+240,i=0===l?0:.5>=d?l/u:l/(2-u),[Math.round(t)%360,i,d,null==o?1:o]},u.hsla.from=function(e){if(null==e[0]||null==e[1]||null==e[2])return[null,null,null,e[3]];var t=e[0]/360,i=e[1],s=e[2],a=e[3],o=.5>=s?s*(1+i):s+i-s*i,r=2*s-o;return[Math.round(255*n(r,o,t+1/3)),Math.round(255*n(r,o,t)),Math.round(255*n(r,o,t-1/3)),a]},f(u,function(s,n){var a=n.props,o=n.cache,h=n.to,u=n.from;l.fn[s]=function(s){if(h&&!this[o]&&(this[o]=h(this._rgba)),s===t)return this[o].slice();var n,r=e.type(s),d="array"===r||"object"===r?s:arguments,c=this[o].slice();return f(a,function(e,t){var s=d["object"===r?e:t.idx];null==s&&(s=c[t.idx]),c[t.idx]=i(s,t)}),u?(n=l(u(c)),n[o]=c,n):l(c)},f(a,function(t,i){l.fn[t]||(l.fn[t]=function(n){var a,o=e.type(n),h="alpha"===t?this._hsla?"hsla":"rgba":s,l=this[h](),u=l[i.idx];return"undefined"===o?u:("function"===o&&(n=n.call(this,u),o=e.type(n)),null==n&&i.empty?this:("string"===o&&(a=r.exec(n),a&&(n=u+parseFloat(a[2])*("+"===a[1]?1:-1))),l[i.idx]=n,this[h](l)))})})}),l.hook=function(t){var i=t.split(" ");f(i,function(t,i){e.cssHooks[i]={set:function(t,n){var a,o,r="";if("transparent"!==n&&("string"!==e.type(n)||(a=s(n)))){if(n=l(a||n),!c.rgba&&1!==n._rgba[3]){for(o="backgroundColor"===i?t.parentNode:t;(""===r||"transparent"===r)&&o&&o.style;)try{r=e.css(o,"backgroundColor"),o=o.parentNode}catch(h){}n=n.blend(r&&"transparent"!==r?r:"_default")}n=n.toRgbaString()}try{t.style[i]=n}catch(h){}}},e.fx.step[i]=function(t){t.colorInit||(t.start=l(t.elem,i),t.end=l(t.end),t.colorInit=!0),e.cssHooks[i].set(t.elem,t.start.transition(t.end,t.pos))}})},l.hook(o),e.cssHooks.borderColor={expand:function(e){var t={};return f(["Top","Right","Bottom","Left"],function(i,s){t["border"+s+"Color"]=e}),t}},a=e.Color.names={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",transparent:[null,null,null,0],_default:"#ffffff"}}(b),function(){function t(t){var i,s,n=t.ownerDocument.defaultView?t.ownerDocument.defaultView.getComputedStyle(t,null):t.currentStyle,a={};if(n&&n.length&&n[0]&&n[n[0]])for(s=n.length;s--;)i=n[s],"string"==typeof n[i]&&(a[e.camelCase(i)]=n[i]);else for(i in n)"string"==typeof n[i]&&(a[i]=n[i]);return a}function i(t,i){var s,a,o={};for(s in i)a=i[s],t[s]!==a&&(n[s]||(e.fx.step[s]||!isNaN(parseFloat(a)))&&(o[s]=a));return o}var s=["add","remove","toggle"],n={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};e.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,i){e.fx.step[i]=function(e){("none"!==e.end&&!e.setAttr||1===e.pos&&!e.setAttr)&&(b.style(e.elem,i,e.end),e.setAttr=!0)}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e.effects.animateClass=function(n,a,o,r){var h=e.speed(a,o,r);return this.queue(function(){var a,o=e(this),r=o.attr("class")||"",l=h.children?o.find("*").addBack():o;l=l.map(function(){var i=e(this);return{el:i,start:t(this)}}),a=function(){e.each(s,function(e,t){n[t]&&o[t+"Class"](n[t])})},a(),l=l.map(function(){return this.end=t(this.el[0]),this.diff=i(this.start,this.end),this}),o.attr("class",r),l=l.map(function(){var t=this,i=e.Deferred(),s=e.extend({},h,{queue:!1,complete:function(){i.resolve(t)}});return this.el.animate(this.diff,s),i.promise()}),e.when.apply(e,l.get()).done(function(){a(),e.each(arguments,function(){var t=this.el;e.each(this.diff,function(e){t.css(e,"")})}),h.complete.call(o[0])})})},e.fn.extend({addClass:function(t){return function(i,s,n,a){return s?e.effects.animateClass.call(this,{add:i},s,n,a):t.apply(this,arguments)}}(e.fn.addClass),removeClass:function(t){return function(i,s,n,a){return arguments.length>1?e.effects.animateClass.call(this,{remove:i},s,n,a):t.apply(this,arguments)}}(e.fn.removeClass),toggleClass:function(t){return function(i,s,n,a,o){return"boolean"==typeof s||void 0===s?n?e.effects.animateClass.call(this,s?{add:i}:{remove:i},n,a,o):t.apply(this,arguments):e.effects.animateClass.call(this,{toggle:i},s,n,a)}}(e.fn.toggleClass),switchClass:function(t,i,s,n,a){return e.effects.animateClass.call(this,{add:i,remove:t},s,n,a)}})}(),function(){function t(t,i,s,n){return e.isPlainObject(t)&&(i=t,t=t.effect),t={effect:t},null==i&&(i={}),e.isFunction(i)&&(n=i,s=null,i={}),("number"==typeof i||e.fx.speeds[i])&&(n=s,s=i,i={}),e.isFunction(s)&&(n=s,s=null),i&&e.extend(t,i),s=s||i.duration,t.duration=e.fx.off?0:"number"==typeof s?s:s in e.fx.speeds?e.fx.speeds[s]:e.fx.speeds._default,t.complete=n||i.complete,t}function i(t){return!t||"number"==typeof t||e.fx.speeds[t]?!0:"string"!=typeof t||e.effects.effect[t]?e.isFunction(t)?!0:"object"!=typeof t||t.effect?!1:!0:!0}e.extend(e.effects,{version:"1.11.4",save:function(e,t){for(var i=0;t.length>i;i++)null!==t[i]&&e.data(y+t[i],e[0].style[t[i]])},restore:function(e,t){var i,s;for(s=0;t.length>s;s++)null!==t[s]&&(i=e.data(y+t[s]),void 0===i&&(i=""),e.css(t[s],i))},setMode:function(e,t){return"toggle"===t&&(t=e.is(":hidden")?"show":"hide"),t},getBaseline:function(e,t){var i,s;switch(e[0]){case"top":i=0;break;case"middle":i=.5;break;case"bottom":i=1;break;default:i=e[0]/t.height}switch(e[1]){case"left":s=0;break;case"center":s=.5;break;case"right":s=1;break;default:s=e[1]/t.width}return{x:s,y:i}},createWrapper:function(t){if(t.parent().is(".ui-effects-wrapper"))return t.parent();var i={width:t.outerWidth(!0),height:t.outerHeight(!0),"float":t.css("float")},s=e("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),n={width:t.width(),height:t.height()},a=document.activeElement;try{a.id}catch(o){a=document.body}return t.wrap(s),(t[0]===a||e.contains(t[0],a))&&e(a).focus(),s=t.parent(),"static"===t.css("position")?(s.css({position:"relative"}),t.css({position:"relative"})):(e.extend(i,{position:t.css("position"),zIndex:t.css("z-index")}),e.each(["top","left","bottom","right"],function(e,s){i[s]=t.css(s),isNaN(parseInt(i[s],10))&&(i[s]="auto")}),t.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),t.css(n),s.css(i).show()},removeWrapper:function(t){var i=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),(t[0]===i||e.contains(t[0],i))&&e(i).focus()),t},setTransition:function(t,i,s,n){return n=n||{},e.each(i,function(e,i){var a=t.cssUnit(i);a[0]>0&&(n[i]=a[0]*s+a[1])}),n}}),e.fn.extend({effect:function(){function i(t){function i(){e.isFunction(a)&&a.call(n[0]),e.isFunction(t)&&t()}var n=e(this),a=s.complete,r=s.mode;(n.is(":hidden")?"hide"===r:"show"===r)?(n[r](),i()):o.call(n[0],s,i)}var s=t.apply(this,arguments),n=s.mode,a=s.queue,o=e.effects.effect[s.effect];return e.fx.off||!o?n?this[n](s.duration,s.complete):this.each(function(){s.complete&&s.complete.call(this)}):a===!1?this.each(i):this.queue(a||"fx",i)},show:function(e){return function(s){if(i(s))return e.apply(this,arguments);var n=t.apply(this,arguments);return n.mode="show",this.effect.call(this,n)}}(e.fn.show),hide:function(e){return function(s){if(i(s))return e.apply(this,arguments);var n=t.apply(this,arguments);return n.mode="hide",this.effect.call(this,n)}}(e.fn.hide),toggle:function(e){return function(s){if(i(s)||"boolean"==typeof s)return e.apply(this,arguments);var n=t.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)}}(e.fn.toggle),cssUnit:function(t){var i=this.css(t),s=[];return e.each(["em","px","%","pt"],function(e,t){i.indexOf(t)>0&&(s=[parseFloat(i),t])}),s}})}(),function(){var t={};e.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,i){t[i]=function(t){return Math.pow(t,e+2)}}),e.extend(t,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return 0===e||1===e?e:-Math.pow(2,8*(e-1))*Math.sin((80*(e-1)-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(e){for(var t,i=4;((t=Math.pow(2,--i))-1)/11>e;);return 1/Math.pow(4,3-i)-7.5625*Math.pow((3*t-2)/22-e,2)}}),e.each(t,function(t,i){e.easing["easeIn"+t]=i,e.easing["easeOut"+t]=function(e){return 1-i(1-e)},e.easing["easeInOut"+t]=function(e){return.5>e?i(2*e)/2:1-i(-2*e+2)/2}})}(),e.effects,e.effects.effect.blind=function(t,i){var s,n,a,o=e(this),r=/up|down|vertical/,h=/up|left|vertical|horizontal/,l=["position","top","bottom","left","right","height","width"],u=e.effects.setMode(o,t.mode||"hide"),d=t.direction||"up",c=r.test(d),p=c?"height":"width",f=c?"top":"left",m=h.test(d),g={},v="show"===u;o.parent().is(".ui-effects-wrapper")?e.effects.save(o.parent(),l):e.effects.save(o,l),o.show(),s=e.effects.createWrapper(o).css({overflow:"hidden"}),n=s[p](),a=parseFloat(s.css(f))||0,g[p]=v?n:0,m||(o.css(c?"bottom":"right",0).css(c?"top":"left","auto").css({position:"absolute"}),g[f]=v?a:n+a),v&&(s.css(p,0),m||s.css(f,a+n)),s.animate(g,{duration:t.duration,easing:t.easing,queue:!1,complete:function(){"hide"===u&&o.hide(),e.effects.restore(o,l),e.effects.removeWrapper(o),i()}})},e.effects.effect.bounce=function(t,i){var s,n,a,o=e(this),r=["position","top","bottom","left","right","height","width"],h=e.effects.setMode(o,t.mode||"effect"),l="hide"===h,u="show"===h,d=t.direction||"up",c=t.distance,p=t.times||5,f=2*p+(u||l?1:0),m=t.duration/f,g=t.easing,v="up"===d||"down"===d?"top":"left",y="up"===d||"left"===d,b=o.queue(),_=b.length;for((u||l)&&r.push("opacity"),e.effects.save(o,r),o.show(),e.effects.createWrapper(o),c||(c=o["top"===v?"outerHeight":"outerWidth"]()/3),u&&(a={opacity:1},a[v]=0,o.css("opacity",0).css(v,y?2*-c:2*c).animate(a,m,g)),l&&(c/=Math.pow(2,p-1)),a={},a[v]=0,s=0;p>s;s++)n={},n[v]=(y?"-=":"+=")+c,o.animate(n,m,g).animate(a,m,g),c=l?2*c:c/2;l&&(n={opacity:0},n[v]=(y?"-=":"+=")+c,o.animate(n,m,g)),o.queue(function(){l&&o.hide(),e.effects.restore(o,r),e.effects.removeWrapper(o),i()}),_>1&&b.splice.apply(b,[1,0].concat(b.splice(_,f+1))),o.dequeue()},e.effects.effect.clip=function(t,i){var s,n,a,o=e(this),r=["position","top","bottom","left","right","height","width"],h=e.effects.setMode(o,t.mode||"hide"),l="show"===h,u=t.direction||"vertical",d="vertical"===u,c=d?"height":"width",p=d?"top":"left",f={};e.effects.save(o,r),o.show(),s=e.effects.createWrapper(o).css({overflow:"hidden"}),n="IMG"===o[0].tagName?s:o,a=n[c](),l&&(n.css(c,0),n.css(p,a/2)),f[c]=l?a:0,f[p]=l?0:a/2,n.animate(f,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){l||o.hide(),e.effects.restore(o,r),e.effects.removeWrapper(o),i()}})},e.effects.effect.drop=function(t,i){var s,n=e(this),a=["position","top","bottom","left","right","opacity","height","width"],o=e.effects.setMode(n,t.mode||"hide"),r="show"===o,h=t.direction||"left",l="up"===h||"down"===h?"top":"left",u="up"===h||"left"===h?"pos":"neg",d={opacity:r?1:0};e.effects.save(n,a),n.show(),e.effects.createWrapper(n),s=t.distance||n["top"===l?"outerHeight":"outerWidth"](!0)/2,r&&n.css("opacity",0).css(l,"pos"===u?-s:s),d[l]=(r?"pos"===u?"+=":"-=":"pos"===u?"-=":"+=")+s,n.animate(d,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){"hide"===o&&n.hide(),e.effects.restore(n,a),e.effects.removeWrapper(n),i()}})},e.effects.effect.explode=function(t,i){function s(){b.push(this),b.length===d*c&&n()}function n(){p.css({visibility:"visible"}),e(b).remove(),m||p.hide(),i()}var a,o,r,h,l,u,d=t.pieces?Math.round(Math.sqrt(t.pieces)):3,c=d,p=e(this),f=e.effects.setMode(p,t.mode||"hide"),m="show"===f,g=p.show().css("visibility","hidden").offset(),v=Math.ceil(p.outerWidth()/c),y=Math.ceil(p.outerHeight()/d),b=[];for(a=0;d>a;a++)for(h=g.top+a*y,u=a-(d-1)/2,o=0;c>o;o++)r=g.left+o*v,l=o-(c-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-o*v,top:-a*y}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:v,height:y,left:r+(m?l*v:0),top:h+(m?u*y:0),opacity:m?0:1}).animate({left:r+(m?0:l*v),top:h+(m?0:u*y),opacity:m?1:0},t.duration||500,t.easing,s)},e.effects.effect.fade=function(t,i){var s=e(this),n=e.effects.setMode(s,t.mode||"toggle");s.animate({opacity:n},{queue:!1,duration:t.duration,easing:t.easing,complete:i})},e.effects.effect.fold=function(t,i){var s,n,a=e(this),o=["position","top","bottom","left","right","height","width"],r=e.effects.setMode(a,t.mode||"hide"),h="show"===r,l="hide"===r,u=t.size||15,d=/([0-9]+)%/.exec(u),c=!!t.horizFirst,p=h!==c,f=p?["width","height"]:["height","width"],m=t.duration/2,g={},v={};e.effects.save(a,o),a.show(),s=e.effects.createWrapper(a).css({overflow:"hidden"}),n=p?[s.width(),s.height()]:[s.height(),s.width()],d&&(u=parseInt(d[1],10)/100*n[l?0:1]),h&&s.css(c?{height:0,width:u}:{height:u,width:0}),g[f[0]]=h?n[0]:u,v[f[1]]=h?n[1]:0,s.animate(g,m,t.easing).animate(v,m,t.easing,function(){l&&a.hide(),e.effects.restore(a,o),e.effects.removeWrapper(a),i()})},e.effects.effect.highlight=function(t,i){var s=e(this),n=["backgroundImage","backgroundColor","opacity"],a=e.effects.setMode(s,t.mode||"show"),o={backgroundColor:s.css("backgroundColor")};"hide"===a&&(o.opacity=0),e.effects.save(s,n),s.show().css({backgroundImage:"none",backgroundColor:t.color||"#ffff99"}).animate(o,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){"hide"===a&&s.hide(),e.effects.restore(s,n),i()}})},e.effects.effect.size=function(t,i){var s,n,a,o=e(this),r=["position","top","bottom","left","right","width","height","overflow","opacity"],h=["position","top","bottom","left","right","overflow","opacity"],l=["width","height","overflow"],u=["fontSize"],d=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],c=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=e.effects.setMode(o,t.mode||"effect"),f=t.restore||"effect"!==p,m=t.scale||"both",g=t.origin||["middle","center"],v=o.css("position"),y=f?r:h,b={height:0,width:0,outerHeight:0,outerWidth:0};"show"===p&&o.show(),s={height:o.height(),width:o.width(),outerHeight:o.outerHeight(),outerWidth:o.outerWidth()},"toggle"===t.mode&&"show"===p?(o.from=t.to||b,o.to=t.from||s):(o.from=t.from||("show"===p?b:s),o.to=t.to||("hide"===p?b:s)),a={from:{y:o.from.height/s.height,x:o.from.width/s.width},to:{y:o.to.height/s.height,x:o.to.width/s.width}},("box"===m||"both"===m)&&(a.from.y!==a.to.y&&(y=y.concat(d),o.from=e.effects.setTransition(o,d,a.from.y,o.from),o.to=e.effects.setTransition(o,d,a.to.y,o.to)),a.from.x!==a.to.x&&(y=y.concat(c),o.from=e.effects.setTransition(o,c,a.from.x,o.from),o.to=e.effects.setTransition(o,c,a.to.x,o.to))),("content"===m||"both"===m)&&a.from.y!==a.to.y&&(y=y.concat(u).concat(l),o.from=e.effects.setTransition(o,u,a.from.y,o.from),o.to=e.effects.setTransition(o,u,a.to.y,o.to)),e.effects.save(o,y),o.show(),e.effects.createWrapper(o),o.css("overflow","hidden").css(o.from),g&&(n=e.effects.getBaseline(g,s),o.from.top=(s.outerHeight-o.outerHeight())*n.y,o.from.left=(s.outerWidth-o.outerWidth())*n.x,o.to.top=(s.outerHeight-o.to.outerHeight)*n.y,o.to.left=(s.outerWidth-o.to.outerWidth)*n.x),o.css(o.from),("content"===m||"both"===m)&&(d=d.concat(["marginTop","marginBottom"]).concat(u),c=c.concat(["marginLeft","marginRight"]),l=r.concat(d).concat(c),o.find("*[width]").each(function(){var i=e(this),s={height:i.height(),width:i.width(),outerHeight:i.outerHeight(),outerWidth:i.outerWidth()};
f&&e.effects.save(i,l),i.from={height:s.height*a.from.y,width:s.width*a.from.x,outerHeight:s.outerHeight*a.from.y,outerWidth:s.outerWidth*a.from.x},i.to={height:s.height*a.to.y,width:s.width*a.to.x,outerHeight:s.height*a.to.y,outerWidth:s.width*a.to.x},a.from.y!==a.to.y&&(i.from=e.effects.setTransition(i,d,a.from.y,i.from),i.to=e.effects.setTransition(i,d,a.to.y,i.to)),a.from.x!==a.to.x&&(i.from=e.effects.setTransition(i,c,a.from.x,i.from),i.to=e.effects.setTransition(i,c,a.to.x,i.to)),i.css(i.from),i.animate(i.to,t.duration,t.easing,function(){f&&e.effects.restore(i,l)})})),o.animate(o.to,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){0===o.to.opacity&&o.css("opacity",o.from.opacity),"hide"===p&&o.hide(),e.effects.restore(o,y),f||("static"===v?o.css({position:"relative",top:o.to.top,left:o.to.left}):e.each(["top","left"],function(e,t){o.css(t,function(t,i){var s=parseInt(i,10),n=e?o.to.left:o.to.top;return"auto"===i?n+"px":s+n+"px"})})),e.effects.removeWrapper(o),i()}})},e.effects.effect.scale=function(t,i){var s=e(this),n=e.extend(!0,{},t),a=e.effects.setMode(s,t.mode||"effect"),o=parseInt(t.percent,10)||(0===parseInt(t.percent,10)?0:"hide"===a?0:100),r=t.direction||"both",h=t.origin,l={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()},u={y:"horizontal"!==r?o/100:1,x:"vertical"!==r?o/100:1};n.effect="size",n.queue=!1,n.complete=i,"effect"!==a&&(n.origin=h||["middle","center"],n.restore=!0),n.from=t.from||("show"===a?{height:0,width:0,outerHeight:0,outerWidth:0}:l),n.to={height:l.height*u.y,width:l.width*u.x,outerHeight:l.outerHeight*u.y,outerWidth:l.outerWidth*u.x},n.fade&&("show"===a&&(n.from.opacity=0,n.to.opacity=1),"hide"===a&&(n.from.opacity=1,n.to.opacity=0)),s.effect(n)},e.effects.effect.puff=function(t,i){var s=e(this),n=e.effects.setMode(s,t.mode||"hide"),a="hide"===n,o=parseInt(t.percent,10)||150,r=o/100,h={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()};e.extend(t,{effect:"scale",queue:!1,fade:!0,mode:n,complete:i,percent:a?o:100,from:a?h:{height:h.height*r,width:h.width*r,outerHeight:h.outerHeight*r,outerWidth:h.outerWidth*r}}),s.effect(t)},e.effects.effect.pulsate=function(t,i){var s,n=e(this),a=e.effects.setMode(n,t.mode||"show"),o="show"===a,r="hide"===a,h=o||"hide"===a,l=2*(t.times||5)+(h?1:0),u=t.duration/l,d=0,c=n.queue(),p=c.length;for((o||!n.is(":visible"))&&(n.css("opacity",0).show(),d=1),s=1;l>s;s++)n.animate({opacity:d},u,t.easing),d=1-d;n.animate({opacity:d},u,t.easing),n.queue(function(){r&&n.hide(),i()}),p>1&&c.splice.apply(c,[1,0].concat(c.splice(p,l+1))),n.dequeue()},e.effects.effect.shake=function(t,i){var s,n=e(this),a=["position","top","bottom","left","right","height","width"],o=e.effects.setMode(n,t.mode||"effect"),r=t.direction||"left",h=t.distance||20,l=t.times||3,u=2*l+1,d=Math.round(t.duration/u),c="up"===r||"down"===r?"top":"left",p="up"===r||"left"===r,f={},m={},g={},v=n.queue(),y=v.length;for(e.effects.save(n,a),n.show(),e.effects.createWrapper(n),f[c]=(p?"-=":"+=")+h,m[c]=(p?"+=":"-=")+2*h,g[c]=(p?"-=":"+=")+2*h,n.animate(f,d,t.easing),s=1;l>s;s++)n.animate(m,d,t.easing).animate(g,d,t.easing);n.animate(m,d,t.easing).animate(f,d/2,t.easing).queue(function(){"hide"===o&&n.hide(),e.effects.restore(n,a),e.effects.removeWrapper(n),i()}),y>1&&v.splice.apply(v,[1,0].concat(v.splice(y,u+1))),n.dequeue()},e.effects.effect.slide=function(t,i){var s,n=e(this),a=["position","top","bottom","left","right","width","height"],o=e.effects.setMode(n,t.mode||"show"),r="show"===o,h=t.direction||"left",l="up"===h||"down"===h?"top":"left",u="up"===h||"left"===h,d={};e.effects.save(n,a),n.show(),s=t.distance||n["top"===l?"outerHeight":"outerWidth"](!0),e.effects.createWrapper(n).css({overflow:"hidden"}),r&&n.css(l,u?isNaN(s)?"-"+s:-s:s),d[l]=(r?u?"+=":"-=":u?"-=":"+=")+s,n.animate(d,{queue:!1,duration:t.duration,easing:t.easing,complete:function(){"hide"===o&&n.hide(),e.effects.restore(n,a),e.effects.removeWrapper(n),i()}})},e.effects.effect.transfer=function(t,i){var s=e(this),n=e(t.to),a="fixed"===n.css("position"),o=e("body"),r=a?o.scrollTop():0,h=a?o.scrollLeft():0,l=n.offset(),u={top:l.top-r,left:l.left-h,height:n.innerHeight(),width:n.innerWidth()},d=s.offset(),c=e("<div class='ui-effects-transfer'></div>").appendTo(document.body).addClass(t.className).css({top:d.top-r,left:d.left-h,height:s.innerHeight(),width:s.innerWidth(),position:a?"fixed":"absolute"}).animate(u,t.duration,t.easing,function(){c.remove(),i()})},e.widget("ui.progressbar",{version:"1.11.4",options:{max:100,value:0,change:null,complete:null},min:0,_create:function(){this.oldValue=this.options.value=this._constrainedValue(),this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min}),this.valueDiv=e("<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(e){return void 0===e?this.options.value:(this.options.value=this._constrainedValue(e),this._refreshValue(),void 0)},_constrainedValue:function(e){return void 0===e&&(e=this.options.value),this.indeterminate=e===!1,"number"!=typeof e&&(e=0),this.indeterminate?!1:Math.min(this.options.max,Math.max(this.min,e))},_setOptions:function(e){var t=e.value;delete e.value,this._super(e),this.options.value=this._constrainedValue(t),this._refreshValue()},_setOption:function(e,t){"max"===e&&(t=Math.max(this.min,t)),"disabled"===e&&this.element.toggleClass("ui-state-disabled",!!t).attr("aria-disabled",t),this._super(e,t)},_percentage:function(){return this.indeterminate?100:100*(this.options.value-this.min)/(this.options.max-this.min)},_refreshValue:function(){var t=this.options.value,i=this._percentage();this.valueDiv.toggle(this.indeterminate||t>this.min).toggleClass("ui-corner-right",t===this.options.max).width(i.toFixed(0)+"%"),this.element.toggleClass("ui-progressbar-indeterminate",this.indeterminate),this.indeterminate?(this.element.removeAttr("aria-valuenow"),this.overlayDiv||(this.overlayDiv=e("<div class='ui-progressbar-overlay'></div>").appendTo(this.valueDiv))):(this.element.attr({"aria-valuemax":this.options.max,"aria-valuenow":t}),this.overlayDiv&&(this.overlayDiv.remove(),this.overlayDiv=null)),this.oldValue!==t&&(this.oldValue=t,this._trigger("change")),t===this.options.max&&this._trigger("complete")}}),e.widget("ui.selectable",e.ui.mouse,{version:"1.11.4",options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch",selected:null,selecting:null,start:null,stop:null,unselected:null,unselecting:null},_create:function(){var t,i=this;this.element.addClass("ui-selectable"),this.dragged=!1,this.refresh=function(){t=e(i.options.filter,i.element[0]),t.addClass("ui-selectee"),t.each(function(){var t=e(this),i=t.offset();e.data(this,"selectable-item",{element:this,$element:t,left:i.left,top:i.top,right:i.left+t.outerWidth(),bottom:i.top+t.outerHeight(),startselected:!1,selected:t.hasClass("ui-selected"),selecting:t.hasClass("ui-selecting"),unselecting:t.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=t.addClass("ui-selectee"),this._mouseInit(),this.helper=e("<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(t){var i=this,s=this.options;this.opos=[t.pageX,t.pageY],this.options.disabled||(this.selectees=e(s.filter,this.element[0]),this._trigger("start",t),e(s.appendTo).append(this.helper),this.helper.css({left:t.pageX,top:t.pageY,width:0,height:0}),s.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var s=e.data(this,"selectable-item");s.startselected=!0,t.metaKey||t.ctrlKey||(s.$element.removeClass("ui-selected"),s.selected=!1,s.$element.addClass("ui-unselecting"),s.unselecting=!0,i._trigger("unselecting",t,{unselecting:s.element}))}),e(t.target).parents().addBack().each(function(){var s,n=e.data(this,"selectable-item");return n?(s=!t.metaKey&&!t.ctrlKey||!n.$element.hasClass("ui-selected"),n.$element.removeClass(s?"ui-unselecting":"ui-selected").addClass(s?"ui-selecting":"ui-unselecting"),n.unselecting=!s,n.selecting=s,n.selected=s,s?i._trigger("selecting",t,{selecting:n.element}):i._trigger("unselecting",t,{unselecting:n.element}),!1):void 0}))},_mouseDrag:function(t){if(this.dragged=!0,!this.options.disabled){var i,s=this,n=this.options,a=this.opos[0],o=this.opos[1],r=t.pageX,h=t.pageY;return a>r&&(i=r,r=a,a=i),o>h&&(i=h,h=o,o=i),this.helper.css({left:a,top:o,width:r-a,height:h-o}),this.selectees.each(function(){var i=e.data(this,"selectable-item"),l=!1;i&&i.element!==s.element[0]&&("touch"===n.tolerance?l=!(i.left>r||a>i.right||i.top>h||o>i.bottom):"fit"===n.tolerance&&(l=i.left>a&&r>i.right&&i.top>o&&h>i.bottom),l?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,s._trigger("selecting",t,{selecting:i.element}))):(i.selecting&&((t.metaKey||t.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),s._trigger("unselecting",t,{unselecting:i.element}))),i.selected&&(t.metaKey||t.ctrlKey||i.startselected||(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,s._trigger("unselecting",t,{unselecting:i.element})))))}),!1}},_mouseStop:function(t){var i=this;return this.dragged=!1,e(".ui-unselecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-unselecting"),s.unselecting=!1,s.startselected=!1,i._trigger("unselected",t,{unselected:s.element})}),e(".ui-selecting",this.element[0]).each(function(){var s=e.data(this,"selectable-item");s.$element.removeClass("ui-selecting").addClass("ui-selected"),s.selecting=!1,s.selected=!0,s.startselected=!0,i._trigger("selected",t,{selected:s.element})}),this._trigger("stop",t),this.helper.remove(),!1}}),e.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,change:null,close:null,focus:null,open:null,select:null},_create:function(){var e=this.element.uniqueId().attr("id");this.ids={element:e,button:e+"-button",menu:e+"-menu"},this._drawButton(),this._drawMenu(),this.options.disabled&&this.disable()},_drawButton:function(){var t=this;this.label=e("label[for='"+this.ids.element+"']").attr("for",this.ids.button),this._on(this.label,{click:function(e){this.button.focus(),e.preventDefault()}}),this.element.hide(),this.button=e("<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),e("<span>",{"class":"ui-icon "+this.options.icons.button}).prependTo(this.button),this.buttonText=e("<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(){t.menuItems||t._refreshMenu()}),this._hoverable(this.button),this._focusable(this.button)},_drawMenu:function(){var t=this;this.menu=e("<ul>",{"aria-hidden":"true","aria-labelledby":this.ids.button,id:this.ids.menu}),this.menuWrap=e("<div>",{"class":"ui-selectmenu-menu ui-front"}).append(this.menu).appendTo(this._appendTo()),this.menuInstance=this.menu.menu({role:"listbox",select:function(e,i){e.preventDefault(),t._setSelection(),t._select(i.item.data("ui-selectmenu-item"),e)},focus:function(e,i){var s=i.item.data("ui-selectmenu-item");null!=t.focusIndex&&s.index!==t.focusIndex&&(t._trigger("focus",e,{item:s}),t.isOpen||t._select(s,e)),t.focusIndex=s.index,t.button.attr("aria-activedescendant",t.menuItems.eq(s.index).attr("id"))}}).menu("instance"),this.menu.addClass("ui-corner-bottom").removeClass("ui-corner-all"),this.menuInstance._off(this.menu,"mouseleave"),this.menuInstance._closeOnDocumentClick=function(){return!1},this.menuInstance._isDivider=function(){return!1}},refresh:function(){this._refreshMenu(),this._setText(this.buttonText,this._getSelectedItem().text()),this.options.width||this._resizeButton()},_refreshMenu:function(){this.menu.empty();var e,t=this.element.find("option");t.length&&(this._parseOptions(t),this._renderMenu(this.menu,this.items),this.menuInstance.refresh(),this.menuItems=this.menu.find("li").not(".ui-selectmenu-optgroup"),e=this._getSelectedItem(),this.menuInstance.focus(null,e),this._setAria(e.data("ui-selectmenu-item")),this._setOption("disabled",this.element.prop("disabled")))},open:function(e){this.options.disabled||(this.menuItems?(this.menu.find(".ui-state-focus").removeClass("ui-state-focus"),this.menuInstance.focus(null,this._getSelectedItem())):this._refreshMenu(),this.isOpen=!0,this._toggleAttr(),this._resizeMenu(),this._position(),this._on(this.document,this._documentClick),this._trigger("open",e))},_position:function(){this.menuWrap.position(e.extend({of:this.button},this.options.position))},close:function(e){this.isOpen&&(this.isOpen=!1,this._toggleAttr(),this.range=null,this._off(this.document),this._trigger("close",e))},widget:function(){return this.button},menuWidget:function(){return this.menu},_renderMenu:function(t,i){var s=this,n="";e.each(i,function(i,a){a.optgroup!==n&&(e("<li>",{"class":"ui-selectmenu-optgroup ui-menu-divider"+(a.element.parent("optgroup").prop("disabled")?" ui-state-disabled":""),text:a.optgroup}).appendTo(t),n=a.optgroup),s._renderItemData(t,a)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-selectmenu-item",t)},_renderItem:function(t,i){var s=e("<li>");return i.disabled&&s.addClass("ui-state-disabled"),this._setText(s,i.label),s.appendTo(t)},_setText:function(e,t){t?e.text(t):e.html("&#160;")},_move:function(e,t){var i,s,n=".ui-menu-item";this.isOpen?i=this.menuItems.eq(this.focusIndex):(i=this.menuItems.eq(this.element[0].selectedIndex),n+=":not(.ui-state-disabled)"),s="first"===e||"last"===e?i["first"===e?"prevAll":"nextAll"](n).eq(-1):i[e+"All"](n).eq(0),s.length&&this.menuInstance.focus(t,s)},_getSelectedItem:function(){return this.menuItems.eq(this.element[0].selectedIndex)},_toggle:function(e){this[this.isOpen?"close":"open"](e)},_setSelection:function(){var e;this.range&&(window.getSelection?(e=window.getSelection(),e.removeAllRanges(),e.addRange(this.range)):this.range.select(),this.button.focus())},_documentClick:{mousedown:function(t){this.isOpen&&(e(t.target).closest(".ui-selectmenu-menu, #"+this.ids.button).length||this.close(t))}},_buttonEvents:{mousedown:function(){var e;window.getSelection?(e=window.getSelection(),e.rangeCount&&(this.range=e.getRangeAt(0))):this.range=document.selection.createRange()},click:function(e){this._setSelection(),this._toggle(e)},keydown:function(t){var i=!0;switch(t.keyCode){case e.ui.keyCode.TAB:case e.ui.keyCode.ESCAPE:this.close(t),i=!1;break;case e.ui.keyCode.ENTER:this.isOpen&&this._selectFocusedItem(t);break;case e.ui.keyCode.UP:t.altKey?this._toggle(t):this._move("prev",t);break;case e.ui.keyCode.DOWN:t.altKey?this._toggle(t):this._move("next",t);break;case e.ui.keyCode.SPACE:this.isOpen?this._selectFocusedItem(t):this._toggle(t);break;case e.ui.keyCode.LEFT:this._move("prev",t);break;case e.ui.keyCode.RIGHT:this._move("next",t);break;case e.ui.keyCode.HOME:case e.ui.keyCode.PAGE_UP:this._move("first",t);break;case e.ui.keyCode.END:case e.ui.keyCode.PAGE_DOWN:this._move("last",t);break;default:this.menu.trigger(t),i=!1}i&&t.preventDefault()}},_selectFocusedItem:function(e){var t=this.menuItems.eq(this.focusIndex);t.hasClass("ui-state-disabled")||this._select(t.data("ui-selectmenu-item"),e)},_select:function(e,t){var i=this.element[0].selectedIndex;this.element[0].selectedIndex=e.index,this._setText(this.buttonText,e.label),this._setAria(e),this._trigger("select",t,{item:e}),e.index!==i&&this._trigger("change",t,{item:e}),this.close(t)},_setAria:function(e){var t=this.menuItems.eq(e.index).attr("id");this.button.attr({"aria-labelledby":t,"aria-activedescendant":t}),this.menu.attr("aria-activedescendant",t)},_setOption:function(e,t){"icons"===e&&this.button.find("span.ui-icon").removeClass(this.options.icons.button).addClass(t.button),this._super(e,t),"appendTo"===e&&this.menuWrap.appendTo(this._appendTo()),"disabled"===e&&(this.menuInstance.option("disabled",t),this.button.toggleClass("ui-state-disabled",t).attr("aria-disabled",t),this.element.prop("disabled",t),t?(this.button.attr("tabindex",-1),this.close()):this.button.attr("tabindex",0)),"width"===e&&this._resizeButton()},_appendTo:function(){var t=this.options.appendTo;return t&&(t=t.jquery||t.nodeType?e(t):this.document.find(t).eq(0)),t&&t[0]||(t=this.element.closest(".ui-front")),t.length||(t=this.document[0].body),t},_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 e=this.options.width;e||(e=this.element.show().outerWidth(),this.element.hide()),this.button.outerWidth(e)},_resizeMenu:function(){this.menu.outerWidth(Math.max(this.button.outerWidth(),this.menu.width("").outerWidth()+1))},_getCreateOptions:function(){return{disabled:this.element.prop("disabled")}},_parseOptions:function(t){var i=[];t.each(function(t,s){var n=e(s),a=n.parent("optgroup");i.push({element:n,index:t,value:n.val(),label:n.text(),optgroup:a.attr("label")||"",disabled:a.prop("disabled")||n.prop("disabled")})}),this.items=i},_destroy:function(){this.menuWrap.remove(),this.button.remove(),this.element.show(),this.element.removeUniqueId(),this.label.attr("for",this.ids.element)}}),e.widget("ui.slider",e.ui.mouse,{version:"1.11.4",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},numPages:5,_create:function(){this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,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=!1},_refresh:function(){this._createRange(),this._createHandles(),this._setupEvents(),this._refreshValue()},_createHandles:function(){var t,i,s=this.options,n=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),a="<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>",o=[];for(i=s.values&&s.values.length||1,n.length>i&&(n.slice(i).remove(),n=n.slice(0,i)),t=n.length;i>t;t++)o.push(a);this.handles=n.add(e(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)})},_createRange:function(){var t=this.options,i="";t.range?(t.range===!0&&(t.values?t.values.length&&2!==t.values.length?t.values=[t.values[0],t.values[0]]:e.isArray(t.values)&&(t.values=t.values.slice(0)):t.values=[this._valueMin(),this._valueMin()]),this.range&&this.range.length?this.range.removeClass("ui-slider-range-min ui-slider-range-max").css({left:"",bottom:""}):(this.range=e("<div></div>").appendTo(this.element),i="ui-slider-range ui-widget-header ui-corner-all"),this.range.addClass(i+("min"===t.range||"max"===t.range?" ui-slider-range-"+t.range:""))):(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(),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(t){var i,s,n,a,o,r,h,l,u=this,d=this.options;return d.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),i={x:t.pageX,y:t.pageY},s=this._normValueFromMouse(i),n=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var i=Math.abs(s-u.values(t));(n>i||n===i&&(t===u._lastChangedValue||u.values(t)===d.min))&&(n=i,a=e(this),o=t)}),r=this._start(t,o),r===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,a.addClass("ui-state-active").focus(),h=a.offset(),l=!e(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:t.pageX-h.left-a.width()/2,top:t.pageY-h.top-a.height()/2-(parseInt(a.css("borderTopWidth"),10)||0)-(parseInt(a.css("borderBottomWidth"),10)||0)+(parseInt(a.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,s),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},i=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,i),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation="vertical"===this.options.orientation?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,i,s,n,a;return"horizontal"===this.orientation?(t=this.elementSize.width,i=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,i=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),s=i/t,s>1&&(s=1),0>s&&(s=0),"vertical"===this.orientation&&(s=1-s),n=this._valueMax()-this._valueMin(),a=this._valueMin()+s*n,this._trimAlignValue(a)},_start:function(e,t){var i={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._trigger("start",e,i)},_slide:function(e,t,i){var s,n,a;this.options.values&&this.options.values.length?(s=this.values(t?0:1),2===this.options.values.length&&this.options.range===!0&&(0===t&&i>s||1===t&&s>i)&&(i=s),i!==this.values(t)&&(n=this.values(),n[t]=i,a=this._trigger("slide",e,{handle:this.handles[t],value:i,values:n}),s=this.values(t?0:1),a!==!1&&this.values(t,i))):i!==this.value()&&(a=this._trigger("slide",e,{handle:this.handles[t],value:i}),a!==!1&&this.value(i))},_stop:function(e,t){var i={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._trigger("stop",e,i)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var i={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(i.value=this.values(t),i.values=this.values()),this._lastChangedValue=t,this._trigger("change",e,i)}},value:function(e){return arguments.length?(this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0),void 0):this._value()},values:function(t,i){var s,n,a;if(arguments.length>1)return this.options.values[t]=this._trimAlignValue(i),this._refreshValue(),this._change(null,t),void 0;if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();for(s=this.options.values,n=arguments[0],a=0;s.length>a;a+=1)s[a]=this._trimAlignValue(n[a]),this._change(null,a);this._refreshValue()},_setOption:function(t,i){var s,n=0;switch("range"===t&&this.options.range===!0&&("min"===i?(this.options.value=this._values(0),this.options.values=null):"max"===i&&(this.options.value=this._values(this.options.values.length-1),this.options.values=null)),e.isArray(this.options.values)&&(n=this.options.values.length),"disabled"===t&&this.element.toggleClass("ui-state-disabled",!!i),this._super(t,i),t){case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue(),this.handles.css("horizontal"===i?"bottom":"left","");break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":for(this._animateOff=!0,this._refreshValue(),s=0;n>s;s+=1)this._change(null,s);this._animateOff=!1;break;case"step":case"min":case"max":this._animateOff=!0,this._calculateNewMax(),this._refreshValue(),this._animateOff=!1;break;case"range":this._animateOff=!0,this._refresh(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e)},_values:function(e){var t,i,s;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t);if(this.options.values&&this.options.values.length){for(i=this.options.values.slice(),s=0;i.length>s;s+=1)i[s]=this._trimAlignValue(i[s]);return i}return[]},_trimAlignValue:function(e){if(this._valueMin()>=e)return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,i=(e-this._valueMin())%t,s=e-i;return 2*Math.abs(i)>=t&&(s+=i>0?t:-t),parseFloat(s.toFixed(5))},_calculateNewMax:function(){var e=this.options.max,t=this._valueMin(),i=this.options.step,s=Math.floor(+(e-t).toFixed(this._precision())/i)*i;e=s+t,this.max=parseFloat(e.toFixed(this._precision()))},_precision:function(){var e=this._precisionOf(this.options.step);return null!==this.options.min&&(e=Math.max(e,this._precisionOf(this.options.min))),e},_precisionOf:function(e){var t=""+e,i=t.indexOf(".");return-1===i?0:t.length-i-1},_valueMin:function(){return this.options.min},_valueMax:function(){return this.max},_refreshValue:function(){var t,i,s,n,a,o=this.options.range,r=this.options,h=this,l=this._animateOff?!1:r.animate,u={};this.options.values&&this.options.values.length?this.handles.each(function(s){i=100*((h.values(s)-h._valueMin())/(h._valueMax()-h._valueMin())),u["horizontal"===h.orientation?"left":"bottom"]=i+"%",e(this).stop(1,1)[l?"animate":"css"](u,r.animate),h.options.range===!0&&("horizontal"===h.orientation?(0===s&&h.range.stop(1,1)[l?"animate":"css"]({left:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({width:i-t+"%"},{queue:!1,duration:r.animate})):(0===s&&h.range.stop(1,1)[l?"animate":"css"]({bottom:i+"%"},r.animate),1===s&&h.range[l?"animate":"css"]({height:i-t+"%"},{queue:!1,duration:r.animate}))),t=i}):(s=this.value(),n=this._valueMin(),a=this._valueMax(),i=a!==n?100*((s-n)/(a-n)):0,u["horizontal"===this.orientation?"left":"bottom"]=i+"%",this.handle.stop(1,1)[l?"animate":"css"](u,r.animate),"min"===o&&"horizontal"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({width:i+"%"},r.animate),"max"===o&&"horizontal"===this.orientation&&this.range[l?"animate":"css"]({width:100-i+"%"},{queue:!1,duration:r.animate}),"min"===o&&"vertical"===this.orientation&&this.range.stop(1,1)[l?"animate":"css"]({height:i+"%"},r.animate),"max"===o&&"vertical"===this.orientation&&this.range[l?"animate":"css"]({height:100-i+"%"},{queue:!1,duration:r.animate}))},_handleEvents:{keydown:function(t){var i,s,n,a,o=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(t.preventDefault(),!this._keySliding&&(this._keySliding=!0,e(t.target).addClass("ui-state-active"),i=this._start(t,o),i===!1))return}switch(a=this.options.step,s=n=this.options.values&&this.options.values.length?this.values(o):this.value(),t.keyCode){case e.ui.keyCode.HOME:n=this._valueMin();break;case e.ui.keyCode.END:n=this._valueMax();break;case e.ui.keyCode.PAGE_UP:n=this._trimAlignValue(s+(this._valueMax()-this._valueMin())/this.numPages);break;case e.ui.keyCode.PAGE_DOWN:n=this._trimAlignValue(s-(this._valueMax()-this._valueMin())/this.numPages);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(s===this._valueMax())return;n=this._trimAlignValue(s+a);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(s===this._valueMin())return;n=this._trimAlignValue(s-a)}this._slide(t,o,n)},keyup:function(t){var i=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,i),this._change(t,i),e(t.target).removeClass("ui-state-active"))}}}),e.widget("ui.sortable",e.ui.mouse,{version:"1.11.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,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(e,t,i){return e>=t&&t+i>e},_isFloating:function(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))},_create:function(){this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(e,t){this._super(e,t),"handle"===e&&this._setHandleClassName()},_setHandleClassName:function(){this.element.find(".ui-sortable-handle").removeClass("ui-sortable-handle"),e.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 e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(t,i){var s=null,n=!1,a=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(t),e(t.target).parents().each(function(){return e.data(this,a.widgetName+"-item")===a?(s=e(this),!1):void 0}),e.data(t.target,a.widgetName+"-item")===a&&(s=e(t.target)),s?!this.options.handle||i||(e(this.options.handle,s).find("*").addBack().each(function(){this===t.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(t,i,s){var n,a,o=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(a=this.document.find("body"),this.storedCursor=a.css("cursor"),a.css("cursor",o.cursor),this.storedStylesheet=e("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(a)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",t,this._uiHash(this));
return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var i,s,n,a,o=this.options,r=!1;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+o.scrollSpeed:t.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+o.scrollSpeed:t.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(t.pageY-this.document.scrollTop()<o.scrollSensitivity?r=this.document.scrollTop(this.document.scrollTop()-o.scrollSpeed):this.window.height()-(t.pageY-this.document.scrollTop())<o.scrollSensitivity&&(r=this.document.scrollTop(this.document.scrollTop()+o.scrollSpeed)),t.pageX-this.document.scrollLeft()<o.scrollSensitivity?r=this.document.scrollLeft(this.document.scrollLeft()-o.scrollSpeed):this.window.width()-(t.pageX-this.document.scrollLeft())<o.scrollSensitivity&&(r=this.document.scrollLeft(this.document.scrollLeft()+o.scrollSpeed))),r!==!1&&e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)),this.positionAbs=this._convertPositionTo("absolute"),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"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],a=this._intersectsWithPointer(s),a&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===a?"next":"prev"]()[0]!==n&&!e.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],n):!0)){if(this.direction=1===a?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(t,s),this._trigger("change",t,this._uiHash());break}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,i){if(t){if(e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t),this.options.revert){var s=this,n=this.placeholder.offset(),a=this.options.axis,o={};a&&"x"!==a||(o.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),a&&"y"!==a||(o.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,e(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){s._clear(t)})}else this._clear(t,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},e(i).each(function(){var i=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);i&&s.push((t.key||i[1]+"[]")+"="+(t.key&&t.expression?i[1]:i[2]))}),!s.length&&t.key&&s.push(t.key+"="),s.join("&")},toArray:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},i.each(function(){s.push(e(t.item||this).attr(t.attribute||"id")||"")}),s},_intersectsWith:function(e){var t=this.positionAbs.left,i=t+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,a=e.left,o=a+e.width,r=e.top,h=r+e.height,l=this.offset.click.top,u=this.offset.click.left,d="x"===this.options.axis||s+l>r&&h>s+l,c="y"===this.options.axis||t+u>a&&o>t+u,p=d&&c;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?p:t+this.helperProportions.width/2>a&&o>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(e){var t="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),i="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),s=t&&i,n=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return s?this.floating?a&&"right"===a||"down"===n?2:1:n&&("down"===n?2:1):!1},_intersectsWithSides:function(e){var t=this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&t||"up"===s&&!t)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){function i(){r.push(this)}var s,n,a,o,r=[],h=[],l=this._connectWith();if(l&&t)for(s=l.length-1;s>=0;s--)for(a=e(l[s],this.document[0]),n=a.length-1;n>=0;n--)o=e.data(a[n],this.widgetFullName),o&&o!==this&&!o.options.disabled&&h.push([e.isFunction(o.options.items)?o.options.items.call(o.element):e(o.options.items,o.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),o]);for(h.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return e(r)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var i=0;t.length>i;i++)if(t[i]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var i,s,n,a,o,r,h,l,u=this.items,d=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],c=this._connectWith();if(c&&this.ready)for(i=c.length-1;i>=0;i--)for(n=e(c[i],this.document[0]),s=n.length-1;s>=0;s--)a=e.data(n[s],this.widgetFullName),a&&a!==this&&!a.options.disabled&&(d.push([e.isFunction(a.options.items)?a.options.items.call(a.element[0],t,{item:this.currentItem}):e(a.options.items,a.element),a]),this.containers.push(a));for(i=d.length-1;i>=0;i--)for(o=d[i][1],r=d[i][0],s=0,l=r.length;l>s;s++)h=e(r[s]),h.data(this.widgetName+"-item",o),u.push({item:h,instance:o,width:0,height:0,left:0,top:0})},refreshPositions:function(t){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,a;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?e(this.options.toleranceElement,s.item):s.item,t||(s.width=n.outerWidth(),s.height=n.outerHeight()),a=n.offset(),s.left=a.left,s.top=a.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--)a=this.containers[i].element.offset(),this.containers[i].containerCache.left=a.left,this.containers[i].containerCache.top=a.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(t){t=t||this;var i,s=t.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=t.currentItem[0].nodeName.toLowerCase(),n=e("<"+s+">",t.document[0]).addClass(i||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tbody"===s?t._createTrPlaceholder(t.currentItem.find("tr").eq(0),e("<tr>",t.document[0]).appendTo(n)):"tr"===s?t._createTrPlaceholder(t.currentItem,n):"img"===s&&n.attr("src",t.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(e,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10)))}}),t.placeholder=e(s.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),s.placeholder.update(t,t.placeholder)},_createTrPlaceholder:function(t,i){var s=this;t.children().each(function(){e("<td>&#160;</td>",s.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(t){var i,s,n,a,o,r,h,l,u,d,c=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!e.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(c&&e.contains(this.containers[i].element[0],c.element[0]))continue;c=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0);if(c)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,a=null,u=c.floating||this._isFloating(this.currentItem),o=u?"left":"top",r=u?"width":"height",d=u?"clientX":"clientY",s=this.items.length-1;s>=0;s--)e.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[o],l=!1,t[d]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(t[d]-h)&&(n=Math.abs(t[d]-h),a=this.items[s],this.direction=l?"up":"down"));if(!a&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",t,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;a?this._rearrange(t,a,null,!0):this._rearrange(t,null,this.containers[p].element,!0),this._trigger("change",t,this._uiHash()),this.containers[p]._trigger("change",t,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||e("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[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")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),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(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].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.currentItem.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.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 t,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.width():this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(t=e(n.containment)[0],i=e(n.containment).offset(),s="hidden"!==e(t).css("overflow"),this.containment=[i.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(t,i){i||(i=this.position);var s="absolute"===t?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():a?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():a?0:n.scrollLeft())*s}},_generatePosition:function(t){var i,s,n=this.options,a=t.pageX,o=t.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(a=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(o=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(a=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1],o=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((a-this.originalPageX)/n.grid[0])*n.grid[0],a=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:a-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(e,t,i,s){i?i[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(e,t){function i(e,t,i){return function(s){i._trigger(e,s,t._uiHash(t))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!t&&n.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||t||n.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(t||(n.push(function(e){this._trigger("remove",e,this._uiHash())}),n.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)t||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,t||this._trigger("beforeStop",e,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!t){for(s=0;n.length>s;s++)n[s].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var i=t||this;return{helper:i.helper,placeholder:i.placeholder||e([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:t?t.element:null}}}),e.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:!0,max:null,min:null,numberFormat:null,page:10,step:1,change:null,spin:null,start:null,stop:null},_create:function(){this._setOption("max",this.options.max),this._setOption("min",this.options.min),this._setOption("step",this.options.step),""!==this.value()&&this._value(this.element.val(),!0),this._draw(),this._on(this._events),this._refresh(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_getCreateOptions:function(){var t={},i=this.element;return e.each(["min","max","step"],function(e,s){var n=i.attr(s);void 0!==n&&n.length&&(t[s]=n)}),t},_events:{keydown:function(e){this._start(e)&&this._keydown(e)&&e.preventDefault()},keyup:"_stop",focus:function(){this.previous=this.element.val()},blur:function(e){return this.cancelBlur?(delete this.cancelBlur,void 0):(this._stop(),this._refresh(),this.previous!==this.element.val()&&this._trigger("change",e),void 0)},mousewheel:function(e,t){if(t){if(!this.spinning&&!this._start(e))return!1;this._spin((t>0?1:-1)*this.options.step,e),clearTimeout(this.mousewheelTimer),this.mousewheelTimer=this._delay(function(){this.spinning&&this._stop(e)},100),e.preventDefault()}},"mousedown .ui-spinner-button":function(t){function i(){var e=this.element[0]===this.document[0].activeElement;e||(this.element.focus(),this.previous=s,this._delay(function(){this.previous=s}))}var s;s=this.element[0]===this.document[0].activeElement?this.previous:this.element.val(),t.preventDefault(),i.call(this),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur,i.call(this)}),this._start(t)!==!1&&this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t)},"mouseup .ui-spinner-button":"_stop","mouseenter .ui-spinner-button":function(t){return e(t.currentTarget).hasClass("ui-state-active")?this._start(t)===!1?!1:(this._repeat(null,e(t.currentTarget).hasClass("ui-spinner-up")?1:-1,t),void 0):void 0},"mouseleave .ui-spinner-button":"_stop"},_draw:function(){var e=this.uiSpinner=this.element.addClass("ui-spinner-input").attr("autocomplete","off").wrap(this._uiSpinnerHtml()).parent().append(this._buttonHtml());this.element.attr("role","spinbutton"),this.buttons=e.find(".ui-spinner-button").attr("tabIndex",-1).button().removeClass("ui-corner-all"),this.buttons.height()>Math.ceil(.5*e.height())&&e.height()>0&&e.height(e.height()),this.options.disabled&&this.disable()},_keydown:function(t){var i=this.options,s=e.ui.keyCode;switch(t.keyCode){case s.UP:return this._repeat(null,1,t),!0;case s.DOWN:return this._repeat(null,-1,t),!0;case s.PAGE_UP:return this._repeat(null,i.page,t),!0;case s.PAGE_DOWN:return this._repeat(null,-i.page,t),!0}return!1},_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(e){return this.spinning||this._trigger("start",e)!==!1?(this.counter||(this.counter=1),this.spinning=!0,!0):!1},_repeat:function(e,t,i){e=e||500,clearTimeout(this.timer),this.timer=this._delay(function(){this._repeat(40,t,i)},e),this._spin(t*this.options.step,i)},_spin:function(e,t){var i=this.value()||0;this.counter||(this.counter=1),i=this._adjustValue(i+e*this._increment(this.counter)),this.spinning&&this._trigger("spin",t,{value:i})===!1||(this._value(i),this.counter++)},_increment:function(t){var i=this.options.incremental;return i?e.isFunction(i)?i(t):Math.floor(t*t*t/5e4-t*t/500+17*t/200+1):1},_precision:function(){var e=this._precisionOf(this.options.step);return null!==this.options.min&&(e=Math.max(e,this._precisionOf(this.options.min))),e},_precisionOf:function(e){var t=""+e,i=t.indexOf(".");return-1===i?0:t.length-i-1},_adjustValue:function(e){var t,i,s=this.options;return t=null!==s.min?s.min:0,i=e-t,i=Math.round(i/s.step)*s.step,e=t+i,e=parseFloat(e.toFixed(this._precision())),null!==s.max&&e>s.max?s.max:null!==s.min&&s.min>e?s.min:e},_stop:function(e){this.spinning&&(clearTimeout(this.timer),clearTimeout(this.mousewheelTimer),this.counter=0,this.spinning=!1,this._trigger("stop",e))},_setOption:function(e,t){if("culture"===e||"numberFormat"===e){var i=this._parse(this.element.val());return this.options[e]=t,this.element.val(this._format(i)),void 0}("max"===e||"min"===e||"step"===e)&&"string"==typeof t&&(t=this._parse(t)),"icons"===e&&(this.buttons.first().find(".ui-icon").removeClass(this.options.icons.up).addClass(t.up),this.buttons.last().find(".ui-icon").removeClass(this.options.icons.down).addClass(t.down)),this._super(e,t),"disabled"===e&&(this.widget().toggleClass("ui-state-disabled",!!t),this.element.prop("disabled",!!t),this.buttons.button(t?"disable":"enable"))},_setOptions:h(function(e){this._super(e)}),_parse:function(e){return"string"==typeof e&&""!==e&&(e=window.Globalize&&this.options.numberFormat?Globalize.parseFloat(e,10,this.options.culture):+e),""===e||isNaN(e)?null:e},_format:function(e){return""===e?"":window.Globalize&&this.options.numberFormat?Globalize.format(e,this.options.numberFormat,this.options.culture):e},_refresh:function(){this.element.attr({"aria-valuemin":this.options.min,"aria-valuemax":this.options.max,"aria-valuenow":this._parse(this.element.val())})},isValid:function(){var e=this.value();return null===e?!1:e===this._adjustValue(e)},_value:function(e,t){var i;""!==e&&(i=this._parse(e),null!==i&&(t||(i=this._adjustValue(i)),e=this._format(i))),this.element.val(e),this._refresh()},_destroy:function(){this.element.removeClass("ui-spinner-input").prop("disabled",!1).removeAttr("autocomplete").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.uiSpinner.replaceWith(this.element)},stepUp:h(function(e){this._stepUp(e)}),_stepUp:function(e){this._start()&&(this._spin((e||1)*this.options.step),this._stop())},stepDown:h(function(e){this._stepDown(e)}),_stepDown:function(e){this._start()&&(this._spin((e||1)*-this.options.step),this._stop())},pageUp:h(function(e){this._stepUp((e||1)*this.options.page)}),pageDown:h(function(e){this._stepDown((e||1)*this.options.page)}),value:function(e){return arguments.length?(h(this._value).call(this,e),void 0):this._parse(this.element.val())},widget:function(){return this.uiSpinner}}),e.widget("ui.tabs",{version:"1.11.4",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_isLocal:function(){var e=/#.*$/;return function(t){var i,s;t=t.cloneNode(!1),i=t.href.replace(e,""),s=location.href.replace(e,"");try{i=decodeURIComponent(i)}catch(n){}try{s=decodeURIComponent(s)}catch(n){}return t.hash.length>1&&i===s}}(),_create:function(){var t=this,i=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",i.collapsible),this._processTabs(),i.active=this._initialActive(),e.isArray(i.disabled)&&(i.disabled=e.unique(i.disabled.concat(e.map(this.tabs.filter(".ui-state-disabled"),function(e){return t.tabs.index(e)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):e(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var t=this.options.active,i=this.options.collapsible,s=location.hash.substring(1);return null===t&&(s&&this.tabs.each(function(i,n){return e(n).attr("aria-controls")===s?(t=i,!1):void 0}),null===t&&(t=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===t||-1===t)&&(t=this.tabs.length?0:!1)),t!==!1&&(t=this.tabs.index(this.tabs.eq(t)),-1===t&&(t=i?!1:0)),!i&&t===!1&&this.anchors.length&&(t=0),t},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):e()}},_tabKeydown:function(t){var i=e(this.document[0].activeElement).closest("li"),s=this.tabs.index(i),n=!0;if(!this._handlePageNav(t)){switch(t.keyCode){case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:s++;break;case e.ui.keyCode.UP:case e.ui.keyCode.LEFT:n=!1,s--;break;case e.ui.keyCode.END:s=this.anchors.length-1;break;case e.ui.keyCode.HOME:s=0;break;case e.ui.keyCode.SPACE:return t.preventDefault(),clearTimeout(this.activating),this._activate(s),void 0;case e.ui.keyCode.ENTER:return t.preventDefault(),clearTimeout(this.activating),this._activate(s===this.options.active?!1:s),void 0;default:return}t.preventDefault(),clearTimeout(this.activating),s=this._focusNextTab(s,n),t.ctrlKey||t.metaKey||(i.attr("aria-selected","false"),this.tabs.eq(s).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",s)},this.delay))}},_panelKeydown:function(t){this._handlePageNav(t)||t.ctrlKey&&t.keyCode===e.ui.keyCode.UP&&(t.preventDefault(),this.active.focus())},_handlePageNav:function(t){return t.altKey&&t.keyCode===e.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):t.altKey&&t.keyCode===e.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):void 0},_findNextTab:function(t,i){function s(){return t>n&&(t=0),0>t&&(t=n),t}for(var n=this.tabs.length-1;-1!==e.inArray(s(),this.options.disabled);)t=i?t+1:t-1;return t},_focusNextTab:function(e,t){return e=this._findNextTab(e,t),this.tabs.eq(e).focus(),e},_setOption:function(e,t){return"active"===e?(this._activate(t),void 0):"disabled"===e?(this._setupDisabled(t),void 0):(this._super(e,t),"collapsible"===e&&(this.element.toggleClass("ui-tabs-collapsible",t),t||this.options.active!==!1||this._activate(0)),"event"===e&&this._setupEvents(t),"heightStyle"===e&&this._setupHeightStyle(t),void 0)},_sanitizeSelector:function(e){return e?e.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,i=this.tablist.children(":has(a[href])");t.disabled=e.map(i.filter(".ui-state-disabled"),function(e){return i.index(e)}),this._processTabs(),t.active!==!1&&this.anchors.length?this.active.length&&!e.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=e()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active):(t.active=!1,this.active=e()),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"}),this.active.length?(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"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var t=this,i=this.tabs,s=this.anchors,n=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").delegate("> li","mousedown"+this.eventNamespace,function(t){e(this).is(".ui-state-disabled")&&t.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){e(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 e("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=e(),this.anchors.each(function(i,s){var n,a,o,r=e(s).uniqueId().attr("id"),h=e(s).closest("li"),l=h.attr("aria-controls");t._isLocal(s)?(n=s.hash,o=n.substring(1),a=t.element.find(t._sanitizeSelector(n))):(o=h.attr("aria-controls")||e({}).uniqueId()[0].id,n="#"+o,a=t.element.find(n),a.length||(a=t._createPanel(o),a.insertAfter(t.panels[i-1]||t.tablist)),a.attr("aria-live","polite")),a.length&&(t.panels=t.panels.add(a)),l&&h.data("ui-tabs-aria-controls",l),h.attr({"aria-controls":o,"aria-labelledby":r}),a.attr("aria-labelledby",r)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel"),i&&(this._off(i.not(this.tabs)),this._off(s.not(this.anchors)),this._off(n.not(this.panels)))},_getList:function(){return this.tablist||this.element.find("ol,ul").eq(0)},_createPanel:function(t){return e("<div>").attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(t){e.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1);for(var i,s=0;i=this.tabs[s];s++)t===!0||-1!==e.inArray(s,t)?e(i).addClass("ui-state-disabled").attr("aria-disabled","true"):e(i).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=t},_setupEvents:function(t){var i={};t&&e.each(t.split(" "),function(e,t){i[t]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(!0,this.anchors,{click:function(e){e.preventDefault()}}),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var i,s=this.element.parent();"fill"===t?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var t=e(this),s=t.css("position");"absolute"!==s&&"fixed"!==s&&(i-=t.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=e(this).outerHeight(!0)}),this.panels.each(function(){e(this).height(Math.max(0,i-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):"auto"===t&&(i=0,this.panels.each(function(){i=Math.max(i,e(this).height("").height())}).height(i))},_eventHandler:function(t){var i=this.options,s=this.active,n=e(t.currentTarget),a=n.closest("li"),o=a[0]===s[0],r=o&&i.collapsible,h=r?e():this._getPanelForTab(a),l=s.length?this._getPanelForTab(s):e(),u={oldTab:s,oldPanel:l,newTab:r?e():a,newPanel:h};t.preventDefault(),a.hasClass("ui-state-disabled")||a.hasClass("ui-tabs-loading")||this.running||o&&!i.collapsible||this._trigger("beforeActivate",t,u)===!1||(i.active=r?!1:this.tabs.index(a),this.active=o?e():a,this.xhr&&this.xhr.abort(),l.length||h.length||e.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(a),t),this._toggle(t,u))},_toggle:function(t,i){function s(){a.running=!1,a._trigger("activate",t,i)}function n(){i.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),o.length&&a.options.show?a._show(o,a.options.show,s):(o.show(),s())}var a=this,o=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),n()}):(i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),r.hide(),n()),r.attr("aria-hidden","true"),i.oldTab.attr({"aria-selected":"false","aria-expanded":"false"}),o.length&&r.length?i.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return 0===e(this).attr("tabIndex")}).attr("tabIndex",-1),o.attr("aria-hidden","false"),i.newTab.attr({"aria-selected":"true","aria-expanded":"true",tabIndex:0})},_activate:function(t){var i,s=this._findActive(t);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:e.noop}))},_findActive:function(t){return t===!1?e():this.tabs.eq(t)},_getIndex:function(e){return"string"==typeof e&&(e=this.anchors.index(this.anchors.filter("[href$='"+e+"']"))),e},_destroy:function(){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(){e.data(this,"ui-tabs-destroy")?e(this).remove():e(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 t=e(this),i=t.data("ui-tabs-aria-controls");i?t.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):t.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(t){var i=this.options.disabled;i!==!1&&(void 0===t?i=!1:(t=this._getIndex(t),i=e.isArray(i)?e.map(i,function(e){return e!==t?e:null}):e.map(this.tabs,function(e,i){return i!==t?i:null})),this._setupDisabled(i))},disable:function(t){var i=this.options.disabled;if(i!==!0){if(void 0===t)i=!0;else{if(t=this._getIndex(t),-1!==e.inArray(t,i))return;i=e.isArray(i)?e.merge([t],i).sort():[t]}this._setupDisabled(i)}},load:function(t,i){t=this._getIndex(t);var s=this,n=this.tabs.eq(t),a=n.find(".ui-tabs-anchor"),o=this._getPanelForTab(n),r={tab:n,panel:o},h=function(e,t){"abort"===t&&s.panels.stop(!1,!0),n.removeClass("ui-tabs-loading"),o.removeAttr("aria-busy"),e===s.xhr&&delete s.xhr};this._isLocal(a[0])||(this.xhr=e.ajax(this._ajaxSettings(a,i,r)),this.xhr&&"canceled"!==this.xhr.statusText&&(n.addClass("ui-tabs-loading"),o.attr("aria-busy","true"),this.xhr.done(function(e,t,n){setTimeout(function(){o.html(e),s._trigger("load",i,r),h(n,t)},1)}).fail(function(e,t){setTimeout(function(){h(e,t)},1)})))},_ajaxSettings:function(t,i,s){var n=this;return{url:t.attr("href"),beforeSend:function(t,a){return n._trigger("beforeLoad",i,e.extend({jqXHR:t,ajaxSettings:a},s))}}},_getPanelForTab:function(t){var i=e(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}}),e.widget("ui.tooltip",{version:"1.11.4",options:{content:function(){var t=e(this).attr("title")||"";return e("<a>").text(t).html()},hide:!0,items:"[title]:not([disabled])",position:{my:"left top+15",at:"left bottom",collision:"flipfit flip"},show:!0,tooltipClass:null,track:!1,close:null,open:null},_addDescribedBy:function(t,i){var s=(t.attr("aria-describedby")||"").split(/\s+/);s.push(i),t.data("ui-tooltip-id",i).attr("aria-describedby",e.trim(s.join(" ")))},_removeDescribedBy:function(t){var i=t.data("ui-tooltip-id"),s=(t.attr("aria-describedby")||"").split(/\s+/),n=e.inArray(i,s);-1!==n&&s.splice(n,1),t.removeData("ui-tooltip-id"),s=e.trim(s.join(" ")),s?t.attr("aria-describedby",s):t.removeAttr("aria-describedby")},_create:function(){this._on({mouseover:"open",focusin:"open"}),this.tooltips={},this.parents={},this.options.disabled&&this._disable(),this.liveRegion=e("<div>").attr({role:"log","aria-live":"assertive","aria-relevant":"additions"}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body)},_setOption:function(t,i){var s=this;return"disabled"===t?(this[i?"_disable":"_enable"](),this.options[t]=i,void 0):(this._super(t,i),"content"===t&&e.each(this.tooltips,function(e,t){s._updateContent(t.element)}),void 0)},_disable:function(){var t=this;e.each(this.tooltips,function(i,s){var n=e.Event("blur");n.target=n.currentTarget=s.element[0],t.close(n,!0)}),this.element.find(this.options.items).addBack().each(function(){var t=e(this);t.is("[title]")&&t.data("ui-tooltip-title",t.attr("title")).removeAttr("title")})},_enable:function(){this.element.find(this.options.items).addBack().each(function(){var t=e(this);t.data("ui-tooltip-title")&&t.attr("title",t.data("ui-tooltip-title"))})},open:function(t){var i=this,s=e(t?t.target:this.element).closest(this.options.items);s.length&&!s.data("ui-tooltip-id")&&(s.attr("title")&&s.data("ui-tooltip-title",s.attr("title")),s.data("ui-tooltip-open",!0),t&&"mouseover"===t.type&&s.parents().each(function(){var t,s=e(this);s.data("ui-tooltip-open")&&(t=e.Event("blur"),t.target=t.currentTarget=this,i.close(t,!0)),s.attr("title")&&(s.uniqueId(),i.parents[this.id]={element:this,title:s.attr("title")},s.attr("title",""))}),this._registerCloseHandlers(t,s),this._updateContent(s,t))},_updateContent:function(e,t){var i,s=this.options.content,n=this,a=t?t.type:null;return"string"==typeof s?this._open(t,e,s):(i=s.call(e[0],function(i){n._delay(function(){e.data("ui-tooltip-open")&&(t&&(t.type=a),this._open(t,e,i))})}),i&&this._open(t,e,i),void 0)},_open:function(t,i,s){function n(e){l.of=e,o.is(":hidden")||o.position(l)}var a,o,r,h,l=e.extend({},this.options.position);if(s){if(a=this._find(i))return a.tooltip.find(".ui-tooltip-content").html(s),void 0;i.is("[title]")&&(t&&"mouseover"===t.type?i.attr("title",""):i.removeAttr("title")),a=this._tooltip(i),o=a.tooltip,this._addDescribedBy(i,o.attr("id")),o.find(".ui-tooltip-content").html(s),this.liveRegion.children().hide(),s.clone?(h=s.clone(),h.removeAttr("id").find("[id]").removeAttr("id")):h=s,e("<div>").html(h).appendTo(this.liveRegion),this.options.track&&t&&/^mouse/.test(t.type)?(this._on(this.document,{mousemove:n}),n(t)):o.position(e.extend({of:i},this.options.position)),o.hide(),this._show(o,this.options.show),this.options.show&&this.options.show.delay&&(r=this.delayedShow=setInterval(function(){o.is(":visible")&&(n(l.of),clearInterval(r))},e.fx.interval)),this._trigger("open",t,{tooltip:o})}},_registerCloseHandlers:function(t,i){var s={keyup:function(t){if(t.keyCode===e.ui.keyCode.ESCAPE){var s=e.Event(t);s.currentTarget=i[0],this.close(s,!0)}}};i[0]!==this.element[0]&&(s.remove=function(){this._removeTooltip(this._find(i).tooltip)}),t&&"mouseover"!==t.type||(s.mouseleave="close"),t&&"focusin"!==t.type||(s.focusout="close"),this._on(!0,i,s)},close:function(t){var i,s=this,n=e(t?t.currentTarget:this.element),a=this._find(n);return a?(i=a.tooltip,a.closing||(clearInterval(this.delayedShow),n.data("ui-tooltip-title")&&!n.attr("title")&&n.attr("title",n.data("ui-tooltip-title")),this._removeDescribedBy(n),a.hiding=!0,i.stop(!0),this._hide(i,this.options.hide,function(){s._removeTooltip(e(this))}),n.removeData("ui-tooltip-open"),this._off(n,"mouseleave focusout keyup"),n[0]!==this.element[0]&&this._off(n,"remove"),this._off(this.document,"mousemove"),t&&"mouseleave"===t.type&&e.each(this.parents,function(t,i){e(i.element).attr("title",i.title),delete s.parents[t]}),a.closing=!0,this._trigger("close",t,{tooltip:i}),a.hiding||(a.closing=!1)),void 0):(n.removeData("ui-tooltip-open"),void 0)},_tooltip:function(t){var i=e("<div>").attr("role","tooltip").addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content "+(this.options.tooltipClass||"")),s=i.uniqueId().attr("id");return e("<div>").addClass("ui-tooltip-content").appendTo(i),i.appendTo(this.document[0].body),this.tooltips[s]={element:t,tooltip:i}},_find:function(e){var t=e.data("ui-tooltip-id");return t?this.tooltips[t]:null},_removeTooltip:function(e){e.remove(),delete this.tooltips[e.attr("id")]},_destroy:function(){var t=this;e.each(this.tooltips,function(i,s){var n=e.Event("blur"),a=s.element;n.target=n.currentTarget=a[0],t.close(n,!0),e("#"+i).remove(),a.data("ui-tooltip-title")&&(a.attr("title")||a.attr("title",a.data("ui-tooltip-title")),a.removeData("ui-tooltip-title"))}),this.liveRegion.remove()}})});;
// Change JQueryUI plugin names to fix name collision with Bootstrap.
$.widget.bridge('uibutton', $.ui.button);
$.widget.bridge('uitooltip', $.ui.tooltip);
;
/*
 * MultiDatesPicker v1.6.3
 * http://multidatespickr.sourceforge.net/
 * 
 * Copyright 2014, Luca Lauretta
 * Dual licensed under the MIT or GPL version 2 licenses.
 */
(function( $ ){
	$.extend($.ui, { multiDatesPicker: { version: "1.6.3" } });
	
	$.fn.multiDatesPicker = function(method) {
		var mdp_arguments = arguments;
		var ret = this;
		var today_date = new Date();
		var day_zero = new Date(0);
		var mdp_events = {};
		
		function removeDate(date, type) {
			if(!type) type = 'picked';
			date = dateConvert.call(this, date);
			for(var i = 0; i < this.multiDatesPicker.dates[type].length; i++)
				if(!methods.compareDates(this.multiDatesPicker.dates[type][i], date))
					return this.multiDatesPicker.dates[type].splice(i, 1).pop();
		}
		function removeIndex(index, type) {
			if(!type) type = 'picked';
			return this.multiDatesPicker.dates[type].splice(index, 1).pop();
		}
		function addDate(date, type, no_sort) {
			if(!type) type = 'picked';
			date = dateConvert.call(this, date);
			
			// @todo: use jQuery UI datepicker method instead
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
			
			if (methods.gotDate.call(this, date, type) === false) {
				this.multiDatesPicker.dates[type].push(date);
				if(!no_sort) this.multiDatesPicker.dates[type].sort(methods.compareDates);
			} 
		}
		function sortDates(type) {
			if(!type) type = 'picked';
			this.multiDatesPicker.dates[type].sort(methods.compareDates);
		}
		function dateConvert(date, desired_type, date_format) {
			if(!desired_type) desired_type = 'object';/*
			if(!date_format && (typeof date == 'string')) {
				date_format = $(this).datepicker('option', 'dateFormat');
				if(!date_format) date_format = $.datepicker._defaults.dateFormat;
			}
			*/
			return methods.dateConvert.call(this, date, desired_type, date_format);
		}
		
		var methods = {
			init : function( options ) {
				var $this = $(this);
				this.multiDatesPicker.changed = false;
				
				var mdp_events = {
					beforeShow: function(input, inst) {
						this.multiDatesPicker.changed = false;
						if(this.multiDatesPicker.originalBeforeShow) 
							this.multiDatesPicker.originalBeforeShow.call(this, input, inst);
					},
					onSelect : function(dateText, inst) {
						var $this = $(this);
						this.multiDatesPicker.changed = true;
						
						if (dateText) {
							$this.multiDatesPicker('toggleDate', dateText);
							this.multiDatesPicker.changed = true;
							// @todo: this will be optimized when I'll move methods to the singleton.
						}
						
						if (this.multiDatesPicker.mode == 'normal' && this.multiDatesPicker.pickableRange) {
							if(this.multiDatesPicker.dates.picked.length > 0) {
								var min_date = this.multiDatesPicker.dates.picked[0],
									max_date = new Date(min_date.getTime());
								
								methods.sumDays(max_date, this.multiDatesPicker.pickableRange-1);
									
								// counts the number of disabled dates in the range
								if(this.multiDatesPicker.adjustRangeToDisabled) {
									var c_disabled, 
										disabled = this.multiDatesPicker.dates.disabled.slice(0);
									do {
										c_disabled = 0;
										for(var i = 0; i < disabled.length; i++) {
											if(disabled[i].getTime() <= max_date.getTime()) {
												if((min_date.getTime() <= disabled[i].getTime()) && (disabled[i].getTime() <= max_date.getTime()) ) {
													c_disabled++;
												}
												disabled.splice(i, 1);
												i--;
											}
										}
										max_date.setDate(max_date.getDate() + c_disabled);
									} while(c_disabled != 0);
								}
								
								if(this.multiDatesPicker.maxDate && (max_date > this.multiDatesPicker.maxDate))
									max_date = this.multiDatesPicker.maxDate;
								
								$this
									.datepicker("option", "minDate", min_date)
									.datepicker("option", "maxDate", max_date);
							} else {
								$this
									.datepicker("option", "minDate", this.multiDatesPicker.minDate)
									.datepicker("option", "maxDate", this.multiDatesPicker.maxDate);
							}
						}
						
						if(this.multiDatesPicker.originalOnSelect && dateText)
							this.multiDatesPicker.originalOnSelect.call(this, dateText, inst);
						
					},
					beforeShowDay : function(date) {
						var $this = $(this),
							gotThisDate = $this.multiDatesPicker('gotDate', date) !== false,
							isDisabledCalendar = $this.datepicker('option', 'disabled'),
							isDisabledDate = $this.multiDatesPicker('gotDate', date, 'disabled') !== false,
							areAllSelected = this.multiDatesPicker.maxPicks <= this.multiDatesPicker.dates.picked.length;
						
						var bsdReturn = [true, '', null];
						if(this.multiDatesPicker.originalBeforeShowDay)
							bsdReturn = this.multiDatesPicker.originalBeforeShowDay.call(this, date);
						
						bsdReturn[1] = gotThisDate ? 'ui-state-highlight' : bsdReturn[1];
						bsdReturn[0] = bsdReturn[0] && !(isDisabledCalendar || isDisabledDate || (areAllSelected && !bsdReturn[1]));
						return bsdReturn;
					}
				};
				
				// value have to be extracted before datepicker is initiated
				if($this.val()) var inputDates = $this.val()
				this.multiDatesPicker.separator = ', ';
				
				if(options) {
					// value have to be extracted before datepicker is initiated
					//if(options.altField) var inputDates = $(options.altField).val();
					if(options.separator) this.multiDatesPicker.separator = options.separator;
					
					this.multiDatesPicker.originalBeforeShow = options.beforeShow;
					this.multiDatesPicker.originalOnSelect = options.onSelect;
					this.multiDatesPicker.originalBeforeShowDay = options.beforeShowDay;
					this.multiDatesPicker.originalOnClose = options.onClose;
					
					// datepicker init
					$this.datepicker(options);
					
					this.multiDatesPicker.minDate = $.datepicker._determineDate(this, options.minDate, null);
					this.multiDatesPicker.maxDate = $.datepicker._determineDate(this, options.maxDate, null);
					if(options.addDates) methods.addDates.call(this, options.addDates);
					 
					if(options.addDisabledDates)
						methods.addDates.call(this, options.addDisabledDates, 'disabled');
					
					methods.setMode.call(this, options);
				} else {
					$this.datepicker();
				}
				$this.datepicker('option', mdp_events);
				
				// adds any dates found in the input or alt field
				if(inputDates) $this.multiDatesPicker('value', inputDates);
				
				// generates the new string of added dates
				var inputs_values = $this.multiDatesPicker('value');
				
				// fills the input field back with all the dates in the calendar
				if(this.tagName == 'INPUT')	$this.val(inputs_values);
				
				// Fixes the altField filled with defaultDate by default
				var altFieldOption = $this.datepicker('option', 'altField');
				if (altFieldOption) $(altFieldOption).val(inputs_values);
				
				// Updates the calendar view
				$this.datepicker('refresh');
			},
			compareDates : function(date1, date2) {
				date1 = dateConvert.call(this, date1);
				date2 = dateConvert.call(this, date2);
				// return > 0 means date1 is later than date2 
				// return == 0 means date1 is the same day as date2 
				// return < 0 means date1 is earlier than date2 
				var diff = date1.getFullYear() - date2.getFullYear();
				if(!diff) {
					diff = date1.getMonth() - date2.getMonth();
					if(!diff) 
						diff = date1.getDate() - date2.getDate();
				}
				return diff;
			},
			sumDays : function( date, n_days ) {
				var origDateType = typeof date;
				obj_date = dateConvert.call(this, date);
				obj_date.setDate(obj_date.getDate() + n_days);
				return dateConvert.call(this, obj_date, origDateType);
			},
			dateConvert : function( date, desired_format, dateFormat ) {
				var from_format = typeof date;
				
				if(from_format == desired_format) {
					if(from_format == 'object') {
						try {
							date.getTime();
						} catch (e) {
							$.error('Received date is in a non supported format!');
							return false;
						}
					}
					return date;
				}
				
				var $this = $(this);
				if(typeof date == 'undefined') date = new Date(0);
				
				if(desired_format != 'string' && desired_format != 'object' && desired_format != 'number')
					$.error('Date format "'+ desired_format +'" not supported!');
				
				if(!dateFormat) {
					dateFormat = $.datepicker._defaults.dateFormat;
					
					// thanks to bibendus83 -> http://sourceforge.net/tracker/index.php?func=detail&aid=3213174&group_id=358205&atid=1495382
					var dp_dateFormat = $this.datepicker('option', 'dateFormat');
					if (dp_dateFormat) {
						dateFormat = dp_dateFormat;
					}
				}
				
				// converts to object as a neutral format
				switch(from_format) {
					case 'object': break;
					case 'string': date = $.datepicker.parseDate(dateFormat, date); break;
					case 'number': date = new Date(date); break;
					default: $.error('Conversion from "'+ desired_format +'" format not allowed on jQuery.multiDatesPicker');
				}
				// then converts to the desired format
				switch(desired_format) {
					case 'object': return date;
					case 'string': return $.datepicker.formatDate(dateFormat, date);
					case 'number': return date.getTime();
					default: $.error('Conversion to "'+ desired_format +'" format not allowed on jQuery.multiDatesPicker');
				}
				return false;
			},
			gotDate : function( date, type ) {
				if(!type) type = 'picked';
				for(var i = 0; i < this.multiDatesPicker.dates[type].length; i++) {
					if(methods.compareDates.call(this, this.multiDatesPicker.dates[type][i], date) === 0) {
						return i;
					}
				}
				return false;
			},
			value : function( value ) {
				if(value && typeof value == 'string') {
					methods.addDates.call(this, value.split(this.multiDatesPicker.separator));
				} else {
					var dates = methods.getDates.call(this, 'string');
					return dates.length
						? dates.join(this.multiDatesPicker.separator)
						: "";
				}
			},
			getDates : function( format, type ) {
				if(!format) format = 'string';
				if(!type) type = 'picked';
				switch (format) {
					case 'object':
						return this.multiDatesPicker.dates[type];
					case 'string':
					case 'number':
						var o_dates = new Array();
						for(var i in this.multiDatesPicker.dates[type])
							o_dates.push(
								dateConvert.call(
									this, 
									this.multiDatesPicker.dates[type][i], 
									format
								)
							);
						return o_dates;
					
					default: $.error('Format "'+format+'" not supported!');
				}
			},
			addDates : function( dates, type ) {
				if(dates.length > 0) {
					if(!type) type = 'picked';
					switch(typeof dates) {
						case 'object':
						case 'array':
							if(dates.length) {
								for(var i = 0; i < dates.length; i++)
									addDate.call(this, dates[i], type, true);
								sortDates.call(this, type);
								break;
							} // else does the same as 'string'
						case 'string':
						case 'number':
							addDate.call(this, dates, type);
							break;
						default: 
							$.error('Date format "'+ typeof dates +'" not allowed on jQuery.multiDatesPicker');
					}
					//$(this).datepicker('refresh');
				} else {
					$.error('Empty array of dates received.');
				}
			},
			removeDates : function( dates, type ) {
				if(!type) type = 'picked';
				var removed = [];
				if (Object.prototype.toString.call(dates) === '[object Array]') {
					for(var i in dates.sort(function(a,b){return b-a})) {
						removed.push(removeDate.call(this, dates[i], type));
					}
				} else {
					removed.push(removeDate.call(this, dates, type));
				}
				return removed;
			},
			removeIndexes : function( indexes, type ) {
				if(!type) type = 'picked';
				var removed = [];
				if (Object.prototype.toString.call(indexes) === '[object Array]') {
					for(var i in indexes.sort(function(a,b){return b-a})) {
						removed.push(removeIndex.call(this, indexes[i], type));
					}
				} else {
					removed.push(removeIndex.call(this, indexes, type));
				}
				return removed;
			},
			resetDates : function ( type ) {
				if(!type) type = 'picked';
				this.multiDatesPicker.dates[type] = [];
			},
			toggleDate : function( date, type ) {
				if(!type) type = 'picked';
				
				switch(this.multiDatesPicker.mode) {
					case 'daysRange':
						this.multiDatesPicker.dates[type] = []; // deletes all picked/disabled dates
						var end = this.multiDatesPicker.autoselectRange[1];
						var begin = this.multiDatesPicker.autoselectRange[0];
						if(end < begin) { // switch
							end = this.multiDatesPicker.autoselectRange[0];
							begin = this.multiDatesPicker.autoselectRange[1];
						}
						for(var i = begin; i < end; i++) 
							methods.addDates.call(this, methods.sumDays(date, i), type);
						break;
					default:
						if(methods.gotDate.call(this, date) === false) // adds dates
							methods.addDates.call(this, date, type);
						else // removes dates
							methods.removeDates.call(this, date, type);
						break;
				}
			}, 
			setMode : function( options ) {
				var $this = $(this);
				if(options.mode) this.multiDatesPicker.mode = options.mode;
				
				switch(this.multiDatesPicker.mode) {
					case 'normal':
						for(option in options)
							switch(option) {
								case 'maxPicks':
								case 'minPicks':
								case 'pickableRange':
								case 'adjustRangeToDisabled':
									this.multiDatesPicker[option] = options[option];
									break;
								//default: $.error('Option ' + option + ' ignored for mode "'.options.mode.'".');
							}
					break;
					case 'daysRange':
					case 'weeksRange':
						var mandatory = 1;
						for(option in options)
							switch(option) {
								case 'autoselectRange':
									mandatory--;
								case 'pickableRange':
								case 'adjustRangeToDisabled':
									this.multiDatesPicker[option] = options[option];
									break;
								//default: $.error('Option ' + option + ' does not exist for setMode on jQuery.multiDatesPicker');
							}
						if(mandatory > 0) $.error('Some mandatory options not specified!');
					break;
				}
				
				/*
				if(options.pickableRange) {
					$this.datepicker("option", "maxDate", options.pickableRange);
					$this.datepicker("option", "minDate", this.multiDatesPicker.minDate);
				}
				*/
				
				if(mdp_events.onSelect)
					mdp_events.onSelect();
			},
			destroy: function(){
				this.multiDatesPicker = null;
				$(this).datepicker('destroy');
			}
		};
		
		this.each(function() {
			var $this = $(this);
			if (!this.multiDatesPicker) {
				this.multiDatesPicker = {
					dates: {
						picked: [],
						disabled: []
					},
					mode: 'normal',
					adjustRangeToDisabled: true
				};
			}
			
			if(methods[method]) {
				var exec_result = methods[method].apply(this, Array.prototype.slice.call(mdp_arguments, 1));
				switch(method) {
					case 'removeDates':
					case 'removeIndexes':
					case 'resetDates':
					case 'toggleDate':
					case 'addDates':
						var altField = $this.datepicker('option', 'altField');
						// @todo: should use altFormat for altField
						var dates_string = methods.value.call(this);
						if (altField !== undefined && altField != "") {
							$(altField).val(dates_string);
						}
						if(this.tagName == 'INPUT') { // for inputs
							$this.val(dates_string);
						}
						
						$.datepicker._refreshDatepicker(this);
				}
				switch(method) {
					case 'removeDates':
					case 'getDates':
					case 'gotDate':
					case 'sumDays':
					case 'compareDates':
					case 'dateConvert':
					case 'value':
						ret = exec_result;
				}
				return exec_result;
			} else if( typeof method === 'object' || ! method ) {
				return methods.init.apply(this, mdp_arguments);
			} else {
				$.error('Method ' +  method + ' does not exist on jQuery.multiDatesPicker');
			}
			return false;
		}); 
		
		return ret;
	};

	var PROP_NAME = 'multiDatesPicker';
	var dpuuid = new Date().getTime();
	var instActive;

	$.multiDatesPicker = {version: false};
	//$.multiDatesPicker = new MultiDatesPicker(); // singleton instance
	$.multiDatesPicker.initialized = false;
	$.multiDatesPicker.uuid = new Date().getTime();
	$.multiDatesPicker.version = $.ui.multiDatesPicker.version;
	
	// allows MDP not to hide everytime a date is picked
	$.multiDatesPicker._hideDatepicker = $.datepicker._hideDatepicker;
	$.datepicker._hideDatepicker = function(){
		var target = this._curInst.input[0];
		var mdp = target.multiDatesPicker;
		if(!mdp || (this._curInst.inline === false && !mdp.changed)) {
			return $.multiDatesPicker._hideDatepicker.apply(this, arguments);
		} else {
			mdp.changed = false;
			$.datepicker._refreshDatepicker(target);
			return;
		}
	};

	// Workaround for #4055
	// Add another global to avoid noConflict issues with inline event handlers
	window['DP_jQuery_' + dpuuid] = $;
})( jQuery );;
/*!
 * jQuery Validation Plugin v1.14.0
 *
 * http://jqueryvalidation.org/
 *
 * Copyright (c) 2015 Jörn Zaefferer
 * Released under the MIT license
 */
(function(n){typeof define=="function"&&define.amd?define(["jquery"],n):n(jQuery)})(function(n){n.extend(n.fn,{validate:function(t){if(!this.length){t&&t.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing.");return}var i=n.data(this[0],"validator");if(i)return i;if(this.attr("novalidate","novalidate"),i=new n.validator(t,this[0]),n.data(this[0],"validator",i),i.settings.onsubmit){this.on("click.validate",":submit",function(t){i.settings.submitHandler&&(i.submitButton=t.target);n(this).hasClass("cancel")&&(i.cancelSubmit=!0);n(this).attr("formnovalidate")!==undefined&&(i.cancelSubmit=!0)});this.on("submit.validate",function(t){function r(){var u,r;return i.settings.submitHandler?(i.submitButton&&(u=n("<input type='hidden'/>").attr("name",i.submitButton.name).val(n(i.submitButton).val()).appendTo(i.currentForm)),r=i.settings.submitHandler.call(i,i.currentForm,t),i.submitButton&&u.remove(),r!==undefined)?r:!1:!0}return(i.settings.debug&&t.preventDefault(),i.cancelSubmit)?(i.cancelSubmit=!1,r()):i.form()?i.pendingRequest?(i.formSubmitted=!0,!1):r():(i.focusInvalid(),!1)})}return i},valid:function(){var t,i,r;return n(this[0]).is("form")?t=this.validate().form():(r=[],t=!0,i=n(this[0].form).validate(),this.each(function(){t=i.element(this)&&t;r=r.concat(i.errorList)}),i.errorList=r),t},rules:function(t,i){var r=this[0],e,s,f,u,o,h;if(t){e=n.data(r.form,"validator").settings;s=e.rules;f=n.validator.staticRules(r);switch(t){case"add":n.extend(f,n.validator.normalizeRule(i));delete f.messages;s[r.name]=f;i.messages&&(e.messages[r.name]=n.extend(e.messages[r.name],i.messages));break;case"remove":return i?(h={},n.each(i.split(/\s/),function(t,i){h[i]=f[i];delete f[i];i==="required"&&n(r).removeAttr("aria-required")}),h):(delete s[r.name],f)}}return u=n.validator.normalizeRules(n.extend({},n.validator.classRules(r),n.validator.attributeRules(r),n.validator.dataRules(r),n.validator.staticRules(r)),r),u.required&&(o=u.required,delete u.required,u=n.extend({required:o},u),n(r).attr("aria-required","true")),u.remote&&(o=u.remote,delete u.remote,u=n.extend(u,{remote:o})),u}});n.extend(n.expr[":"],{blank:function(t){return!n.trim(""+n(t).val())},filled:function(t){return!!n.trim(""+n(t).val())},unchecked:function(t){return!n(t).prop("checked")}});n.validator=function(t,i){this.settings=n.extend(!0,{},n.validator.defaults,t);this.currentForm=i;this.init()};n.validator.format=function(t,i){return arguments.length===1?function(){var i=n.makeArray(arguments);return i.unshift(t),n.validator.format.apply(this,i)}:(arguments.length>2&&i.constructor!==Array&&(i=n.makeArray(arguments).slice(1)),i.constructor!==Array&&(i=[i]),n.each(i,function(n,i){t=t.replace(new RegExp("\\{"+n+"\\}","g"),function(){return i})}),t)};n.extend(n.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:n([]),errorLabelContainer:n([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(n){this.lastActive=n;this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,n,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(n)))},onfocusout:function(n){!this.checkable(n)&&(n.name in this.submitted||!this.optional(n))&&this.element(n)},onkeyup:function(t,i){(i.which!==9||this.elementValue(t)!=="")&&n.inArray(i.keyCode,[16,17,18,20,35,36,37,38,39,40,45,144,225])===-1&&(t.name in this.submitted||t===this.lastElement)&&this.element(t)},onclick:function(n){n.name in this.submitted?this.element(n):n.parentNode.name in this.submitted&&this.element(n.parentNode)},highlight:function(t,i,r){t.type==="radio"?this.findByName(t.name).addClass(i).removeClass(r):n(t).addClass(i).removeClass(r)},unhighlight:function(t,i,r){t.type==="radio"?this.findByName(t.name).removeClass(i).addClass(r):n(t).removeClass(i).addClass(r)}},setDefaults:function(t){n.extend(n.validator.defaults,t)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date ( ISO ).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",maxlength:n.validator.format("Please enter no more than {0} characters."),minlength:n.validator.format("Please enter at least {0} characters."),rangelength:n.validator.format("Please enter a value between {0} and {1} characters long."),range:n.validator.format("Please enter a value between {0} and {1}."),max:n.validator.format("Please enter a value less than or equal to {0}."),min:n.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function i(t){var r=n.data(this.form,"validator"),u="on"+t.type.replace(/^validate/,""),i=r.settings;i[u]&&!n(this).is(i.ignore)&&i[u].call(r,this,t)}this.labelContainer=n(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||n(this.currentForm);this.containers=n(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var r=this.groups={},t;n.each(this.settings.groups,function(t,i){typeof i=="string"&&(i=i.split(/\s/));n.each(i,function(n,i){r[i]=t})});t=this.settings.rules;n.each(t,function(i,r){t[i]=n.validator.normalizeRule(r)});n(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox']",i).on("click.validate","select, option, [type='radio'], [type='checkbox']",i);if(this.settings.invalidHandler)n(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler);n(this.currentForm).find("[required], [data-rule-required], .required").attr("aria-required","true")},form:function(){return this.checkForm(),n.extend(this.submitted,this.errorMap),this.invalid=n.extend({},this.errorMap),this.valid()||n(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var n=0,t=this.currentElements=this.elements();t[n];n++)this.check(t[n]);return this.valid()},element:function(t){var u=this.clean(t),i=this.validationTargetFor(u),r=!0;return this.lastElement=i,i===undefined?delete this.invalid[u.name]:(this.prepareElement(i),this.currentElements=n(i),r=this.check(i)!==!1,r?delete this.invalid[i.name]:this.invalid[i.name]=!0),n(t).attr("aria-invalid",!r),this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),r},showErrors:function(t){if(t){n.extend(this.errorMap,t);this.errorList=[];for(var i in t)this.errorList.push({message:t[i],element:this.findByName(i)[0]});this.successList=n.grep(this.successList,function(n){return!(n.name in t)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){n.fn.resetForm&&n(this.currentForm).resetForm();this.submitted={};this.lastElement=null;this.prepareForm();this.hideErrors();var t,i=this.elements().removeData("previousValue").removeAttr("aria-invalid");if(this.settings.unhighlight)for(t=0;i[t];t++)this.settings.unhighlight.call(this,i[t],this.settings.errorClass,"");else i.removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(n){var t=0;for(var i in n)t++;return t},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(n){n.not(this.containers).text("");this.addWrapper(n).hide()},valid:function(){return this.size()===0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{n(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(t){}},findLastActive:function(){var t=this.lastActive;return t&&n.grep(this.errorList,function(n){return n.element.name===t.name}).length===1&&t},elements:function(){var t=this,i={};return n(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){return(!this.name&&t.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.name in i||!t.objectLength(n(this).rules()))?!1:(i[this.name]=!0,!0)})},clean:function(t){return n(t)[0]},errors:function(){var t=this.settings.errorClass.split(" ").join(".");return n(this.settings.errorElement+"."+t,this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=n([]);this.toHide=n([]);this.currentElements=n([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},prepareElement:function(n){this.reset();this.toHide=this.errorsFor(n)},elementValue:function(t){var i,u=n(t),r=t.type;return r==="radio"||r==="checkbox"?this.findByName(t.name).filter(":checked").val():r==="number"&&typeof t.validity!="undefined"?t.validity.badInput?!1:u.val():(i=u.val(),typeof i=="string")?i.replace(/\r/g,""):i},check:function(t){t=this.validationTargetFor(this.clean(t));var r=n(t).rules(),s=n.map(r,function(n,t){return t}).length,o=!1,h=this.elementValue(t),u,f,i;for(f in r){i={method:f,parameters:r[f]};try{if(u=n.validator.methods[f].call(this,h,t,i.parameters),u==="dependency-mismatch"&&s===1){o=!0;continue}if(o=!1,u==="pending"){this.toHide=this.toHide.not(this.errorsFor(t));return}if(!u)return this.formatAndAdd(t,i),!1}catch(e){this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+t.id+", check the '"+i.method+"' method.",e);e instanceof TypeError&&(e.message+=".  Exception occurred when checking element "+t.id+", check the '"+i.method+"' method.");throw e;}}if(!o)return this.objectLength(r)&&this.successList.push(t),!0},customDataMessage:function(t,i){return n(t).data("msg"+i.charAt(0).toUpperCase()+i.substring(1).toLowerCase())||n(t).data("msg")},customMessage:function(n,t){var i=this.settings.messages[n];return i&&(i.constructor===String?i:i[t])},findDefined:function(){for(var n=0;n<arguments.length;n++)if(arguments[n]!==undefined)return arguments[n];return undefined},defaultMessage:function(t,i){return this.findDefined(this.customMessage(t.name,i),this.customDataMessage(t,i),!this.settings.ignoreTitle&&t.title||undefined,n.validator.messages[i],"<strong>Warning: No message defined for "+t.name+"<\/strong>")},formatAndAdd:function(t,i){var r=this.defaultMessage(t,i.method),u=/\$?\{(\d+)\}/g;typeof r=="function"?r=r.call(this,i.parameters,t):u.test(r)&&(r=n.validator.format(r.replace(u,"{$1}"),i.parameters));this.errorList.push({message:r,element:t,method:i.method});this.errorMap[t.name]=r;this.submitted[t.name]=r},addWrapper:function(n){return this.settings.wrapper&&(n=n.add(n.parent(this.settings.wrapper))),n},defaultShowErrors:function(){for(var i,t,n=0;this.errorList[n];n++)t=this.errorList[n],this.settings.highlight&&this.settings.highlight.call(this,t.element,this.settings.errorClass,this.settings.validClass),this.showLabel(t.element,t.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(n=0;this.successList[n];n++)this.showLabel(this.successList[n]);if(this.settings.unhighlight)for(n=0,i=this.validElements();i[n];n++)this.settings.unhighlight.call(this,i[n],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow);this.hideErrors();this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return n(this.errorList).map(function(){return this.element})},showLabel:function(t,i){var u,o,e,r=this.errorsFor(t),s=this.idOrName(t),f=n(t).attr("aria-describedby");r.length?(r.removeClass(this.settings.validClass).addClass(this.settings.errorClass),r.html(i)):(r=n("<"+this.settings.errorElement+">").attr("id",s+"-error").addClass(this.settings.errorClass).html(i||""),u=r,this.settings.wrapper&&(u=r.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(u):this.settings.errorPlacement?this.settings.errorPlacement(u,n(t)):u.insertAfter(t),r.is("label")?r.attr("for",s):r.parents("label[for='"+s+"']").length===0&&(e=r.attr("id").replace(/(:|\.|\[|\]|\$)/g,"\\$1"),f?f.match(new RegExp("\\b"+e+"\\b"))||(f+=" "+e):f=e,n(t).attr("aria-describedby",f),o=this.groups[t.name],o&&n.each(this.groups,function(t,i){i===o&&n("[name='"+t+"']",this.currentForm).attr("aria-describedby",r.attr("id"))})));!i&&this.settings.success&&(r.text(""),typeof this.settings.success=="string"?r.addClass(this.settings.success):this.settings.success(r,t));this.toShow=this.toShow.add(r)},errorsFor:function(t){var r=this.idOrName(t),u=n(t).attr("aria-describedby"),i="label[for='"+r+"'], label[for='"+r+"'] *";return u&&(i=i+", #"+u.replace(/\s+/g,", #")),this.errors().filter(i)},idOrName:function(n){return this.groups[n.name]||(this.checkable(n)?n.name:n.id||n.name)},validationTargetFor:function(t){return this.checkable(t)&&(t=this.findByName(t.name)),n(t).not(this.settings.ignore)[0]},checkable:function(n){return/radio|checkbox/i.test(n.type)},findByName:function(t){return n(this.currentForm).find("[name='"+t+"']")},getLength:function(t,i){switch(i.nodeName.toLowerCase()){case"select":return n("option:selected",i).length;case"input":if(this.checkable(i))return this.findByName(i.name).filter(":checked").length}return t.length},depend:function(n,t){return this.dependTypes[typeof n]?this.dependTypes[typeof n](n,t):!0},dependTypes:{boolean:function(n){return n},string:function(t,i){return!!n(t,i.form).length},"function":function(n,t){return n(t)}},optional:function(t){var i=this.elementValue(t);return!n.validator.methods.required.call(this,i,t)&&"dependency-mismatch"},startRequest:function(n){this.pending[n.name]||(this.pendingRequest++,this.pending[n.name]=!0)},stopRequest:function(t,i){this.pendingRequest--;this.pendingRequest<0&&(this.pendingRequest=0);delete this.pending[t.name];i&&this.pendingRequest===0&&this.formSubmitted&&this.form()?(n(this.currentForm).submit(),this.formSubmitted=!1):!i&&this.pendingRequest===0&&this.formSubmitted&&(n(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(t){return n.data(t,"previousValue")||n.data(t,"previousValue",{old:null,valid:!0,message:this.defaultMessage(t,"remote")})},destroy:function(){this.resetForm();n(this.currentForm).off(".validate").removeData("validator")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(t,i){t.constructor===String?this.classRuleSettings[t]=i:n.extend(this.classRuleSettings,t)},classRules:function(t){var i={},r=n(t).attr("class");return r&&n.each(r.split(" "),function(){this in n.validator.classRuleSettings&&n.extend(i,n.validator.classRuleSettings[this])}),i},normalizeAttributeRule:function(n,t,i,r){/min|max/.test(i)&&(t===null||/number|range|text/.test(t))&&(r=Number(r),isNaN(r)&&(r=undefined));r||r===0?n[i]=r:t===i&&t!=="range"&&(n[i]=!0)},attributeRules:function(t){var r={},f=n(t),e=t.getAttribute("type"),u,i;for(u in n.validator.methods)u==="required"?(i=t.getAttribute(u),i===""&&(i=!0),i=!!i):i=f.attr(u),this.normalizeAttributeRule(r,e,u,i);return r.maxlength&&/-1|2147483647|524288/.test(r.maxlength)&&delete r.maxlength,r},dataRules:function(t){var r={},f=n(t),e=t.getAttribute("type"),i,u;for(i in n.validator.methods)u=f.data("rule"+i.charAt(0).toUpperCase()+i.substring(1).toLowerCase()),this.normalizeAttributeRule(r,e,i,u);return r},staticRules:function(t){var i={},r=n.data(t.form,"validator");return r.settings.rules&&(i=n.validator.normalizeRule(r.settings.rules[t.name])||{}),i},normalizeRules:function(t,i){return n.each(t,function(r,u){if(u===!1){delete t[r];return}if(u.param||u.depends){var f=!0;switch(typeof u.depends){case"string":f=!!n(u.depends,i.form).length;break;case"function":f=u.depends.call(i,i)}f?t[r]=u.param!==undefined?u.param:!0:delete t[r]}}),n.each(t,function(r,u){t[r]=n.isFunction(u)?u(i):u}),n.each(["minlength","maxlength"],function(){t[this]&&(t[this]=Number(t[this]))}),n.each(["rangelength","range"],function(){var i;t[this]&&(n.isArray(t[this])?t[this]=[Number(t[this][0]),Number(t[this][1])]:typeof t[this]=="string"&&(i=t[this].replace(/[\[\]]/g,"").split(/[\s,]+/),t[this]=[Number(i[0]),Number(i[1])]))}),n.validator.autoCreateRanges&&(t.min!=null&&t.max!=null&&(t.range=[t.min,t.max],delete t.min,delete t.max),t.minlength!=null&&t.maxlength!=null&&(t.rangelength=[t.minlength,t.maxlength],delete t.minlength,delete t.maxlength)),t},normalizeRule:function(t){if(typeof t=="string"){var i={};n.each(t.split(/\s/),function(){i[this]=!0});t=i}return t},addMethod:function(t,i,r){n.validator.methods[t]=i;n.validator.messages[t]=r!==undefined?r:n.validator.messages[t];i.length<3&&n.validator.addClassRules(t,n.validator.normalizeRule(t))},methods:{required:function(t,i,r){if(!this.depend(r,i))return"dependency-mismatch";if(i.nodeName.toLowerCase()==="select"){var u=n(i).val();return u&&u.length>0}return this.checkable(i)?this.getLength(t,i)>0:t.length>0},email:function(n,t){return this.optional(t)||/^[a-zA-Z0-9.!#$%()&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9.-]+\.(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(n)},url:function(n,t){return this.optional(t)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(n)},date:function(n,t){return this.optional(t)||!/Invalid|NaN/.test(new Date(n).toString())},dateISO:function(n,t){return this.optional(t)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(n)},number:function(n,t){return this.optional(t)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(n)},digits:function(n,t){return this.optional(t)||/^\d+$/.test(n)},creditcard:function(n,t){if(this.optional(t))return"dependency-mismatch";if(/[^0-9 \-]+/.test(n))return!1;var f=0,i=0,u=!1,r,e;if(n=n.replace(/\D/g,""),n.length<13||n.length>19)return!1;for(r=n.length-1;r>=0;r--)e=n.charAt(r),i=parseInt(e,10),u&&(i*=2)>9&&(i-=9),f+=i,u=!u;return f%10==0},minlength:function(t,i,r){var u=n.isArray(t)?t.length:this.getLength(t,i);return this.optional(i)||u>=r},maxlength:function(t,i,r){var u=n.isArray(t)?t.length:this.getLength(t,i);return this.optional(i)||u<=r},rangelength:function(t,i,r){var u=n.isArray(t)?t.length:this.getLength(t,i);return this.optional(i)||u>=r[0]&&u<=r[1]},min:function(n,t,i){return this.optional(t)||n>=i},max:function(n,t,i){return this.optional(t)||n<=i},range:function(n,t,i){return this.optional(t)||n>=i[0]&&n<=i[1]},equalTo:function(t,i,r){var u=n(r);if(this.settings.onfocusout)u.off(".validate-equalTo").on("blur.validate-equalTo",function(){n(i).valid()});return t===u.val()},remote:function(t,i,r){if(this.optional(i))return"dependency-mismatch";var f=this.previousValue(i),u,e;return(this.settings.messages[i.name]||(this.settings.messages[i.name]={}),f.originalMessage=this.settings.messages[i.name].remote,this.settings.messages[i.name].remote=f.message,r=typeof r=="string"&&{url:r}||r,f.old===t)?f.valid:(f.old=t,u=this,this.startRequest(i),e={},e[i.name]=t,n.ajax(n.extend(!0,{mode:"abort",port:"validate"+i.name,dataType:"json",data:e,context:u.currentForm,success:function(r){var o=r===!0||r==="true",s,e,h;u.settings.messages[i.name].remote=f.originalMessage;o?(h=u.formSubmitted,u.prepareElement(i),u.formSubmitted=h,u.successList.push(i),delete u.invalid[i.name],u.showErrors()):(s={},e=r||u.defaultMessage(i,"remote"),s[i.name]=f.message=n.isFunction(e)?e(t):e,u.invalid[i.name]=!0,u.showErrors(s));f.valid=o;u.stopRequest(i,o)}},r)),"pending")}}});var t={},i;n.ajaxPrefilter?n.ajaxPrefilter(function(n,i,r){var u=n.port;n.mode==="abort"&&(t[u]&&t[u].abort(),t[u]=r)}):(i=n.ajax,n.ajax=function(r){var f=("mode"in r?r:n.ajaxSettings).mode,u=("port"in r?r:n.ajaxSettings).port;return f==="abort"?(t[u]&&t[u].abort(),t[u]=i.apply(this,arguments),t[u]):i.apply(this,arguments)})});;
/* NUGET: BEGIN LICENSE TEXT
 *
 * Microsoft grants you the right to use these script files for the sole
 * purpose of either: (i) interacting through your browser with the Microsoft
 * website or online service, subject to the applicable licensing or use
 * terms; or (ii) using the files as included with a Microsoft product subject
 * to that product's license terms. Microsoft reserves all other rights to the
 * files not expressly granted by Microsoft, whether by implication, estoppel
 * or otherwise. Insofar as a script file is dual licensed under GPL,
 * Microsoft neither took the code under GPL nor distributes it thereunder but
 * under the terms set out in this paragraph. All notices and licenses
 * below are for informational purposes only.
 *
 * NUGET: END LICENSE TEXT */
/*
** Unobtrusive validation support library for jQuery and jQuery Validate
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var d=a.validator,b,e="unobtrusiveValidation";function c(a,b,c){a.rules[b]=c;if(a.message)a.messages[b]=a.message}function j(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function f(a){return a.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function h(a){return a.substr(0,a.lastIndexOf(".")+1)}function g(a,b){if(a.indexOf("*.")===0)a=a.replace("*.",b);return a}function m(c,e){var b=a(this).find("[data-valmsg-for='"+f(e[0].name)+"']"),d=b.attr("data-valmsg-replace"),g=d?a.parseJSON(d)!==false:null;b.removeClass("field-validation-valid").addClass("field-validation-error");c.data("unobtrusiveContainer",b);if(g){b.empty();c.removeClass("input-validation-error").appendTo(b)}else c.hide()}function l(e,d){var c=a(this).find("[data-valmsg-summary=true]"),b=c.find("ul");if(b&&b.length&&d.errorList.length){b.empty();c.addClass("validation-summary-errors").removeClass("validation-summary-valid");a.each(d.errorList,function(){a("<li />").html(this.message).appendTo(b)})}}function k(d){var b=d.data("unobtrusiveContainer"),c=b.attr("data-valmsg-replace"),e=c?a.parseJSON(c):null;if(b){b.addClass("field-validation-valid").removeClass("field-validation-error");d.removeData("unobtrusiveContainer");e&&b.empty()}}function n(){var b=a(this),c="__jquery_unobtrusive_validation_form_reset";if(b.data(c))return;b.data(c,true);try{b.data("validator").resetForm()}finally{b.removeData(c)}b.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors");b.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}function i(b){var c=a(b),f=c.data(e),i=a.proxy(n,b),g=d.unobtrusive.options||{},h=function(e,d){var c=g[e];c&&a.isFunction(c)&&c.apply(b,d)};if(!f){f={options:{errorClass:g.errorClass||"input-validation-error",errorElement:g.errorElement||"span",errorPlacement:function(){m.apply(b,arguments);h("errorPlacement",arguments)},invalidHandler:function(){l.apply(b,arguments);h("invalidHandler",arguments)},messages:{},rules:{},success:function(){k.apply(b,arguments);h("success",arguments)}},attachValidation:function(){c.off("reset."+e,i).on("reset."+e,i).validate(this.options)},validate:function(){c.validate();return c.valid()}};c.data(e,f)}return f}d.unobtrusive={adapters:[],parseElement:function(b,h){var d=a(b),f=d.parents("form")[0],c,e,g;if(!f)return;c=i(f);c.options.rules[b.name]=e={};c.options.messages[b.name]=g={};a.each(this.adapters,function(){var c="data-val-"+this.name,i=d.attr(c),h={};if(i!==undefined){c+="-";a.each(this.params,function(){h[this]=d.attr(c+this)});this.adapt({element:b,form:f,message:i,params:h,rules:e,messages:g})}});a.extend(e,{__dummy__:true});!h&&c.attachValidation()},parse:function(c){var b=a(c),e=b.parents().addBack().filter("form").add(b.find("form")).has("[data-val=true]");b.find("[data-val=true]").each(function(){d.unobtrusive.parseElement(this,true)});e.each(function(){var a=i(this);a&&a.attachValidation()})}};b=d.unobtrusive.adapters;b.add=function(c,a,b){if(!b){b=a;a=[]}this.push({name:c,params:a,adapt:b});return this};b.addBool=function(a,b){return this.add(a,function(d){c(d,b||a,true)})};b.addMinMax=function(e,g,f,a,d,b){return this.add(e,[d||"min",b||"max"],function(b){var e=b.params.min,d=b.params.max;if(e&&d)c(b,a,[e,d]);else if(e)c(b,g,e);else d&&c(b,f,d)})};b.addSingleVal=function(a,b,d){return this.add(a,[b||"val"],function(e){c(e,d||a,e.params[b])})};d.addMethod("__dummy__",function(){return true});d.addMethod("regex",function(b,c,d){var a;if(this.optional(c))return true;a=(new RegExp(d)).exec(b);return a&&a.index===0&&a[0].length===b.length});d.addMethod("nonalphamin",function(c,d,b){var a;if(b){a=c.match(/\W/g);a=a&&a.length>=b}return a});if(d.methods.extension){b.addSingleVal("accept","mimtype");b.addSingleVal("extension","extension")}else b.addSingleVal("extension","extension","accept");b.addSingleVal("regex","pattern");b.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");b.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range");b.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength");b.add("equalto",["other"],function(b){var i=h(b.element.name),j=b.params.other,d=g(j,i),e=a(b.form).find(":input").filter("[name='"+f(d)+"']")[0];c(b,"equalTo",e)});b.add("required",function(a){(a.element.tagName.toUpperCase()!=="INPUT"||a.element.type.toUpperCase()!=="CHECKBOX")&&c(a,"required",true)});b.add("remote",["url","type","additionalfields"],function(b){var d={url:b.params.url,type:b.params.type||"GET",data:{}},e=h(b.element.name);a.each(j(b.params.additionalfields||b.element.name),function(i,h){var c=g(h,e);d.data[c]=function(){var d=a(b.form).find(":input").filter("[name='"+f(c)+"']");return d.is(":checkbox")?d.filter(":checked").val()||d.filter(":hidden").val()||"":d.is(":radio")?d.filter(":checked").val()||"":d.val()}});c(b,"remote",d)});b.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&c(a,"minlength",a.params.min);a.params.nonalphamin&&c(a,"nonalphamin",a.params.nonalphamin);a.params.regex&&c(a,"regex",a.params.regex)});a(function(){d.unobtrusive.parse(document)})})(jQuery);;
/*!
 * Modernizr v2.8.3
 * www.modernizr.com
 *
 * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton
 * Available under the BSD and MIT licenses: www.modernizr.com/license/
 */

/*
 * Modernizr tests which native CSS3 and HTML5 features are available in
 * the current UA and makes the results available to you in two ways:
 * as properties on a global Modernizr object, and as classes on the
 * <html> element. This information allows you to progressively enhance
 * your pages with a granular level of control over the experience.
 *
 * Modernizr has an optional (not included) conditional resource loader
 * called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
 * To get a build that includes Modernizr.load(), as well as choosing
 * which tests to include, go to www.modernizr.com/download/
 *
 * Authors        Faruk Ates, Paul Irish, Alex Sexton
 * Contributors   Ryan Seddon, Ben Alman
 */

window.Modernizr = (function( window, document, undefined ) {

    var version = '2.8.3',

    Modernizr = {},

    /*>>cssclasses*/
    // option for enabling the HTML classes to be added
    enableClasses = true,
    /*>>cssclasses*/

    docElement = document.documentElement,

    /**
     * Create our "modernizr" element that we do most feature tests on.
     */
    mod = 'modernizr',
    modElem = document.createElement(mod),
    mStyle = modElem.style,

    /**
     * Create the input element for various Web Forms feature tests.
     */
    inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ ,

    /*>>smile*/
    smile = ':)',
    /*>>smile*/

    toString = {}.toString,

    // TODO :: make the prefixes more granular
    /*>>prefixes*/
    // List of property values to set for css tests. See ticket #21
    prefixes = ' -webkit- -moz- -o- -ms- '.split(' '),
    /*>>prefixes*/

    /*>>domprefixes*/
    // Following spec is to expose vendor-specific style properties as:
    //   elem.style.WebkitBorderRadius
    // and the following would be incorrect:
    //   elem.style.webkitBorderRadius

    // Webkit ghosts their properties in lowercase but Opera & Moz do not.
    // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+
    //   erik.eae.net/archives/2008/03/10/21.48.10/

    // More here: github.com/Modernizr/Modernizr/issues/issue/21
    omPrefixes = 'Webkit Moz O ms',

    cssomPrefixes = omPrefixes.split(' '),

    domPrefixes = omPrefixes.toLowerCase().split(' '),
    /*>>domprefixes*/

    /*>>ns*/
    ns = {'svg': 'http://www.w3.org/2000/svg'},
    /*>>ns*/

    tests = {},
    inputs = {},
    attrs = {},

    classes = [],

    slice = classes.slice,

    featureName, // used in testing loop


    /*>>teststyles*/
    // Inject element with style element and some CSS rules
    injectElementWithStyles = function( rule, callback, nodes, testnames ) {

      var style, ret, node, docOverflow,
          div = document.createElement('div'),
          // After page load injecting a fake body doesn't work so check if body exists
          body = document.body,
          // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it.
          fakeBody = body || document.createElement('body');

      if ( parseInt(nodes, 10) ) {
          // In order not to give false positives we create a node for each test
          // This also allows the method to scale for unspecified uses
          while ( nodes-- ) {
              node = document.createElement('div');
              node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
              div.appendChild(node);
          }
      }

      // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
      // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
      // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
      // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
      // Documents served as xml will throw if using &shy; so use xml friendly encoded version. See issue #277
      style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join('');
      div.id = mod;
      // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.
      // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270
      (body ? div : fakeBody).innerHTML += style;
      fakeBody.appendChild(div);
      if ( !body ) {
          //avoid crashing IE8, if background image is used
          fakeBody.style.background = '';
          //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
          fakeBody.style.overflow = 'hidden';
          docOverflow = docElement.style.overflow;
          docElement.style.overflow = 'hidden';
          docElement.appendChild(fakeBody);
      }

      ret = callback(div, rule);
      // If this is done after page load we don't want to remove the body so check if body exists
      if ( !body ) {
          fakeBody.parentNode.removeChild(fakeBody);
          docElement.style.overflow = docOverflow;
      } else {
          div.parentNode.removeChild(div);
      }

      return !!ret;

    },
    /*>>teststyles*/

    /*>>mq*/
    // adapted from matchMedia polyfill
    // by Scott Jehl and Paul Irish
    // gist.github.com/786768
    testMediaQuery = function( mq ) {

      var matchMedia = window.matchMedia || window.msMatchMedia;
      if ( matchMedia ) {
        return matchMedia(mq) && matchMedia(mq).matches || false;
      }

      var bool;

      injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
        bool = (window.getComputedStyle ?
                  getComputedStyle(node, null) :
                  node.currentStyle)['position'] == 'absolute';
      });

      return bool;

     },
     /*>>mq*/


    /*>>hasevent*/
    //
    // isEventSupported determines if a given element supports the given event
    // kangax.github.com/iseventsupported/
    //
    // The following results are known incorrects:
    //   Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative
    //   Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333
    //   ...
    isEventSupported = (function() {

      var TAGNAMES = {
        'select': 'input', 'change': 'input',
        'submit': 'form', 'reset': 'form',
        'error': 'img', 'load': 'img', 'abort': 'img'
      };

      function isEventSupported( eventName, element ) {

        element = element || document.createElement(TAGNAMES[eventName] || 'div');
        eventName = 'on' + eventName;

        // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
        var isSupported = eventName in element;

        if ( !isSupported ) {
          // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
          if ( !element.setAttribute ) {
            element = document.createElement('div');
          }
          if ( element.setAttribute && element.removeAttribute ) {
            element.setAttribute(eventName, '');
            isSupported = is(element[eventName], 'function');

            // If property was created, "remove it" (by setting value to `undefined`)
            if ( !is(element[eventName], 'undefined') ) {
              element[eventName] = undefined;
            }
            element.removeAttribute(eventName);
          }
        }

        element = null;
        return isSupported;
      }
      return isEventSupported;
    })(),
    /*>>hasevent*/

    // TODO :: Add flag for hasownprop ? didn't last time

    // hasOwnProperty shim by kangax needed for Safari 2.0 support
    _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp;

    if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) {
      hasOwnProp = function (object, property) {
        return _hasOwnProperty.call(object, property);
      };
    }
    else {
      hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
        return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
      };
    }

    // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js
    // es5.github.com/#x15.3.4.5

    if (!Function.prototype.bind) {
      Function.prototype.bind = function bind(that) {

        var target = this;

        if (typeof target != "function") {
            throw new TypeError();
        }

        var args = slice.call(arguments, 1),
            bound = function () {

            if (this instanceof bound) {

              var F = function(){};
              F.prototype = target.prototype;
              var self = new F();

              var result = target.apply(
                  self,
                  args.concat(slice.call(arguments))
              );
              if (Object(result) === result) {
                  return result;
              }
              return self;

            } else {

              return target.apply(
                  that,
                  args.concat(slice.call(arguments))
              );

            }

        };

        return bound;
      };
    }

    /**
     * setCss applies given styles to the Modernizr DOM node.
     */
    function setCss( str ) {
        mStyle.cssText = str;
    }

    /**
     * setCssAll extrapolates all vendor-specific css strings.
     */
    function setCssAll( str1, str2 ) {
        return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
    }

    /**
     * is returns a boolean for if typeof obj is exactly type.
     */
    function is( obj, type ) {
        return typeof obj === type;
    }

    /**
     * contains returns a boolean for if substr is found within str.
     */
    function contains( str, substr ) {
        return !!~('' + str).indexOf(substr);
    }

    /*>>testprop*/

    // testProps is a generic CSS / DOM property test.

    // In testing support for a given CSS property, it's legit to test:
    //    `elem.style[styleName] !== undefined`
    // If the property is supported it will return an empty string,
    // if unsupported it will return undefined.

    // We'll take advantage of this quick test and skip setting a style
    // on our modernizr element, but instead just testing undefined vs
    // empty string.

    // Because the testing of the CSS property names (with "-", as
    // opposed to the camelCase DOM properties) is non-portable and
    // non-standard but works in WebKit and IE (but not Gecko or Opera),
    // we explicitly reject properties with dashes so that authors
    // developing in WebKit or IE first don't end up with
    // browser-specific content by accident.

    function testProps( props, prefixed ) {
        for ( var i in props ) {
            var prop = props[i];
            if ( !contains(prop, "-") && mStyle[prop] !== undefined ) {
                return prefixed == 'pfx' ? prop : true;
            }
        }
        return false;
    }
    /*>>testprop*/

    // TODO :: add testDOMProps
    /**
     * testDOMProps is a generic DOM property test; if a browser supports
     *   a certain property, it won't return undefined for it.
     */
    function testDOMProps( props, obj, elem ) {
        for ( var i in props ) {
            var item = obj[props[i]];
            if ( item !== undefined) {

                // return the property name as a string
                if (elem === false) return props[i];

                // let's bind a function
                if (is(item, 'function')){
                  // default to autobind unless override
                  return item.bind(elem || obj);
                }

                // return the unbound function or obj or value
                return item;
            }
        }
        return false;
    }

    /*>>testallprops*/
    /**
     * testPropsAll tests a list of DOM properties we want to check against.
     *   We specify literally ALL possible (known and/or likely) properties on
     *   the element including the non-vendor prefixed one, for forward-
     *   compatibility.
     */
    function testPropsAll( prop, prefixed, elem ) {

        var ucProp  = prop.charAt(0).toUpperCase() + prop.slice(1),
            props   = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');

        // did they call .prefixed('boxSizing') or are we just testing a prop?
        if(is(prefixed, "string") || is(prefixed, "undefined")) {
          return testProps(props, prefixed);

        // otherwise, they called .prefixed('requestAnimationFrame', window[, elem])
        } else {
          props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
          return testDOMProps(props, prefixed, elem);
        }
    }
    /*>>testallprops*/


    /**
     * Tests
     * -----
     */

    // The *new* flexbox
    // dev.w3.org/csswg/css3-flexbox

    tests['flexbox'] = function() {
      return testPropsAll('flexWrap');
    };

    // The *old* flexbox
    // www.w3.org/TR/2009/WD-css3-flexbox-20090723/

    tests['flexboxlegacy'] = function() {
        return testPropsAll('boxDirection');
    };

    // On the S60 and BB Storm, getContext exists, but always returns undefined
    // so we actually have to call getContext() to verify
    // github.com/Modernizr/Modernizr/issues/issue/97/

    tests['canvas'] = function() {
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    };

    tests['canvastext'] = function() {
        return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
    };

    // webk.it/70117 is tracking a legit WebGL feature detect proposal

    // We do a soft detect which may false positive in order to avoid
    // an expensive context creation: bugzil.la/732441

    tests['webgl'] = function() {
        return !!window.WebGLRenderingContext;
    };

    /*
     * The Modernizr.touch test only indicates if the browser supports
     *    touch events, which does not necessarily reflect a touchscreen
     *    device, as evidenced by tablets running Windows 7 or, alas,
     *    the Palm Pre / WebOS (touch) phones.
     *
     * Additionally, Chrome (desktop) used to lie about its support on this,
     *    but that has since been rectified: crbug.com/36415
     *
     * We also test for Firefox 4 Multitouch Support.
     *
     * For more info, see: modernizr.github.com/Modernizr/touch.html
     */

    tests['touch'] = function() {
        var bool;

        if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
          bool = true;
        } else {
          injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) {
            bool = node.offsetTop === 9;
          });
        }

        return bool;
    };


    // geolocation is often considered a trivial feature detect...
    // Turns out, it's quite tricky to get right:
    //
    // Using !!navigator.geolocation does two things we don't want. It:
    //   1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513
    //   2. Disables page caching in WebKit: webk.it/43956
    //
    // Meanwhile, in Firefox < 8, an about:config setting could expose
    // a false positive that would throw an exception: bugzil.la/688158

    tests['geolocation'] = function() {
        return 'geolocation' in navigator;
    };


    tests['postmessage'] = function() {
      return !!window.postMessage;
    };


    // Chrome incognito mode used to throw an exception when using openDatabase
    // It doesn't anymore.
    tests['websqldatabase'] = function() {
      return !!window.openDatabase;
    };

    // Vendors had inconsistent prefixing with the experimental Indexed DB:
    // - Webkit's implementation is accessible through webkitIndexedDB
    // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
    // For speed, we don't test the legacy (and beta-only) indexedDB
    tests['indexedDB'] = function() {
      return !!testPropsAll("indexedDB", window);
    };

    // documentMode logic from YUI to filter out IE8 Compat Mode
    //   which false positives.
    tests['hashchange'] = function() {
      return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
    };

    // Per 1.6:
    // This used to be Modernizr.historymanagement but the longer
    // name has been deprecated in favor of a shorter and property-matching one.
    // The old API is still available in 1.6, but as of 2.0 will throw a warning,
    // and in the first release thereafter disappear entirely.
    tests['history'] = function() {
      return !!(window.history && history.pushState);
    };

    tests['draganddrop'] = function() {
        var div = document.createElement('div');
        return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
    };

    // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10
    // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17.
    // FF10 still uses prefixes, so check for it until then.
    // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/
    tests['websockets'] = function() {
        return 'WebSocket' in window || 'MozWebSocket' in window;
    };


    // css-tricks.com/rgba-browser-support/
    tests['rgba'] = function() {
        // Set an rgba() color and check the returned value

        setCss('background-color:rgba(150,255,150,.5)');

        return contains(mStyle.backgroundColor, 'rgba');
    };

    tests['hsla'] = function() {
        // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
        //   except IE9 who retains it as hsla

        setCss('background-color:hsla(120,40%,100%,.5)');

        return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
    };

    tests['multiplebgs'] = function() {
        // Setting multiple images AND a color on the background shorthand property
        //  and then querying the style.background property value for the number of
        //  occurrences of "url(" is a reliable method for detecting ACTUAL support for this!

        setCss('background:url(https://),url(https://),red url(https://)');

        // If the UA supports multiple backgrounds, there should be three occurrences
        //   of the string "url(" in the return value for elemStyle.background

        return (/(url\s*\(.*?){3}/).test(mStyle.background);
    };



    // this will false positive in Opera Mini
    //   github.com/Modernizr/Modernizr/issues/396

    tests['backgroundsize'] = function() {
        return testPropsAll('backgroundSize');
    };

    tests['borderimage'] = function() {
        return testPropsAll('borderImage');
    };


    // Super comprehensive table about all the unique implementations of
    // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance

    tests['borderradius'] = function() {
        return testPropsAll('borderRadius');
    };

    // WebOS unfortunately false positives on this test.
    tests['boxshadow'] = function() {
        return testPropsAll('boxShadow');
    };

    // FF3.0 will false positive on this test
    tests['textshadow'] = function() {
        return document.createElement('div').style.textShadow === '';
    };


    tests['opacity'] = function() {
        // Browsers that actually have CSS Opacity implemented have done so
        //  according to spec, which means their return values are within the
        //  range of [0.0,1.0] - including the leading zero.

        setCssAll('opacity:.55');

        // The non-literal . in this regex is intentional:
        //   German Chrome returns this value as 0,55
        // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
        return (/^0.55$/).test(mStyle.opacity);
    };


    // Note, Android < 4 will pass this test, but can only animate
    //   a single property at a time
    //   goo.gl/v3V4Gp
    tests['cssanimations'] = function() {
        return testPropsAll('animationName');
    };


    tests['csscolumns'] = function() {
        return testPropsAll('columnCount');
    };


    tests['cssgradients'] = function() {
        /**
         * For CSS Gradients syntax, please see:
         * webkit.org/blog/175/introducing-css-gradients/
         * developer.mozilla.org/en/CSS/-moz-linear-gradient
         * developer.mozilla.org/en/CSS/-moz-radial-gradient
         * dev.w3.org/csswg/css3-images/#gradients-
         */

        var str1 = 'background-image:',
            str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
            str3 = 'linear-gradient(left top,#9f9, white);';

        setCss(
             // legacy webkit syntax (FIXME: remove when syntax not in use anymore)
              (str1 + '-webkit- '.split(' ').join(str2 + str1) +
             // standard syntax             // trailing 'background-image:'
              prefixes.join(str3 + str1)).slice(0, -str1.length)
        );

        return contains(mStyle.backgroundImage, 'gradient');
    };


    tests['cssreflections'] = function() {
        return testPropsAll('boxReflect');
    };


    tests['csstransforms'] = function() {
        return !!testPropsAll('transform');
    };


    tests['csstransforms3d'] = function() {

        var ret = !!testPropsAll('perspective');

        // Webkit's 3D transforms are passed off to the browser's own graphics renderer.
        //   It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
        //   some conditions. As a result, Webkit typically recognizes the syntax but
        //   will sometimes throw a false positive, thus we must do a more thorough check:
        if ( ret && 'webkitPerspective' in docElement.style ) {

          // Webkit allows this media query to succeed only if the feature is enabled.
          // `@media (transform-3d),(-webkit-transform-3d){ ... }`
          injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) {
            ret = node.offsetLeft === 9 && node.offsetHeight === 3;
          });
        }
        return ret;
    };


    tests['csstransitions'] = function() {
        return testPropsAll('transition');
    };


    /*>>fontface*/
    // @font-face detection routine by Diego Perini
    // javascript.nwbox.com/CSSSupport/

    // false positives:
    //   WebOS github.com/Modernizr/Modernizr/issues/342
    //   WP7   github.com/Modernizr/Modernizr/issues/538
    tests['fontface'] = function() {
        var bool;

        injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) {
          var style = document.getElementById('smodernizr'),
              sheet = style.sheet || style.styleSheet,
              cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : '';

          bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0;
        });

        return bool;
    };
    /*>>fontface*/

    // CSS generated content detection
    tests['generatedcontent'] = function() {
        var bool;

        injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) {
          bool = node.offsetHeight >= 3;
        });

        return bool;
    };



    // These tests evaluate support of the video/audio elements, as well as
    // testing what types of content they support.
    //
    // We're using the Boolean constructor here, so that we can extend the value
    // e.g.  Modernizr.video     // true
    //       Modernizr.video.ogg // 'probably'
    //
    // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
    //                     thx to NielsLeenheer and zcorpan

    // Note: in some older browsers, "no" was a return value instead of empty string.
    //   It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2
    //   It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5

    tests['video'] = function() {
        var elem = document.createElement('video'),
            bool = false;

        // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
        try {
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('video/ogg; codecs="theora"')      .replace(/^no$/,'');

                // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
                bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,'');

                bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,'');
            }

        } catch(e) { }

        return bool;
    };

    tests['audio'] = function() {
        var elem = document.createElement('audio'),
            bool = false;

        try {
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,'');
                bool.mp3  = elem.canPlayType('audio/mpeg;')               .replace(/^no$/,'');

                // Mimetypes accepted:
                //   developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
                //   bit.ly/iphoneoscodecs
                bool.wav  = elem.canPlayType('audio/wav; codecs="1"')     .replace(/^no$/,'');
                bool.m4a  = ( elem.canPlayType('audio/x-m4a;')            ||
                              elem.canPlayType('audio/aac;'))             .replace(/^no$/,'');
            }
        } catch(e) { }

        return bool;
    };


    // In FF4, if disabled, window.localStorage should === null.

    // Normally, we could not test that directly and need to do a
    //   `('localStorage' in window) && ` test first because otherwise Firefox will
    //   throw bugzil.la/365772 if cookies are disabled

    // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem
    // will throw the exception:
    //   QUOTA_EXCEEDED_ERRROR DOM Exception 22.
    // Peculiarly, getItem and removeItem calls do not throw.

    // Because we are forced to try/catch this, we'll go aggressive.

    // Just FWIW: IE8 Compat mode supports these features completely:
    //   www.quirksmode.org/dom/html5.html
    // But IE8 doesn't support either with local files

    tests['localstorage'] = function() {
        try {
            localStorage.setItem(mod, mod);
            localStorage.removeItem(mod);
            return true;
        } catch(e) {
            return false;
        }
    };

    tests['sessionstorage'] = function() {
        try {
            sessionStorage.setItem(mod, mod);
            sessionStorage.removeItem(mod);
            return true;
        } catch(e) {
            return false;
        }
    };


    tests['webworkers'] = function() {
        return !!window.Worker;
    };


    tests['applicationcache'] = function() {
        return !!window.applicationCache;
    };


    // Thanks to Erik Dahlstrom
    tests['svg'] = function() {
        return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
    };

    // specifically for SVG inline in HTML, not within XHTML
    // test page: paulirish.com/demo/inline-svg
    tests['inlinesvg'] = function() {
      var div = document.createElement('div');
      div.innerHTML = '<svg/>';
      return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
    };

    // SVG SMIL animation
    tests['smil'] = function() {
        return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
    };

    // This test is only for clip paths in SVG proper, not clip paths on HTML content
    // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg

    // However read the comments to dig into applying SVG clippaths to HTML content here:
    //   github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491
    tests['svgclippaths'] = function() {
        return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
    };

    /*>>webforms*/
    // input features and input types go directly onto the ret object, bypassing the tests loop.
    // Hold this guy to execute in a moment.
    function webforms() {
        /*>>input*/
        // Run through HTML5's new input attributes to see if the UA understands any.
        // We're using f which is the <input> element created early on
        // Mike Taylr has created a comprehensive resource for testing these attributes
        //   when applied to all input types:
        //   miketaylr.com/code/input-type-attr.html
        // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary

        // Only input placeholder is tested while textarea's placeholder is not.
        // Currently Safari 4 and Opera 11 have support only for the input placeholder
        // Both tests are available in feature-detects/forms-placeholder.js
        Modernizr['input'] = (function( props ) {
            for ( var i = 0, len = props.length; i < len; i++ ) {
                attrs[ props[i] ] = !!(props[i] in inputElem);
            }
            if (attrs.list){
              // safari false positive's on datalist: webk.it/74252
              // see also github.com/Modernizr/Modernizr/issues/146
              attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement);
            }
            return attrs;
        })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));
        /*>>input*/

        /*>>inputtypes*/
        // Run through HTML5's new input types to see if the UA understands any.
        //   This is put behind the tests runloop because it doesn't return a
        //   true/false like all the other tests; instead, it returns an object
        //   containing each input type with its corresponding true/false value

        // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/
        Modernizr['inputtypes'] = (function(props) {

            for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {

                inputElem.setAttribute('type', inputElemType = props[i]);
                bool = inputElem.type !== 'text';

                // We first check to see if the type we give it sticks..
                // If the type does, we feed it a textual value, which shouldn't be valid.
                // If the value doesn't stick, we know there's input sanitization which infers a custom UI
                if ( bool ) {

                    inputElem.value         = smile;
                    inputElem.style.cssText = 'position:absolute;visibility:hidden;';

                    if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {

                      docElement.appendChild(inputElem);
                      defaultView = document.defaultView;

                      // Safari 2-4 allows the smiley as a value, despite making a slider
                      bool =  defaultView.getComputedStyle &&
                              defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
                              // Mobile android web browser has false positive, so must
                              // check the height to see if the widget is actually there.
                              (inputElem.offsetHeight !== 0);

                      docElement.removeChild(inputElem);

                    } else if ( /^(search|tel)$/.test(inputElemType) ){
                      // Spec doesn't define any special parsing or detectable UI
                      //   behaviors so we pass these through as true

                      // Interestingly, opera fails the earlier test, so it doesn't
                      //  even make it here.

                    } else if ( /^(url|email)$/.test(inputElemType) ) {
                      // Real url and email support comes with prebaked validation.
                      bool = inputElem.checkValidity && inputElem.checkValidity() === false;

                    } else {
                      // If the upgraded input compontent rejects the :) text, we got a winner
                      bool = inputElem.value != smile;
                    }
                }

                inputs[ props[i] ] = !!bool;
            }
            return inputs;
        })('search tel url email datetime date month week time datetime-local number range color'.split(' '));
        /*>>inputtypes*/
    }
    /*>>webforms*/


    // End of test definitions
    // -----------------------



    // Run through all tests and detect their support in the current UA.
    // todo: hypothetically we could be doing an array of tests and use a basic loop here.
    for ( var feature in tests ) {
        if ( hasOwnProp(tests, feature) ) {
            // run the test, throw the return value into the Modernizr,
            //   then based on that boolean, define an appropriate className
            //   and push it into an array of classes we'll join later.
            featureName  = feature.toLowerCase();
            Modernizr[featureName] = tests[feature]();

            classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
        }
    }

    /*>>webforms*/
    // input tests need to run.
    Modernizr.input || webforms();
    /*>>webforms*/


    /**
     * addTest allows the user to define their own feature tests
     * the result will be added onto the Modernizr object,
     * as well as an appropriate className set on the html element
     *
     * @param feature - String naming the feature
     * @param test - Function returning true if feature is supported, false if not
     */
     Modernizr.addTest = function ( feature, test ) {
       if ( typeof feature == 'object' ) {
         for ( var key in feature ) {
           if ( hasOwnProp( feature, key ) ) {
             Modernizr.addTest( key, feature[ key ] );
           }
         }
       } else {

         feature = feature.toLowerCase();

         if ( Modernizr[feature] !== undefined ) {
           // we're going to quit if you're trying to overwrite an existing test
           // if we were to allow it, we'd do this:
           //   var re = new RegExp("\\b(no-)?" + feature + "\\b");
           //   docElement.className = docElement.className.replace( re, '' );
           // but, no rly, stuff 'em.
           return Modernizr;
         }

         test = typeof test == 'function' ? test() : test;

         if (typeof enableClasses !== "undefined" && enableClasses) {
           docElement.className += ' ' + (test ? '' : 'no-') + feature;
         }
         Modernizr[feature] = test;

       }

       return Modernizr; // allow chaining.
     };


    // Reset modElem.cssText to nothing to reduce memory footprint.
    setCss('');
    modElem = inputElem = null;

    /*>>shiv*/
    /**
     * @preserve HTML5 Shiv prev3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
     */
    ;(function(window, document) {
        /*jshint evil:true */
        /** version */
        var version = '3.7.0';

        /** Preset options */
        var options = window.html5 || {};

        /** Used to skip problem elements */
        var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;

        /** Not all elements can be cloned in IE **/
        var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;

        /** Detect whether the browser supports default html5 styles */
        var supportsHtml5Styles;

        /** Name of the expando, to work with multiple documents or to re-shiv one document */
        var expando = '_html5shiv';

        /** The id for the the documents expando */
        var expanID = 0;

        /** Cached data for each document */
        var expandoData = {};

        /** Detect whether the browser supports unknown elements */
        var supportsUnknownElements;

        (function() {
          try {
            var a = document.createElement('a');
            a.innerHTML = '<xyz></xyz>';
            //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
            supportsHtml5Styles = ('hidden' in a);

            supportsUnknownElements = a.childNodes.length == 1 || (function() {
              // assign a false positive if unable to shiv
              (document.createElement)('a');
              var frag = document.createDocumentFragment();
              return (
                typeof frag.cloneNode == 'undefined' ||
                typeof frag.createDocumentFragment == 'undefined' ||
                typeof frag.createElement == 'undefined'
              );
            }());
          } catch(e) {
            // assign a false positive if detection fails => unable to shiv
            supportsHtml5Styles = true;
            supportsUnknownElements = true;
          }

        }());

        /*--------------------------------------------------------------------------*/

        /**
         * Creates a style sheet with the given CSS text and adds it to the document.
         * @private
         * @param {Document} ownerDocument The document.
         * @param {String} cssText The CSS text.
         * @returns {StyleSheet} The style element.
         */
        function addStyleSheet(ownerDocument, cssText) {
          var p = ownerDocument.createElement('p'),
          parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;

          p.innerHTML = 'x<style>' + cssText + '</style>';
          return parent.insertBefore(p.lastChild, parent.firstChild);
        }

        /**
         * Returns the value of `html5.elements` as an array.
         * @private
         * @returns {Array} An array of shived element node names.
         */
        function getElements() {
          var elements = html5.elements;
          return typeof elements == 'string' ? elements.split(' ') : elements;
        }

        /**
         * Returns the data associated to the given document
         * @private
         * @param {Document} ownerDocument The document.
         * @returns {Object} An object of data.
         */
        function getExpandoData(ownerDocument) {
          var data = expandoData[ownerDocument[expando]];
          if (!data) {
            data = {};
            expanID++;
            ownerDocument[expando] = expanID;
            expandoData[expanID] = data;
          }
          return data;
        }

        /**
         * returns a shived element for the given nodeName and document
         * @memberOf html5
         * @param {String} nodeName name of the element
         * @param {Document} ownerDocument The context document.
         * @returns {Object} The shived element.
         */
        function createElement(nodeName, ownerDocument, data){
          if (!ownerDocument) {
            ownerDocument = document;
          }
          if(supportsUnknownElements){
            return ownerDocument.createElement(nodeName);
          }
          if (!data) {
            data = getExpandoData(ownerDocument);
          }
          var node;

          if (data.cache[nodeName]) {
            node = data.cache[nodeName].cloneNode();
          } else if (saveClones.test(nodeName)) {
            node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
          } else {
            node = data.createElem(nodeName);
          }

          // Avoid adding some elements to fragments in IE < 9 because
          // * Attributes like `name` or `type` cannot be set/changed once an element
          //   is inserted into a document/fragment
          // * Link elements with `src` attributes that are inaccessible, as with
          //   a 403 response, will cause the tab/window to crash
          // * Script elements appended to fragments will execute when their `src`
          //   or `text` property is set
          return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
        }

        /**
         * returns a shived DocumentFragment for the given document
         * @memberOf html5
         * @param {Document} ownerDocument The context document.
         * @returns {Object} The shived DocumentFragment.
         */
        function createDocumentFragment(ownerDocument, data){
          if (!ownerDocument) {
            ownerDocument = document;
          }
          if(supportsUnknownElements){
            return ownerDocument.createDocumentFragment();
          }
          data = data || getExpandoData(ownerDocument);
          var clone = data.frag.cloneNode(),
          i = 0,
          elems = getElements(),
          l = elems.length;
          for(;i<l;i++){
            clone.createElement(elems[i]);
          }
          return clone;
        }

        /**
         * Shivs the `createElement` and `createDocumentFragment` methods of the document.
         * @private
         * @param {Document|DocumentFragment} ownerDocument The document.
         * @param {Object} data of the document.
         */
        function shivMethods(ownerDocument, data) {
          if (!data.cache) {
            data.cache = {};
            data.createElem = ownerDocument.createElement;
            data.createFrag = ownerDocument.createDocumentFragment;
            data.frag = data.createFrag();
          }


          ownerDocument.createElement = function(nodeName) {
            //abort shiv
            if (!html5.shivMethods) {
              return data.createElem(nodeName);
            }
            return createElement(nodeName, ownerDocument, data);
          };

          ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
                                                          'var n=f.cloneNode(),c=n.createElement;' +
                                                          'h.shivMethods&&(' +
                                                          // unroll the `createElement` calls
                                                          getElements().join().replace(/[\w\-]+/g, function(nodeName) {
            data.createElem(nodeName);
            data.frag.createElement(nodeName);
            return 'c("' + nodeName + '")';
          }) +
            ');return n}'
                                                         )(html5, data.frag);
        }

        /*--------------------------------------------------------------------------*/

        /**
         * Shivs the given document.
         * @memberOf html5
         * @param {Document} ownerDocument The document to shiv.
         * @returns {Document} The shived document.
         */
        function shivDocument(ownerDocument) {
          if (!ownerDocument) {
            ownerDocument = document;
          }
          var data = getExpandoData(ownerDocument);

          if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
            data.hasCSS = !!addStyleSheet(ownerDocument,
                                          // corrects block display not defined in IE6/7/8/9
                                          'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
                                            // adds styling not present in IE6/7/8/9
                                            'mark{background:#FF0;color:#000}' +
                                            // hides non-rendered elements
                                            'template{display:none}'
                                         );
          }
          if (!supportsUnknownElements) {
            shivMethods(ownerDocument, data);
          }
          return ownerDocument;
        }

        /*--------------------------------------------------------------------------*/

        /**
         * The `html5` object is exposed so that more elements can be shived and
         * existing shiving can be detected on iframes.
         * @type Object
         * @example
         *
         * // options can be changed before the script is included
         * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
         */
        var html5 = {

          /**
           * An array or space separated string of node names of the elements to shiv.
           * @memberOf html5
           * @type Array|String
           */
          'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video',

          /**
           * current version of html5shiv
           */
          'version': version,

          /**
           * A flag to indicate that the HTML5 style sheet should be inserted.
           * @memberOf html5
           * @type Boolean
           */
          'shivCSS': (options.shivCSS !== false),

          /**
           * Is equal to true if a browser supports creating unknown/HTML5 elements
           * @memberOf html5
           * @type boolean
           */
          'supportsUnknownElements': supportsUnknownElements,

          /**
           * A flag to indicate that the document's `createElement` and `createDocumentFragment`
           * methods should be overwritten.
           * @memberOf html5
           * @type Boolean
           */
          'shivMethods': (options.shivMethods !== false),

          /**
           * A string to describe the type of `html5` object ("default" or "default print").
           * @memberOf html5
           * @type String
           */
          'type': 'default',

          // shivs the document according to the specified `html5` object options
          'shivDocument': shivDocument,

          //creates a shived element
          createElement: createElement,

          //creates a shived documentFragment
          createDocumentFragment: createDocumentFragment
        };

        /*--------------------------------------------------------------------------*/

        // expose html5
        window.html5 = html5;

        // shiv the document
        shivDocument(document);

    }(this, document));
    /*>>shiv*/

    // Assign private properties to the return object with prefix
    Modernizr._version      = version;

    // expose these for the plugin API. Look in the source for how to join() them against your input
    /*>>prefixes*/
    Modernizr._prefixes     = prefixes;
    /*>>prefixes*/
    /*>>domprefixes*/
    Modernizr._domPrefixes  = domPrefixes;
    Modernizr._cssomPrefixes  = cssomPrefixes;
    /*>>domprefixes*/

    /*>>mq*/
    // Modernizr.mq tests a given media query, live against the current state of the window
    // A few important notes:
    //   * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
    //   * A max-width or orientation query will be evaluated against the current state, which may change later.
    //   * You must specify values. Eg. If you are testing support for the min-width media query use:
    //       Modernizr.mq('(min-width:0)')
    // usage:
    // Modernizr.mq('only screen and (max-width:768)')
    Modernizr.mq            = testMediaQuery;
    /*>>mq*/

    /*>>hasevent*/
    // Modernizr.hasEvent() detects support for a given event, with an optional element to test on
    // Modernizr.hasEvent('gesturestart', elem)
    Modernizr.hasEvent      = isEventSupported;
    /*>>hasevent*/

    /*>>testprop*/
    // Modernizr.testProp() investigates whether a given style property is recognized
    // Note that the property names must be provided in the camelCase variant.
    // Modernizr.testProp('pointerEvents')
    Modernizr.testProp      = function(prop){
        return testProps([prop]);
    };
    /*>>testprop*/

    /*>>testallprops*/
    // Modernizr.testAllProps() investigates whether a given style property,
    //   or any of its vendor-prefixed variants, is recognized
    // Note that the property names must be provided in the camelCase variant.
    // Modernizr.testAllProps('boxSizing')
    Modernizr.testAllProps  = testPropsAll;
    /*>>testallprops*/


    /*>>teststyles*/
    // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
    // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
    Modernizr.testStyles    = injectElementWithStyles;
    /*>>teststyles*/


    /*>>prefixed*/
    // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
    // Modernizr.prefixed('boxSizing') // 'MozBoxSizing'

    // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
    // Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
    //
    //     str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');

    // If you're trying to ascertain which transition end event to bind to, you might do something like...
    //
    //     var transEndEventNames = {
    //       'WebkitTransition' : 'webkitTransitionEnd',
    //       'MozTransition'    : 'transitionend',
    //       'OTransition'      : 'oTransitionEnd',
    //       'msTransition'     : 'MSTransitionEnd',
    //       'transition'       : 'transitionend'
    //     },
    //     transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];

    Modernizr.prefixed      = function(prop, obj, elem){
      if(!obj) {
        return testPropsAll(prop, 'pfx');
      } else {
        // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame'
        return testPropsAll(prop, obj, elem);
      }
    };
    /*>>prefixed*/


    /*>>cssclasses*/
    // Remove "no-js" class from <html> element, if it exists:
    docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') +

                            // Add the new classes to the <html> element.
                            (enableClasses ? ' js ' + classes.join(' ') : '');
    /*>>cssclasses*/

    return Modernizr;

})(this, this.document);
;
var SKEDCONFIG_ServerTimeZone = "Etc/UTC";
if (SKEDCONFIG_ServerTimeZone.indexOf("{SKED.SeverTimeZone}") != -1) {
	SKEDCONFIG_ServerTimeZone = "Pacific/Auckland";
}

var SKEDCONFIG_UseLocalISOTimeString = "true";
if (SKEDCONFIG_UseLocalISOTimeString.indexOf("{SKED.UseLocalISOTimeString}") != -1) {
	SKEDCONFIG_UseLocalISOTimeString = "false";
}

var SKEDCONFIG_SkedCache = "//sportsgroundproduction.blob.core.windows.net/skedcache/";
if (SKEDCONFIG_SkedCache.indexOf("{SKED.SkedCacheUrl}") != -1) {
    SKEDCONFIG_SkedCache = "https://sportsgrounddevelopment.blob.core.windows.net/skedcache/";
};
/*!
 * Bootstrap v3.3.5 (http://getbootstrap.com)
 * Copyright 2011-2015 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.5",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.5",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.5",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.5",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",c).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f,g.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var d=this,e=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(e),this.isShown||e.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){d.$element.one("mouseup.dismiss.bs.modal",function(b){a(b.target).is(d.$element)&&(d.ignoreBackdropClick=!0)})}),this.backdrop(function(){var e=a.support.transition&&d.$element.hasClass("fade");d.$element.parent().length||d.$element.appendTo(d.$body),d.$element.show().scrollTop(0),d.adjustDialog(),e&&d.$element[0].offsetWidth,d.$element.addClass("in"),d.enforceFocus();var f=a.Event("shown.bs.modal",{relatedTarget:b});e?d.$dialog.one("bsTransitionEnd",function(){d.$element.trigger("focus").trigger(f)}).emulateTransitionEnd(c.TRANSITION_DURATION):d.$element.trigger("focus").trigger(f)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(c.TRANSITION_DURATION):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},c.prototype.resize=function(){this.isShown?a(window).on("resize.bs.modal",a.proxy(this.handleUpdate,this)):a(window).off("resize.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$body.removeClass("modal-open"),a.resetAdjustments(),a.resetScrollbar(),a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var d=this,e=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var f=a.support.transition&&e;if(this.$backdrop=a(document.createElement("div")).addClass("modal-backdrop "+e).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),f&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;f?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var g=function(){d.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",g).emulateTransitionEnd(c.BACKDROP_TRANSITION_DURATION):g()}else b&&b()},c.prototype.handleUpdate=function(){this.adjustDialog()},c.prototype.adjustDialog=function(){var a=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth<a,this.scrollbarWidth=this.measureScrollbar()},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",a,b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-m<o.top?"bottom":"right"==h&&k.right+l>o.width?"left":"left"==h&&k.left-l<o.left?"right":h,f.removeClass(n).addClass(h)}var p=this.getCalculatedOffset(h,k,l,m);this.applyPlacement(p,h);var q=function(){var a=e.hoverState;e.$element.trigger("shown.bs."+e.type),e.hoverState=null,"out"==a&&e.leave(e)};a.support.transition&&this.$tip.hasClass("fade")?f.one("bsTransitionEnd",q).emulateTransitionEnd(c.TRANSITION_DURATION):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top+=g,b.left+=h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=/top|bottom/.test(c),m=l?2*k.left-e+i:2*k.top-f+j,n=l?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(m,d[0][n],l)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c?"left":"top",50*(1-a/b)+"%").css(c?"top":"left","")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(b){function d(){"in"!=e.hoverState&&f.detach(),e.$element.removeAttr("aria-describedby").trigger("hidden.bs."+e.type),b&&b()}var e=this,f=a(this.$tip),g=a.Event("hide.bs."+this.type);return this.$element.trigger(g),g.isDefaultPrevented()?void 0:(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",d).emulateTransitionEnd(c.TRANSITION_DURATION):d(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName,e=c.getBoundingClientRect();null==e.width&&(e=a.extend({},e,{width:e.right-e.left,height:e.bottom-e.top}));var f=d?{top:0,left:0}:b.offset(),g={scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop()},h=d?{width:a(window).width(),height:a(window).height()}:null;return a.extend({},e,g,h,f)},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.5",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.5",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<e[0])return this.activeTarget=null,this.clear();for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(void 0===e[a+1]||b<e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,this.clear();var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),
d.trigger("activate.bs.scrollspy")},b.prototype.clear=function(){a(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.3.5",c.TRANSITION_DURATION=150,c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a"),f=a.Event("hide.bs.tab",{relatedTarget:b[0]}),g=a.Event("show.bs.tab",{relatedTarget:e[0]});if(e.trigger(f),b.trigger(g),!g.isDefaultPrevented()&&!f.isDefaultPrevented()){var h=a(d);this.activate(b.closest("li"),c),this.activate(h,h.parent(),function(){e.trigger({type:"hidden.bs.tab",relatedTarget:b[0]}),b.trigger({type:"shown.bs.tab",relatedTarget:e[0]})})}}},c.prototype.activate=function(b,d,e){function f(){g.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.5",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);;
/**
 * bootstrap-multiselect.js
 * https://github.com/davidstutz/bootstrap-multiselect
 *
 * Copyright 2012 - 2014 David Stutz
 *
 * Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0.
 */
!function($) {
 
    "use strict";// jshint ;_;

    if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) {
        ko.bindingHandlers.multiselect = {

            init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

                var listOfSelectedItems = allBindingsAccessor().selectedOptions,
                    config = ko.utils.unwrapObservable(valueAccessor());

                $(element).multiselect(config);

                if (isObservableArray(listOfSelectedItems)) {
                   //set the initial selection state on the multi-select list
                    $(element).multiselect('select', ko.utils.unwrapObservable(listOfSelectedItems));
                    // Subscribe to the selectedOptions: ko.observableArray
                    listOfSelectedItems.subscribe(function (changes) {
                        var addedArray = [], deletedArray = [];
                        forEach(changes, function (change) {
                            switch (change.status) {
                                case 'added':
                                    addedArray.push(change.value);
                                    break;
                                case 'deleted':
                                    deletedArray.push(change.value);
                                    break;
                            }
                        });
                        if (addedArray.length > 0) {
                            $(element).multiselect('select', addedArray);
                        };
                        if (deletedArray.length > 0) {
                            $(element).multiselect('deselect', deletedArray);
                        };
                    }, null, "arrayChange");
                }
            },

            update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

                var listOfItems = allBindingsAccessor().options,
                    ms = $(element).data('multiselect'),
                    config = ko.utils.unwrapObservable(valueAccessor());

                if (isObservableArray(listOfItems)) {
                    // Subscribe to the options: ko.observableArray incase it changes later
                    listOfItems.subscribe(function (theArray) {
                        $(element).multiselect('rebuild');
                    });
                }

                if (!ms) {
                    $(element).multiselect(config);
                }
                else {
                    ms.updateOriginalOptions();
                }
            }
        };
    }

    function isObservableArray(obj) {
        return ko.isObservable(obj) && !(obj.destroyAll === undefined);
    }

    function forEach(array, callback) {
        var index;
        for (index = 0; index < array.length; ++index) {
            callback(array[index]);
        }
    }

    /**
     * Constructor to create a new multiselect using the given select.
     * 
     * @param {jQuery} select
     * @param {Object} options
     * @returns {Multiselect}
     */
    function Multiselect(select, options) {

        this.options = this.mergeOptions(options);
        this.$select = $(select);

        // Initialization.
        // We have to clone to create a new reference.
        this.originalOptions = this.$select.clone()[0].options;
        this.query = '';
        this.searchTimeout = null;

        this.options.multiple = this.$select.attr('multiple') === "multiple";
        this.options.onChange = $.proxy(this.options.onChange, this);
        this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this);
        this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this);
        this.options.onDropdownShown = $.proxy(this.options.onDropdownShown, this);
        this.options.onDropdownHidden = $.proxy(this.options.onDropdownHidden, this);
        
        // Build select all if enabled.
        this.buildContainer();
        this.buildButton();
        this.buildDropdown();
        this.buildSelectAll();
        this.buildDropdownOptions();
        this.buildFilter();
        
        this.updateButtonText();
        this.updateSelectAll();
        
        if (this.options.disableIfEmpty) {
            this.disableIfEmpty();
        }
        
        this.$select.hide().after(this.$container);
    };

    Multiselect.prototype = {

        defaults: {
            /**
             * Default text function will either print 'None selected' in case no
             * option is selected or a list of the selected options up to a length of 3 selected options.
             * 
             * @param {jQuery} options
             * @param {jQuery} select
             * @returns {String}
             */
            buttonText: function(options, select) {
                if (options.length === 0) {
                    return this.nonSelectedText + ' <b class="caret"></b>';
                }
                else {
                    if (options.length > this.numberDisplayed) {
                        return options.length + ' ' + this.nSelectedText + ' <b class="caret"></b>';
                    }
                    else {
                        var selected = '';
                        options.each(function() {
                            var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html();

                            selected += label + ', ';
                        });
                        return selected.substr(0, selected.length - 2) + ' <b class="caret"></b>';
                    }
                }
            },
            /**
             * Updates the title of the button similar to the buttonText function.
             * @param {jQuery} options
             * @param {jQuery} select
             * @returns {@exp;selected@call;substr}
             */
            buttonTitle: function(options, select) {
                if (options.length === 0) {
                    return this.nonSelectedText;
                }
                else {
                    var selected = '';
                    options.each(function () {
                        selected += $(this).text() + ', ';
                    });
                    return selected.substr(0, selected.length - 2);
                }
            },
            /**
             * Create a label.
             * 
             * @param {jQuery} element
             * @returns {String}
             */
            label: function(element){
                return $(element).attr('label') || $(element).html();
            },
            /**
             * Triggered on change of the multiselect.
             * Not triggered when selecting/deselecting options manually.
             * 
             * @param {jQuery} option
             * @param {Boolean} checked
             */
            onChange : function(option, checked) {

            },
            /**
             * Triggered when the dropdown is shown.
             * 
             * @param {jQuery} event
             */
            onDropdownShow: function(event) {
                
            },
            /**
             * Triggered when the dropdown is hidden.
             * 
             * @param {jQuery} event
             */
            onDropdownHide: function(event) {
                
            },
            /**
             * Triggered after the dropdown is shown.
             * 
             * @param {jQuery} event
             */
            onDropdownShown: function(event) {
                
            },
            /**
             * Triggered after the dropdown is hidden.
             * 
             * @param {jQuery} event
             */
            onDropdownHidden: function(event) {
                
            },
            buttonClass: 'btn btn-default',
            dropRight: false,
            selectedClass: 'active',
            buttonWidth: 'auto',
            buttonContainer: '<div class="btn-group" />',
            // Maximum height of the dropdown menu.
            // If maximum height is exceeded a scrollbar will be displayed.
            maxHeight: false,
            checkboxName: 'multiselect',
            includeSelectAllOption: false,
            includeSelectAllIfMoreThan: 0,
            selectAllText: ' Select all',
            selectAllValue: 'multiselect-all',
            enableFiltering: false,
            enableCaseInsensitiveFiltering: false,
            filterPlaceholder: 'Search',
            // possible options: 'text', 'value', 'both'
            filterBehavior: 'text',
            preventInputChangeEvent: false,
            nonSelectedText: 'None selected',
            nSelectedText: 'selected',
            numberDisplayed: 3,
            disableIfEmpty: false,
            templates: {
                button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
                ul: '<ul class="multiselect-container dropdown-menu"></ul>',
                filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span><input class="form-control multiselect-search" type="text"></div></li>',
                li: '<li><a href="javascript:void(0);"><label></label></a></li>',
                divider: '<li class="multiselect-item divider"></li>',
                liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
            }
        },

        constructor: Multiselect,

        /**
         * Builds the container of the multiselect.
         */
        buildContainer: function() {
            this.$container = $(this.options.buttonContainer);
            this.$container.on('show.bs.dropdown', this.options.onDropdownShow);
            this.$container.on('hide.bs.dropdown', this.options.onDropdownHide);
            this.$container.on('shown.bs.dropdown', this.options.onDropdownShown);
            this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden);
        },

        /**
         * Builds the button of the multiselect.
         */
        buildButton: function() {
            this.$button = $(this.options.templates.button).addClass(this.options.buttonClass);

            // Adopt active state.
            if (this.$select.prop('disabled')) {
                this.disable();
            }
            else {
                this.enable();
            }

            // Manually add button width if set.
            if (this.options.buttonWidth && this.options.buttonWidth !== 'auto') {
                this.$button.css({
                    'width' : this.options.buttonWidth
                });
                this.$container.css({
                    'width': this.options.buttonWidth
                });
            }

            // Keep the tab index from the select.
            var tabindex = this.$select.attr('tabindex');
            if (tabindex) {
                this.$button.attr('tabindex', tabindex);
            }

            this.$container.prepend(this.$button);
        },

        /**
         * Builds the ul representing the dropdown menu.
         */
        buildDropdown: function() {

            // Build ul.
            this.$ul = $(this.options.templates.ul);

            if (this.options.dropRight) {
                this.$ul.addClass('pull-right');
            }

            // Set max height of dropdown menu to activate auto scrollbar.
            if (this.options.maxHeight) {
                // TODO: Add a class for this option to move the css declarations.
                this.$ul.css({
                    'max-height': this.options.maxHeight + 'px',
                    'overflow-y': 'auto',
                    'overflow-x': 'hidden'
                });
            }

            this.$container.append(this.$ul);
        },

        /**
         * Build the dropdown options and binds all nessecary events.
         * Uses createDivider and createOptionValue to create the necessary options.
         */
        buildDropdownOptions: function() {

            this.$select.children().each($.proxy(function(index, element) {
                
                // Support optgroups and options without a group simultaneously.
                var tag = $(element).prop('tagName')
                    .toLowerCase();
            
                if ($(element).prop('value') == this.options.selectAllValue) {
                    return;
                }

                if (tag === 'optgroup') {
                    this.createOptgroup(element);
                }
                else if (tag === 'option') {

                    if ($(element).data('role') === 'divider') {
                        this.createDivider();
                    }
                    else {
                        this.createOptionValue(element);
                    }

                }
                
                // Other illegal tags will be ignored.
            }, this));

            // Bind the change event on the dropdown elements.
            $('li input', this.$ul).on('change', $.proxy(function(event) {
                var $target = $(event.target);

                var checked = $target.prop('checked') || false;
                var isSelectAllOption = $target.val() === this.options.selectAllValue;

                // Apply or unapply the configured selected class.
                if (this.options.selectedClass) {
                    if (checked) {
                        $target.parents('li')
                            .addClass(this.options.selectedClass);
                    }
                    else {
                        $target.parents('li')
                            .removeClass(this.options.selectedClass);
                    }
                }

                // Get the corresponding option.
                var value = $target.val();
                var $option = this.getOptionByValue(value);

                var $optionsNotThis = $('option', this.$select).not($option);
                var $checkboxesNotThis = $('input', this.$container).not($target);

                if (isSelectAllOption) {
                    if (checked) {
                        this.selectall();
                    }
                    else {
                        this.deselectall();
                    }
                }

                if(!isSelectAllOption){
                    if (checked) {
                        $option.prop('selected', true);

                        if (this.options.multiple) {
                            // Simply select additional option.
                            $option.prop('selected', true);
                        }
                        else {
                            // Unselect all other options and corresponding checkboxes.
                            if (this.options.selectedClass) {
                                $($checkboxesNotThis).parents('li').removeClass(this.options.selectedClass);
                            }

                            $($checkboxesNotThis).prop('checked', false);
                            $optionsNotThis.prop('selected', false);

                            // It's a single selection, so close.
                            this.$button.click();
                        }

                        if (this.options.selectedClass === "active") {
                            $optionsNotThis.parents("a").css("outline", "");
                        }
                    }
                    else {
                        // Unselect option.
                        $option.prop('selected', false);
                    }
                }

                this.$select.change();

                this.updateButtonText();
                this.updateSelectAll();
                
                this.options.onChange($option, checked);

                if(this.options.preventInputChangeEvent) {
                    return false;
                }
            }, this));

            $('li a', this.$ul).on('touchstart click', function(event) {
                event.stopPropagation();

                var $target = $(event.target);

                if (event.shiftKey) {
                    var checked = $target.prop('checked') || false;

                    if (checked) {
                        var prev = $target.parents('li:last')
                            .siblings('li[class="active"]:first');

                        var currentIdx = $target.parents('li')
                            .index();
                        var prevIdx = prev.index();

                        if (currentIdx > prevIdx) {
                            $target.parents("li:last").prevUntil(prev).each(
                                function() {
                                    $(this).find("input:first").prop("checked", true)
                                        .trigger("change");
                                }
                            );
                        }
                        else {
                            $target.parents("li:last").nextUntil(prev).each(
                                function() {
                                    $(this).find("input:first").prop("checked", true)
                                        .trigger("change");
                                }
                            );
                        }
                    }
                }

                $target.blur();
            });

            // Keyboard support.
            this.$container.off('keydown.multiselect').on('keydown.multiselect', $.proxy(function(event) {
                if ($('input[type="text"]', this.$container).is(':focus')) {
                    return;
                }
                if ((event.keyCode === 9 || event.keyCode === 27)
                        && this.$container.hasClass('open')) {
                    
                    // Close on tab or escape.
                    this.$button.click();
                }
                else {
                    var $items = $(this.$container).find("li:not(.divider):not(.disabled) a").filter(":visible");

                    if (!$items.length) {
                        return;
                    }

                    var index = $items.index($items.filter(':focus'));

                    // Navigation up.
                    if (event.keyCode === 38 && index > 0) {
                        index--;
                    }
                    // Navigate down.
                    else if (event.keyCode === 40 && index < $items.length - 1) {
                        index++;
                    }
                    else if (!~index) {
                        index = 0;
                    }

                    var $current = $items.eq(index);
                    $current.focus();

                    if (event.keyCode === 32 || event.keyCode === 13) {
                        var $checkbox = $current.find('input');

                        $checkbox.prop("checked", !$checkbox.prop("checked"));
                        $checkbox.change();
                    }

                    event.stopPropagation();
                    event.preventDefault();
                }
            }, this));
        },

        /**
         * Create an option using the given select option.
         * 
         * @param {jQuery} element
         */
        createOptionValue: function(element) {
            if ($(element).is(':selected')) {
                $(element).prop('selected', true);
            }

            // Support the label attribute on options.
            var label = this.options.label(element);
            var value = $(element).val();
            var inputType = this.options.multiple ? "checkbox" : "radio";

            var $li = $(this.options.templates.li);
            $('label', $li).addClass(inputType);
            $('label', $li).append('<input type="' + inputType + '" name="' + this.options.checkboxName + '" />');

            var selected = $(element).prop('selected') || false;
            var $checkbox = $('input', $li);
            $checkbox.val(value);

            if (value === this.options.selectAllValue) {
                $li.addClass("multiselect-item multiselect-all");
                $checkbox.parent().parent()
                    .addClass('multiselect-all');
            }

            $('label', $li).append(" " + label);

            this.$ul.append($li);

            if ($(element).is(':disabled')) {
                $checkbox.attr('disabled', 'disabled')
                    .prop('disabled', true)
                    .parents('a')
                    .attr("tabindex", "-1")
                    .parents('li')
                    .addClass('disabled');
            }

            $checkbox.prop('checked', selected);

            if (selected && this.options.selectedClass) {
                $checkbox.parents('li')
                    .addClass(this.options.selectedClass);
            }
        },

        /**
         * Creates a divider using the given select option.
         * 
         * @param {jQuery} element
         */
        createDivider: function(element) {
            var $divider = $(this.options.templates.divider);
            this.$ul.append($divider);
        },

        /**
         * Creates an optgroup.
         * 
         * @param {jQuery} group
         */
        createOptgroup: function(group) {
            var groupName = $(group).prop('label');

            // Add a header for the group.
            var $li = $(this.options.templates.liGroup);
            $('label', $li).text(groupName);

            this.$ul.append($li);

            if ($(group).is(':disabled')) {
                $li.addClass('disabled');
            }

            // Add the options of the group.
            $('option', group).each($.proxy(function(index, element) {
                this.createOptionValue(element);
            }, this));
        },

        /**
         * Build the selct all.
         * Checks if a select all has already been created.
         */
        buildSelectAll: function() {
            var alreadyHasSelectAll = this.hasSelectAll();
            
            if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple
                    && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) {
                
                // Check whether to add a divider after the select all.
                if (this.options.includeSelectAllDivider) {
                    this.$ul.prepend($(this.options.templates.divider));
                }

                var $li = $(this.options.templates.li);
                $('label', $li).addClass("checkbox");
                $('label', $li).append('<input type="checkbox" name="' + this.options.checkboxName + '" />');

                var $checkbox = $('input', $li);
                $checkbox.val(this.options.selectAllValue);

                $li.addClass("multiselect-item multiselect-all");
                $checkbox.parent().parent()
                    .addClass('multiselect-all');

                $('label', $li).append(" " + this.options.selectAllText);

                this.$ul.prepend($li);

                $checkbox.prop('checked', false);
            }
        },

        /**
         * Builds the filter.
         */
        buildFilter: function() {

            // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength.
            if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) {
                var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering);

                if (this.$select.find('option').length >= enableFilterLength) {

                    this.$filter = $(this.options.templates.filter);
                    $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder);
                    this.$ul.prepend(this.$filter);

                    this.$filter.val(this.query).on('click', function(event) {
                        event.stopPropagation();
                    }).on('input keydown', $.proxy(function(event) {
                        // This is useful to catch "keydown" events after the browser has updated the control.
                        clearTimeout(this.searchTimeout);

                        this.searchTimeout = this.asyncFunction($.proxy(function() {

                            if (this.query !== event.target.value) {
                                this.query = event.target.value;

                                $.each($('li', this.$ul), $.proxy(function(index, element) {
                                    var value = $('input', element).val();
                                    var text = $('label', element).text();

                                    var filterCandidate = '';
                                    if ((this.options.filterBehavior === 'text')) {
                                        filterCandidate = text;
                                    }
                                    else if ((this.options.filterBehavior === 'value')) {
                                        filterCandidate = value;
                                    }
                                    else if (this.options.filterBehavior === 'both') {
                                        filterCandidate = text + '\n' + value;
                                    }

                                    if (value !== this.options.selectAllValue && text) {
                                        // by default lets assume that element is not
                                        // interesting for this search
                                        var showElement = false;

                                        if (this.options.enableCaseInsensitiveFiltering && filterCandidate.toLowerCase().indexOf(this.query.toLowerCase()) > -1) {
                                            showElement = true;
                                        }
                                        else if (filterCandidate.indexOf(this.query) > -1) {
                                            showElement = true;
                                        }

                                        if (showElement) {
                                            $(element).show().removeClass("filter-hidden");
                                        }
                                        else {
                                            $(element).hide().addClass("filter-hidden");
                                        }
                                    }
                                }, this));
                            }

                            this.updateSelectAll();
                        }, this), 300, this);
                    }, this));
                }
            }
        },

        /**
         * Unbinds the whole plugin.
         */
        destroy: function() {
            this.$container.remove();
            this.$select.show();
            this.$select.data('multiselect', null);
        },

        /**
         * Refreshs the multiselect based on the selected options of the select.
         */
        refresh: function() {
            $('option', this.$select).each($.proxy(function(index, element) {
                var $input = $('li input', this.$ul).filter(function() {
                    return $(this).val() === $(element).val();
                });

                if ($(element).is(':selected')) {
                    $input.prop('checked', true);

                    if (this.options.selectedClass) {
                        $input.parents('li')
                            .addClass(this.options.selectedClass);
                    }
                }
                else {
                    $input.prop('checked', false);

                    if (this.options.selectedClass) {
                        $input.parents('li')
                            .removeClass(this.options.selectedClass);
                    }
                }

                if ($(element).is(":disabled")) {
                    $input.attr('disabled', 'disabled')
                        .prop('disabled', true)
                        .parents('li')
                        .addClass('disabled');
                }
                else {
                    $input.prop('disabled', false)
                        .parents('li')
                        .removeClass('disabled');
                }
            }, this));

            this.updateButtonText();
            this.updateSelectAll();
        },

        /**
         * Select all options of the given values.
         * 
         * @param {Array} selectValues
         */
        select: function(selectValues, triggerOnChange) {
            if(!$.isArray(selectValues)) {
                selectValues = [selectValues];
            }

            for (var i = 0; i < selectValues.length; i++) {
                var value = selectValues[i];

                var $option = this.getOptionByValue(value);
                var $checkbox = this.getInputByValue(value);

                if($option === void(0) || $checkbox === void(0))
                {
                  continue;
                }
                
                if (this.options.selectedClass) {
                    $checkbox.parents('li')
                        .addClass(this.options.selectedClass);
                }

                $checkbox.prop('checked', true);
                $option.prop('selected', true);
            }

            this.updateButtonText();

            if (triggerOnChange && selectValues.length == 1) {
                this.options.onChange($option, true);
            }
        },

        /**
         * Clears all selected items
         * 
         */
        clearSelection: function () {
            this.deselectall(false);
            this.updateButtonText();
            this.updateSelectAll();
        },

        /**
         * Deselects all options of the given values.
         * 
         * @param {Array} deselectValues
         */
        deselect: function(deselectValues, triggerOnChange) {
            if(!$.isArray(deselectValues)) {
                deselectValues = [deselectValues];
            }

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

                var value = deselectValues[i];

                var $option = this.getOptionByValue(value);
                var $checkbox = this.getInputByValue(value);

                if($option === void(0) || $checkbox === void(0))
                {
                  continue;
                }

                if (this.options.selectedClass) {
                    $checkbox.parents('li')
                        .removeClass(this.options.selectedClass);
                }

                $checkbox.prop('checked', false);
                $option.prop('selected', false);
            }

            this.updateButtonText();

            if (triggerOnChange && deselectValues.length == 1) {
                this.options.onChange($option, false);
            }
        },
        
        /**
         * Selects all enabled & visible options.
         * 
         */
        selectall: function () {
            var allCheckboxes = $("li input[type='checkbox']:enabled", this.$ul),
                visibleCheckboxes = allCheckboxes.filter(":visible"),
                allCheckboxesCount = allCheckboxes.length,
                visibleCheckboxesCount = visibleCheckboxes.length;
                
            visibleCheckboxes.prop('checked', true);
            $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").addClass(this.options.selectedClass);
            
            if (allCheckboxesCount === visibleCheckboxesCount) {
                $("option:enabled", this.$select).prop('selected', true);
            }
            else {
                var values = visibleCheckboxes.map(function() { return $(this).val() }).get();
                $("option:enabled", this.$select).filter(function(index){ return $.inArray($(this).val(), values) !== -1; }).prop('selected', true);
            }
        },

        /**
         * Deselects all options.
         * If justVisible is true or not specified, only visible options are deselected.
         * 
         * @param {Boolean} justVisible
         */
        deselectall: function (justVisible) {
            var allCheckboxes = $("li input[type='checkbox']:enabled", this.$ul),                
                justVisible = typeof justVisible === 'undefined' ? true : justVisible,
                visibleCheckboxes = void(0);
            
            if(justVisible) {
                var values = void(0);                
                visibleCheckboxes = allCheckboxes.filter(":visible");
                visibleCheckboxes.prop('checked', false);
                
                values = visibleCheckboxes.map(function() { return $(this).val() }).get();
                
                $("option:enabled", this.$select).filter(function(index){ return $.inArray($(this).val(), values) !== -1; }).prop('selected', false);
                
                $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass);
                
            }else {
                allCheckboxes.prop('checked', false);
                $("option:enabled", this.$select).prop('selected', false);
                $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass);
            }
        },

        /**
         * Rebuild the plugin.
         * Rebuilds the dropdown, the filter and the select all option.
         */
        rebuild: function() {
            this.$ul.html('');

            // Important to distinguish between radios and checkboxes.
            this.options.multiple = this.$select.attr('multiple') === "multiple";

            this.buildSelectAll();
            this.buildDropdownOptions();
            this.buildFilter();
            
            this.updateButtonText();
            this.updateSelectAll();
            
            if (this.options.disableIfEmpty) {
                this.disableIfEmpty();
            }
            
            if (this.options.dropRight) {
                this.$ul.addClass('pull-right');
            }
        },

        /**
         * The provided data will be used to build the dropdown.
         * 
         * @param {Array} dataprovider
         */
        dataprovider: function(dataprovider) {
            var optionDOM = "";
            var groupCounter = 0;

            $.each(dataprovider, function (index, option) {
                if ($.isArray(option.children)) {
                    groupCounter++;
                    optionDOM += '<optgroup label="' + (option.title || 'Group ' + groupCounter) + '">';

                    forEach(option.children, function(subOption) {
                        optionDOM += '<option value="' + subOption.value + '">' + (subOption.label || subOption.value) + '</option>';
                    });

                    optionDOM += '</optgroup>';
                }
                else {
                    optionDOM += '<option value="' + option.value + '">' + (option.label || option.value) + '</option>';
                }
            });
            
            this.$select.html(optionDOM);
            this.rebuild();
        },

        /**
         * Enable the multiselect.
         */
        enable: function() {
            this.$select.prop('disabled', false);
            this.$button.prop('disabled', false)
                .removeClass('disabled');
        },

        /**
         * Disable the multiselect.
         */
        disable: function() {
            this.$select.prop('disabled', true);
            this.$button.prop('disabled', true)
                .addClass('disabled');
        },

        /**
         * Disable the multiselect if there are no options in the select.
         */
        disableIfEmpty: function () {
            if ($('option', this.$select).length <= 0) {
                this.disable();
            }
            else {
                this.enable();
            }
        },

        /**
         * Set the options.
         * 
         * @param {Array} options
         */
        setOptions: function(options) {
            this.options = this.mergeOptions(options);
        },

        /**
         * Merges the given options with the default options.
         * 
         * @param {Array} options
         * @returns {Array}
         */
        mergeOptions: function(options) {
            return $.extend(true, {}, this.defaults, options);
        },
        
        /**
         * Checks whether a select all checkbox is present.
         * 
         * @returns {Boolean}
         */
        hasSelectAll: function() {
            return $('li.' + this.options.selectAllValue, this.$ul).length > 0;
        },
        
        /**
         * Updates the select all checkbox based on the currently displayed and selected checkboxes.
         */
        updateSelectAll: function() {
            if (this.hasSelectAll()) {
                var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul),
                    allBoxesLength = allBoxes.length,
                    checkedBoxesLength = allBoxes.filter(":checked").length,
                    selectAllLi  = $("li." + this.options.selectAllValue, this.$ul),
                    selectAllInput = selectAllLi.find("input");
                
                if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) {
                    selectAllInput.prop("checked", true);
                    selectAllLi.addClass(this.options.selectedClass);
                }
                else {
                    selectAllInput.prop("checked", false);
                    selectAllLi.removeClass(this.options.selectedClass);
                }
            }
        },
        
        /**
         * Update the button text and its title based on the currently selected options.
         */
        updateButtonText: function() {
            var options = this.getSelected();
            
            // First update the displayed button text.
            $('button.multiselect', this.$container).html(this.options.buttonText(options, this.$select));
            
            // Now update the title attribute of the button.
            $('button.multiselect', this.$container).attr('title', this.options.buttonTitle(options, this.$select));

        },

        /**
         * Get all selected options.
         * 
         * @returns {jQUery}
         */
        getSelected: function() {
            return $('option', this.$select).filter(":selected");
        },

        /**
         * Gets a select option by its value.
         * 
         * @param {String} value
         * @returns {jQuery}
         */
        getOptionByValue: function (value) {

            var options = $('option', this.$select);
            var valueToCompare = value.toString();

            for (var i = 0; i < options.length; i = i + 1) {
                var option = options[i];
                if (option.value === valueToCompare) {
                    return $(option);
                }
            }
        },

        /**
         * Get the input (radio/checkbox) by its value.
         * 
         * @param {String} value
         * @returns {jQuery}
         */
        getInputByValue: function (value) {

            var checkboxes = $('li input', this.$ul);
            var valueToCompare = value.toString();

            for (var i = 0; i < checkboxes.length; i = i + 1) {
                var checkbox = checkboxes[i];
                if (checkbox.value === valueToCompare) {
                    return $(checkbox);
                }
            }
        },

        /**
         * Used for knockout integration.
         */
        updateOriginalOptions: function() {
            this.originalOptions = this.$select.clone()[0].options;
        },

        asyncFunction: function(callback, timeout, self) {
            var args = Array.prototype.slice.call(arguments, 3);
            return setTimeout(function() {
                callback.apply(self || window, args);
            }, timeout);
        }
    };

    $.fn.multiselect = function(option, parameter, extraOptions) {
        return this.each(function() {
            var data = $(this).data('multiselect');
            var options = typeof option === 'object' && option;
            
            // Initialize the multiselect.
            if (!data) {
                data = new Multiselect(this, options);
                $(this).data('multiselect', data);
            }

            // Call multiselect method.
            if (typeof option === 'string') {
                data[option](parameter, extraOptions);
                
                if (option === 'destroy') {
                    $(this).data('multiselect', false);
                }
            }
        });
    };

    $.fn.multiselect.Constructor = Multiselect;

    $(function() {
        $("select[data-role=multiselect]").multiselect();
    });

}(window.jQuery);
;
/* ========================================================================
 * bootstrap-switch - v3.0.0
 * http://www.bootstrap-switch.org
 * ========================================================================
 * Copyright 2012-2013 Mattia Larentis
 *
 * ========================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================================
 */

(function(){var t=[].slice;!function(s,o){"use strict";var e;return e=function(){function t(t,o){null==o&&(o={}),this.$element=s(t),this.options=s.extend({},s.fn.bootstrapSwitch.defaults,o,{state:this.$element.is(":checked"),size:this.$element.data("size"),animate:this.$element.data("animate"),disabled:this.$element.is(":disabled"),readonly:this.$element.is("[readonly]"),onColor:this.$element.data("on-color"),offColor:this.$element.data("off-color"),onText:this.$element.data("on-text"),offText:this.$element.data("off-text"),labelText:this.$element.data("label-text")}),this.$wrapper=s("<div>",{"class":function(t){return function(){var o;return o=[""+t.options.baseClass],o.push(function(){var o,e,i,n,a,r;if(!s.isArray(t.options.wrapperClass))return""+t.options.baseClass+"-"+t.options.wrapperClass;for(e=[],a=t.options.wrapperClass,r=[],i=0,n=a.length;n>i;i++)o=a[i],r.push(e.push(""+t.options.baseClass+"-"+o));return r}()),o.push(t.options.state?""+t.options.baseClass+"-"+t.options.onModifierClass:""+t.options.baseClass+"-"+t.options.offModifierClass),null!=t.options.size&&o.push(""+t.options.baseClass+"-"+t.options.size),t.options.animate&&o.push(""+t.options.baseClass+"-"+t.options.animateModifierClass),t.options.disabled&&o.push(""+t.options.baseClass+"-"+t.options.disabledModifierClass),t.options.readonly&&o.push(""+t.options.baseClass+"-"+t.options.readonlyModifierClass),t.$element.attr("id")&&o.push(""+t.options.baseClass+"-id-"+t.$element.attr("id")),o.join(" ")}}(this)()}),this.$container=s("<div>",{"class":""+this.options.baseClass+"-container"}),this.$on=s("<span>",{html:this.options.onText,"class":""+this.options.baseClass+"-handle-on "+this.options.baseClass+"-"+this.options.onColor}),this.$off=s("<span>",{html:this.options.offText,"class":""+this.options.baseClass+"-handle-off "+this.options.baseClass+"-"+this.options.offColor}),this.$label=s("<label>",{"for":this.$element.attr("id"),html:this.options.labelText,"class":""+this.options.baseClass+"-label"}),this.$element.on("init.bootstrapSwitch",function(s){return function(){return s.options.onInit.apply(t,arguments)}}(this)),this.$element.on("switchChange.bootstrapSwitch",function(s){return function(){return s.options.onSwitchChange.apply(t,arguments)}}(this)),this.$container=this.$element.wrap(this.$container).parent(),this.$wrapper=this.$container.wrap(this.$wrapper).parent(),this.$element.before(this.$on).before(this.$label).before(this.$off).trigger("init.bootstrapSwitch"),this._elementHandlers(),this._handleHandlers(),this._labelHandlers(),this._formHandler()}return t.prototype.name="bootstrap-switch",t.prototype._constructor=t,t.prototype.state=function(t,s){return"undefined"==typeof t?this.options.state:this.options.disabled||this.options.readonly?this.$element:(t=!!t,this.$element.prop("checked",t).trigger("change.bootstrapSwitch",s),this.$element)},t.prototype.toggleState=function(t){return this.options.disabled||this.options.readonly?this.$element:this.$element.prop("checked",!this.options.state).trigger("change.bootstrapSwitch",t)},t.prototype.size=function(t){return"undefined"==typeof t?this.options.size:(null!=this.options.size&&this.$wrapper.removeClass(""+this.options.baseClass+"-"+this.options.size),this.$wrapper.addClass(""+this.options.baseClass+"-"+t),this.options.size=t,this.$element)},t.prototype.animate=function(t){return"undefined"==typeof t?this.options.animate:(t=!!t,this.$wrapper[t?"addClass":"removeClass"](""+this.options.baseClass+"-"+this.options.animateModifierClass),this.options.animate=t,this.$element)},t.prototype.disabled=function(t){return"undefined"==typeof t?this.options.disabled:(t=!!t,this.$wrapper[t?"addClass":"removeClass"](""+this.options.baseClass+"-"+this.options.disabledModifierClass),this.$element.prop("disabled",t),this.options.disabled=t,this.$element)},t.prototype.toggleDisabled=function(){return this.$element.prop("disabled",!this.options.disabled),this.$wrapper.toggleClass(""+this.options.baseClass+"-"+this.options.disabledModifierClass),this.options.disabled=!this.options.disabled,this.$element},t.prototype.readonly=function(t){return"undefined"==typeof t?this.options.readonly:(t=!!t,this.$wrapper[t?"addClass":"removeClass"](""+this.options.baseClass+"-"+this.options.readonlyModifierClass),this.$element.prop("readonly",t),this.options.readonly=t,this.$element)},t.prototype.toggleReadonly=function(){return this.$element.prop("readonly",!this.options.readonly),this.$wrapper.toggleClass(""+this.options.baseClass+"-"+this.options.readonlyModifierClass),this.options.readonly=!this.options.readonly,this.$element},t.prototype.onColor=function(t){var s;return s=this.options.onColor,"undefined"==typeof t?s:(null!=s&&this.$on.removeClass(""+this.options.baseClass+"-"+s),this.$on.addClass(""+this.options.baseClass+"-"+t),this.options.onColor=t,this.$element)},t.prototype.offColor=function(t){var s;return s=this.options.offColor,"undefined"==typeof t?s:(null!=s&&this.$off.removeClass(""+this.options.baseClass+"-"+s),this.$off.addClass(""+this.options.baseClass+"-"+t),this.options.offColor=t,this.$element)},t.prototype.onText=function(t){return"undefined"==typeof t?this.options.onText:(this.$on.html(t),this.options.onText=t,this.$element)},t.prototype.offText=function(t){return"undefined"==typeof t?this.options.offText:(this.$off.html(t),this.options.offText=t,this.$element)},t.prototype.labelText=function(t){return"undefined"==typeof t?this.options.labelText:(this.$label.html(t),this.options.labelText=t,this.$element)},t.prototype.baseClass=function(){return this.options.baseClass},t.prototype.wrapperClass=function(t){var o;return"undefined"==typeof t?this.options.wrapperClass:(o=function(t){return function(o){var e,i,n,a;if(!s.isArray(o))return""+t.options.baseClass+"-"+o;for(i=[],n=0,a=o.length;a>n;n++)e=o[n],i.push(""+t.options.baseClass+"-"+e);return i.join(" ")}}(this),this.$wrapper.removeClass(o(this.options.wrapperClass)),this.$wrapper.addClass(o(t)),this.options.wrapperClass=t,this.$element)},t.prototype.onModifierClass=function(t){return"undefined"==typeof t?this.options.onModifierClass:(this.$wrapper.hasClass(""+this.options.baseClass+"-"+this.options.onModifierClass)&&this.$wrapper.removeClass(""+this.options.baseClass+"-"+this.options.onModifierClass).addClass(""+this.options.baseClass+"-"+t),this.options.onModifierClass=t,this.$element)},t.prototype.offModifierClass=function(t){return"undefined"==typeof t?this.options.offModifierClass:(this.$wrapper.hasClass(""+this.options.baseClass+"-"+this.options.offModifierClass)&&this.$wrapper.removeClass(""+this.options.baseClass+"-"+this.options.offModifierClass).addClass(""+this.options.baseClass+"-"+t),this.options.offModifierClass=t,this.$element)},t.prototype.focusedModifierClass=function(t){return"undefined"==typeof t?this.options.focusedModifierClass:(this.$wrapper.hasClass(""+this.options.baseClass+"-"+this.options.focusedModifierClass)&&this.$wrapper.removeClass(""+this.options.baseClass+"-"+this.options.focusedModifierClass).addClass(""+this.options.baseClass+"-"+t),this.options.focusedModifierClass=t,this.$element)},t.prototype.animateModifierClass=function(t){return"undefined"==typeof t?this.options.animateModifierClass:(this.$wrapper.hasClass(""+this.options.baseClass+"-"+this.options.animateModifierClass)&&this.$wrapper.removeClass(""+this.options.baseClass+"-"+this.options.animateModifierClass).addClass(""+this.options.baseClass+"-"+t),this.options.animateModifierClass=t,this.$element)},t.prototype.disabledModifierClass=function(t){return"undefined"==typeof t?this.options.disabledModifierClass:(this.$wrapper.hasClass(""+this.options.baseClass+"-"+this.options.disabledModifierClass)&&this.$wrapper.removeClass(""+this.options.baseClass+"-"+this.options.disabledModifierClass).addClass(""+this.options.baseClass+"-"+t),this.options.disabledModifierClass=t,this.$element)},t.prototype.readonlyModifierClass=function(t){return"undefined"==typeof t?this.options.readonlyModifierClass:(this.$wrapper.hasClass(""+this.options.baseClass+"-"+this.options.readonlyModifierClass)&&this.$wrapper.removeClass(""+this.options.baseClass+"-"+this.options.readonlyModifierClass).addClass(""+this.options.baseClass+"-"+t),this.options.readonlyModifierClass=t,this.$element)},t.prototype.destroy=function(){var t;return t=this.$element.closest("form"),t.length&&t.off("reset.bootstrapSwitch").removeData("bootstrap-switch"),this.$container.children().not(this.$element).remove(),this.$element.unwrap().unwrap().off(".bootstrapSwitch").removeData("bootstrap-switch"),this.$element},t.prototype._elementHandlers=function(){return this.$element.on({"change.bootstrapSwitch":function(t){return function(o,e){var i;return o.preventDefault(),o.stopPropagation(),o.stopImmediatePropagation(),i=t.$element.is(":checked"),i!==t.options.state?(t.options.state=i,t.$wrapper.removeClass(i?""+t.options.baseClass+"-"+t.options.offModifierClass:""+t.options.baseClass+"-"+t.options.onModifierClass).addClass(i?""+t.options.baseClass+"-"+t.options.onModifierClass:""+t.options.baseClass+"-"+t.options.offModifierClass),e?void 0:(t.$element.is(":radio")&&s("[name='"+t.$element.attr("name")+"']").not(t.$element).prop("checked",!1).trigger("change.bootstrapSwitch",!0),t.$element.trigger("switchChange.bootstrapSwitch",[i]))):void 0}}(this),"focus.bootstrapSwitch":function(t){return function(s){return s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation(),t.$wrapper.addClass(""+t.options.baseClass+"-"+t.options.focusedModifierClass)}}(this),"blur.bootstrapSwitch":function(t){return function(s){return s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation(),t.$wrapper.removeClass(""+t.options.baseClass+"-"+t.options.focusedModifierClass)}}(this),"keydown.bootstrapSwitch":function(t){return function(s){if(s.which&&!t.options.disabled&&!t.options.readonly)switch(s.which){case 32:return s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation(),t.toggleState();case 37:return s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation(),t.state(!1);case 39:return s.preventDefault(),s.stopPropagation(),s.stopImmediatePropagation(),t.state(!0)}}}(this)})},t.prototype._handleHandlers=function(){return this.$on.on("click.bootstrapSwitch",function(t){return function(){return t.state(!1),t.$element.trigger("focus.bootstrapSwitch")}}(this)),this.$off.on("click.bootstrapSwitch",function(t){return function(){return t.state(!0),t.$element.trigger("focus.bootstrapSwitch")}}(this))},t.prototype._labelHandlers=function(){return this.$label.on({"mousemove.bootstrapSwitch touchmove.bootstrapSwitch":function(t){return function(s){var o,e,i;if(t.drag)return s.preventDefault(),e=((s.pageX||s.originalEvent.touches[0].pageX)-t.$wrapper.offset().left)/t.$wrapper.width()*100,o=25,i=75,o>e?e=o:e>i&&(e=i),t.$container.css("margin-left",""+(e-i)+"%"),t.$element.trigger("focus.bootstrapSwitch")}}(this),"mousedown.bootstrapSwitch touchstart.bootstrapSwitch":function(t){return function(s){return t.drag||t.options.disabled||t.options.readonly?void 0:(s.preventDefault(),t.drag=!0,t.options.animate&&t.$wrapper.removeClass(""+t.options.baseClass+"-"+t.options.animateModifierClass),t.$element.trigger("focus.bootstrapSwitch"))}}(this),"mouseup.bootstrapSwitch touchend.bootstrapSwitch":function(t){return function(s){return t.drag?(s.preventDefault(),t.drag=!1,t.$element.prop("checked",parseInt(t.$container.css("margin-left"),10)>-(t.$container.width()/6)).trigger("change.bootstrapSwitch"),t.$container.css("margin-left",""),t.options.animate?t.$wrapper.addClass(""+t.options.baseClass+"-"+t.options.animateModifierClass):void 0):void 0}}(this),"mouseleave.bootstrapSwitch":function(t){return function(){return t.$label.trigger("mouseup.bootstrapSwitch")}}(this)})},t.prototype._formHandler=function(){var t;return t=this.$element.closest("form"),t.data("bootstrap-switch")?void 0:t.on("reset.bootstrapSwitch",function(){return o.setTimeout(function(){return t.find("input").filter(function(){return s(this).data("bootstrap-switch")}).each(function(){return s(this).bootstrapSwitch("state",!1)})},1)}).data("bootstrap-switch",!0)},t}(),s.fn.bootstrapSwitch=function(){var o,i,n;return i=arguments[0],o=2<=arguments.length?t.call(arguments,1):[],n=this,this.each(function(){var t,a;return t=s(this),a=t.data("bootstrap-switch"),a||t.data("bootstrap-switch",a=new e(this,i)),"string"==typeof i?n=a[i].apply(a,o):void 0}),n},s.fn.bootstrapSwitch.Constructor=e,s.fn.bootstrapSwitch.defaults={state:!0,size:null,animate:!0,disabled:!1,readonly:!1,onColor:"primary",offColor:"default",onText:"ON",offText:"OFF",labelText:"&nbsp;",baseClass:"bootstrap-switch",wrapperClass:"wrapper",onModifierClass:"on",offModifierClass:"off",focusedModifierClass:"focused",animateModifierClass:"animate",disabledModifierClass:"disabled",readonlyModifierClass:"readonly",onInit:function(){},onSwitchChange:function(){}}}(window.jQuery,window)}).call(this);;
/* =========================================================
 * bootstrap-treeview.js v1.0.2
 * =========================================================
 * Copyright 2013 Jonathan Miles 
 * Project URL : http://www.jondmiles.com/bootstrap-treeview
 *	
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

;(function($, window, document, undefined) {

	/*global jQuery, console*/

	'use strict';

	var pluginName = 'treeview';

	var Tree = function(element, options) {

		this.$element = $(element);
		this._element = element;
		this._elementId = this._element.id;
		this._styleId = this._elementId + '-style';

		this.tree = [];
		this.nodes = [];
		this.selectedNode = options.selectedPage;
		
		this._init(options);
	};

	Tree.defaults = {

		injectStyle: true,

		levels: 2,

		expandIcon: 'glyphicon glyphicon-plus',
		collapseIcon: 'glyphicon glyphicon-minus',
		emptyIcon: 'glyphicon',
		nodeIcon: 'glyphicon glyphicon-stop',

		color: undefined, // '#000000',
		backColor: undefined, // '#FFFFFF',
		borderColor: undefined, // '#dddddd',
		onhoverColor: '#F5F5F5',
		selectedColor: '#FFFFFF',
		selectedBackColor: '#428bca',

		enableLinks: false,
		highlightSelected: true,
		showBorder: true,
		showTags: false,

		// Event handler for when a node is selected
		onNodeSelected: undefined
	};

	Tree.prototype = {

		remove: function() {

			this._destroy();
			$.removeData(this, 'plugin_' + pluginName);
			$('#' + this._styleId).remove();
		},

		_destroy: function() {

			if (this.initialized) {
				this.$wrapper.remove();
				this.$wrapper = null;

				// Switch off events
				this._unsubscribeEvents();
			}

			// Reset initialized flag
			this.initialized = false;
		},

		_init: function(options) {
		
			if (options.data) {
				if (typeof options.data === 'string') {
					options.data = $.parseJSON(options.data);
				}
				this.tree = $.extend(true, [], options.data);
				delete options.data;
			}

			this.options = $.extend({}, Tree.defaults, options);

			this._setInitialLevels(this.tree, 0);

			this._destroy();
			this._subscribeEvents();
			this._render();
		},

		_unsubscribeEvents: function() {

			this.$element.off('click');

			if (typeof (this.options.onNodeSelected) === 'function') {
				this.$element.off('nodeSelected');
			}
		},

		_subscribeEvents: function() {

			this._unsubscribeEvents();

			this.$element.on('click', $.proxy(this._clickHandler, this));

			if (typeof (this.options.onNodeSelected) === 'function') {
				this.$element.on('nodeSelected', this.options.onNodeSelected);
			}
		},

		_clickHandler: function(event) {

			if (!this.options.enableLinks) { event.preventDefault(); }
			
			var target = $(event.target),
				classList = target.attr('class') ? target.attr('class').split(' ') : [],
				node = this._findNode(target);

			if ((classList.indexOf('click-expand') != -1) ||
					(classList.indexOf('click-collapse') != -1)) {
				// Expand or collapse node by toggling child node visibility
				this._toggleNodes(node);
				this._render();
			}
			else if (node) {
				if (this._isSelectable(node)) {
					this._setSelectedNode(node);
				} else {
					this._toggleNodes(node);
					this._render();
				}
			}
		},

		// Looks up the DOM for the closest parent list item to retrieve the 
		// data attribute nodeid, which is used to lookup the node in the flattened structure.
		_findNode: function(target) {

			var nodeId = target.closest('li.list-group-item').attr('data-nodeid'),
				node = this.nodes[nodeId];

			if (!node) {
				console.log('Error: node does not exist');
			}
			return node;
		},

		// Actually triggers the nodeSelected event
		_triggerNodeSelectedEvent: function(node) {

			this.$element.trigger('nodeSelected', [$.extend(true, {}, node)]);
		},

		// Handles selecting and unselecting of nodes, 
		// as well as determining whether or not to trigger the nodeSelected event
		_setSelectedNode: function(node) {

			if (!node) { return; }
			
			if (node === this.selectedNode) {
				this.selectedNode = {};
			}
			else {
				this._triggerNodeSelectedEvent(this.selectedNode = node);
			}
			
			this._render();
		},

		// On initialization recurses the entire tree structure 
		// setting expanded / collapsed states based on initial levels
		_setInitialLevels: function(nodes, level) {

			if (!nodes) { return; }
			level += 1;

			var self = this;
			$.each(nodes, function addNodes(id, node) {
				
				if (level >= self.options.levels) {
					self._toggleNodes(node);
				}

				// Need to traverse both nodes and _nodes to ensure 
				// all levels collapsed beyond levels
				var nodes = node.nodes ? node.nodes : node._nodes ? node._nodes : undefined;
				if (nodes) {
					return self._setInitialLevels(nodes, level);
				}
			});
		},

		// Toggle renaming nodes -> _nodes, _nodes -> nodes
		// to simulate expanding or collapsing a node.
		_toggleNodes: function(node) {

			if (!node.nodes && !node._nodes) {
				return;
			}

			if (node.nodes) {
				node._nodes = node.nodes;
				delete node.nodes;
			}
			else {
				node.nodes = node._nodes;
				delete node._nodes;
			}
		},

		// Returns true if the node is selectable in the tree
		_isSelectable: function (node) {
			return node.selectable !== false;
		},

		_render: function() {

			var self = this;

			if (!self.initialized) {

				// Setup first time only components
				self.$element.addClass(pluginName);
				self.$wrapper = $(self._template.list);

				self._injectStyle();
				
				self.initialized = true;
			}

			self.$element.empty().append(self.$wrapper.empty());

			// Build tree
			self.nodes = [];
			self._buildTree(self.tree, 0);
		},

		// Starting from the root node, and recursing down the 
		// structure we build the tree one node at a time
		_buildTree: function(nodes, level) {

			if (!nodes) { return; }
			level += 1;

			var self = this;
			$.each(nodes, function addNodes(id, node) {

				node.nodeId = self.nodes.length;
				self.nodes.push(node);

				var isSelected = (self.selectedNode != null) && (node.value === self.selectedNode.value);
				var treeItem = $(self._template.item)
					.addClass('node-' + self._elementId)
					.addClass(isSelected ? 'node-selected' : '')
					.attr('data-nodeid', node.nodeId)
					.attr('style', self._buildStyleOverride(node));

				// Add indent/spacer to mimic tree structure
				for (var i = 0; i < (level - 1); i++) {
					treeItem.append(self._template.indent);
				}

				// Add expand, collapse or empty spacer icons 
				// to facilitate tree structure navigation
				if (node._nodes) {
					treeItem
						.append($(self._template.expandCollapseIcon)
							.addClass('click-expand')
							.addClass(self.options.expandIcon)
						);
				}
				else if (node.nodes) {
					treeItem
						.append($(self._template.expandCollapseIcon)
							.addClass('click-collapse')
							.addClass(self.options.collapseIcon)
						);
				}
				else {
					treeItem
						.append($(self._template.expandCollapseIcon)
							.addClass(self.options.emptyIcon)
						);
				}

				// Add node icon
				treeItem
					.append($(self._template.icon)
						.addClass(node.icon ? node.icon : self.options.nodeIcon)
					);

				// Add text
				if (self.options.enableLinks) {
					// Add hyperlink
					treeItem
						.append($(self._template.link)
							.attr('href', node.href)
							.append(node.text)
						);
				}
				else {
					// otherwise just text
					treeItem
						.append(node.text);
				}

				// Add tags as badges
				if (self.options.showTags && node.tags) {
					$.each(node.tags, function addTag(id, tag) {
						treeItem
							.append($(self._template.badge)
								.append(tag)
							);
					});
				}

				// Add item to the tree
				self.$wrapper.append(treeItem);

				// Recursively add child ndoes
				if (node.nodes) {
					return self._buildTree(node.nodes, level);
				}
			});
		},

		// Define any node level style override for
		// 1. selectedNode
		// 2. node|data assigned color overrides
		_buildStyleOverride: function(node) {

			var style = '';
			if (this.options.highlightSelected && (node === this.selectedNode)) {
				style += 'color:' + this.options.selectedColor + ';';
			}
			else if (node.color) {
				style += 'color:' + node.color + ';';
			}

			if (this.options.highlightSelected && (node === this.selectedNode)) {
				style += 'background-color:' + this.options.selectedBackColor + ';';
			}
			else if (node.backColor) {
				style += 'background-color:' + node.backColor + ';';
			}

			return style;
		},

		// Add inline style into head 
		_injectStyle: function() {

			if (this.options.injectStyle && !document.getElementById(this._styleId)) {
				$('<style type="text/css" id="' + this._styleId + '"> ' + this._buildStyle() + ' </style>').appendTo('head');
			}
		},

		// Construct trees style based on user options
		_buildStyle: function() {

			var style = '.node-' + this._elementId + '{';
			if (this.options.color) {
				style += 'color:' + this.options.color + ';';
			}
			if (this.options.backColor) {
				style += 'background-color:' + this.options.backColor + ';';
			}
			if (!this.options.showBorder) {
				style += 'border:none;';
			}
			else if (this.options.borderColor) {
				style += 'border:1px solid ' + this.options.borderColor + ';';
			}
			style += '}';

			if (this.options.onhoverColor) {
				style += '.node-' + this._elementId + ':hover{' +
				'background-color:' + this.options.onhoverColor + ';' +
				'}';
			}

			return this._css + style;
		},

		_template: {
			list: '<ul class="list-group"></ul>',
			item: '<li class="list-group-item"></li>',
			indent: '<span class="indent"></span>',
			expandCollapseIcon: '<span class="expand-collapse"></span>',
			icon: '<span class="icon"></span>',
			link: '<a href="#" style="color:inherit;"></a>',
			badge: '<span class="badge"></span>'
		},

		_css: '.treeview .list-group-item{cursor:pointer}.treeview span.indent{margin-left:10px;margin-right:10px}.treeview span.expand-collapse{width:1rem;height:1rem}.treeview span.icon{margin-left:10px;margin-right:5px}'
		// _css: '.list-group-item{cursor:pointer;}.list-group-item:hover{background-color:#f5f5f5;}span.indent{margin-left:10px;margin-right:10px}span.icon{margin-right:5px}'

	};

	var logError = function(message) {
        if(window.console) {
            window.console.error(message);
        }
    };

	// Prevent against multiple instantiations,
	// handle updates and method calls
	$.fn[pluginName] = function(options, args) {
		return this.each(function() {
			var self = $.data(this, 'plugin_' + pluginName);
			if (typeof options === 'string') {
				if (!self) {
					logError('Not initialized, can not call method : ' + options);
				}
				else if (!$.isFunction(self[options]) || options.charAt(0) === '_') {
					logError('No such method : ' + options);
				}
				else {
					if (typeof args === 'string') {
						args = [args];
					}
					self[options].apply(self, args);
				}
			}
			else {
				if (!self) {
					$.data(this, 'plugin_' + pluginName, new Tree(this, $.extend(true, {}, options)));
				}
				else {
					self._init(options);
				}
			}
		});
	};

})(jQuery, window, document);;
/*
 * jQuery File Upload Plugin 5.9
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, document, Blob, FormData, location */

(function(factory) {
	'use strict';
	if (typeof define === 'function' && define.amd) {
		// Register as an anonymous AMD module:
		define([
			'jquery',
			'jquery.ui.widget'
		], factory);
	} else {
		// Browser globals:
		factory(window.jQuery);
	}
}(function($) {
	'use strict';

	// The FileReader API is not actually used, but works as feature detection,
	// as e.g. Safari supports XHR file uploads via the FormData API,
	// but not non-multipart XHR file uploads:
	$.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
	$.support.xhrFormDataFileUpload = !!window.FormData;

	// The fileupload widget listens for change events on file input fields defined
	// via fileInput setting and paste or drop events of the given dropZone.
	// In addition to the default jQuery Widget methods, the fileupload widget
	// exposes the "add" and "send" methods, to add or directly send files using
	// the fileupload API.
	// By default, files added via file input selection, paste, drag & drop or
	// "add" method are uploaded immediately, but it is possible to override
	// the "add" callback option to queue file uploads.
	$.widget('blueimp.fileupload', {
		options: {
			// The namespace used for event handler binding on the dropZone and
			// fileInput collections.
			// If not set, the name of the widget ("fileupload") is used.
			namespace: undefined,
			// The drop target collection, by the default the complete document.
			// Set to null or an empty collection to disable drag & drop support:
			dropZone: $(document),
			// The file input field collection, that is listened for change events.
			// If undefined, it is set to the file input fields inside
			// of the widget element on plugin initialization.
			// Set to null or an empty collection to disable the change listener.
			fileInput: undefined,
			// By default, the file input field is replaced with a clone after
			// each input field change event. This is required for iframe transport
			// queues and allows change events to be fired for the same file
			// selection, but can be disabled by setting the following option to false:
			replaceFileInput: true,
			// The parameter name for the file form data (the request argument name).
			// If undefined or empty, the name property of the file input field is
			// used, or "files[]" if the file input name property is also empty:
			paramName: undefined,
			// By default, each file of a selection is uploaded using an individual
			// request for XHR type uploads. Set to false to upload file
			// selections in one request each:
			singleFileUploads: true,
			// To limit the number of files uploaded with one XHR request,
			// set the following option to an integer greater than 0:
			limitMultiFileUploads: undefined,
			// Set the following option to true to issue all file upload requests
			// in a sequential order:
			sequentialUploads: false,
			// To limit the number of concurrent uploads,
			// set the following option to an integer greater than 0:
			limitConcurrentUploads: undefined,
			// Set the following option to true to force iframe transport uploads:
			forceIframeTransport: false,
			// Set the following option to the location of a redirect url on the
			// origin server, for cross-domain iframe transport uploads:
			redirect: undefined,
			// The parameter name for the redirect url, sent as part of the form
			// data and set to 'redirect' if this option is empty:
			redirectParamName: undefined,
			// Set the following option to the location of a postMessage window,
			// to enable postMessage transport uploads:
			postMessage: undefined,
			// By default, XHR file uploads are sent as multipart/form-data.
			// The iframe transport is always using multipart/form-data.
			// Set to false to enable non-multipart XHR uploads:
			multipart: true,
			// To upload large files in smaller chunks, set the following option
			// to a preferred maximum chunk size. If set to 0, null or undefined,
			// or the browser does not support the required Blob API, files will
			// be uploaded as a whole.
			maxChunkSize: undefined,
			// When a non-multipart upload or a chunked multipart upload has been
			// aborted, this option can be used to resume the upload by setting
			// it to the size of the already uploaded bytes. This option is most
			// useful when modifying the options object inside of the "add" or
			// "send" callbacks, as the options are cloned for each file upload.
			uploadedBytes: undefined,
			// By default, failed (abort or error) file uploads are removed from the
			// global progress calculation. Set the following option to false to
			// prevent recalculating the global progress data:
			recalculateProgress: true,

			// Additional form data to be sent along with the file uploads can be set
			// using this option, which accepts an array of objects with name and
			// value properties, a function returning such an array, a FormData
			// object (for XHR file uploads), or a simple object.
			// The form of the first fileInput is given as parameter to the function:
			formData: function(form) {
				return form.serializeArray();
			},

			// The add callback is invoked as soon as files are added to the fileupload
			// widget (via file input selection, drag & drop, paste or add API call).
			// If the singleFileUploads option is enabled, this callback will be
			// called once for each file in the selection for XHR file uplaods, else
			// once for each file selection.
			// The upload starts when the submit method is invoked on the data parameter.
			// The data object contains a files property holding the added files
			// and allows to override plugin options as well as define ajax settings.
			// Listeners for this callback can also be bound the following way:
			// .bind('fileuploadadd', func);
			// data.submit() returns a Promise object and allows to attach additional
			// handlers using jQuery's Deferred callbacks:
			// data.submit().done(func).fail(func).always(func);
			add: function(e, data) {
				data.submit();
			},

			// Other callbacks:
			// Callback for the submit event of each file upload:
			// submit: function (e, data) {}, // .bind('fileuploadsubmit', func);
			// Callback for the start of each file upload request:
			// send: function (e, data) {}, // .bind('fileuploadsend', func);
			// Callback for successful uploads:
			// done: function (e, data) {}, // .bind('fileuploaddone', func);
			// Callback for failed (abort or error) uploads:
			// fail: function (e, data) {}, // .bind('fileuploadfail', func);
			// Callback for completed (success, abort or error) requests:
			// always: function (e, data) {}, // .bind('fileuploadalways', func);
			// Callback for upload progress events:
			// progress: function (e, data) {}, // .bind('fileuploadprogress', func);
			// Callback for global upload progress events:
			// progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
			// Callback for uploads start, equivalent to the global ajaxStart event:
			// start: function (e) {}, // .bind('fileuploadstart', func);
			// Callback for uploads stop, equivalent to the global ajaxStop event:
			// stop: function (e) {}, // .bind('fileuploadstop', func);
			// Callback for change events of the fileInput collection:
			// change: function (e, data) {}, // .bind('fileuploadchange', func);
			// Callback for paste events to the dropZone collection:
			// paste: function (e, data) {}, // .bind('fileuploadpaste', func);
			// Callback for drop events of the dropZone collection:
			// drop: function (e, data) {}, // .bind('fileuploaddrop', func);
			// Callback for dragover events of the dropZone collection:
			// dragover: function (e) {}, // .bind('fileuploaddragover', func);

			// The plugin options are used as settings object for the ajax calls.
			// The following are jQuery ajax settings required for the file uploads:
			processData: false,
			contentType: false,
			cache: false
		},

		// A list of options that require a refresh after assigning a new value:
		_refreshOptionsList: [
			'namespace',
			'dropZone',
			'fileInput',
			'multipart',
			'forceIframeTransport'
		],

		_isXHRUpload: function(options) {
			return !options.forceIframeTransport &&
			((!options.multipart && $.support.xhrFileUpload) ||
				$.support.xhrFormDataFileUpload);
		},

		_getFormData: function(options) {
			var formData;
			if (typeof options.formData === 'function') {
				return options.formData(options.form);
			} else if ($.isArray(options.formData)) {
				return options.formData;
			} else if (options.formData) {
				formData = [];
				$.each(options.formData, function(name, value) {
					formData.push({ name: name, value: value });
				});
				return formData;
			}
			return [];
		},

		_getTotal: function(files) {
			var total = 0;
			$.each(files, function(index, file) {
				total += file.size || 1;
			});
			return total;
		},

		_onProgress: function(e, data) {
			if (e.lengthComputable) {
				var total = data.total || this._getTotal(data.files),
					loaded = parseInt(
						e.loaded / e.total * (data.chunkSize || total),
						10
					) + (data.uploadedBytes || 0);
				this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
				data.lengthComputable = true;
				data.loaded = loaded;
				data.total = total;
				// Trigger a custom progress event with a total data property set
				// to the file size(s) of the current upload and a loaded data
				// property calculated accordingly:
				this._trigger('progress', e, data);
				// Trigger a global progress event for all current file uploads,
				// including ajax calls queued for sequential file uploads:
				this._trigger('progressall', e, {
					lengthComputable: true,
					loaded: this._loaded,
					total: this._total
				});
			}
		},

		_initProgressListener: function(options) {
			var that = this,
				xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
			// Accesss to the native XHR object is required to add event listeners
			// for the upload progress event:
			if (xhr.upload) {
				$(xhr.upload).bind('progress', function(e) {
					var oe = e.originalEvent;
					// Make sure the progress event properties get copied over:
					e.lengthComputable = oe.lengthComputable;
					e.loaded = oe.loaded;
					e.total = oe.total;
					that._onProgress(e, options);
				});
				options.xhr = function() {
					return xhr;
				};
			}
		},

		_initXHRData: function(options) {
			var formData,
				file = options.files[0],
				// Ignore non-multipart setting if not supported:
				multipart = options.multipart || !$.support.xhrFileUpload;
			if (!multipart || options.blob) {
				// For non-multipart uploads and chunked uploads,
				// file meta data is not part of the request body,
				// so we transmit this data as part of the HTTP headers.
				// For cross domain requests, these headers must be allowed
				// via Access-Control-Allow-Headers or removed using
				// the beforeSend callback:
				options.headers = $.extend(options.headers, {
					'X-File-Name': file.name,
					'X-File-Type': file.type,
					'X-File-Size': file.size
				});
				if (!options.blob) {
					// Non-chunked non-multipart upload:
					options.contentType = file.type;
					options.data = file;
				} else if (!multipart) {
					// Chunked non-multipart upload:
					options.contentType = 'application/octet-stream';
					options.data = options.blob;
				}
			}
			if (multipart && $.support.xhrFormDataFileUpload) {
				if (options.postMessage) {
					// window.postMessage does not allow sending FormData
					// objects, so we just add the File/Blob objects to
					// the formData array and let the postMessage window
					// create the FormData object out of this array:
					formData = this._getFormData(options);
					if (options.blob) {
						formData.push({
							name: options.paramName,
							value: options.blob
						});
					} else {
						$.each(options.files, function(index, file) {
							formData.push({
								name: options.paramName,
								value: file
							});
						});
					}
				} else {
					if (options.formData instanceof FormData) {
						formData = options.formData;
					} else {
						formData = new FormData();
						$.each(this._getFormData(options), function(index, field) {
							formData.append(field.name, field.value);
						});
					}
					if (options.blob) {
						formData.append(options.paramName, options.blob, file.name);
					} else {
						$.each(options.files, function(index, file) {
							// File objects are also Blob instances.
							// This check allows the tests to run with
							// dummy objects:
							if (file instanceof Blob) {
								formData.append(options.paramName, file, file.name);
							}
						});
					}
				}
				options.data = formData;
			}
			// Blob reference is not needed anymore, free memory:
			options.blob = null;
		},

		_initIframeSettings: function(options) {
			// Setting the dataType to iframe enables the iframe transport:
			options.dataType = 'iframe ' + (options.dataType || '');
			// The iframe transport accepts a serialized array as form data:
			options.formData = this._getFormData(options);
			// Add redirect url to form data on cross-domain uploads:
			if (options.redirect && $('<a></a>').prop('href', options.url)
				.prop('host') !== location.host) {
				options.formData.push({
					name: options.redirectParamName || 'redirect',
					value: options.redirect
				});
			}
		},

		_initDataSettings: function(options) {
			if (this._isXHRUpload(options)) {
				if (!this._chunkedUpload(options, true)) {
					if (!options.data) {
						this._initXHRData(options);
					}
					this._initProgressListener(options);
				}
				if (options.postMessage) {
					// Setting the dataType to postmessage enables the
					// postMessage transport:
					options.dataType = 'postmessage ' + (options.dataType || '');
				}
			} else {
				this._initIframeSettings(options, 'iframe');
			}
		},

		_initFormSettings: function(options) {
			// Retrieve missing options from the input field and the
			// associated form, if available:
			if (!options.form || !options.form.length) {
				options.form = $(options.fileInput.prop('form'));
			}
			if (!options.paramName) {
				options.paramName = options.fileInput.prop('name') ||
					'files[]';
			}
			if (!options.url) {
				options.url = options.form.prop('action') || location.href;
			}
			// The HTTP request method must be "POST" or "PUT":
			options.type = (options.type || options.form.prop('method') || '')
				.toUpperCase();
			if (options.type !== 'POST' && options.type !== 'PUT') {
				options.type = 'POST';
			}
		},

		_getAJAXSettings: function(data) {
			var options = $.extend({}, this.options, data);
			this._initFormSettings(options);
			this._initDataSettings(options);
			return options;
		},

		// Maps jqXHR callbacks to the equivalent
		// methods of the given Promise object:
		_enhancePromise: function(promise) {
			promise.success = promise.done;
			promise.error = promise.fail;
			promise.complete = promise.always;
			return promise;
		},

		// Creates and returns a Promise object enhanced with
		// the jqXHR methods abort, success, error and complete:
		_getXHRPromise: function(resolveOrReject, context, args) {
			var dfd = $.Deferred(),
				promise = dfd.promise();
			context = context || this.options.context || promise;
			if (resolveOrReject === true) {
				dfd.resolveWith(context, args);
			} else if (resolveOrReject === false) {
				dfd.rejectWith(context, args);
			}
			promise.abort = dfd.promise;
			return this._enhancePromise(promise);
		},

		// Uploads a file in multiple, sequential requests
		// by splitting the file up in multiple blob chunks.
		// If the second parameter is true, only tests if the file
		// should be uploaded in chunks, but does not invoke any
		// upload requests:
		_chunkedUpload: function(options, testOnly) {
			var that = this,
				file = options.files[0],
				fs = file.size,
				ub = options.uploadedBytes = options.uploadedBytes || 0,
				mcs = options.maxChunkSize || fs,
				// Use the Blob methods with the slice implementation
				// according to the W3C Blob API specification:
				slice = file.webkitSlice || file.mozSlice || file.slice,
				upload,
				n,
				jqXHR,
				pipe;
			if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
				options.data) {
				return false;
			}
			if (testOnly) {
				return true;
			}
			if (ub >= fs) {
				file.error = 'uploadedBytes';
				return this._getXHRPromise(
					false,
					options.context,
					[null, 'error', file.error]
				);
			}
			// n is the number of blobs to upload,
			// calculated via filesize, uploaded bytes and max chunk size:
			n = Math.ceil((fs - ub) / mcs);
			// The chunk upload method accepting the chunk number as parameter:
			upload = function(i) {
				if (!i) {
					return that._getXHRPromise(true, options.context);
				}
				// Upload the blobs in sequential order:
				return upload(i -= 1).pipe(function() {
					// Clone the options object for each chunk upload:
					var o = $.extend({}, options);
					o.blob = slice.call(
						file,
						ub + i * mcs,
						ub + (i + 1) * mcs
					);
					// Store the current chunk size, as the blob itself
					// will be dereferenced after data processing:
					o.chunkSize = o.blob.size;
					// Process the upload data (the blob and potential form data):
					that._initXHRData(o);
					// Add progress listeners for this chunk upload:
					that._initProgressListener(o);
					jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
						.done(function() {
							// Create a progress event if upload is done and
							// no progress event has been invoked for this chunk:
							if (!o.loaded) {
								that._onProgress($.Event('progress', {
									lengthComputable: true,
									loaded: o.chunkSize,
									total: o.chunkSize
								}), o);
							}
							options.uploadedBytes = o.uploadedBytes +=
								o.chunkSize;
						});
					return jqXHR;
				});
			};
			// Return the piped Promise object, enhanced with an abort method,
			// which is delegated to the jqXHR object of the current upload,
			// and jqXHR callbacks mapped to the equivalent Promise methods:
			pipe = upload(n);
			pipe.abort = function() {
				return jqXHR.abort();
			};
			return this._enhancePromise(pipe);
		},

		_beforeSend: function(e, data) {
			if (this._active === 0) {
				// the start callback is triggered when an upload starts
				// and no other uploads are currently running,
				// equivalent to the global ajaxStart event:
				this._trigger('start');
			}
			this._active += 1;
			// Initialize the global progress values:
			this._loaded += data.uploadedBytes || 0;
			this._total += this._getTotal(data.files);
		},

		_onDone: function(result, textStatus, jqXHR, options) {
			if (!this._isXHRUpload(options)) {
				// Create a progress event for each iframe load:
				this._onProgress($.Event('progress', {
					lengthComputable: true,
					loaded: 1,
					total: 1
				}), options);
			}
			options.result = result;
			options.textStatus = textStatus;
			options.jqXHR = jqXHR;
			this._trigger('done', null, options);
		},

		_onFail: function(jqXHR, textStatus, errorThrown, options) {
			options.jqXHR = jqXHR;
			options.textStatus = textStatus;
			options.errorThrown = errorThrown;
			this._trigger('fail', null, options);
			if (options.recalculateProgress) {
				// Remove the failed (error or abort) file upload from
				// the global progress calculation:
				this._loaded -= options.loaded || options.uploadedBytes || 0;
				this._total -= options.total || this._getTotal(options.files);
			}
		},

		_onAlways: function(jqXHRorResult, textStatus, jqXHRorError, options) {
			this._active -= 1;
			options.textStatus = textStatus;
			if (jqXHRorError && jqXHRorError.always) {
				options.jqXHR = jqXHRorError;
				options.result = jqXHRorResult;
			} else {
				options.jqXHR = jqXHRorResult;
				options.errorThrown = jqXHRorError;
			}
			this._trigger('always', null, options);
			if (this._active === 0) {
				// The stop callback is triggered when all uploads have
				// been completed, equivalent to the global ajaxStop event:
				this._trigger('stop');
				// Reset the global progress values:
				this._loaded = this._total = 0;
			}
		},

		_onSend: function(e, data) {
			var that = this,
				jqXHR,
				slot,
				pipe,
				options = that._getAJAXSettings(data),
				send = function(resolve, args) {
					that._sending += 1;
					jqXHR = jqXHR || (
						(resolve !== false &&
								that._trigger('send', e, options) !== false &&
								(that._chunkedUpload(options) || $.ajax(options))) ||
							that._getXHRPromise(false, options.context, args)
					).done(function(result, textStatus, jqXHR) {
						that._onDone(result, textStatus, jqXHR, options);
					}).fail(function(jqXHR, textStatus, errorThrown) {
						that._onFail(jqXHR, textStatus, errorThrown, options);
					}).always(function(jqXHRorResult, textStatus, jqXHRorError) {
						that._sending -= 1;
						that._onAlways(
							jqXHRorResult,
							textStatus,
							jqXHRorError,
							options
						);
						if (options.limitConcurrentUploads &&
							options.limitConcurrentUploads > that._sending) {
							// Start the next queued upload,
							// that has not been aborted:
							var nextSlot = that._slots.shift();
							while (nextSlot) {
								if (!nextSlot.isRejected()) {
									nextSlot.resolve();
									break;
								}
								nextSlot = that._slots.shift();
							}
						}
					});
					return jqXHR;
				};
			this._beforeSend(e, options);
			if (this.options.sequentialUploads ||
			(this.options.limitConcurrentUploads &&
				this.options.limitConcurrentUploads <= this._sending)) {
				if (this.options.limitConcurrentUploads > 1) {
					slot = $.Deferred();
					this._slots.push(slot);
					pipe = slot.pipe(send);
				} else {
					pipe = (this._sequence = this._sequence.pipe(send, send));
				}
				// Return the piped Promise object, enhanced with an abort method,
				// which is delegated to the jqXHR object of the current upload,
				// and jqXHR callbacks mapped to the equivalent Promise methods:
				pipe.abort = function() {
					var args = [undefined, 'abort', 'abort'];
					if (!jqXHR) {
						if (slot) {
							slot.rejectWith(args);
						}
						return send(false, args);
					}
					return jqXHR.abort();
				};
				return this._enhancePromise(pipe);
			}
			return send();
		},

		_onAdd: function(e, data) {
			var that = this,
				result = true,
				options = $.extend({}, this.options, data),
				limit = options.limitMultiFileUploads,
				fileSet,
				i;
			if (!(options.singleFileUploads || limit) ||
				!this._isXHRUpload(options)) {
				fileSet = [data.files];
			} else if (!options.singleFileUploads && limit) {
				fileSet = [];
				for (i = 0; i < data.files.length; i += limit) {
					fileSet.push(data.files.slice(i, i + limit));
				}
			}
			data.originalFiles = data.files;
			$.each(fileSet || data.files, function(index, element) {
				var files = fileSet ? element : [element],
					newData = $.extend({}, data, { files: files });
				newData.submit = function() {
					newData.jqXHR = this.jqXHR =
						(that._trigger('submit', e, this) !== false) &&
						that._onSend(e, this);
					return this.jqXHR;
				};
				return (result = that._trigger('add', e, newData));
			});
			return result;
		},

		// File Normalization for Gecko 1.9.1 (Firefox 3.5) support:
		_normalizeFile: function(index, file) {
			if (file.name === undefined && file.size === undefined) {
				file.name = file.fileName;
				file.size = file.fileSize;
			}
		},

		_replaceFileInput: function(input) {
			var inputClone = input.clone(true);
			$('<form></form>').append(inputClone)[0].reset();
			// Detaching allows to insert the fileInput on another form
			// without loosing the file input value:
			input.after(inputClone).detach();
			// Avoid memory leaks with the detached file input:
			$.cleanData(input.unbind('remove'));
			// Replace the original file input element in the fileInput
			// collection with the clone, which has been copied including
			// event handlers:
			this.options.fileInput = this.options.fileInput.map(function(i, el) {
				if (el === input[0]) {
					return inputClone[0];
				}
				return el;
			});
			// If the widget has been initialized on the file input itself,
			// override this.element with the file input clone:
			if (input[0] === this.element[0]) {
				this.element = inputClone;
			}
		},

		_onChange: function(e) {
			var that = e.data.fileupload,
				data = {
					files: $.each($.makeArray(e.target.files), that._normalizeFile),
					fileInput: $(e.target),
					form: $(e.target.form)
				};
			if (!data.files.length) {
				// If the files property is not available, the browser does not
				// support the File API and we add a pseudo File object with
				// the input value as name with path information removed:
				data.files = [{ name: e.target.value.replace(/^.*\\/, '') }];
			}
			if (that.options.replaceFileInput) {
				that._replaceFileInput(data.fileInput);
			}
			if (that._trigger('change', e, data) === false ||
				that._onAdd(e, data) === false) {
				return false;
			}
		},

		_onPaste: function(e) {
			var that = e.data.fileupload,
				cbd = e.originalEvent.clipboardData,
				items = (cbd && cbd.items) || [],
				data = { files: [] };
			$.each(items, function(index, item) {
				var file = item.getAsFile && item.getAsFile();
				if (file) {
					data.files.push(file);
				}
			});
			if (that._trigger('paste', e, data) === false ||
				that._onAdd(e, data) === false) {
				return false;
			}
		},

		_onDrop: function(e) {
			var that = e.data.fileupload,
				dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
				data = {
					files: $.each(
						$.makeArray(dataTransfer && dataTransfer.files),
						that._normalizeFile
					)
				};
			if (that._trigger('drop', e, data) === false ||
				that._onAdd(e, data) === false) {
				return false;
			}
			e.preventDefault();
		},

		_onDragOver: function(e) {
			var that = e.data.fileupload,
				dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
			if (that._trigger('dragover', e) === false) {
				return false;
			}
			if (dataTransfer) {
				dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy';
			}
			e.preventDefault();
		},

		_initEventHandlers: function() {
			var ns = this.options.namespace;
			if (this._isXHRUpload(this.options)) {
				this.options.dropZone
					.bind('dragover.' + ns, { fileupload: this }, this._onDragOver)
					.bind('drop.' + ns, { fileupload: this }, this._onDrop)
					.bind('paste.' + ns, { fileupload: this }, this._onPaste);
			}
			this.options.fileInput
				.bind('change.' + ns, { fileupload: this }, this._onChange);
		},

		_destroyEventHandlers: function() {
			var ns = this.options.namespace;
			this.options.dropZone
				.unbind('dragover.' + ns, this._onDragOver)
				.unbind('drop.' + ns, this._onDrop)
				.unbind('paste.' + ns, this._onPaste);
			this.options.fileInput
				.unbind('change.' + ns, this._onChange);
		},

		_setOption: function(key, value) {
			var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
			if (refresh) {
				this._destroyEventHandlers();
			}
			$.Widget.prototype._setOption.call(this, key, value);
			if (refresh) {
				this._initSpecialOptions();
				this._initEventHandlers();
			}
		},

		_initSpecialOptions: function() {
			var options = this.options;
			if (options.fileInput === undefined) {
				options.fileInput = this.element.is('input:file') ?
					this.element : this.element.find('input:file');
			} else if (!(options.fileInput instanceof $)) {
				options.fileInput = $(options.fileInput);
			}
			if (!(options.dropZone instanceof $)) {
				options.dropZone = $(options.dropZone);
			}
		},

		_create: function() {
			var options = this.options,
				dataOpts = $.extend({}, this.element.data());
			dataOpts[this.widgetName] = undefined;
			$.extend(options, dataOpts);
			options.namespace = options.namespace || this.widgetName;
			this._initSpecialOptions();
			this._slots = [];
			this._sequence = this._getXHRPromise(true);
			this._sending = this._active = this._loaded = this._total = 0;
			this._initEventHandlers();
		},

		destroy: function() {
			this._destroyEventHandlers();
			$.Widget.prototype.destroy.call(this);
		},

		enable: function() {
			$.Widget.prototype.enable.call(this);
			this._initEventHandlers();
		},

		disable: function() {
			this._destroyEventHandlers();
			$.Widget.prototype.disable.call(this);
		},

		// This method is exposed to the widget API and allows adding files
		// using the fileupload API. The data parameter accepts an object which
		// must have a files property and can contain additional options:
		// .fileupload('add', {files: filesList});
		add: function(data) {
			if (!data || this.options.disabled) {
				return;
			}
			data.files = $.each($.makeArray(data.files), this._normalizeFile);
			this._onAdd(null, data);
		},

		// This method is exposed to the widget API and allows sending files
		// using the fileupload API. The data parameter accepts an object which
		// must have a files property and can contain additional options:
		// .fileupload('send', {files: filesList});
		// The method returns a Promise object for the file upload call.
		send: function(data) {
			if (data && !this.options.disabled) {
				data.files = $.each($.makeArray(data.files), this._normalizeFile);
				if (data.files.length) {
					return this._onSend(null, data);
				}
			}
			return this._getXHRPromise(false, data && data.context);
		}

	});

}));;
/**
 * Font Selector - jQuery plugin 0.1
 *
 * Copyright (c) 2012 Chris Dyer
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
 * conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
 * disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
 * and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */


(function( $ ) {

  var settings;

  var methods = {
    init : function(options) {

        fonts = [
            "Amatic SC, sans-serif",
            "Arial,Helvetica,sans-serif",
            "Arial Black,Gadget,sans-serif",
            "Arvo, sans-serif",
            "Comic Sans MS,cursive,sans-serif",
            "Courier New,Courier, monospace",
            "Georgia,serif",
            "Helvetica, sans-serif",
            "Impact,Charcoal,sans-serif",
            "Lato, sans-serif",
            "Lucida Console,Monaco,monospace",
            "Lucida Sans Unicode,Lucida Grande,sans-serif",
            "Montserrat, sans-serif",
            "MS Sans Serif,Geneva,sans-serif",
            "Nunito, sans-serif",
            "Nunito Sans, sans-serif",
            "Open Sans, sans-serif",
            "Oswald, sans-serif",
            "Palatino Linotype,Book Antiqua,Palatino, serif",
            "Playfair Display, sans-serif",
            "Quicksand, sans-serif",
            "Raleway, sans-serif",
            "Roboto,Roboto,Arial",
            "Roboto Light,Roboto,Arial",
            "Roboto Slab,Roboto,Arial",
            "Tahoma,Geneva,sans-serif",
            "Times New Roman,Times,serif",
            "Trebuchet MS,Helvetica,sans-serif",
            "Verdana,Geneva,sans-serif"
        ];

        var orgId = $('#OrganisationId').val();
          if (orgId == 15776 || orgId == 16000 || orgId == 13957) {
            fonts.push("Hurme Geometric Sans,sans-serif");
        }

      settings = $.extend( {
        'hide_fallbacks' : false,
        'selected' : function(style) {},
        'initial' : '',
          'fonts': fonts
      }, options);

      var root = this;
      root.callback = settings['selected'];
      var visible = false;
      var selected = false;

      var displayName = function(font) {
        if (settings['hide_fallbacks'])
          return font.substr(0, font.indexOf(','));
        else
          return font;
      };

      var select = function(font) {
        root.find('span').html(displayName(font).replace(/["']{1}/gi,""));
        root.css('font-family', font);
        selected = font;

        root.callback(selected);
      }

      var positionUl = function() {
        var left, top;
        left = $(root).offset().left;
        top = $(root).offset().top + $(root).outerHeight();

        $(ul).css({
          'position': 'absolute',
          'left': left + 'px',
          'top': top + 'px'
        });
      }

      // Setup markup
      $(this).prepend('<span>' + settings['initial'].replace(/'/g,'&#039;') + '</span>');
      var ul = $('<ul class="fontSelectUl" style="z-index:10100;"></ul>').appendTo('body');
      ul.hide();
      positionUl();

      for (var i = 0; i < settings['fonts'].length; i++) {
      	var item = $('<li style="z-index:10101;">' + displayName(settings['fonts'][i]) + '</li>').appendTo(ul);
        $(item).css('font-family', settings['fonts'][i]);
      }

      if (settings['initial'] != '')
        select(settings['initial']);

      ul.find('li').click(function() {

        if (!visible)
          return;

        positionUl();
        ul.slideUp('fast', function() {
          visible = false;
        });

        select($(this).css('font-family'));
      });

      $(this).click(function(event) {

        if (visible)
          return;

        event.stopPropagation();

        positionUl();
        ul.slideDown('fast', function() {
          visible = true;
        });
      });

      $('html').click(function () {
      	if (visible) {
      		ul.slideUp('fast', function () {
      			visible = false;
      		});
      	}
      });
    },
    selected : function() {
      return this.css('font-family');
    },
	select : function(font) {
        this.find('span').html(font.substr(0, font.indexOf(',')).replace(/["']{1}/gi,""));
        this.css('font-family', font);
        selected = font;
      }
  };

  $.fn.fontSelector = function(method) {
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.fontSelector' );
    }
  }
}) ( jQuery );

;
(function ($) {

	var settings;

	var methods = {
		init: function (options) {
			settings = $.extend({
				selected: function (style) { },
				initial: 1,
				fontsizes: [
					"Small",
					"Medium",
					"Large"
				]
			}, options);

			var $root = $(this);
			var visible = false;
			var selected = settings.initial;

			$root.callback = settings.selected;

			var displayName = function (fontsize) {
				return settings.fontsizes[fontsize];
			}

			var select = function (fontsize) {
				$root.find('span').html(displayName(fontsize));
				$root.data('fontsize', fontsize);
				selected = fontsize;

				$root.callback(selected);
			}

			var positionUl = function () {
				var left, top;
				left = $root.offset().left;
				top = $root.offset().top + $root.outerHeight();

				$(ul).css({
					'position': 'absolute',
					'left': left + 'px',
					'top': top + 'px'
				});
			}

			// Setup markup
			$root.prepend('<span>' + displayName(settings.initial) + '</span>');
			var ul = $('<ul class="fontSelectUl" style="z-index:10100;"></ul>').appendTo('body');
			ul.hide();
			positionUl();

			for (var i = 0; i < settings.fontsizes.length; i++) {
				var item = $('<li style="z-index:10101;">' + displayName(i) + '</li>').appendTo(ul);
				item.data('fontsize', i);
			}

			if (settings.initial) {
				select(settings.initial);
			}

			ul.find('li').click(function () {
				if (!visible) {
					return;
				}

				positionUl();
				ul.slideUp('fast', function () {
					visible = false;
				});

				select($(this).data('fontsize'));
			});

			$root.click(function (event) {
				if (visible) {
					return;
				}
				event.stopPropagation();

				positionUl();
				ul.slideDown('fast', function () {
					visible = true;
				});
			});

			$('html').click(function () {
				if (visible) {
					ul.slideUp('fast', function () {
						visible = false;
					});
				}
			});
		},
		selected: function () {
			return $root.data('fontsize');
		},
		select: function (fontsize) {
			$root.find('span').html(displayName(fontsize));
			$root.data('fontsize', fontsize);
			selected = fontsize;
		}
	};

	$.fn.fontSizeSelector = function (method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.fontSizeSelector');
		}
	}
})(jQuery);

;

(function( $ ) {

  var settings;

  var methods = {
    init : function(options) {

      settings = $.extend( {
        'hide_fallbacks' : false,
        'selected' : function(style) {},
        'initial' : '',
        'fonts': [
                    "8px",
					"9px",
                    "10px",
                    "11px",
					"12px",
					"14px",
                    "16px",
                    "18px",
                    "20px",
                    "22px",
					"24px",
                    "26px",
                    "28px",
                    "36px",
                    "48px",
                    "72px"
        ]
      }, options);

      var root = this;
      root.callback = settings['selected'];
      var visible = false;
      var selected = false;

      var displayName = function(font) {
        if (settings['hide_fallbacks'])
          return font.substr(0, font.indexOf('px'));
        else
          return font;
      }

      var select = function(font) {
        root.find('span').html(displayName(font).replace(/["']{1}/gi,""));
        selected = font;

        root.callback(selected);
      }

      var positionUl = function() {
        var left, top;
        left = $(root).offset().left;
        top = $(root).offset().top + $(root).outerHeight();

        $(ul).css({
          'position': 'absolute',
          'left': left + 'px',
          'top': top + 'px'
        });
      }

      // Setup markup
      $(this).prepend('<span>' + settings['initial'].replace(/'/g,'&#039;') + '</span>');
      var ul = $('<ul class="fontSelectUl fontSizeSelectUI" style="z-index:10100;"></ul>').appendTo('body');
      ul.hide();
      positionUl();

      for (var i = 0; i < settings['fonts'].length; i++) {
          var item = $('<li style="z-index:10101;">' + displayName(settings['fonts'][i]) + '</li>').appendTo(ul);
          $(item).css('font-size', settings['fonts'][i]);
      }

      if (settings['initial'] != '')
        select(settings['initial']);

      ul.find('li').click(function() {

        if (!visible)
          return;

        positionUl();
        ul.slideUp('fast', function() {
          visible = false;
        });

        select($(this).css('font-size'));
      });

      $(this).click(function(event) {

        if (visible)
          return;

        event.stopPropagation();

        positionUl();
        ul.slideDown('fast', function() {
          visible = true;
        });
      });

      $('html').click(function () {
      	if (visible) {
      		ul.slideUp('fast', function () {
      			visible = false;
      		});
      	}
      });
    },
    selected : function() {
      return this.css('font-size');
    },
	select : function(font) {
        this.find('span').html(font);
        selected = font;
      }
  };

  $.fn.sportyfontSizeSelector = function(method) {
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
        $.error('Method ' + method + ' does not exist on jQuery.sportyfontSizeSelector' );
    }
  }
}) ( jQuery );

;
/*!
 * jQuery Form Plugin
 * version: 3.51.0-2014.06.20
 * Requires jQuery v1.5 or later
 * Copyright (c) 2014 M. Alsup
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Project repository: https://github.com/malsup/form
 * Dual licensed under the MIT and GPL licenses.
 * https://github.com/malsup/form#copyright-and-license
 */
(function(n){"use strict";typeof define=="function"&&define.amd?define(["jquery"],n):n(typeof jQuery!="undefined"?jQuery:window.Zepto)})(function(n){"use strict";function u(t){var i=t.data;t.isDefaultPrevented()||(t.preventDefault(),n(t.target).ajaxSubmit(i))}function f(t){var r=t.target,u=n(r),f,i,e;if(!u.is("[type=submit],[type=image]")){if(f=u.closest("[type=submit]"),f.length===0)return;r=f[0]}i=this;i.clk=r;r.type=="image"&&(t.offsetX!==undefined?(i.clk_x=t.offsetX,i.clk_y=t.offsetY):typeof n.fn.offset=="function"?(e=u.offset(),i.clk_x=t.pageX-e.left,i.clk_y=t.pageY-e.top):(i.clk_x=t.pageX-r.offsetLeft,i.clk_y=t.pageY-r.offsetTop));setTimeout(function(){i.clk=i.clk_x=i.clk_y=null},100)}function t(){if(n.fn.ajaxSubmit.debug){var t="[jquery.form] "+Array.prototype.join.call(arguments,"");window.console&&window.console.log?window.console.log(t):window.opera&&window.opera.postError&&window.opera.postError(t)}}var i={},r;i.fileapi=n("<input type='file'/>").get(0).files!==undefined;i.formdata=window.FormData!==undefined;r=!!n.fn.prop;n.fn.attr2=function(){if(!r)return this.attr.apply(this,arguments);var n=this.prop.apply(this,arguments);return n&&n.jquery||typeof n=="string"?n:this.attr.apply(this,arguments)};n.fn.ajaxSubmit=function(u){function ot(t){for(var r=n.param(t,u.traditional).split("&"),o=r.length,e=[],f,i=0;i<o;i++)r[i]=r[i].replace(/\+/g," "),f=r[i].split("="),e.push([decodeURIComponent(f[0]),decodeURIComponent(f[1])]);return e}function st(t){for(var f,r,s,o=new FormData,i=0;i<t.length;i++)o.append(t[i].name,t[i].value);if(u.extraData)for(f=ot(u.extraData),i=0;i<f.length;i++)f[i]&&o.append(f[i][0],f[i][1]);return u.data=null,r=n.extend(!0,{},n.ajaxSettings,u,{contentType:!1,processData:!1,cache:!1,type:e||"POST"}),u.uploadProgress&&(r.xhr=function(){var t=n.ajaxSettings.xhr();return t.upload&&t.upload.addEventListener("progress",function(n){var t=0,i=n.loaded||n.position,r=n.total;n.lengthComputable&&(t=Math.ceil(i/r*100));u.uploadProgress(n,i,r,t)},!1),t}),r.data=null,s=r.beforeSend,r.beforeSend=function(n,t){t.data=u.formData?u.formData:o;s&&s.call(this,n,t)},n.ajax(r)}function ft(i){function ot(n){var i=null;try{n.contentWindow&&(i=n.contentWindow.document)}catch(r){t("cannot get iframe.contentWindow document: "+r)}if(i)return i;try{i=n.contentDocument?n.contentDocument:n.document}catch(r){t("cannot get iframe.contentDocument: "+r);i=n.document}return i}function st(){function h(){try{var n=ot(a).readyState;t("state = "+n);n&&n.toLowerCase()=="uninitialized"&&setTimeout(h,50)}catch(i){t("Server abort: ",i," (",i.name,")");b(tt);g&&clearTimeout(g);g=undefined}}var u=f.attr2("target"),s=f.attr2("action"),y=f.attr("enctype")||f.attr("encoding")||"multipart/form-data",r,i,c;l.setAttribute("target",d);(!e||/post/i.test(e))&&l.setAttribute("method","POST");s!=o.url&&l.setAttribute("action",o.url);o.skipEncodingOverride||e&&!/post/i.test(e)||f.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"});o.timeout&&(g=setTimeout(function(){rt=!0;b(ut)},o.timeout));r=[];try{if(o.extraData)for(i in o.extraData)o.extraData.hasOwnProperty(i)&&(n.isPlainObject(o.extraData[i])&&o.extraData[i].hasOwnProperty("name")&&o.extraData[i].hasOwnProperty("value")?r.push(n('<input type="hidden" name="'+o.extraData[i].name+'">').val(o.extraData[i].value).appendTo(l)[0]):r.push(n('<input type="hidden" name="'+i+'">').val(o.extraData[i]).appendTo(l)[0]));o.iframeTarget||v.appendTo("body");a.attachEvent?a.attachEvent("onload",b):a.addEventListener("load",b,!1);setTimeout(h,15);try{l.submit()}catch(p){c=document.createElement("form").submit;c.apply(l)}}finally{l.setAttribute("action",s);l.setAttribute("enctype",y);u?l.setAttribute("target",u):f.removeAttr("target");n(r).remove()}}function b(i){var r,u,w,f,k,d,e,c,l;if(!s.aborted&&!lt){if(h=ot(a),h||(t("cannot access response document"),i=tt),i===ut&&s){s.abort("timeout");y.reject(s,"timeout");return}if(i==tt&&s){s.abort("server abort");y.reject(s,"error","server abort");return}if(h&&h.location.href!=o.iframeSrc||rt){a.detachEvent?a.detachEvent("onload",b):a.removeEventListener("load",b,!1);r="success";try{if(rt)throw"timeout";if(w=o.dataType=="xml"||h.XMLDocument||n.isXMLDoc(h),t("isXml="+w),!w&&window.opera&&(h.body===null||!h.body.innerHTML)&&--ct){t("requeing onLoad callback, DOM not available");setTimeout(b,250);return}f=h.body?h.body:h.documentElement;s.responseText=f?f.innerHTML:null;s.responseXML=h.XMLDocument?h.XMLDocument:h;w&&(o.dataType="xml");s.getResponseHeader=function(n){var t={"content-type":o.dataType};return t[n.toLowerCase()]};f&&(s.status=Number(f.getAttribute("status"))||s.status,s.statusText=f.getAttribute("statusText")||s.statusText);k=(o.dataType||"").toLowerCase();d=/(json|script|text)/.test(k);d||o.textarea?(e=h.getElementsByTagName("textarea")[0],e?(s.responseText=e.value,s.status=Number(e.getAttribute("status"))||s.status,s.statusText=e.getAttribute("statusText")||s.statusText):d&&(c=h.getElementsByTagName("pre")[0],l=h.getElementsByTagName("body")[0],c?s.responseText=c.textContent?c.textContent:c.innerText:l&&(s.responseText=l.textContent?l.textContent:l.innerText))):k=="xml"&&!s.responseXML&&s.responseText&&(s.responseXML=at(s.responseText));try{ht=yt(s,k,o)}catch(nt){r="parsererror";s.error=u=nt||r}}catch(nt){t("error caught: ",nt);r="error";s.error=u=nt||r}s.aborted&&(t("upload aborted"),r=null);s.status&&(r=s.status>=200&&s.status<300||s.status===304?"success":"error");r==="success"?(o.success&&o.success.call(o.context,ht,"success",s),y.resolve(s.responseText,"success",s),p&&n.event.trigger("ajaxSuccess",[s,o])):r&&(u===undefined&&(u=s.statusText),o.error&&o.error.call(o.context,s,r,u),y.reject(s,"error",u),p&&n.event.trigger("ajaxError",[s,o,u]));p&&n.event.trigger("ajaxComplete",[s,o]);p&&!--n.active&&n.event.trigger("ajaxStop");o.complete&&o.complete.call(o.context,s,r);lt=!0;o.timeout&&clearTimeout(g);setTimeout(function(){o.iframeTarget?v.attr("src",o.iframeSrc):v.remove();s.responseXML=null},100)}}}var l=f[0],it,nt,o,p,d,v,a,s,k,w,rt,g,y=n.Deferred(),ut,tt,ft,et,ht,h,ct,lt;if(y.abort=function(n){s.abort(n)},i)for(nt=0;nt<c.length;nt++)it=n(c[nt]),r?it.prop("disabled",!1):it.removeAttr("disabled");if(o=n.extend(!0,{},n.ajaxSettings,u),o.context=o.context||o,d="jqFormIO"+(new Date).getTime(),o.iframeTarget?(v=n(o.iframeTarget),w=v.attr2("name"),w?d=w:v.attr2("name",d)):(v=n('<iframe name="'+d+'" src="'+o.iframeSrc+'" />'),v.css({position:"absolute",top:"-1000px",left:"-1000px"})),a=v[0],s={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(i){var r=i==="timeout"?"timeout":"aborted";t("aborting upload... "+r);this.aborted=1;try{a.contentWindow.document.execCommand&&a.contentWindow.document.execCommand("Stop")}catch(u){}v.attr("src",o.iframeSrc);s.error=r;o.error&&o.error.call(o.context,s,r,i);p&&n.event.trigger("ajaxError",[s,o,r]);o.complete&&o.complete.call(o.context,s,r)}},p=o.global,p&&0==n.active++&&n.event.trigger("ajaxStart"),p&&n.event.trigger("ajaxSend",[s,o]),o.beforeSend&&o.beforeSend.call(o.context,s,o)===!1)return o.global&&n.active--,y.reject(),y;if(s.aborted)return y.reject(),y;k=l.clk;k&&(w=k.name,w&&!k.disabled&&(o.extraData=o.extraData||{},o.extraData[w]=k.value,k.type=="image"&&(o.extraData[w+".x"]=l.clk_x,o.extraData[w+".y"]=l.clk_y)));ut=1;tt=2;ft=n("meta[name=csrf-token]").attr("content");et=n("meta[name=csrf-param]").attr("content");et&&ft&&(o.extraData=o.extraData||{},o.extraData[et]=ft);o.forceSync?st():setTimeout(st,10);ct=50;var at=n.parseXML||function(n,t){return window.ActiveXObject?(t=new ActiveXObject("Microsoft.XMLDOM"),t.async="false",t.loadXML(n)):t=(new DOMParser).parseFromString(n,"text/xml"),t&&t.documentElement&&t.documentElement.nodeName!="parsererror"?t:null},vt=n.parseJSON||function(s){return window.eval("("+s+")")},yt=function(t,i,r){var f=t.getResponseHeader("content-type")||"",e=i==="xml"||!i&&f.indexOf("xml")>=0,u=e?t.responseXML:t.responseText;return e&&u.documentElement.nodeName==="parsererror"&&n.error&&n.error("parsererror"),r&&r.dataFilter&&(u=r.dataFilter(u,i)),typeof u=="string"&&(i==="json"||!i&&f.indexOf("json")>=0?u=vt(u):(i==="script"||!i&&f.indexOf("javascript")>=0)&&n.globalEval(u)),u};return y}var e,b,o,f,a,v,c,y,s,l,h,d,g,nt,ut,p,w;if(!this.length)return t("ajaxSubmit: skipping submit process - no element selected"),this;if(f=this,typeof u=="function"?u={success:u}:u===undefined&&(u={}),e=u.type||this.attr2("method"),b=u.url||this.attr2("action"),o=typeof b=="string"?n.trim(b):"",o=o||window.location.href||"",o&&(o=(o.match(/^([^#]+)/)||[])[1]),u=n.extend(!0,{url:o,success:n.ajaxSettings.success,type:e||n.ajaxSettings.type,iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank"},u),a={},this.trigger("form-pre-serialize",[this,u,a]),a.veto)return t("ajaxSubmit: submit vetoed via form-pre-serialize trigger"),this;if(u.beforeSerialize&&u.beforeSerialize(this,u)===!1)return t("ajaxSubmit: submit aborted via beforeSerialize callback"),this;if(v=u.traditional,v===undefined&&(v=n.ajaxSettings.traditional),c=[],s=this.formToArray(u.semantic,c),u.data&&(u.extraData=u.data,y=n.param(u.data,v)),u.beforeSubmit&&u.beforeSubmit(s,this,u)===!1)return t("ajaxSubmit: submit aborted via beforeSubmit callback"),this;if(this.trigger("form-submit-validate",[s,this,u,a]),a.veto)return t("ajaxSubmit: submit vetoed via form-submit-validate trigger"),this;l=n.param(s,v);y&&(l=l?l+"&"+y:y);u.type.toUpperCase()=="GET"?(u.url+=(u.url.indexOf("?")>=0?"&":"?")+l,u.data=null):u.data=l;h=[];u.resetForm&&h.push(function(){f.resetForm()});u.clearForm&&h.push(function(){f.clearForm(u.includeHidden)});!u.dataType&&u.target?(d=u.success||function(){},h.push(function(t){var i=u.replaceTarget?"replaceWith":"html";n(u.target)[i](t).each(d,arguments)})):u.success&&h.push(u.success);u.success=function(n,t,i){for(var e=u.context||this,r=0,o=h.length;r<o;r++)h[r].apply(e,[n,t,i||f,f])};u.error&&(g=u.error,u.error=function(n,t,i){var r=u.context||this;g.apply(r,[n,t,i,f])});u.complete&&(nt=u.complete,u.complete=function(n,t){var i=u.context||this;nt.apply(i,[n,t,f])});var et=n("input[type=file]:enabled",this).filter(function(){return n(this).val()!==""}),tt=et.length>0,it="multipart/form-data",rt=f.attr("enctype")==it||f.attr("encoding")==it,k=i.fileapi&&i.formdata;for(t("fileAPI :"+k),ut=(tt||rt)&&!k,u.iframe!==!1&&(u.iframe||ut)?u.closeKeepAlive?n.get(u.closeKeepAlive,function(){p=ft(s)}):p=ft(s):p=(tt||rt)&&k?st(s):n.ajax(u),f.removeData("jqxhr").data("jqxhr",p),w=0;w<c.length;w++)c[w]=null;return this.trigger("form-submit-notify",[this,u]),this};n.fn.ajaxForm=function(i){if(i=i||{},i.delegation=i.delegation&&n.isFunction(n.fn.on),!i.delegation&&this.length===0){var r={s:this.selector,c:this.context};return!n.isReady&&r.s?(t("DOM not ready, queuing ajaxForm"),n(function(){n(r.s,r.c).ajaxForm(i)}),this):(t("terminating; zero elements found by selector"+(n.isReady?"":" (DOM not ready)")),this)}if(i.delegation){n(document).off("submit.form-plugin",this.selector,u).off("click.form-plugin",this.selector,f).on("submit.form-plugin",this.selector,i,u).on("click.form-plugin",this.selector,i,f);return this}return this.ajaxFormUnbind().bind("submit.form-plugin",i,u).bind("click.form-plugin",i,f)};n.fn.ajaxFormUnbind=function(){return this.unbind("submit.form-plugin click.form-plugin")};n.fn.formToArray=function(t,r){var e=[],l,h,f,c,u,b,k,a,p,v;if(this.length===0)return e;var o=this[0],w=this.attr("id"),s=t?o.getElementsByTagName("*"):o.elements,y;if(s&&!/MSIE [678]/.test(navigator.userAgent)&&(s=n(s).get()),w&&(y=n(':input[form="'+w+'"]').get(),y.length&&(s=(s||[]).concat(y))),!s||!s.length)return e;for(l=0,b=s.length;l<b;l++)if(u=s[l],f=u.name,f&&!u.disabled){if(t&&o.clk&&u.type=="image"){o.clk==u&&(e.push({name:f,value:n(u).val(),type:u.type}),e.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}));continue}if(c=n.fieldValue(u,!0),c&&c.constructor==Array)for(r&&r.push(u),h=0,k=c.length;h<k;h++)e.push({name:f,value:c[h]});else if(i.fileapi&&u.type=="file")if(r&&r.push(u),a=u.files,a.length)for(h=0;h<a.length;h++)e.push({name:f,value:a[h],type:u.type});else e.push({name:f,value:"",type:u.type});else c!==null&&typeof c!="undefined"&&(r&&r.push(u),e.push({name:f,value:c,type:u.type,required:u.required}))}return!t&&o.clk&&(p=n(o.clk),v=p[0],f=v.name,f&&!v.disabled&&v.type=="image"&&(e.push({name:f,value:p.val()}),e.push({name:f+".x",value:o.clk_x},{name:f+".y",value:o.clk_y}))),e};n.fn.formSerialize=function(t){return n.param(this.formToArray(t))};n.fn.fieldSerialize=function(t){var i=[];return this.each(function(){var f=this.name,r,u,e;if(f)if(r=n.fieldValue(this,t),r&&r.constructor==Array)for(u=0,e=r.length;u<e;u++)i.push({name:f,value:r[u]});else r!==null&&typeof r!="undefined"&&i.push({name:this.name,value:r})}),n.param(i)};n.fn.fieldValue=function(t){for(var f,i,r=[],u=0,e=this.length;u<e;u++)(f=this[u],i=n.fieldValue(f,t),i!==null&&typeof i!="undefined"&&(i.constructor!=Array||i.length))&&(i.constructor==Array?n.merge(r,i):r.push(i));return r};n.fieldValue=function(t,i){var a=t.name,u=t.type,h=t.tagName.toLowerCase(),e,o,r,f;if(i===undefined&&(i=!0),i&&(!a||t.disabled||u=="reset"||u=="button"||(u=="checkbox"||u=="radio")&&!t.checked||(u=="submit"||u=="image")&&t.form&&t.form.clk!=t||h=="select"&&t.selectedIndex==-1))return null;if(h=="select"){if(e=t.selectedIndex,e<0)return null;var c=[],l=t.options,s=u=="select-one",v=s?e+1:l.length;for(o=s?e:0;o<v;o++)if(r=l[o],r.selected){if(f=r.value,f||(f=r.attributes&&r.attributes.value&&!r.attributes.value.specified?r.text:r.value),s)return f;c.push(f)}return c}return n(t).val()};n.fn.clearForm=function(t){return this.each(function(){n("input,select,textarea",this).clearFields(t)})};n.fn.clearFields=n.fn.clearInputs=function(t){var i=/^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i;return this.each(function(){var r=this.type,u=this.tagName.toLowerCase();i.test(r)||u=="textarea"?this.value="":r=="checkbox"||r=="radio"?this.checked=!1:u=="select"?this.selectedIndex=-1:r=="file"?/MSIE/.test(navigator.userAgent)?n(this).replaceWith(n(this).clone(!0)):n(this).val(""):t&&(t===!0&&/hidden/.test(r)||typeof t=="string"&&n(this).is(t))&&(this.value="")})};n.fn.resetForm=function(){return this.each(function(){typeof this.reset!="function"&&(typeof this.reset!="object"||this.reset.nodeType)||this.reset()})};n.fn.enable=function(n){return n===undefined&&(n=!0),this.each(function(){this.disabled=!n})};n.fn.selected=function(t){return t===undefined&&(t=!0),this.each(function(){var r=this.type,i;r=="checkbox"||r=="radio"?this.checked=t:this.tagName.toLowerCase()=="option"&&(i=n(this).parent("select"),t&&i[0]&&i[0].type=="select-one"&&i.find("option").selected(!1),this.selected=t)})};n.fn.ajaxSubmit.debug=!1});
/*
//# sourceMappingURL=jquery.form.min.js.map
*/;
// jQuery Autocomplete plugin

(function ($) {

    $.fn.locationAutoComplete = function (options) {

        var settings = $.extend({}, $.fn.locationAutoComplete.defaults, options);

		// Create the autocomplete object, restricting the search to geographical location types.
		// When the user selects an address from the dropdown, populate the address fields in the form.
		function initAutocomplete(element) {
  
            $(element).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/suggest?f=json&maxSuggestions=6&countryCode=" + sportyApp.country,
                        dataType: "jsonp",
                        data: {
                            text: request.term
                        },
                        success: function (data) {
                            response($.map(data.suggestions, function (item) {
                                return {
                                    label: item.text,
                                    value: item.text,
                                    magicKey: item.magicKey
                                };
                            }));
                        }
                    });
                },
                minLength: 2,
                select: function (event, ui) {
                    $.ajax({
                        url: "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/findAddressCandidates?f=json&outFields=Addr_type,Match_addr,StAddr,City,Postal,Region,Country,MetroArea,Subregion,Nbrhd",
                        dataType: "jsonp",
                        data: {
                            magicKey: ui.item.magicKey
                        },
                        success: function (data) {

                            var location = data.candidates[0].location;
                            var address = data.candidates[0].attributes.StAddr;

                            if (settings.isCompBuilder) {
                                address = data.candidates[0].address;
                            }

                            var suburb = data.candidates[0].attributes.Nbrhd;
                            var city = data.candidates[0].attributes.City;
                            var country = data.candidates[0].attributes.Country;
                            var postCode = data.candidates[0].attributes.Postal;
                            
                            //set map position
                            if (settings.map) {
                                settings.map.setCenter({ lat: location.y, lng: location.x });
                                settings.map.setZoom(17); // Why 17? Because it looks good.
                            }

                            //set marker position
                            if (settings.marker) {
                                settings.marker.setPosition({ lat: location.y, lng: location.x });
                                settings.marker.setVisible(true);
                            }

                            fillInAddress(address, suburb, city, country, postCode, location.y, location.x);

                        }
                    });
                }
            });
		}

        function fillInAddress(fullAddress, suburb, city, country, postCode, lat, lng) {

            if (settings.isCompBuilder) {
                
                settings.editingLocation.Lat = lat;
                settings.editingLocation.Lng = lng;
                
                settings.editingLocation.Address = fullAddress;
                settings.editingLocation.Postcode = postCode;
                settings.editingLocation.Suburb = suburb;
                settings.editingLocation.Region = city;
                settings.editingLocation.Country = country;

               
                $("#suburb-input").val(suburb);
                $("#city-input").val(city);
                $("#country-input").val(country);
                $("#postcode-input").val(postCode);


                settings.compBuilderScope.safeApply();

                setTimeout(function () {
                    settings.compBuilderScope.safeApply();
                    $(".location-input-wrapper input").focus();
                }, 1000);

            }
            else {

                $(settings.addressField).val(fullAddress);
                $(settings.suburbField).val(suburb);
                $(settings.cityField).val(city);
                $(settings.postCodeField).val(postCode);
                $(settings.latField).val(lat);
                $(settings.lngField).val(lng);
            }

		}

		this.each(function () {			
            initAutocomplete(this);
		});

		return this;
	};

    $.fn.locationAutoComplete.defaults = {
        addressField: '#PostalAddressAddressLine',
        suburbField: "div[data-firstmappingfield='PostalAddressSuburb'] input",
        cityField: '#PostalAddressCity',
        countryField: '#PostalAddressCountry',
        postCodeField: '#PostalAddressPostCode',
        latField: '#hdnLat',
        lngField: '#hdnLong',
        map: null,
        marker: null,
        isCompBuilder: false,
        editingLocation: null,
        compBuilderScope: null
	};

}(jQuery));
;
/*
 * jQuery Iframe Transport Plugin 1.3
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2011, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint unparam: true, nomen: true */
/*global define, window, document */

(function(factory) {
	'use strict';
	if (typeof define === 'function' && define.amd) {
		// Register as an anonymous AMD module:
		define(['jquery'], factory);
	} else {
		// Browser globals:
		factory(window.jQuery);
	}
}(function($) {
	'use strict';

	// Helper variable to create unique names for the transport iframes:
	var counter = 0;

	// The iframe transport accepts three additional options:
	// options.fileInput: a jQuery collection of file input fields
	// options.paramName: the parameter name for the file form data,
	//  overrides the name property of the file input field(s)
	// options.formData: an array of objects with name and value properties,
	//  equivalent to the return data of .serializeArray(), e.g.:
	//  [{name: 'a', value: 1}, {name: 'b', value: 2}]
	$.ajaxTransport('iframe', function(options) {
		if (options.async && (options.type === 'POST' || options.type === 'GET')) {
			var form,
				iframe;
			return {
				send: function(_, completeCallback) {
					form = $('<form style="display:none;"></form>');
					// javascript:false as initial iframe src
					// prevents warning popups on HTTPS in IE6.
					// IE versions below IE8 cannot set the name property of
					// elements that have already been added to the DOM,
					// so we set the name along with the iframe HTML markup:
					iframe = $(
						'<iframe src="javascript:false;" name="iframe-transport-' +
						(counter += 1) + '"></iframe>'
					).bind('load', function() {
						var fileInputClones;
						iframe
							.unbind('load')
							.bind('load', function() {
								var response;
								// Wrap in a try/catch block to catch exceptions thrown
								// when trying to access cross-domain iframe contents:
								try {
									response = iframe.contents();
									// Google Chrome and Firefox do not throw an
									// exception when calling iframe.contents() on
									// cross-domain requests, so we unify the response:
									if (!response.length || !response[0].firstChild) {
										throw new Error();
									}
								} catch (e) {
									response = undefined;
								}
								// The complete callback returns the
								// iframe content document as response object:
								completeCallback(
									200,
									'success',
									{ 'iframe': response }
								);
								// Fix for IE endless progress bar activity bug
								// (happens on form submits to iframe targets):
								$('<iframe src="javascript:false;"></iframe>')
									.appendTo(form);
								form.remove();
							});
						form
							.prop('target', iframe.prop('name'))
							.prop('action', options.url)
							.prop('method', options.type);
						if (options.formData) {
							$.each(options.formData, function(index, field) {
								$('<input type="hidden"/>')
									.prop('name', field.name)
									.val(field.value)
									.appendTo(form);
							});
						}
						if (options.fileInput && options.fileInput.length &&
							options.type === 'POST') {
							fileInputClones = options.fileInput.clone();
							// Insert a clone for each file input field:
							options.fileInput.after(function(index) {
								return fileInputClones[index];
							});
							if (options.paramName) {
								options.fileInput.each(function() {
									$(this).prop('name', options.paramName);
								});
							}
							// Appending the file input fields to the hidden form
							// removes them from their original location:
							form
								.append(options.fileInput)
								.prop('enctype', 'multipart/form-data')
								// enctype must be set as encoding for IE:
								.prop('encoding', 'multipart/form-data');
						}
						form.submit();
						// Insert the file input fields at their original location
						// by replacing the clones with the originals:
						if (fileInputClones && fileInputClones.length) {
							options.fileInput.each(function(index, input) {
								var clone = $(fileInputClones[index]);
								$(input).prop('name', clone.prop('name'));
								clone.replaceWith(input);
							});
						}
					});
					form.append(iframe).appendTo(document.body);
				},
				abort: function() {
					if (iframe) {
						// javascript:false as iframe src aborts the request
						// and prevents warning popups on HTTPS in IE6.
						// concat is used to avoid the "Script URL" JSLint error:
						iframe
							.unbind('load')
							.prop('src', 'javascript'.concat(':false;'));
					}
					if (form) {
						form.remove();
					}
				}
			};
		}
	});

	// The iframe transport returns the iframe content document as response.
	// The following adds converters from iframe to text, json, html, and script:
	$.ajaxSetup({
		converters: {
			'iframe text': function(iframe) {
				return $(iframe[0].body).text();
			},
			'iframe json': function(iframe) {
				return $.parseJSON($(iframe[0].body).text());
			},
			'iframe html': function(iframe) {
				return $(iframe[0].body).html();
			},
			'iframe script': function(iframe) {
				return $.globalEval($(iframe[0].body).text());
			}
		}
	});

}));;
/*
 * Very simple jQuery Color Picker
 * https://github.com/tkrotoff/jquery-simplecolorpicker
 *
 * Copyright (C) 2012-2013 Tanguy Krotoff <tkrotoff@gmail.com>
 *
 * Licensed under the MIT license
 */

/*
	IMPORTANT: 
	RED JUNGLE: 
		This file has been heavily modified to suit our needs, 
		disabling of colors removed, runs off textbox now, ability to add colors.
		Kyle
*/

(function($) {
  'use strict';

  /**
   * Constructor.
   */
  var SimpleColorPicker = function(textbox, options) {
  	this.init('simplecolorpicker', textbox, options);
  };

  /**
   * SimpleColorPicker class.
   */
  SimpleColorPicker.prototype = {
    constructor: SimpleColorPicker,


    init: function (type, textbox, options) {
      var self = this;

      self.type = type;

      self.$textbox = $(textbox);
      self.$textbox.hide();

      self.options = $.extend({}, $.fn.simplecolorpicker.defaults, options);

      self.$colorList = null;
      var selectedValue = self.$textbox.val();

      if (self.options.picker === true) {
        self.$icon = $('<span class="simplecolorpicker icon input-group-addon"'
                     + ' title="' + selectedValue + '"'
                     + ' style="width:100%;background-color: ' + selectedValue + ';"'
                     + ' role="button" tabindex="0">'
                     + '</span>').insertAfter(self.$textbox);
        self.$icon.on('click.' + self.type, $.proxy(self.showPicker, self));

				// BUG: Color picker not scrolling with modal
        //self.$picker = $('<span class="simplecolorpicker picker ' + self.options.theme + '"></span>').appendTo(document.body);
        self.$picker = $('<span class="simplecolorpicker picker ' + self.options.theme + '"></span>').insertAfter(self.$textbox);
        self.$colorList = self.$picker;

        // Hide picker when clicking outside
        $(document).on('mousedown.' + self.type, $.proxy(self.hidePicker, self));
        self.$picker.on('mousedown.' + self.type, $.proxy(self.mousedown, self));
      } else {
      	self.$inline = $('<span class="simplecolorpicker inline ' + self.options.theme + '"></span>').insertAfter(self.$textbox);
        self.$colorList = self.$inline;
      }

      // Build the list of colors
    	// <span class="color selected" title="Green" style="background-color: #7bd148;" role="button"></span>
      $.each(self.options.colors, function () {  
	      var color = this;
        var selected = '';
        if (selectedValue === this) {
          selected = ' data-selected';
        }

        var $colorSpan = $('<span class="color" ' +
							'title="' + color + '" ' +
							'style="background-color: ' + color + ';" ' +
							'data-color="' + color + '"' +
							selected +
							' role="button" tabindex="0">' +
							'</span>');

        self.$colorList.append($colorSpan);
      
        $colorSpan.on('click.' + self.type, $.proxy(self.colorSpanClicked, self));
      });

      self.$colorList.append('<div class="hexValContainer form-group" style="margin-right:5px;"><div class="input-group"><span class="input-group-addon">#</span><input style="min-width:140px;width:100%;" type="text" class="form-control HexColor" id="" name="HexColor" placeholder="Hex colour"/><span class="input-group-btn"><button id="" class="btn btn-default addColorButton" type="button">Add</button></span></div></div>');
          
    	// Attach enter keypress handler for new-hex-color textbox
      $(".HexColor").keypress(function (e) {
      	if (e.which == 13) {
      		e.preventDefault();
      		$(".addColorButton").click();
      	}
      });

      // Append custom site colors
      $.get("/cms/site/" + $("#SiteId").val() + "/getcustomcolors/", function (data) {
      	$(data).each(function () {
      		self.addCustomColor($(this)[0].HexValue);
      	});

      	var display = 'inline-block;';
	      if ($('.custom-color', self.$colorList).length == 0)
		      display = 'none;';

      	var $clearButtonMarkup = $("<a class='clearAllColors' style='display:" + display + "'>Clear colours</a>");
      	self.$colorList.append($clearButtonMarkup);
      	$clearButtonMarkup.on('click.' + self.type, function () {
      		// show bootbox confirmation ??
      		$(".custom-color").remove();
      		$.ajax("/Site/RemoveSiteCustomColors?siteId=" + $("#SiteId").val());

      		$('.clearAllColors', self.$colorList).hide("fast");
      	});
      });

      	// set handler for trigger 
      if (self.options.trigger != '') {
      	var triggerId = self.options.trigger;
      	$("#" +triggerId).on('click.' + self.type, $.proxy(self.showPicker, self));
      }

      var addColorButton = $('.addColorButton', self.$colorList);
      addColorButton.on('click', function () {
      	var hexValue = $('input', self.$colorList).val();

				// hex value empty
      	if (hexValue == "") {
      		$('input', self.$colorList).parent().parent().addClass("has-error");
		      return;
      	}

				// prepend # if string doesn't contain already
      	if (hexValue.slice(0, 1) != "#")
      		hexValue = "#" + hexValue;

      	var re = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
      	if (!re.test(hexValue) || $('.color[data-color=' + hexValue + ']').length > 0) {
      		$('input', self.$colorList).parent().parent().addClass("has-error");
		      return;
      	}
      	$('input', self.$colorList).parent().parent().removeClass("has-error");

	      self.addCustomColor(hexValue);

      	//save this custom color to db
      	$.get("/cms/site/" + $("#SiteId").val() + "/addcustomcolor/%23" + hexValue.slice(1, hexValue.length));

      	// Add the color to the CKEditor colors
				// This shit doesn't work, todo
      	//CKEDITOR.updateColorPalette(CKEDITOR.config);
	      //CKEDITOR.plugins.registered.colorbutton.init();

      	// Clear hex value input
	      $('input', self.$colorList).val("");
      });
    },

    addCustomColor: function(hexValue) {
    	var self = this;
    	var colorSpan = $('<span class="color custom-color selected" title="' + hexValue + '" style="background-color: ' + hexValue + ';" data-color="' + hexValue + '" role="button" tabindex="0"></span>');
    	colorSpan.insertAfter($('.hexValContainer', self.$colorList));
    	colorSpan.on('click.' + self.type, $.proxy(self.colorSpanClicked, self));
    	$('.clearAllColors', self.$colorList).show("fast");
    },

    /**
     * Changes the selected color.
     *
     * @param color the hexadecimal color to select, ex: '#fbd75b'
     */
    selectColor: function(color) {
      var self = this;

      var $colorSpan = self.$colorList.find('> span.color').filter(function() {
        return $(this).data('color').toLowerCase() === color.toLowerCase();
      });

      if ($colorSpan.length > 0) {
        self.selectColorSpan($colorSpan);
      } else {
        console.error("The given color '" + color + "' could not be found");
      }
    },

    showPicker: function() {
    	var pos = this.$icon.offset();
			// BUG: color picker not scrolling with modal
      //this.$picker.css({
        // Remove some pixels to align the picker icon with the icons inside the dropdown
        //left: pos.left - 6,
        //top: pos.top + this.$icon.outerHeight()
      //});

      this.$picker.show(this.options.pickerDelay);
    },

    hidePicker: function() {
      this.$picker.hide(this.options.pickerDelay);
    },

    /**
     * Selects the given span inside $colorList.
     *
     * The given span becomes the selected one.
     * It also changes the HTML select value, this will emit the 'change' event.
     */
    selectColorSpan: function($colorSpan) {
      var color = $colorSpan.data('color');
      var title = $colorSpan.prop('title');

      // Mark this span as the selected one
      $colorSpan.siblings().removeAttr('data-selected');
      $colorSpan.attr('data-selected', '');

      if (this.options.picker === true) {
        this.$icon.css('background-color', color);
        this.$icon.prop('title', title);
        this.hidePicker();
      }

      // Change HTML select value
      this.$textbox.val(color);
    },

    /**
     * The user clicked on a color inside $colorList.
     */
    colorSpanClicked: function(e) {
      // When a color is clicked, make it the new selected one (unless disabled)
      if ($(e.target).is('[data-disabled]') === false) {
        this.selectColorSpan($(e.target));
        this.$textbox.trigger('change');
      }
    },

    /**
     * Prevents the mousedown event from "eating" the click event.
     */
    mousedown: function (e) {
    	e.stopPropagation();
	    if (e.target.nodeName != 'INPUT') {
		    e.preventDefault();
	    }
    },

    destroy: function() {
      if (this.options.picker === true) {
        this.$icon.off('.' + this.type);
        this.$icon.remove();
        $(document).off('.' + this.type);
      }

      this.$colorList.off('.' + this.type);
      this.$colorList.remove();

      this.$textbox.removeData(this.type);
      this.$textbox.show();
    },

  
  };

  /**
   * Plugin definition.
   * How to use: $('#id').simplecolorpicker()
   */
  $.fn.simplecolorpicker = function(option) {
    var args = $.makeArray(arguments);
    args.shift();

    // For HTML element passed to the plugin
    return this.each(function() {
      var $this = $(this),
        data = $this.data('simplecolorpicker'),
        options = typeof option === 'object' && option;
      if (data === undefined) {
        $this.data('simplecolorpicker', (data = new SimpleColorPicker(this, options)));
      }
      if (typeof option === 'string') {
        data[option].apply(data, args);
      }
    });
  };

  /**
   * Default options.
   */
  var colorsArray = ["#000000", "#434343", "#666666", "#999999", "#b7b7b7", "#cccccc", "#d9d9d9", "#efefef", "#f3f3f3", "#ffffff",
					 "#9a0000", "#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff", "#4683eb", "#0000ff", "#9a00ff", "#ff00ff",
					 "#e7b8ae", "#f5cccb", "#fde5cc", "#fff3ca", "#d9ead2", "#d0e0e4", "#c9d9f9", "#cee2f4", "#d9d1e9", "#ead1dc",
					 "#df7e68", "#ec9998", "#F9CB9C", "#ffe694", "#b5d8a6", "#a1c4ca", "#a3c1f6", "#9ec5ea", "#b4a6d8", "#d6a5bd",
					 "#ce401a", "#e26564", "#F6B26B", "#ffda5c", "#91c57a", "#74a5b0", "#6a9ced", "#6da7de", "#8e7ac5", "#c379a0",
					 "#a81a00", "#cf0000", "#e8912a", "#f2c314", "#68a94a", "#42818f", "#3875db", "#3983c9", "#674ba9", "#a84b79",
					 "#871f02", "#9b0000", "#AA6021", "#c19100", "#357714", "#0e4f5c", "#0651cf", "#025196", "#315777", "#751847",
				     "#5c0e00", "#670000", "#793f00", "#806100", "#264f0e", "#09343d", "#194389", "#033664", "#200f4e", "#4d1030"];

  $.fn.simplecolorpicker.defaults = {
  	trigger: '',
  	selectedColor: colorsArray[0],
    // No theme by default
    theme: '',
    // Show the picker or make it inline
    picker: true,
    pickerDelay: 0,
    colors: colorsArray
  };

})(jQuery);
;
/*! TinySort 1.5.6
* Copyright (c) 2008-2013 Ron Valstar http://tinysort.sjeiti.com/
* License:
*     MIT: http://www.opensource.org/licenses/mit-license.php
*     GPL: http://www.gnu.org/licenses/gpl.html
*/
!function(a,b){"use strict";function c(a){return a&&a.toLowerCase?a.toLowerCase():a}function d(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]==b)return!e;return e}var e=!1,f=null,g=parseFloat,h=Math.min,i=/(-?\d+\.?\d*)$/g,j=/(\d+\.?\d*)$/g,k=[],l=[],m=function(a){return"string"==typeof a},n=function(a,b){for(var c,d=a.length,e=d;e--;)c=d-e-1,b(a[c],c)},o=Array.prototype.indexOf||function(a){var b=this.length,c=Number(arguments[1])||0;for(c=0>c?Math.ceil(c):Math.floor(c),0>c&&(c+=b);b>c;c++)if(c in this&&this[c]===a)return c;return-1};a.tinysort={id:"TinySort",version:"1.5.6",copyright:"Copyright (c) 2008-2013 Ron Valstar",uri:"http://tinysort.sjeiti.com/",licensed:{MIT:"http://www.opensource.org/licenses/mit-license.php",GPL:"http://www.gnu.org/licenses/gpl.html"},plugin:function(){var a=function(a,b){k.push(a),l.push(b)};return a.indexOf=o,a}(),defaults:{order:"asc",attr:f,data:f,useVal:e,place:"start",returns:e,cases:e,forceStrings:e,ignoreDashes:e,sortFunction:f}},a.fn.extend({tinysort:function(){var p,q,r,s,t=this,u=[],v=[],w=[],x=[],y=0,z=[],A=[],B=function(a){n(k,function(b){b.call(b,a)})},C=function(a,b){return"string"==typeof b&&(a.cases||(b=c(b)),b=b.replace(/^\s*(.*?)\s*$/i,"$1")),b},D=function(a,b){var c=0;for(0!==y&&(y=0);0===c&&s>y;){var d=x[y],f=d.oSettings,h=f.ignoreDashes?j:i;if(B(f),f.sortFunction)c=f.sortFunction(a,b);else if("rand"==f.order)c=Math.random()<.5?1:-1;else{var k=e,o=C(f,a.s[y]),p=C(f,b.s[y]);if(!f.forceStrings){var q=m(o)?o&&o.match(h):e,r=m(p)?p&&p.match(h):e;if(q&&r){var t=o.substr(0,o.length-q[0].length),u=p.substr(0,p.length-r[0].length);t==u&&(k=!e,o=g(q[0]),p=g(r[0]))}}c=d.iAsc*(p>o?-1:o>p?1:0)}n(l,function(a){c=a.call(a,k,o,p,c)}),0===c&&y++}return c};for(p=0,r=arguments.length;r>p;p++){var E=arguments[p];m(E)?z.push(E)-1>A.length&&(A.length=z.length-1):A.push(E)>z.length&&(z.length=A.length)}for(z.length>A.length&&(A.length=z.length),s=z.length,0===s&&(s=z.length=1,A.push({})),p=0,r=s;r>p;p++){var F=z[p],G=a.extend({},a.tinysort.defaults,A[p]),H=!(!F||""===F),I=H&&":"===F[0];x.push({sFind:F,oSettings:G,bFind:H,bAttr:!(G.attr===f||""===G.attr),bData:G.data!==f,bFilter:I,$Filter:I?t.filter(F):t,fnSort:G.sortFunction,iAsc:"asc"==G.order?1:-1})}return t.each(function(c,d){var e,f=a(d),g=f.parent().get(0),h=[];for(q=0;s>q;q++){var i=x[q],j=i.bFind?i.bFilter?i.$Filter.filter(d):f.find(i.sFind):f;h.push(i.bData?j.data(i.oSettings.data):i.bAttr?j.attr(i.oSettings.attr):i.oSettings.useVal?j.val():j.text()),e===b&&(e=j)}var k=o.call(w,g);0>k&&(k=w.push(g)-1,v[k]={s:[],n:[]}),e.length>0?v[k].s.push({s:h,e:f,n:c}):v[k].n.push({e:f,n:c})}),n(v,function(a){a.s.sort(D)}),n(v,function(a){var b=a.s,c=a.n,f=b.length,g=c.length,i=f+g,j=[],k=i,l=[0,0];switch(G.place){case"first":n(b,function(a){k=h(k,a.n)});break;case"org":n(b,function(a){j.push(a.n)});break;case"end":k=g;break;default:k=0}for(p=0;i>p;p++){var m=d(j,p)?!e:p>=k&&k+f>p,o=m?0:1,q=(m?b:c)[l[o]].e;q.parent().append(q),(m||!G.returns)&&u.push(q.get(0)),l[o]++}}),t.length=0,Array.prototype.push.apply(t,u),t}}),a.fn.TinySort=a.fn.Tinysort=a.fn.tsort=a.fn.tinysort}(jQuery);;
/*! waitForImages jQuery Plugin 2013-07-20 */
!function (a) { var b = "waitForImages"; a.waitForImages = { hasImageProperties: ["backgroundImage", "listStyleImage", "borderImage", "borderCornerImage", "cursor"] }, a.expr[":"].uncached = function (b) { if (!a(b).is('img[src!=""]')) return !1; var c = new Image; return c.src = b.src, !c.complete }, a.fn.waitForImages = function (c, d, e) { var f = 0, g = 0; if (a.isPlainObject(arguments[0]) && (e = arguments[0].waitForAll, d = arguments[0].each, c = arguments[0].finished), c = c || a.noop, d = d || a.noop, e = !!e, !a.isFunction(c) || !a.isFunction(d)) throw new TypeError("An invalid callback was supplied."); return this.each(function () { var h = a(this), i = [], j = a.waitForImages.hasImageProperties || [], k = /url\(\s*(['"]?)(.*?)\1\s*\)/g; e ? h.find("*").addBack().each(function () { var b = a(this); b.is("img:uncached") && i.push({ src: b.attr("src"), element: b[0] }), a.each(j, function (a, c) { var d, e = b.css(c); if (!e) return !0; for (; d = k.exec(e) ;) i.push({ src: d[2], element: b[0] }) }) }) : h.find("img:uncached").each(function () { i.push({ src: this.src, element: this }) }), f = i.length, g = 0, 0 === f && c.call(h[0]), a.each(i, function (e, i) { var j = new Image; a(j).on("load." + b + " error." + b, function (a) { return g++, d.call(i.element, g, f, "load" == a.type), g == f ? (c.call(h[0]), !1) : void 0 }), j.src = i.src }) }) } }(jQuery);;
/*
 *	jQuery dotdotdot 1.8.3
 *
 *	Copyright (c) Fred Heusschen
 *	www.frebsite.nl
 *
 *	Plugin website:
 *	dotdotdot.frebsite.nl
 *
 *	Licensed under the MIT license.
 *	http://en.wikipedia.org/wiki/MIT_License
 */
!function(t,e){function n(t,e,n){var r=t.children(),o=!1;t.empty();for(var i=0,d=r.length;d>i;i++){var l=r.eq(i);if(t.append(l),n&&t.append(n),a(t,e)){l.remove(),o=!0;break}n&&n.detach()}return o}function r(e,n,i,d,l){var s=!1,c="a, table, thead, tbody, tfoot, tr, col, colgroup, object, embed, param, ol, ul, dl, blockquote, select, optgroup, option, textarea, script, style",u="script, .dotdotdot-keep";return e.contents().detach().each(function(){var h=this,f=t(h);if("undefined"==typeof h)return!0;if(f.is(u))e.append(f);else{if(s)return!0;e.append(f),!l||f.is(d.after)||f.find(d.after).length||e[e.is(c)?"after":"append"](l),a(i,d)&&(s=3==h.nodeType?o(f,n,i,d,l):r(f,n,i,d,l)),s||l&&l.detach()}}),n.addClass("is-truncated"),s}function o(e,n,r,o,d){var c=e[0];if(!c)return!1;var h=s(c),f=-1!==h.indexOf(" ")?" ":"　",p="letter"==o.wrap?"":f,g=h.split(p),v=-1,w=-1,b=0,m=g.length-1;for(o.fallbackToLetter&&0==b&&0==m&&(p="",g=h.split(p),m=g.length-1);m>=b&&(0!=b||0!=m);){var y=Math.floor((b+m)/2);if(y==w)break;w=y,l(c,g.slice(0,w+1).join(p)+o.ellipsis),r.children().each(function(){t(this).toggle().toggle()}),a(r,o)?(m=w,o.fallbackToLetter&&0==b&&0==m&&(p="",g=g[0].split(p),v=-1,w=-1,b=0,m=g.length-1)):(v=w,b=w)}if(-1==v||1==g.length&&0==g[0].length){var x=e.parent();e.detach();var C=d&&d.closest(x).length?d.length:0;if(x.contents().length>C?c=u(x.contents().eq(-1-C),n):(c=u(x,n,!0),C||x.detach()),c&&(h=i(s(c),o),l(c,h),C&&d)){var T=d.parent();t(c).parent().append(d),t.trim(T.html())||T.remove()}}else h=i(g.slice(0,v+1).join(p),o),l(c,h);return!0}function a(t,e){return t.innerHeight()>e.maxHeight}function i(e,n){for(;t.inArray(e.slice(-1),n.lastCharacter.remove)>-1;)e=e.slice(0,-1);return t.inArray(e.slice(-1),n.lastCharacter.noEllipsis)<0&&(e+=n.ellipsis),e}function d(t){return{width:t.innerWidth(),height:t.innerHeight()}}function l(t,e){t.innerText?t.innerText=e:t.nodeValue?t.nodeValue=e:t.textContent&&(t.textContent=e)}function s(t){return t.innerText?t.innerText:t.nodeValue?t.nodeValue:t.textContent?t.textContent:""}function c(t){do t=t.previousSibling;while(t&&1!==t.nodeType&&3!==t.nodeType);return t}function u(e,n,r){var o,a=e&&e[0];if(a){if(!r){if(3===a.nodeType)return a;if(t.trim(e.text()))return u(e.contents().last(),n)}for(o=c(a);!o;){if(e=e.parent(),e.is(n)||!e.length)return!1;o=c(e[0])}if(o)return u(t(o),n)}return!1}function h(e,n){return e?"string"==typeof e?(e=t(e,n),e.length?e:!1):e.jquery?e:!1:!1}function f(t){for(var e=t.innerHeight(),n=["paddingTop","paddingBottom"],r=0,o=n.length;o>r;r++){var a=parseInt(t.css(n[r]),10);isNaN(a)&&(a=0),e-=a}return e}if(!t.fn.dotdotdot){t.fn.dotdotdot=function(e){if(0==this.length)return t.fn.dotdotdot.debug('No element found for "'+this.selector+'".'),this;if(this.length>1)return this.each(function(){t(this).dotdotdot(e)});var o=this,i=o.contents();o.data("dotdotdot")&&o.trigger("destroy.dot"),o.data("dotdotdot-style",o.attr("style")||""),o.css("word-wrap","break-word"),"nowrap"===o.css("white-space")&&o.css("white-space","normal"),o.bind_events=function(){return o.bind("update.dot",function(e,d){switch(o.removeClass("is-truncated"),e.preventDefault(),e.stopPropagation(),typeof l.height){case"number":l.maxHeight=l.height;break;case"function":l.maxHeight=l.height.call(o[0]);break;default:l.maxHeight=f(o)}l.maxHeight+=l.tolerance,"undefined"!=typeof d&&(("string"==typeof d||"nodeType"in d&&1===d.nodeType)&&(d=t("<div />").append(d).contents()),d instanceof t&&(i=d)),g=o.wrapInner('<div class="dotdotdot" />').children(),g.contents().detach().end().append(i.clone(!0)).find("br").replaceWith("  <br />  ").end().css({height:"auto",width:"auto",border:"none",padding:0,margin:0});var c=!1,u=!1;return s.afterElement&&(c=s.afterElement.clone(!0),c.show(),s.afterElement.detach()),a(g,l)&&(u="children"==l.wrap?n(g,l,c):r(g,o,g,l,c)),g.replaceWith(g.contents()),g=null,t.isFunction(l.callback)&&l.callback.call(o[0],u,i),s.isTruncated=u,u}).bind("isTruncated.dot",function(t,e){return t.preventDefault(),t.stopPropagation(),"function"==typeof e&&e.call(o[0],s.isTruncated),s.isTruncated}).bind("originalContent.dot",function(t,e){return t.preventDefault(),t.stopPropagation(),"function"==typeof e&&e.call(o[0],i),i}).bind("destroy.dot",function(t){t.preventDefault(),t.stopPropagation(),o.unwatch().unbind_events().contents().detach().end().append(i).attr("style",o.data("dotdotdot-style")||"").removeClass("is-truncated").data("dotdotdot",!1)}),o},o.unbind_events=function(){return o.unbind(".dot"),o},o.watch=function(){if(o.unwatch(),"window"==l.watch){var e=t(window),n=e.width(),r=e.height();e.bind("resize.dot"+s.dotId,function(){n==e.width()&&r==e.height()&&l.windowResizeFix||(n=e.width(),r=e.height(),u&&clearInterval(u),u=setTimeout(function(){o.trigger("update.dot")},100))})}else c=d(o),u=setInterval(function(){if(o.is(":visible")){var t=d(o);c.width==t.width&&c.height==t.height||(o.trigger("update.dot"),c=t)}},500);return o},o.unwatch=function(){return t(window).unbind("resize.dot"+s.dotId),u&&clearInterval(u),o};var l=t.extend(!0,{},t.fn.dotdotdot.defaults,e),s={},c={},u=null,g=null;return l.lastCharacter.remove instanceof Array||(l.lastCharacter.remove=t.fn.dotdotdot.defaultArrays.lastCharacter.remove),l.lastCharacter.noEllipsis instanceof Array||(l.lastCharacter.noEllipsis=t.fn.dotdotdot.defaultArrays.lastCharacter.noEllipsis),s.afterElement=h(l.after,o),s.isTruncated=!1,s.dotId=p++,o.data("dotdotdot",!0).bind_events().trigger("update.dot"),l.watch&&o.watch(),o},t.fn.dotdotdot.defaults={ellipsis:"... ",wrap:"word",fallbackToLetter:!0,lastCharacter:{},tolerance:0,callback:null,after:null,height:null,watch:!1,windowResizeFix:!0},t.fn.dotdotdot.defaultArrays={lastCharacter:{remove:[" ","　",",",";",".","!","?"],noEllipsis:[]}},t.fn.dotdotdot.debug=function(t){};var p=1,g=t.fn.html;t.fn.html=function(n){return n!=e&&!t.isFunction(n)&&this.data("dotdotdot")?this.trigger("update",[n]):g.apply(this,arguments)};var v=t.fn.text;t.fn.text=function(n){return n!=e&&!t.isFunction(n)&&this.data("dotdotdot")?(n=t("<div />").text(n).html(),this.trigger("update",[n])):v.apply(this,arguments)}}}(jQuery),jQuery(document).ready(function(t){t(".dot-ellipsis").each(function(){var e=t(this).hasClass("dot-resize-update"),n=t(this).hasClass("dot-timer-update"),r=0,o=t(this).attr("class").split(/\s+/);t.each(o,function(t,e){var n=e.match(/^dot-height-(\d+)$/);null!==n&&(r=Number(n[1]))});var a=new Object;n&&(a.watch=!0),e&&(a.watch="window"),r>0&&(a.height=r),t(this).dotdotdot(a)})}),jQuery(window).on("load",function(){jQuery(".dot-ellipsis.dot-load-update").trigger("update.dot")});;
/*! Html5 Storage jQuery Plugin - v1.0 - 2013-01-19
* https://github.com/artberri/jquery-html5storage
* Copyright (c) 2013 Alberto Varela; Licensed MIT */
(function(e,t){"use strict";var n=["localStorage","sessionStorage"],r=[];t.each(n,function(n,i){try{r[i]=i in e&&e[i]!==null}catch(s){r[i]=!1}t[i]={settings:{cookiePrefix:"html5fallback:"+i+":",cookieOptions:{path:"/",domain:document.domain,expires:"localStorage"===i?{expires:365}:undefined}},getItem:function(n){var s;return r[i]?s=e[i].getItem(n):s=t.cookie(this.settings.cookiePrefix+n),s},setItem:function(n,s){return r[i]?e[i].setItem(n,s):t.cookie(this.settings.cookiePrefix+n,s,this.settings.cookieOptions)},removeItem:function(n){if(r[i])return e[i].removeItem(n);var s=t.extend(this.settings.cookieOptions,{expires:-1});return t.cookie(this.settings.cookiePrefix+n,null,s)},clear:function(){if(r[i])return e[i].clear();var n=new RegExp("^"+this.settings.cookiePrefix,""),s=t.extend(this.settings.cookieOptions,{expires:-1});document.cookie&&document.cookie!==""&&t.each(document.cookie.split(";"),function(e,r){n.test(r=t.trim(r))&&t.cookie(r.substr(0,r.indexOf("=")),null,s)})}}})})(window,jQuery);;
'use strict';

/**
 * Copyright Marc J. Schmidt. See the LICENSE file at the top-level
 * directory of this distribution and at
 * https://github.com/marcj/css-element-queries/blob/master/LICENSE.
 */
(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define(factory);
    } else if (typeof exports === "object") {
        module.exports = factory();
    } else {
        root.ResizeSensor = factory();
    }
}(typeof window !== 'undefined' ? window : this, function () {

    // Make sure it does not throw in a SSR (Server Side Rendering) situation
    if (typeof window === "undefined") {
        return null;
    }
    // Only used for the dirty checking, so the event callback count is limited to max 1 call per fps per sensor.
    // In combination with the event based resize sensor this saves cpu time, because the sensor is too fast and
    // would generate too many unnecessary events.
    var requestAnimationFrame = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        function (fn) {
            return window.setTimeout(fn, 20);
        };

    /**
     * Iterate over each of the provided element(s).
     *
     * @param {HTMLElement|HTMLElement[]} elements
     * @param {Function}                  callback
     */
    function forEachElement(elements, callback){
        var elementsType = Object.prototype.toString.call(elements);
        var isCollectionTyped = ('[object Array]' === elementsType
            || ('[object NodeList]' === elementsType)
            || ('[object HTMLCollection]' === elementsType)
            || ('[object Object]' === elementsType)
            || ('undefined' !== typeof jQuery && elements instanceof jQuery) //jquery
            || ('undefined' !== typeof Elements && elements instanceof Elements) //mootools
        );
        var i = 0, j = elements.length;
        if (isCollectionTyped) {
            for (; i < j; i++) {
                callback(elements[i]);
            }
        } else {
            callback(elements);
        }
    }

    /**
    * Get element size
    * @param {HTMLElement} element
    * @returns {Object} {width, height}
    */
    function getElementSize(element) {
        if (!element.getBoundingClientRect) {
            return {
                width: element.offsetWidth,
                height: element.offsetHeight
            }
        }

        var rect = element.getBoundingClientRect();
        return {
            width: Math.round(rect.width),
            height: Math.round(rect.height)
        }
    }

    /**
     * Class for dimension change detection.
     *
     * @param {Element|Element[]|Elements|jQuery} element
     * @param {Function} callback
     *
     * @constructor
     */
    var ResizeSensor = function(element, callback) {
        /**
         *
         * @constructor
         */
        function EventQueue() {
            var q = [];
            this.add = function(ev) {
                q.push(ev);
            };

            var i, j;
            this.call = function() {
                for (i = 0, j = q.length; i < j; i++) {
                    q[i].call();
                }
            };

            this.remove = function(ev) {
                var newQueue = [];
                for(i = 0, j = q.length; i < j; i++) {
                    if(q[i] !== ev) newQueue.push(q[i]);
                }
                q = newQueue;
            };

            this.length = function() {
                return q.length;
            }
        }

        /**
         *
         * @param {HTMLElement} element
         * @param {Function}    resized
         */
        function attachResizeEvent(element, resized) {
            if (!element) return;
            if (element.resizedAttached) {
                element.resizedAttached.add(resized);
                return;
            }

            element.resizedAttached = new EventQueue();
            element.resizedAttached.add(resized);

            element.resizeSensor = document.createElement('div');
            element.resizeSensor.dir = 'ltr';
            element.resizeSensor.className = 'resize-sensor';
            var style = 'position: absolute; left: -10px; top: -10px; right: 0; bottom: 0; overflow: hidden; z-index: -1; visibility: hidden;';
            var styleChild = 'position: absolute; left: 0; top: 0; transition: 0s;';

            element.resizeSensor.style.cssText = style;
            element.resizeSensor.innerHTML =
                '<div class="resize-sensor-expand" style="' + style + '">' +
                    '<div style="' + styleChild + '"></div>' +
                '</div>' +
                '<div class="resize-sensor-shrink" style="' + style + '">' +
                    '<div style="' + styleChild + ' width: 200%; height: 200%"></div>' +
                '</div>';
            element.appendChild(element.resizeSensor);

            var position = window.getComputedStyle(element).getPropertyPriority('position');
            if ('absolute' !== position && 'relative' !== position && 'fixed' !== position) {
                element.style.position = 'relative';
            }

            var expand = element.resizeSensor.childNodes[0];
            var expandChild = expand.childNodes[0];
            var shrink = element.resizeSensor.childNodes[1];
            var dirty, rafId, newWidth, newHeight;
            var size = getElementSize(element);
            var lastWidth = size.width;
            var lastHeight = size.height;

            var reset = function() {
                //set display to block, necessary otherwise hidden elements won't ever work
                var invisible = element.offsetWidth === 0 && element.offsetHeight === 0;

                if (invisible) {
                    var saveDisplay = element.style.display;
                    element.style.display = 'block';
                }

                expandChild.style.width = '100000px';
                expandChild.style.height = '100000px';

                expand.scrollLeft = 100000;
                expand.scrollTop = 100000;

                shrink.scrollLeft = 100000;
                shrink.scrollTop = 100000;

                if (invisible) {
                    element.style.display = saveDisplay;
                }
            };
            element.resizeSensor.resetSensor = reset;

            var onResized = function() {
                rafId = 0;

                if (!dirty) return;

                lastWidth = newWidth;
                lastHeight = newHeight;

                if (element.resizedAttached) {
                    element.resizedAttached.call();
                }
            };

            var onScroll = function() {
                var size = getElementSize(element);
                var newWidth = size.width;
                var newHeight = size.height;
                dirty = newWidth != lastWidth || newHeight != lastHeight;

                if (dirty && !rafId) {
                    rafId = requestAnimationFrame(onResized);
                }

                reset();
            };

            var addEvent = function(el, name, cb) {
                if (el.attachEvent) {
                    el.attachEvent('on' + name, cb);
                } else {
                    el.addEventListener(name, cb);
                }
            };

            addEvent(expand, 'scroll', onScroll);
            addEvent(shrink, 'scroll', onScroll);
            
			// Fix for custom Elements
			requestAnimationFrame(reset);
        }

        forEachElement(element, function(elem){
            attachResizeEvent(elem, callback);
        });

        this.detach = function(ev) {
            ResizeSensor.detach(element, ev);
        };

        this.reset = function() {
            element.resizeSensor.resetSensor();
        };
    };

    ResizeSensor.reset = function(element, ev) {
        forEachElement(element, function(elem){
            elem.resizeSensor.resetSensor();
        });
    };

    ResizeSensor.detach = function(element, ev) {
        forEachElement(element, function(elem){
            if (!elem) return;
            if(elem.resizedAttached && typeof ev === "function"){
                elem.resizedAttached.remove(ev);
                if(elem.resizedAttached.length()) return;
            }
            if (elem.resizeSensor) {
                if (elem.contains(elem.resizeSensor)) {
                    elem.removeChild(elem.resizeSensor);
                }
                delete elem.resizeSensor;
                delete elem.resizedAttached;
            }
        });
    };

    return ResizeSensor;

}));
;
'use strict';

/**
 * Copyright Marc J. Schmidt. See the LICENSE file at the top-level
 * directory of this distribution and at
 * https://github.com/marcj/css-element-queries/blob/master/LICENSE.
 */
(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define(['./ResizeSensor.js'], factory);
    } else if (typeof exports === "object") {
        module.exports = factory(require('./ResizeSensor.js'));
    } else {
        root.ElementQueries = factory(root.ResizeSensor);
        root.ElementQueries.listen();
    }
}(typeof window !== 'undefined' ? window : this, function (ResizeSensor) {

    /**
     *
     * @type {Function}
     * @constructor
     */
    var ElementQueries = function () {
        //<style> element with our dynamically created styles
        var cssStyleElement;

        //all rules found for element queries
        var allQueries = {};

        //association map to identify which selector belongs to a element from the animationstart event.
        var idToSelectorMapping = [];

        /**
         *
         * @param element
         * @returns {Number}
         */
        function getEmSize(element) {
            if (!element) {
                element = document.documentElement;
            }
            var fontSize = window.getComputedStyle(element, null).fontSize;
            return parseFloat(fontSize) || 16;
        }

        /**
         * Get element size
         * @param {HTMLElement} element
         * @returns {Object} {width, height}
         */
        function getElementSize(element) {
            if (!element.getBoundingClientRect) {
                return {
                    width: element.offsetWidth,
                    height: element.offsetHeight
                }
            }

            var rect = element.getBoundingClientRect();
            return {
                width: Math.round(rect.width),
                height: Math.round(rect.height)
            }
        }

        /**
         *
         * @copyright https://github.com/Mr0grog/element-query/blob/master/LICENSE
         *
         * @param {HTMLElement} element
         * @param {*} value
         * @returns {*}
         */
        function convertToPx(element, value) {
            var numbers = value.split(/\d/);
            var units = numbers[numbers.length - 1];
            value = parseFloat(value);
            switch (units) {
                case "px":
                    return value;
                case "em":
                    return value * getEmSize(element);
                case "rem":
                    return value * getEmSize();
                // Viewport units!
                // According to http://quirksmode.org/mobile/tableViewport.html
                // documentElement.clientWidth/Height gets us the most reliable info
                case "vw":
                    return value * document.documentElement.clientWidth / 100;
                case "vh":
                    return value * document.documentElement.clientHeight / 100;
                case "vmin":
                case "vmax":
                    var vw = document.documentElement.clientWidth / 100;
                    var vh = document.documentElement.clientHeight / 100;
                    var chooser = Math[units === "vmin" ? "min" : "max"];
                    return value * chooser(vw, vh);
                default:
                    return value;
                // for now, not supporting physical units (since they are just a set number of px)
                // or ex/ch (getting accurate measurements is hard)
            }
        }

        /**
         *
         * @param {HTMLElement} element
         * @param {String} id
         * @constructor
         */
        function SetupInformation(element, id) {
            this.element = element;
            var key, option, elementSize, value, actualValue, attrValues, attrValue, attrName;

            var attributes = ['min-width', 'min-height', 'max-width', 'max-height'];

            /**
             * Extracts the computed width/height and sets to min/max- attribute.
             */
            this.call = function () {
                // extract current dimensions
                elementSize = getElementSize(this.element);

                attrValues = {};

                for (key in allQueries[id]) {
                    if (!allQueries[id].hasOwnProperty(key)) {
                        continue;
                    }
                    option = allQueries[id][key];

                    value = convertToPx(this.element, option.value);

                    actualValue = option.property === 'width' ? elementSize.width : elementSize.height;
                    attrName = option.mode + '-' + option.property;
                    attrValue = '';

                    if (option.mode === 'min' && actualValue >= value) {
                        attrValue += option.value;
                    }

                    if (option.mode === 'max' && actualValue <= value) {
                        attrValue += option.value;
                    }

                    if (!attrValues[attrName]) attrValues[attrName] = '';
                    if (attrValue && -1 === (' ' + attrValues[attrName] + ' ').indexOf(' ' + attrValue + ' ')) {
                        attrValues[attrName] += ' ' + attrValue;
                    }
                }

                for (var k in attributes) {
                    if (!attributes.hasOwnProperty(k)) continue;

                    if (attrValues[attributes[k]]) {
                        this.element.setAttribute(attributes[k], attrValues[attributes[k]].substr(1));
                    } else {
                        this.element.removeAttribute(attributes[k]);
                    }
                }
            };
        }

        /**
         * @param {HTMLElement} element
         * @param {Object}      id
         */
        function setupElement(element, id) {
            if (!element.elementQueriesSetupInformation) {
                element.elementQueriesSetupInformation = new SetupInformation(element, id);
            }
            if (!element.elementQueriesSensor) {
                element.elementQueriesSensor = new ResizeSensor(element, function () {
                    element.elementQueriesSetupInformation.call();
                });
            }

            element.elementQueriesSetupInformation.call();
        }

        /**
         * Stores rules to the selector that should be applied once resized.
         *
         * @param {String} selector
         * @param {String} mode min|max
         * @param {String} property width|height
         * @param {String} value
         */
        function queueQuery(selector, mode, property, value) {
            if (typeof(allQueries[selector]) === 'undefined') {
                allQueries[selector] = [];
                // add animation to trigger animationstart event, so we know exactly when a element appears in the DOM

                var id = idToSelectorMapping.length;
                cssStyleElement.innerHTML += '\n' + selector + ' {animation: 0.1s element-queries;}';
                cssStyleElement.innerHTML += '\n' + selector + ' > .resize-sensor {min-width: '+id+'px;}';
                idToSelectorMapping.push(selector);
            }

            allQueries[selector].push({
                mode: mode,
                property: property,
                value: value
            });
        }

        function getQuery(container) {
            var query;
            if (document.querySelectorAll) query = (container) ? container.querySelectorAll.bind(container) : document.querySelectorAll.bind(document);
            if (!query && 'undefined' !== typeof $$) query = $$;
            if (!query && 'undefined' !== typeof jQuery) query = jQuery;

            if (!query) {
                throw 'No document.querySelectorAll, jQuery or Mootools\'s $$ found.';
            }

            return query;
        }

        /**
         * If animationStart didn't catch a new element in the DOM, we can manually search for it
         */
        function findElementQueriesElements(container) {
            var query = getQuery(container);

            for (var selector in allQueries) if (allQueries.hasOwnProperty(mode)) {
                // find all elements based on the extract query selector from the element query rule
                var elements = query(selector, container);

                for (var i = 0, j = elements.length; i < j; i++) {
                    setupElement(elements[i], selector);
                }
            }
        }

        /**
         *
         * @param {HTMLElement} element
         */
        function attachResponsiveImage(element) {
            var children = [];
            var rules = [];
            var sources = [];
            var defaultImageId = 0;
            var lastActiveImage = -1;
            var loadedImages = [];

            for (var i in element.children) {
                if (!element.children.hasOwnProperty(i)) continue;

                if (element.children[i].tagName && element.children[i].tagName.toLowerCase() === 'img') {
                    children.push(element.children[i]);

                    var minWidth = element.children[i].getAttribute('min-width') || element.children[i].getAttribute('data-min-width');
                    //var minHeight = element.children[i].getAttribute('min-height') || element.children[i].getAttribute('data-min-height');
                    var src = element.children[i].getAttribute('data-src') || element.children[i].getAttribute('url');

                    sources.push(src);

                    var rule = {
                        minWidth: minWidth
                    };

                    rules.push(rule);

                    if (!minWidth) {
                        defaultImageId = children.length - 1;
                        element.children[i].style.display = 'block';
                    } else {
                        element.children[i].style.display = 'none';
                    }
                }
            }

            lastActiveImage = defaultImageId;

            function check() {
                var imageToDisplay = false, i;

                for (i in children) {
                    if (!children.hasOwnProperty(i)) continue;

                    if (rules[i].minWidth) {
                        if (element.offsetWidth > rules[i].minWidth) {
                            imageToDisplay = i;
                        }
                    }
                }

                if (!imageToDisplay) {
                    //no rule matched, show default
                    imageToDisplay = defaultImageId;
                }

                if (lastActiveImage !== imageToDisplay) {
                    //image change

                    if (!loadedImages[imageToDisplay]) {
                        //image has not been loaded yet, we need to load the image first in memory to prevent flash of
                        //no content

                        var image = new Image();
                        image.onload = function () {
                            children[imageToDisplay].src = sources[imageToDisplay];

                            children[lastActiveImage].style.display = 'none';
                            children[imageToDisplay].style.display = 'block';

                            loadedImages[imageToDisplay] = true;

                            lastActiveImage = imageToDisplay;
                        };

                        image.src = sources[imageToDisplay];
                    } else {
                        children[lastActiveImage].style.display = 'none';
                        children[imageToDisplay].style.display = 'block';
                        lastActiveImage = imageToDisplay;
                    }
                } else {
                    //make sure for initial check call the .src is set correctly
                    children[imageToDisplay].src = sources[imageToDisplay];
                }
            }

            element.resizeSensor = new ResizeSensor(element, check);
            check();
        }

        function findResponsiveImages() {
            var query = getQuery();

            var elements = query('[data-responsive-image],[responsive-image]');
            for (var i = 0, j = elements.length; i < j; i++) {
                attachResponsiveImage(elements[i]);
            }
        }

        var regex = /,?[\s\t]*([^,\n]*?)((?:\[[\s\t]*?(?:min|max)-(?:width|height)[\s\t]*?[~$\^]?=[\s\t]*?"[^"]*?"[\s\t]*?])+)([^,\n\s\{]*)/mgi;
        var attrRegex = /\[[\s\t]*?(min|max)-(width|height)[\s\t]*?[~$\^]?=[\s\t]*?"([^"]*?)"[\s\t]*?]/mgi;

        /**
         * @param {String} css
         */
        function extractQuery(css) {
            var match, smatch, attrs, attrMatch;

            css = css.replace(/'/g, '"');
            while (null !== (match = regex.exec(css))) {
                smatch = match[1] + match[3];
                attrs = match[2];

                while (null !== (attrMatch = attrRegex.exec(attrs))) {
                    queueQuery(smatch, attrMatch[1], attrMatch[2], attrMatch[3]);
                }
            }
        }

        /**
         * @param {CssRule[]|String} rules
         */
        function readRules(rules) {
            var selector = '';

            if (!rules) {
                return;
            }

            if ('string' === typeof rules) {
                rules = rules.toLowerCase();
                if (-1 !== rules.indexOf('min-width') || -1 !== rules.indexOf('max-width')) {
                    extractQuery(rules);
                }
            } else {
                for (var i = 0, j = rules.length; i < j; i++) {
                    if (1 === rules[i].type) {
                        selector = rules[i].selectorText || rules[i].cssText;
                        if (-1 !== selector.indexOf('min-height') || -1 !== selector.indexOf('max-height')) {
                            extractQuery(selector);
                        } else if (-1 !== selector.indexOf('min-width') || -1 !== selector.indexOf('max-width')) {
                            extractQuery(selector);
                        }
                    } else if (4 === rules[i].type) {
                        readRules(rules[i].cssRules || rules[i].rules);
                    } else if (3 === rules[i].type) {
                        readRules(rules[i].styleSheet.cssRules);
                    }
                }
            }
        }

        var defaultCssInjected = false;

        /**
         * Searches all css rules and setups the event listener to all elements with element query rules..
         */
        this.init = function () {
            var animationStart = 'animationstart';
            if (typeof document.documentElement.style['webkitAnimationName'] !== 'undefined') {
                animationStart = 'webkitAnimationStart';
            } else if (typeof document.documentElement.style['MozAnimationName'] !== 'undefined') {
                animationStart = 'mozanimationstart';
            } else if (typeof document.documentElement.style['OAnimationName'] !== 'undefined') {
                animationStart = 'oanimationstart';
            }

            document.body.addEventListener(animationStart, function (e) {
                var element = e.target;
                var styles = window.getComputedStyle(element, null);

                if (-1 !== styles.getPropertyValue('animation-name').indexOf('element-queries')) {
                    element.elementQueriesSensor = new ResizeSensor(element, function () {
                        if (element.elementQueriesSetupInformation) {
                            element.elementQueriesSetupInformation.call();
                        }
                    });

                    var sensorStyles = window.getComputedStyle(element.resizeSensor, null);
                    var id = sensorStyles.getPropertyValue('min-width');
                    id = parseInt(id.replace('px', ''));
                    setupElement(e.target, idToSelectorMapping[id]);
                }
            });

            if (!defaultCssInjected) {
                cssStyleElement = document.createElement('style');
                cssStyleElement.type = 'text/css';
                cssStyleElement.innerHTML = '[responsive-image] > img, [data-responsive-image] {overflow: hidden; padding: 0; } [responsive-image] > img, [data-responsive-image] > img {width: 100%;}';

                //safari wants at least one rule in keyframes to start working
                cssStyleElement.innerHTML += '\n@keyframes element-queries { 0% { visibility: inherit; } }';
                document.getElementsByTagName('head')[0].appendChild(cssStyleElement);
                defaultCssInjected = true;
            }

            for (var i = 0, j = document.styleSheets.length; i < j; i++) {
                try {
                    if (document.styleSheets[i].href && 0 === document.styleSheets[i].href.indexOf('file://')) {
                        console.log("CssElementQueries: unable to parse local css files, " + document.styleSheets[i].href);
                    }

                    readRules(document.styleSheets[i].cssRules || document.styleSheets[i].rules || document.styleSheets[i].cssText);
                } catch (e) {
                }
            }

            // findElementQueriesElements();
            findResponsiveImages();
        };

        /**
         * Go through all collected rules (readRules()) and attach the resize-listener.
         * Not necessary to call it manually, since we detect automatically when new elements
         * are available in the DOM. However, sometimes handy for dirty DOM modifications.
         *
         * @param {HTMLElement} container only elements of the container are considered (document.body if not set)
         */
        this.findElementQueriesElements = function (container) {
            findElementQueriesElements(container);
        };

        this.update = function () {
            this.init();
        };
    };

    ElementQueries.update = function () {
        ElementQueries.instance.update();
    };

    /**
     * Removes all sensor and elementquery information from the element.
     *
     * @param {HTMLElement} element
     */
    ElementQueries.detach = function (element) {
        if (element.elementQueriesSetupInformation) {
            //element queries
            element.elementQueriesSensor.detach();
            delete element.elementQueriesSetupInformation;
            delete element.elementQueriesSensor;

        } else if (element.resizeSensor) {
            //responsive image

            element.resizeSensor.detach();
            delete element.resizeSensor;
        }
    };

    ElementQueries.init = function () {
        if (!ElementQueries.instance) {
            ElementQueries.instance = new ElementQueries();
        }

        ElementQueries.instance.init();
    };

    var domLoaded = function (callback) {
        /* Mozilla, Chrome, Opera */
        if (document.addEventListener) {
            document.addEventListener('DOMContentLoaded', callback, false);
        }
        /* Safari, iCab, Konqueror */
        else if (/KHTML|WebKit|iCab/i.test(navigator.userAgent)) {
            var DOMLoadTimer = setInterval(function () {
                if (/loaded|complete/i.test(document.readyState)) {
                    callback();
                    clearInterval(DOMLoadTimer);
                }
            }, 10);
        }
        /* Other web browsers */
        else window.onload = callback;
    };

    ElementQueries.findElementQueriesElements = function (container) {
        ElementQueries.instance.findElementQueriesElements(container);
    };

    ElementQueries.listen = function () {
        domLoaded(ElementQueries.init);
    };

    return ElementQueries;

}));
;
/*!
 * typeahead.js 0.11.1
 * https://github.com/twitter/typeahead.js
 * Copyright 2013-2015 Twitter, Inc. and other contributors; Licensed MIT
 */

!function(a,b){"function"==typeof define&&define.amd?define("bloodhound",["jquery"],function(c){return a.Bloodhound=b(c)}):"object"==typeof exports?module.exports=b(require("jquery")):a.Bloodhound=b(jQuery)}(this,function(a){var b=function(){"use strict";return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},isElement:function(a){return!(!a||1!==a.nodeType)},isJQuery:function(b){return b instanceof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,identity:function(a){return a},clone:function(b){return a.extend(!0,{},b)},getIdGenerator:function(){var a=0;return function(){return a++}},templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},stringify:function(a){return b.isString(a)?a:JSON.stringify(a)},noop:function(){}}}(),c="0.11.1",d=function(){"use strict";function a(a){return a=b.toStr(a),a?a.split(/\s+/):[]}function c(a){return a=b.toStr(a),a?a.split(/\W+/):[]}function d(a){return function(c){return c=b.isArray(c)?c:[].slice.call(arguments,0),function(d){var e=[];return b.each(c,function(c){e=e.concat(a(b.toStr(d[c])))}),e}}}return{nonword:c,whitespace:a,obj:{nonword:d(c),whitespace:d(a)}}}(),e=function(){"use strict";function c(c){this.maxSize=b.isNumber(c)?c:100,this.reset(),this.maxSize<=0&&(this.set=this.get=a.noop)}function d(){this.head=this.tail=null}function e(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(c.prototype,{set:function(a,b){var c,d=this.list.tail;this.size>=this.maxSize&&(this.list.remove(d),delete this.hash[d.key],this.size--),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new e(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];return b?(this.list.moveToFront(b),b.val):void 0},reset:function(){this.size=0,this.hash={},this.list=new d}}),b.mixin(d.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),c}(),f=function(){"use strict";function c(a,c){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+b.escapeRegExChars(this.prefix)),this.ls=c||h,!this.ls&&this._noop()}function d(){return(new Date).getTime()}function e(a){return JSON.stringify(b.isUndefined(a)?null:a)}function f(b){return a.parseJSON(b)}function g(a){var b,c,d=[],e=h.length;for(b=0;e>b;b++)(c=h.key(b)).match(a)&&d.push(c.replace(a,""));return d}var h;try{h=window.localStorage,h.setItem("~~~","!"),h.removeItem("~~~")}catch(i){h=null}return b.mixin(c.prototype,{_prefix:function(a){return this.prefix+a},_ttlKey:function(a){return this._prefix(a)+this.ttlKey},_noop:function(){this.get=this.set=this.remove=this.clear=this.isExpired=b.noop},_safeSet:function(a,b){try{this.ls.setItem(a,b)}catch(c){"QuotaExceededError"===c.name&&(this.clear(),this._noop())}},get:function(a){return this.isExpired(a)&&this.remove(a),f(this.ls.getItem(this._prefix(a)))},set:function(a,c,f){return b.isNumber(f)?this._safeSet(this._ttlKey(a),e(d()+f)):this.ls.removeItem(this._ttlKey(a)),this._safeSet(this._prefix(a),e(c))},remove:function(a){return this.ls.removeItem(this._ttlKey(a)),this.ls.removeItem(this._prefix(a)),this},clear:function(){var a,b=g(this.keyMatcher);for(a=b.length;a--;)this.remove(b[a]);return this},isExpired:function(a){var c=f(this.ls.getItem(this._ttlKey(a)));return b.isNumber(c)&&d()>c?!0:!1}}),c}(),g=function(){"use strict";function c(a){a=a||{},this.cancelled=!1,this.lastReq=null,this._send=a.transport,this._get=a.limiter?a.limiter(this._get):this._get,this._cache=a.cache===!1?new e(0):h}var d=0,f={},g=6,h=new e(10);return c.setMaxPendingRequests=function(a){g=a},c.resetCache=function(){h.reset()},b.mixin(c.prototype,{_fingerprint:function(b){return b=b||{},b.url+b.type+a.param(b.data||{})},_get:function(a,b){function c(a){b(null,a),k._cache.set(i,a)}function e(){b(!0)}function h(){d--,delete f[i],k.onDeckRequestArgs&&(k._get.apply(k,k.onDeckRequestArgs),k.onDeckRequestArgs=null)}var i,j,k=this;i=this._fingerprint(a),this.cancelled||i!==this.lastReq||((j=f[i])?j.done(c).fail(e):g>d?(d++,f[i]=this._send(a).done(c).fail(e).always(h)):this.onDeckRequestArgs=[].slice.call(arguments,0))},get:function(c,d){var e,f;d=d||a.noop,c=b.isString(c)?{url:c}:c||{},f=this._fingerprint(c),this.cancelled=!1,this.lastReq=f,(e=this._cache.get(f))?d(null,e):this._get(c,d)},cancel:function(){this.cancelled=!0}}),c}(),h=window.SearchIndex=function(){"use strict";function c(c){c=c||{},c.datumTokenizer&&c.queryTokenizer||a.error("datumTokenizer and queryTokenizer are both required"),this.identify=c.identify||b.stringify,this.datumTokenizer=c.datumTokenizer,this.queryTokenizer=c.queryTokenizer,this.reset()}function d(a){return a=b.filter(a,function(a){return!!a}),a=b.map(a,function(a){return a.toLowerCase()})}function e(){var a={};return a[i]=[],a[h]={},a}function f(a){for(var b={},c=[],d=0,e=a.length;e>d;d++)b[a[d]]||(b[a[d]]=!0,c.push(a[d]));return c}function g(a,b){var c=0,d=0,e=[];a=a.sort(),b=b.sort();for(var f=a.length,g=b.length;f>c&&g>d;)a[c]<b[d]?c++:a[c]>b[d]?d++:(e.push(a[c]),c++,d++);return e}var h="c",i="i";return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;c.datums[f=c.identify(a)]=a,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b[h][g]||(b[h][g]=e()),b[i].push(f)})})},get:function(a){var c=this;return b.map(a,function(a){return c.datums[a]})},search:function(a){var c,e,j=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length)return!1;for(b=j.trie,c=a.split("");b&&(d=c.shift());)b=b[h][d];return b&&0===c.length?(f=b[i].slice(0),void(e=e?g(e,f):f)):(e=[],!1)}),e?b.map(f(e),function(a){return j.datums[a]}):[]},all:function(){var a=[];for(var b in this.datums)a.push(this.datums[b]);return a},reset:function(){this.datums={},this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){"use strict";function a(a){this.url=a.url,this.ttl=a.ttl,this.cache=a.cache,this.prepare=a.prepare,this.transform=a.transform,this.transport=a.transport,this.thumbprint=a.thumbprint,this.storage=new f(a.cacheKey)}var c;return c={data:"data",protocol:"protocol",thumbprint:"thumbprint"},b.mixin(a.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},store:function(a){this.cache&&(this.storage.set(c.data,a,this.ttl),this.storage.set(c.protocol,location.protocol,this.ttl),this.storage.set(c.thumbprint,this.thumbprint,this.ttl))},fromCache:function(){var a,b={};return this.cache?(b.data=this.storage.get(c.data),b.protocol=this.storage.get(c.protocol),b.thumbprint=this.storage.get(c.thumbprint),a=b.thumbprint!==this.thumbprint||b.protocol!==location.protocol,b.data&&!a?b.data:null):null},fromNetwork:function(a){function b(){a(!0)}function c(b){a(null,e.transform(b))}var d,e=this;a&&(d=this.prepare(this._settings()),this.transport(d).fail(b).done(c))},clear:function(){return this.storage.clear(),this}}),a}(),j=function(){"use strict";function a(a){this.url=a.url,this.prepare=a.prepare,this.transform=a.transform,this.transport=new g({cache:a.cache,limiter:a.limiter,transport:a.transport})}return b.mixin(a.prototype,{_settings:function(){return{url:this.url,type:"GET",dataType:"json"}},get:function(a,b){function c(a,c){b(a?[]:e.transform(c))}var d,e=this;if(b)return a=a||"",d=this.prepare(a,this._settings()),this.transport.get(d,c)},cancelLastRequest:function(){this.transport.cancel()}}),a}(),k=function(){"use strict";function d(d){var e;return d?(e={url:null,ttl:864e5,cache:!0,cacheKey:null,thumbprint:"",prepare:b.identity,transform:b.identity,transport:null},d=b.isString(d)?{url:d}:d,d=b.mixin(e,d),!d.url&&a.error("prefetch requires url to be set"),d.transform=d.filter||d.transform,d.cacheKey=d.cacheKey||d.url,d.thumbprint=c+d.thumbprint,d.transport=d.transport?h(d.transport):a.ajax,d):null}function e(c){var d;if(c)return d={url:null,cache:!0,prepare:null,replace:null,wildcard:null,limiter:null,rateLimitBy:"debounce",rateLimitWait:300,transform:b.identity,transport:null},c=b.isString(c)?{url:c}:c,c=b.mixin(d,c),!c.url&&a.error("remote requires url to be set"),c.transform=c.filter||c.transform,c.prepare=f(c),c.limiter=g(c),c.transport=c.transport?h(c.transport):a.ajax,delete c.replace,delete c.wildcard,delete c.rateLimitBy,delete c.rateLimitWait,c}function f(a){function b(a,b){return b.url=f(b.url,a),b}function c(a,b){return b.url=b.url.replace(g,encodeURIComponent(a)),b}function d(a,b){return b}var e,f,g;return e=a.prepare,f=a.replace,g=a.wildcard,e?e:e=f?b:a.wildcard?c:d}function g(a){function c(a){return function(c){return b.debounce(c,a)}}function d(a){return function(c){return b.throttle(c,a)}}var e,f,g;return e=a.limiter,f=a.rateLimitBy,g=a.rateLimitWait,e||(e=/^throttle$/i.test(f)?d(g):c(g)),e}function h(c){return function(d){function e(a){b.defer(function(){g.resolve(a)})}function f(a){b.defer(function(){g.reject(a)})}var g=a.Deferred();return c(d,e,f),g}}return function(c){var f,g;return f={initialize:!0,identify:b.stringify,datumTokenizer:null,queryTokenizer:null,sufficient:5,sorter:null,local:[],prefetch:null,remote:null},c=b.mixin(f,c||{}),!c.datumTokenizer&&a.error("datumTokenizer is required"),!c.queryTokenizer&&a.error("queryTokenizer is required"),g=c.sorter,c.sorter=g?function(a){return a.sort(g)}:b.identity,c.local=b.isFunction(c.local)?c.local():c.local,c.prefetch=d(c.prefetch),c.remote=e(c.remote),c}}(),l=function(){"use strict";function c(a){a=k(a),this.sorter=a.sorter,this.identify=a.identify,this.sufficient=a.sufficient,this.local=a.local,this.remote=a.remote?new j(a.remote):null,this.prefetch=a.prefetch?new i(a.prefetch):null,this.index=new h({identify:this.identify,datumTokenizer:a.datumTokenizer,queryTokenizer:a.queryTokenizer}),a.initialize!==!1&&this.initialize()}var e;return e=window&&window.Bloodhound,c.noConflict=function(){return window&&(window.Bloodhound=e),c},c.tokenizers=d,b.mixin(c.prototype,{__ttAdapter:function(){function a(a,b,d){return c.search(a,b,d)}function b(a,b){return c.search(a,b)}var c=this;return this.remote?a:b},_loadPrefetch:function(){function b(a,b){return a?c.reject():(e.add(b),e.prefetch.store(e.index.serialize()),void c.resolve())}var c,d,e=this;return c=a.Deferred(),this.prefetch?(d=this.prefetch.fromCache())?(this.index.bootstrap(d),c.resolve()):this.prefetch.fromNetwork(b):c.resolve(),c.promise()},_initialize:function(){function a(){b.add(b.local)}var b=this;return this.clear(),(this.initPromise=this._loadPrefetch()).done(a),this.initPromise},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){return this.index.add(a),this},get:function(a){return a=b.isArray(a)?a:[].slice.call(arguments),this.index.get(a)},search:function(a,c,d){function e(a){var c=[];b.each(a,function(a){!b.some(f,function(b){return g.identify(a)===g.identify(b)})&&c.push(a)}),d&&d(c)}var f,g=this;return f=this.sorter(this.index.search(a)),c(this.remote?f.slice():f),this.remote&&f.length<this.sufficient?this.remote.get(a,e):this.remote&&this.remote.cancelLastRequest(),this},all:function(){return this.index.all()},clear:function(){return this.index.reset(),this},clearPrefetchCache:function(){return this.prefetch&&this.prefetch.clear(),this},clearRemoteCache:function(){return g.resetCache(),this},ttAdapter:function(){return this.__ttAdapter()}}),c}();return l});;
/**
 * bootbox.js v4.2.0
 *
 * http://bootboxjs.com/license.txt
 */
!function(a,b){"use strict";"function"==typeof define&&define.amd?define(["jquery"],b):"object"==typeof exports?module.exports=b(require("jquery")):a.bootbox=b(a.jQuery)}(this,function a(b,c){"use strict";function d(a){var b=q[o.locale];return b?b[a]:q.en[a]}function e(a,c,d){a.stopPropagation(),a.preventDefault();var e=b.isFunction(d)&&d(a)===!1;e||c.modal("hide")}function f(a){var b,c=0;for(b in a)c++;return c}function g(a,c){var d=0;b.each(a,function(a,b){c(a,b,d++)})}function h(a){var c,d;if("object"!=typeof a)throw new Error("Please supply an object of options");if(!a.message)throw new Error("Please specify a message");return a=b.extend({},o,a),a.buttons||(a.buttons={}),a.backdrop=a.backdrop?"static":!1,c=a.buttons,d=f(c),g(c,function(a,e,f){if(b.isFunction(e)&&(e=c[a]={callback:e}),"object"!==b.type(e))throw new Error("button with key "+a+" must be an object");e.label||(e.label=a),e.className||(e.className=2>=d&&f===d-1?"btn-primary":"btn-default")}),a}function i(a,b){var c=a.length,d={};if(1>c||c>2)throw new Error("Invalid argument length");return 2===c||"string"==typeof a[0]?(d[b[0]]=a[0],d[b[1]]=a[1]):d=a[0],d}function j(a,c,d){return b.extend(!0,{},a,i(c,d))}function k(a,b,c,d){var e={className:"bootbox-"+a,buttons:l.apply(null,b)};return m(j(e,d,c),b)}function l(){for(var a={},b=0,c=arguments.length;c>b;b++){var e=arguments[b],f=e.toLowerCase(),g=e.toUpperCase();a[f]={label:d(g)}}return a}function m(a,b){var d={};return g(b,function(a,b){d[b]=!0}),g(a.buttons,function(a){if(d[a]===c)throw new Error("button key "+a+" is not allowed (options are "+b.join("\n")+")")}),a}var n={dialog:"<div class='bootbox modal' tabindex='-1' role='dialog'><div class='modal-dialog'><div class='modal-content'><div class='modal-body'><div class='bootbox-body'></div></div></div></div></div>",header:"<div class='modal-header'><h4 class='modal-title'></h4></div>",footer:"<div class='modal-footer'></div>",closeButton:"<button type='button' class='bootbox-close-button close' data-dismiss='modal' aria-hidden='true'>&times;</button>",form:"<form class='bootbox-form'></form>",inputs:{text:"<input class='bootbox-input bootbox-input-text form-control' autocomplete=off type=text />",textarea:"<textarea class='bootbox-input bootbox-input-textarea form-control'></textarea>",email:"<input class='bootbox-input bootbox-input-email form-control' autocomplete='off' type='email' />",select:"<select class='bootbox-input bootbox-input-select form-control'></select>",checkbox:"<div class='checkbox'><label><input class='bootbox-input bootbox-input-checkbox' type='checkbox' /></label></div>",date:"<input class='bootbox-input bootbox-input-date form-control' autocomplete=off type='date' />",time:"<input class='bootbox-input bootbox-input-time form-control' autocomplete=off type='time' />",number:"<input class='bootbox-input bootbox-input-number form-control' autocomplete=off type='number' />",password:"<input class='bootbox-input bootbox-input-password form-control' autocomplete='off' type='password' />"}},o={locale:"en",backdrop:!0,animate:!0,className:null,closeButton:!0,show:!0,container:"body"},p={};p.alert=function(){var a;if(a=k("alert",["ok"],["message","callback"],arguments),a.callback&&!b.isFunction(a.callback))throw new Error("alert requires callback property to be a function when provided");return a.buttons.ok.callback=a.onEscape=function(){return b.isFunction(a.callback)?a.callback():!0},p.dialog(a)},p.confirm=function(){var a;if(a=k("confirm",["cancel","confirm"],["message","callback"],arguments),a.buttons.cancel.callback=a.onEscape=function(){return a.callback(!1)},a.buttons.confirm.callback=function(){return a.callback(!0)},!b.isFunction(a.callback))throw new Error("confirm requires a callback");return p.dialog(a)},p.prompt=function(){var a,d,e,f,h,i,k;f=b(n.form),d={className:"bootbox-prompt",buttons:l("cancel","confirm"),value:"",inputType:"text"},a=m(j(d,arguments,["title","callback"]),["cancel","confirm"]),i=a.show===c?!0:a.show;var o=["date","time","number"],q=document.createElement("input");if(q.setAttribute("type",a.inputType),o[a.inputType]&&(a.inputType=q.type),a.message=f,a.buttons.cancel.callback=a.onEscape=function(){return a.callback(null)},a.buttons.confirm.callback=function(){var c;switch(a.inputType){case"text":case"textarea":case"email":case"select":case"date":case"time":case"number":case"password":c=h.val();break;case"checkbox":var d=h.find("input:checked");c=[],g(d,function(a,d){c.push(b(d).val())})}return a.callback(c)},a.show=!1,!a.title)throw new Error("prompt requires a title");if(!b.isFunction(a.callback))throw new Error("prompt requires a callback");if(!n.inputs[a.inputType])throw new Error("invalid prompt type");switch(h=b(n.inputs[a.inputType]),a.inputType){case"text":case"textarea":case"email":case"date":case"time":case"number":case"password":h.val(a.value);break;case"select":var r={};if(k=a.inputOptions||[],!k.length)throw new Error("prompt with select requires options");g(k,function(a,d){var e=h;if(d.value===c||d.text===c)throw new Error("given options in wrong format");d.group&&(r[d.group]||(r[d.group]=b("<optgroup/>").attr("label",d.group)),e=r[d.group]),e.append("<option value='"+d.value+"'>"+d.text+"</option>")}),g(r,function(a,b){h.append(b)}),h.val(a.value);break;case"checkbox":var s=b.isArray(a.value)?a.value:[a.value];if(k=a.inputOptions||[],!k.length)throw new Error("prompt with checkbox requires options");if(!k[0].value||!k[0].text)throw new Error("given options in wrong format");h=b("<div/>"),g(k,function(c,d){var e=b(n.inputs[a.inputType]);e.find("input").attr("value",d.value),e.find("label").append(d.text),g(s,function(a,b){b===d.value&&e.find("input").prop("checked",!0)}),h.append(e)})}return a.placeholder&&h.attr("placeholder",a.placeholder),a.pattern&&h.attr("pattern",a.pattern),f.append(h),f.on("submit",function(a){a.preventDefault(),e.find(".btn-primary").click()}),e=p.dialog(a),e.off("shown.bs.modal"),e.on("shown.bs.modal",function(){h.focus()}),i===!0&&e.modal("show"),e},p.dialog=function(a){a=h(a);var c=b(n.dialog),d=c.find(".modal-body"),f=a.buttons,i="",j={onEscape:a.onEscape};if(g(f,function(a,b){i+="<button data-bb-handler='"+a+"' type='button' class='btn "+b.className+"'>"+b.label+"</button>",j[a]=b.callback}),d.find(".bootbox-body").html(a.message),a.animate===!0&&c.addClass("fade"),a.className&&c.addClass(a.className),a.title&&d.before(n.header),a.closeButton){var k=b(n.closeButton);a.title?c.find(".modal-header").prepend(k):k.css("margin-top","-10px").prependTo(d)}return a.title&&c.find(".modal-title").html(a.title),i.length&&(d.after(n.footer),c.find(".modal-footer").html(i)),c.on("hidden.bs.modal",function(a){a.target===this&&c.remove()}),c.on("shown.bs.modal",function(){c.find(".btn-primary:first").focus()}),c.on("escape.close.bb",function(a){j.onEscape&&e(a,c,j.onEscape)}),c.on("click",".modal-footer button",function(a){var d=b(this).data("bb-handler");e(a,c,j[d])}),c.on("click",".bootbox-close-button",function(a){e(a,c,j.onEscape)}),c.on("keyup",function(a){27===a.which&&c.trigger("escape.close.bb")}),b(a.container).append(c),c.modal({backdrop:a.backdrop,keyboard:!1,show:!1}),a.show&&c.modal("show"),c},p.setDefaults=function(){var a={};2===arguments.length?a[arguments[0]]=arguments[1]:a=arguments[0],b.extend(o,a)},p.hideAll=function(){b(".bootbox").modal("hide")};var q={br:{OK:"OK",CANCEL:"Cancelar",CONFIRM:"Sim"},da:{OK:"OK",CANCEL:"Annuller",CONFIRM:"Accepter"},de:{OK:"OK",CANCEL:"Abbrechen",CONFIRM:"Akzeptieren"},en:{OK:"OK",CANCEL:"Cancel",CONFIRM:"OK"},es:{OK:"OK",CANCEL:"Cancelar",CONFIRM:"Aceptar"},fi:{OK:"OK",CANCEL:"Peruuta",CONFIRM:"OK"},fr:{OK:"OK",CANCEL:"Annuler",CONFIRM:"D'accord"},he:{OK:"אישור",CANCEL:"ביטול",CONFIRM:"אישור"},it:{OK:"OK",CANCEL:"Annulla",CONFIRM:"Conferma"},lt:{OK:"Gerai",CANCEL:"Atšaukti",CONFIRM:"Patvirtinti"},lv:{OK:"Labi",CANCEL:"Atcelt",CONFIRM:"Apstiprināt"},nl:{OK:"OK",CANCEL:"Annuleren",CONFIRM:"Accepteren"},no:{OK:"OK",CANCEL:"Avbryt",CONFIRM:"OK"},pl:{OK:"OK",CANCEL:"Anuluj",CONFIRM:"Potwierdź"},ru:{OK:"OK",CANCEL:"Отмена",CONFIRM:"Применить"},sv:{OK:"OK",CANCEL:"Avbryt",CONFIRM:"OK"},tr:{OK:"Tamam",CANCEL:"İptal",CONFIRM:"Onayla"},zh_CN:{OK:"OK",CANCEL:"取消",CONFIRM:"确认"},zh_TW:{OK:"OK",CANCEL:"取消",CONFIRM:"確認"}};return p.init=function(c){return a(c||b)},p});;
/*!

 handlebars v3.0.3

Copyright (C) 2011-2014 by Yehuda Katz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

@license
*/
!function(a,b){"object"==typeof exports&&"object"==typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a}var e=c(8)["default"];b.__esModule=!0;var f=c(1),g=e(f),h=c(2),i=e(h),j=c(3),k=c(4),l=c(5),m=e(l),n=c(6),o=e(n),p=c(7),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=new g.HandlebarsEnvironment;return m.extend(a,g),a.SafeString=i["default"],a.Exception=k["default"],a.Utils=m,a.escapeExpression=m.escapeExpression,a.VM=o,a.template=function(b){return o.template(b,a)},a}var e=c(8)["default"];b.__esModule=!0;var f=c(9),g=e(f),h=c(10),i=e(h),j=c(11),k=e(j),l=c(12),m=e(l),n=c(13),o=e(n),p=c(7),q=e(p),r=d();r.create=d,q["default"](r),r["default"]=r,b["default"]=r,a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0;var c={Program:function(a,b,c,d){this.loc=d,this.type="Program",this.body=a,this.blockParams=b,this.strip=c},MustacheStatement:function(a,b,c,d,e,f){this.loc=f,this.type="MustacheStatement",this.path=a,this.params=b||[],this.hash=c,this.escaped=d,this.strip=e},BlockStatement:function(a,b,c,d,e,f,g,h,i){this.loc=i,this.type="BlockStatement",this.path=a,this.params=b||[],this.hash=c,this.program=d,this.inverse=e,this.openStrip=f,this.inverseStrip=g,this.closeStrip=h},PartialStatement:function(a,b,c,d,e){this.loc=e,this.type="PartialStatement",this.name=a,this.params=b||[],this.hash=c,this.indent="",this.strip=d},ContentStatement:function(a,b){this.loc=b,this.type="ContentStatement",this.original=this.value=a},CommentStatement:function(a,b,c){this.loc=c,this.type="CommentStatement",this.value=a,this.strip=b},SubExpression:function(a,b,c,d){this.loc=d,this.type="SubExpression",this.path=a,this.params=b||[],this.hash=c},PathExpression:function(a,b,c,d,e){this.loc=e,this.type="PathExpression",this.data=a,this.original=d,this.parts=c,this.depth=b},StringLiteral:function(a,b){this.loc=b,this.type="StringLiteral",this.original=this.value=a},NumberLiteral:function(a,b){this.loc=b,this.type="NumberLiteral",this.original=this.value=Number(a)},BooleanLiteral:function(a,b){this.loc=b,this.type="BooleanLiteral",this.original=this.value="true"===a},UndefinedLiteral:function(a){this.loc=a,this.type="UndefinedLiteral",this.original=this.value=void 0},NullLiteral:function(a){this.loc=a,this.type="NullLiteral",this.original=this.value=null},Hash:function(a,b){this.loc=b,this.type="Hash",this.pairs=a},HashPair:function(a,b,c){this.loc=c,this.type="HashPair",this.key=a,this.value=b},helpers:{helperExpression:function(a){return!("SubExpression"!==a.type&&!a.params.length&&!a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;g["default"].yy=o,o.locInfo=function(a){return new o.SourceLocation(b&&b.srcName,a)};var c=new k["default"];return c.accept(g["default"].parse(a))}var e=c(8)["default"];b.__esModule=!0,b.parse=d;var f=c(14),g=e(f),h=c(2),i=e(h),j=c(15),k=e(j),l=c(16),m=e(l),n=c(12);b.parser=g["default"];var o={};n.extend(o,m,i["default"])},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var b=c.parse(a,f),d=(new c.Compiler).compile(b,f),e=(new c.JavaScriptCompiler).compile(d,f,void 0,!0);return c.template(e)}function e(a,b){return g||(g=d()),g.call(this,a,b)}var f=void 0===arguments[1]?{}:arguments[1];if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new k["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);"data"in f||(f.data=!0),f.compat&&(f.useDepths=!0);var g=void 0;return e._setup=function(a){return g||(g=d()),g._setup(a)},e._child=function(a,b,c,e){return g||(g=d()),g._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(l.isArray(a)&&l.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path=new n["default"].PathExpression(!1,0,[b.original+""],b.original+"",b.loc)}}var i=c(8)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var j=c(11),k=i(j),l=c(12),m=c(2),n=i(m),o=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;b>c;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;b>c;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[];var c=b.knownHelpers;if(b.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},c)for(var d in c)d in c&&(b.knownHelpers[d]=c[d]);return this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;c>d;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},PartialStatement:function(a){this.usePartial=!0;var b=a.params;if(b.length>1)throw new k["default"]("Unsupported number of partial arguments: "+b.length,a);b.length||b.push({type:"PathExpression",parts:[],depth:0});var c=a.name.original,d="SubExpression"===a.name.type;d&&this.accept(a.name),this.setupFullMustacheParams(a,void 0,void 0,!0);var e=a.indent||"";this.options.preventIndent&&e&&(this.opcode("appendContent",e),e=""),this.opcode("invokePartial",d,c,e),this.opcode("append")},MustacheStatement:function(a){this.SubExpression(a),this.opcode(a.escaped&&!this.options.noEscape?"appendEscaped":"append")},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){this.accept(a.path),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new k["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,n["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=n["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts)):this.opcode("lookupOnContext",a.parts,a.falsy,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");d>c;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:o.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=n["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&n["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;c>b;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||n["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^\.\//g,"").replace(/^\.$/g,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;c>b;b++){var d=this.options.blockParams[b],e=d&&l.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;g>f;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("this.strict"),"(",e,", ",b.quotedString(c[f]),")"]:e}var g=c(8)["default"];b.__esModule=!0;var h=c(9),i=c(11),j=g(i),k=c(12),l=c(17),m=g(l);e.prototype={nameLookup:function(a,b){return e.isValidJavaScriptVariableName(b)?[a,".",b]:[a,"['",b,"']"]},depthedLookup:function(a){return[this.aliasable("this.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=h.COMPILER_REVISION,b=h.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return k.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;i>h;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new j["default"]("Compile completed with content left on stack");var k=this.createFunctionContext(d);if(this.isChild)return k;var l={compiler:this.compilerInfo(),main:k},m=this.context.programs;for(h=0,i=m.length;i>h;h++)m[h]&&(l[h]=m[h]);return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new m["default"](this.options.srcName)},createFunctionContext:function(a){var b="",c=this.stackVars.concat(this.registers.list);c.length>0&&(b+=", "+c.join(", "));var d=0;for(var e in this.aliases){var f=this.aliases[e];this.aliases.hasOwnProperty(e)&&f.children&&f.referenceCount>1&&(b+=", alias"+ ++d+"="+e,f.children[0]="alias"+d)}var g=["depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&g.push("blockParams"),this.useDepths&&g.push("depths");var h=this.mergeSource(b);return a?(g.push(h),Function.apply(this,g)):this.source.wrap(["function(",g.join(","),") {\n  ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend("  + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},blockValue:function(a){var b=this.aliasable("helpers.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("helpers.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("this.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c){var d=0;c||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[d++])),this.resolvePath("context",a,d,b)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b){this.pushStackLiteral(a?"this.data(data, "+a+")":"data"),this.resolvePath("data",b,0,!0)},resolvePath:function(a,b,c,d){var e=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict,this,b,a));for(var g=b.length;g>c;c++)this.replaceStack(function(f){var g=e.nameLookup(f,b[c],a);return d?[" && ",g]:[" != null ? ",g," : ",f]})},resolvePossibleLambda:function(){this.push([this.aliasable("this.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){this.pushStackLiteral(null!=a?this.programExpression(a):null)},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=c?[e.name," || "]:"",g=["("].concat(f,d);this.options.strict||g.push(" || ",this.aliasable("helpers.helperMissing")),g.push(")"),this.push(this.source.functionCall(g,"call",e.callParams))},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("helpers.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d,!1);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",d.unshift(a?b:this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("this.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):this.pushStackLiteral("SubExpression"===a?"true":"null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;g>f;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);null==h?(this.context.programs.push(""),h=this.context.programs.length,d.index=h,d.name="program"+h,this.context.programs[h]=e.compile(d,b,this.context,!this.precompile),this.context.environments[h]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams):(d.index=h,d.name="program"+h,this.useDepths=this.useDepths||d.useDepths,this.useBlockParams=this.useBlockParams||d.useBlockParams)}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;c>b;b++){var d=this.context.environments[b];if(d&&d.equals(a))return b}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"this.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new j["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;c>b;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new j["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper");return{params:d,paramsInit:e,name:f,callParams:[this.contextName(0)].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=void 0;d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var i=this.popStack(),j=this.popStack();(j||i)&&(d.fn=j||"this.noop",d.inverse=i||"this.noop");for(var k=b;k--;)h=this.popStack(),c[k]=h,this.trackIds&&(g[k]=this.popStack()),this.stringParams&&(f[k]=this.popStack(),e[k]=this.popStack());return this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c,!0);return e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):(c.push(e),"")}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;d>c;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}var e=c(8)["default"];b.__esModule=!0;var f=c(11),g=e(f),h=c(2),i=e(h);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&(!c.type||!i["default"][c.type]))throw new g["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new g["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;c>b;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:function(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")},BlockStatement:function(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash"),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")},PartialStatement:function(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:function(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")},PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){b.Handlebars===a&&(b.Handlebars=d)}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b){this.helpers=a||{},this.partials=b||{},e(this)}function e(a){a.registerHelper("helperMissing",function(){if(1===arguments.length)return void 0;throw new k["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')}),a.registerHelper("blockHelperMissing",function(b,c){var d=c.inverse,e=c.fn;if(b===!0)return e(this);if(b===!1||null==b)return d(this);if(o(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):d(this);if(c.data&&c.ids){var g=f(c.data);g.contextPath=i.appendContextPath(c.data.contextPath,c.name),c={data:g}}return e(b,c)}),a.registerHelper("each",function(a,b){function c(b,c,e){j&&(j.key=b,j.index=c,j.first=0===c,j.last=!!e,l&&(j.contextPath=l+b)),h+=d(a[b],{data:j,blockParams:i.blockParams([a[b],b],[l+b,null])})}if(!b)throw new k["default"]("Must pass iterator to #each");var d=b.fn,e=b.inverse,g=0,h="",j=void 0,l=void 0;if(b.data&&b.ids&&(l=i.appendContextPath(b.data.contextPath,b.ids[0])+"."),p(a)&&(a=a.call(this)),b.data&&(j=f(b.data)),a&&"object"==typeof a)if(o(a))for(var m=a.length;m>g;g++)c(g,g,g===a.length-1);else{var n=void 0;for(var q in a)a.hasOwnProperty(q)&&(n&&c(n,g-1),n=q,g++);n&&c(n,g-1,!0)}return 0===g&&(h=e(this)),h}),a.registerHelper("if",function(a,b){return p(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||i.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){p(a)&&(a=a.call(this));var c=b.fn;if(i.isEmpty(a))return b.inverse(this);if(b.data&&b.ids){var d=f(b.data);d.contextPath=i.appendContextPath(b.data.contextPath,b.ids[0]),b={data:d}}return c(a,b)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)}),a.registerHelper("lookup",function(a,b){return a&&a[b]})}function f(a){var b=i.extend({},a);return b._parent=a,b}var g=c(8)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d,b.createFrame=f;var h=c(12),i=g(h),j=c(11),k=g(j),l="3.0.1";b.VERSION=l;var m=6;b.COMPILER_REVISION=m;var n={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1"};b.REVISION_CHANGES=n;var o=i.isArray,p=i.isFunction,q=i.toString,r="[object Object]";d.prototype={constructor:d,logger:s,log:t,registerHelper:function(a,b){if(q.call(a)===r){if(b)throw new k["default"]("Arg not supported with multiple helpers");i.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(q.call(a)===r)i.extend(this.partials,a);else{if("undefined"==typeof b)throw new k["default"]("Attempting to register a partial as undefined");this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]}};var s={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:1,log:function(a,b){if("undefined"!=typeof console&&s.level<=a){var c=s.methodMap[a];(console[c]||console.log).call(console,b)}}};b.logger=s;var t=s.log;b.log=t},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b){"use strict";function c(a,b){var e=b&&b.loc,f=void 0,g=void 0;e&&(f=e.start.line,g=e.start.column,a+=" - "+f+":"+g);for(var h=Error.prototype.constructor.call(this,a),i=0;i<d.length;i++)this[d[i]]=h[d[i]];Error.captureStackTrace&&Error.captureStackTrace(this,c),e&&(this.lineNumber=f,this.column=g)}b.__esModule=!0;var d=["description","fileName","lineNumber","message","name","number","stack"];c.prototype=new Error,b["default"]=c,a.exports=b["default"]},function(a,b){"use strict";function c(a){return j[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return l.test(a)?a.replace(k,c):a}function g(a){return a||0===a?o(a)&&0===a.length?!0:!1:!0}function h(a,b){return a.path=b,a}function i(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.blockParams=h,b.appendContextPath=i;var j={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},k=/[&<>"'`]/g,l=/[&<>"'`]/,m=Object.prototype.toString;b.toString=m;var n=function(a){return"function"==typeof a};n(/x/)&&(b.isFunction=n=function(a){return"function"==typeof a&&"[object Function]"===m.call(a)});var n;b.isFunction=n;var o=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===m.call(a):!1};b.isArray=o},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=p.COMPILER_REVISION;if(b!==c){if(c>b){var d=p.REVISION_CHANGES[c],e=p.REVISION_CHANGES[b];throw new o["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new o["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=m.extend({},d,e.hash)),c=b.VM.resolvePartial.call(this,c,d,e);var f=b.VM.invokePartial.call(this,c,d,e);if(null==f&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),f=e.partials[e.name](d,e)),null!=f){if(e.indent){for(var g=f.split("\n"),h=0,i=g.length;i>h&&(g[h]||h+1!==i);h++)g[h]=e.indent+g[h];f=g.join("\n")}return f}throw new o["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){var c=void 0===arguments[1]?{}:arguments[1],f=c.data;
d._setup(c),!c.partial&&a.useData&&(f=j(b,f));var g=void 0,h=a.useBlockParams?[]:void 0;return a.useDepths&&(g=c.depths?[b].concat(c.depths):[b]),a.main.call(e,b,e.helpers,e.partials,f,h,g)}if(!b)throw new o["default"]("No environment passed to template");if(!a||!a.main)throw new o["default"]("Unknown template object: "+typeof a);b.VM.checkRevision(a.compiler);var e={strict:function(a,b){if(!(b in a))throw new o["default"]('"'+b+'" not defined in '+a);return a[b]},lookup:function(a,b){for(var c=a.length,d=0;c>d;d++)if(a[d]&&null!=a[d][b])return a[d][b]},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:m.escapeExpression,invokePartial:c,fn:function(b){return a[b]},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=m.extend({},b,a)),c},noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){c.partial?(e.helpers=c.helpers,e.partials=c.partials):(e.helpers=e.merge(c.helpers,b.helpers),a.usePartial&&(e.partials=e.merge(c.partials,b.partials)))},d._child=function(b,c,d,g){if(a.useBlockParams&&!d)throw new o["default"]("must pass block params");if(a.useDepths&&!g)throw new o["default"]("must pass parent depths");return f(e,b,a[b],c,0,d,g)},d}function f(a,b,c,d,e,f,g){function h(b){var e=void 0===arguments[1]?{}:arguments[1];return c.call(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),g&&[b].concat(g))}return h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a=c.partials[c.name],a}function h(a,b,c){if(c.partial=!0,void 0===a)throw new o["default"]("The partial "+c.name+" could not be found");return a instanceof Function?a(b,c):void 0}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?p.createFrame(b):{},b.root=a),b}var k=c(8)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var l=c(12),m=k(l),n=c(11),o=k(n),p=c(9)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,content:12,COMMENT:13,CONTENT:14,openRawBlock:15,END_RAW_BLOCK:16,OPEN_RAW_BLOCK:17,helperName:18,openRawBlock_repetition0:19,openRawBlock_option0:20,CLOSE_RAW_BLOCK:21,openBlock:22,block_option0:23,closeBlock:24,openInverse:25,block_option1:26,OPEN_BLOCK:27,openBlock_repetition0:28,openBlock_option0:29,openBlock_option1:30,CLOSE:31,OPEN_INVERSE:32,openInverse_repetition0:33,openInverse_option0:34,openInverse_option1:35,openInverseChain:36,OPEN_INVERSE_CHAIN:37,openInverseChain_repetition0:38,openInverseChain_option0:39,openInverseChain_option1:40,inverseAndProgram:41,INVERSE:42,inverseChain:43,inverseChain_option0:44,OPEN_ENDBLOCK:45,OPEN:46,mustache_repetition0:47,mustache_option0:48,OPEN_UNESCAPED:49,mustache_repetition1:50,mustache_option1:51,CLOSE_UNESCAPED:52,OPEN_PARTIAL:53,partialName:54,partial_repetition0:55,partial_option0:56,param:57,sexpr:58,OPEN_SEXPR:59,sexpr_repetition0:60,sexpr_option0:61,CLOSE_SEXPR:62,hash:63,hash_repetition_plus0:64,hashSegment:65,ID:66,EQUALS:67,blockParams:68,OPEN_BLOCK_PARAMS:69,blockParams_repetition_plus0:70,CLOSE_BLOCK_PARAMS:71,path:72,dataName:73,STRING:74,NUMBER:75,BOOLEAN:76,UNDEFINED:77,NULL:78,DATA:79,pathSegments:80,SEP:81,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",13:"COMMENT",14:"CONTENT",16:"END_RAW_BLOCK",17:"OPEN_RAW_BLOCK",21:"CLOSE_RAW_BLOCK",27:"OPEN_BLOCK",31:"CLOSE",32:"OPEN_INVERSE",37:"OPEN_INVERSE_CHAIN",42:"INVERSE",45:"OPEN_ENDBLOCK",46:"OPEN",49:"OPEN_UNESCAPED",52:"CLOSE_UNESCAPED",53:"OPEN_PARTIAL",59:"OPEN_SEXPR",62:"CLOSE_SEXPR",66:"ID",67:"EQUALS",69:"OPEN_BLOCK_PARAMS",71:"CLOSE_BLOCK_PARAMS",74:"STRING",75:"NUMBER",76:"BOOLEAN",77:"UNDEFINED",78:"NULL",79:"DATA",81:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[12,1],[10,3],[15,5],[9,4],[9,4],[22,6],[25,6],[36,6],[41,2],[43,3],[43,1],[24,3],[8,5],[8,5],[11,5],[57,1],[57,1],[58,5],[63,1],[65,3],[68,3],[18,1],[18,1],[18,1],[18,1],[18,1],[18,1],[18,1],[54,1],[54,1],[73,2],[72,1],[80,3],[80,1],[6,0],[6,2],[19,0],[19,2],[20,0],[20,1],[23,0],[23,1],[26,0],[26,1],[28,0],[28,2],[29,0],[29,1],[30,0],[30,1],[33,0],[33,2],[34,0],[34,1],[35,0],[35,1],[38,0],[38,2],[39,0],[39,1],[40,0],[40,1],[44,0],[44,1],[47,0],[47,2],[48,0],[48,1],[50,0],[50,2],[51,0],[51,1],[55,0],[55,2],[56,0],[56,1],[60,0],[60,2],[61,0],[61,1],[64,1],[64,2],[70,1],[70,2]],performAction:function(a,b,c,d,e,f){var g=f.length-1;switch(e){case 1:return f[g-1];case 2:this.$=new d.Program(f[g],null,{},d.locInfo(this._$));break;case 3:this.$=f[g];break;case 4:this.$=f[g];break;case 5:this.$=f[g];break;case 6:this.$=f[g];break;case 7:this.$=f[g];break;case 8:this.$=new d.CommentStatement(d.stripComment(f[g]),d.stripFlags(f[g],f[g]),d.locInfo(this._$));break;case 9:this.$=new d.ContentStatement(f[g],d.locInfo(this._$));break;case 10:this.$=d.prepareRawBlock(f[g-2],f[g-1],f[g],this._$);break;case 11:this.$={path:f[g-3],params:f[g-2],hash:f[g-1]};break;case 12:this.$=d.prepareBlock(f[g-3],f[g-2],f[g-1],f[g],!1,this._$);break;case 13:this.$=d.prepareBlock(f[g-3],f[g-2],f[g-1],f[g],!0,this._$);break;case 14:this.$={path:f[g-4],params:f[g-3],hash:f[g-2],blockParams:f[g-1],strip:d.stripFlags(f[g-5],f[g])};break;case 15:this.$={path:f[g-4],params:f[g-3],hash:f[g-2],blockParams:f[g-1],strip:d.stripFlags(f[g-5],f[g])};break;case 16:this.$={path:f[g-4],params:f[g-3],hash:f[g-2],blockParams:f[g-1],strip:d.stripFlags(f[g-5],f[g])};break;case 17:this.$={strip:d.stripFlags(f[g-1],f[g-1]),program:f[g]};break;case 18:var h=d.prepareBlock(f[g-2],f[g-1],f[g],f[g],!1,this._$),i=new d.Program([h],null,{},d.locInfo(this._$));i.chained=!0,this.$={strip:f[g-2].strip,program:i,chain:!0};break;case 19:this.$=f[g];break;case 20:this.$={path:f[g-1],strip:d.stripFlags(f[g-2],f[g])};break;case 21:this.$=d.prepareMustache(f[g-3],f[g-2],f[g-1],f[g-4],d.stripFlags(f[g-4],f[g]),this._$);break;case 22:this.$=d.prepareMustache(f[g-3],f[g-2],f[g-1],f[g-4],d.stripFlags(f[g-4],f[g]),this._$);break;case 23:this.$=new d.PartialStatement(f[g-3],f[g-2],f[g-1],d.stripFlags(f[g-4],f[g]),d.locInfo(this._$));break;case 24:this.$=f[g];break;case 25:this.$=f[g];break;case 26:this.$=new d.SubExpression(f[g-3],f[g-2],f[g-1],d.locInfo(this._$));break;case 27:this.$=new d.Hash(f[g],d.locInfo(this._$));break;case 28:this.$=new d.HashPair(d.id(f[g-2]),f[g],d.locInfo(this._$));break;case 29:this.$=d.id(f[g-1]);break;case 30:this.$=f[g];break;case 31:this.$=f[g];break;case 32:this.$=new d.StringLiteral(f[g],d.locInfo(this._$));break;case 33:this.$=new d.NumberLiteral(f[g],d.locInfo(this._$));break;case 34:this.$=new d.BooleanLiteral(f[g],d.locInfo(this._$));break;case 35:this.$=new d.UndefinedLiteral(d.locInfo(this._$));break;case 36:this.$=new d.NullLiteral(d.locInfo(this._$));break;case 37:this.$=f[g];break;case 38:this.$=f[g];break;case 39:this.$=d.preparePath(!0,f[g],this._$);break;case 40:this.$=d.preparePath(!1,f[g],this._$);break;case 41:f[g-2].push({part:d.id(f[g]),original:f[g],separator:f[g-1]}),this.$=f[g-2];break;case 42:this.$=[{part:d.id(f[g]),original:f[g]}];break;case 43:this.$=[];break;case 44:f[g-1].push(f[g]);break;case 45:this.$=[];break;case 46:f[g-1].push(f[g]);break;case 53:this.$=[];break;case 54:f[g-1].push(f[g]);break;case 59:this.$=[];break;case 60:f[g-1].push(f[g]);break;case 65:this.$=[];break;case 66:f[g-1].push(f[g]);break;case 73:this.$=[];break;case 74:f[g-1].push(f[g]);break;case 77:this.$=[];break;case 78:f[g-1].push(f[g]);break;case 81:this.$=[];break;case 82:f[g-1].push(f[g]);break;case 85:this.$=[];break;case 86:f[g-1].push(f[g]);break;case 89:this.$=[f[g]];break;case 90:f[g-1].push(f[g]);break;case 91:this.$=[f[g]];break;case 92:f[g-1].push(f[g])}},table:[{3:1,4:2,5:[2,43],6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],46:[2,43],49:[2,43],53:[2,43]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:[1,11],14:[1,18],15:16,17:[1,21],22:14,25:15,27:[1,19],32:[1,20],37:[2,2],42:[2,2],45:[2,2],46:[1,12],49:[1,13],53:[1,17]},{1:[2,1]},{5:[2,44],13:[2,44],14:[2,44],17:[2,44],27:[2,44],32:[2,44],37:[2,44],42:[2,44],45:[2,44],46:[2,44],49:[2,44],53:[2,44]},{5:[2,3],13:[2,3],14:[2,3],17:[2,3],27:[2,3],32:[2,3],37:[2,3],42:[2,3],45:[2,3],46:[2,3],49:[2,3],53:[2,3]},{5:[2,4],13:[2,4],14:[2,4],17:[2,4],27:[2,4],32:[2,4],37:[2,4],42:[2,4],45:[2,4],46:[2,4],49:[2,4],53:[2,4]},{5:[2,5],13:[2,5],14:[2,5],17:[2,5],27:[2,5],32:[2,5],37:[2,5],42:[2,5],45:[2,5],46:[2,5],49:[2,5],53:[2,5]},{5:[2,6],13:[2,6],14:[2,6],17:[2,6],27:[2,6],32:[2,6],37:[2,6],42:[2,6],45:[2,6],46:[2,6],49:[2,6],53:[2,6]},{5:[2,7],13:[2,7],14:[2,7],17:[2,7],27:[2,7],32:[2,7],37:[2,7],42:[2,7],45:[2,7],46:[2,7],49:[2,7],53:[2,7]},{5:[2,8],13:[2,8],14:[2,8],17:[2,8],27:[2,8],32:[2,8],37:[2,8],42:[2,8],45:[2,8],46:[2,8],49:[2,8],53:[2,8]},{18:22,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:33,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{4:34,6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],37:[2,43],42:[2,43],45:[2,43],46:[2,43],49:[2,43],53:[2,43]},{4:35,6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],42:[2,43],45:[2,43],46:[2,43],49:[2,43],53:[2,43]},{12:36,14:[1,18]},{18:38,54:37,58:39,59:[1,40],66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{5:[2,9],13:[2,9],14:[2,9],16:[2,9],17:[2,9],27:[2,9],32:[2,9],37:[2,9],42:[2,9],45:[2,9],46:[2,9],49:[2,9],53:[2,9]},{18:41,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:42,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:43,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{31:[2,73],47:44,59:[2,73],66:[2,73],74:[2,73],75:[2,73],76:[2,73],77:[2,73],78:[2,73],79:[2,73]},{21:[2,30],31:[2,30],52:[2,30],59:[2,30],62:[2,30],66:[2,30],69:[2,30],74:[2,30],75:[2,30],76:[2,30],77:[2,30],78:[2,30],79:[2,30]},{21:[2,31],31:[2,31],52:[2,31],59:[2,31],62:[2,31],66:[2,31],69:[2,31],74:[2,31],75:[2,31],76:[2,31],77:[2,31],78:[2,31],79:[2,31]},{21:[2,32],31:[2,32],52:[2,32],59:[2,32],62:[2,32],66:[2,32],69:[2,32],74:[2,32],75:[2,32],76:[2,32],77:[2,32],78:[2,32],79:[2,32]},{21:[2,33],31:[2,33],52:[2,33],59:[2,33],62:[2,33],66:[2,33],69:[2,33],74:[2,33],75:[2,33],76:[2,33],77:[2,33],78:[2,33],79:[2,33]},{21:[2,34],31:[2,34],52:[2,34],59:[2,34],62:[2,34],66:[2,34],69:[2,34],74:[2,34],75:[2,34],76:[2,34],77:[2,34],78:[2,34],79:[2,34]},{21:[2,35],31:[2,35],52:[2,35],59:[2,35],62:[2,35],66:[2,35],69:[2,35],74:[2,35],75:[2,35],76:[2,35],77:[2,35],78:[2,35],79:[2,35]},{21:[2,36],31:[2,36],52:[2,36],59:[2,36],62:[2,36],66:[2,36],69:[2,36],74:[2,36],75:[2,36],76:[2,36],77:[2,36],78:[2,36],79:[2,36]},{21:[2,40],31:[2,40],52:[2,40],59:[2,40],62:[2,40],66:[2,40],69:[2,40],74:[2,40],75:[2,40],76:[2,40],77:[2,40],78:[2,40],79:[2,40],81:[1,45]},{66:[1,32],80:46},{21:[2,42],31:[2,42],52:[2,42],59:[2,42],62:[2,42],66:[2,42],69:[2,42],74:[2,42],75:[2,42],76:[2,42],77:[2,42],78:[2,42],79:[2,42],81:[2,42]},{50:47,52:[2,77],59:[2,77],66:[2,77],74:[2,77],75:[2,77],76:[2,77],77:[2,77],78:[2,77],79:[2,77]},{23:48,36:50,37:[1,52],41:51,42:[1,53],43:49,45:[2,49]},{26:54,41:55,42:[1,53],45:[2,51]},{16:[1,56]},{31:[2,81],55:57,59:[2,81],66:[2,81],74:[2,81],75:[2,81],76:[2,81],77:[2,81],78:[2,81],79:[2,81]},{31:[2,37],59:[2,37],66:[2,37],74:[2,37],75:[2,37],76:[2,37],77:[2,37],78:[2,37],79:[2,37]},{31:[2,38],59:[2,38],66:[2,38],74:[2,38],75:[2,38],76:[2,38],77:[2,38],78:[2,38],79:[2,38]},{18:58,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{28:59,31:[2,53],59:[2,53],66:[2,53],69:[2,53],74:[2,53],75:[2,53],76:[2,53],77:[2,53],78:[2,53],79:[2,53]},{31:[2,59],33:60,59:[2,59],66:[2,59],69:[2,59],74:[2,59],75:[2,59],76:[2,59],77:[2,59],78:[2,59],79:[2,59]},{19:61,21:[2,45],59:[2,45],66:[2,45],74:[2,45],75:[2,45],76:[2,45],77:[2,45],78:[2,45],79:[2,45]},{18:65,31:[2,75],48:62,57:63,58:66,59:[1,40],63:64,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{66:[1,70]},{21:[2,39],31:[2,39],52:[2,39],59:[2,39],62:[2,39],66:[2,39],69:[2,39],74:[2,39],75:[2,39],76:[2,39],77:[2,39],78:[2,39],79:[2,39],81:[1,45]},{18:65,51:71,52:[2,79],57:72,58:66,59:[1,40],63:73,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{24:74,45:[1,75]},{45:[2,50]},{4:76,6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],37:[2,43],42:[2,43],45:[2,43],46:[2,43],49:[2,43],53:[2,43]},{45:[2,19]},{18:77,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{4:78,6:3,13:[2,43],14:[2,43],17:[2,43],27:[2,43],32:[2,43],45:[2,43],46:[2,43],49:[2,43],53:[2,43]},{24:79,45:[1,75]},{45:[2,52]},{5:[2,10],13:[2,10],14:[2,10],17:[2,10],27:[2,10],32:[2,10],37:[2,10],42:[2,10],45:[2,10],46:[2,10],49:[2,10],53:[2,10]},{18:65,31:[2,83],56:80,57:81,58:66,59:[1,40],63:82,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{59:[2,85],60:83,62:[2,85],66:[2,85],74:[2,85],75:[2,85],76:[2,85],77:[2,85],78:[2,85],79:[2,85]},{18:65,29:84,31:[2,55],57:85,58:66,59:[1,40],63:86,64:67,65:68,66:[1,69],69:[2,55],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:65,31:[2,61],34:87,57:88,58:66,59:[1,40],63:89,64:67,65:68,66:[1,69],69:[2,61],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{18:65,20:90,21:[2,47],57:91,58:66,59:[1,40],63:92,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{31:[1,93]},{31:[2,74],59:[2,74],66:[2,74],74:[2,74],75:[2,74],76:[2,74],77:[2,74],78:[2,74],79:[2,74]},{31:[2,76]},{21:[2,24],31:[2,24],52:[2,24],59:[2,24],62:[2,24],66:[2,24],69:[2,24],74:[2,24],75:[2,24],76:[2,24],77:[2,24],78:[2,24],79:[2,24]},{21:[2,25],31:[2,25],52:[2,25],59:[2,25],62:[2,25],66:[2,25],69:[2,25],74:[2,25],75:[2,25],76:[2,25],77:[2,25],78:[2,25],79:[2,25]},{21:[2,27],31:[2,27],52:[2,27],62:[2,27],65:94,66:[1,95],69:[2,27]},{21:[2,89],31:[2,89],52:[2,89],62:[2,89],66:[2,89],69:[2,89]},{21:[2,42],31:[2,42],52:[2,42],59:[2,42],62:[2,42],66:[2,42],67:[1,96],69:[2,42],74:[2,42],75:[2,42],76:[2,42],77:[2,42],78:[2,42],79:[2,42],81:[2,42]},{21:[2,41],31:[2,41],52:[2,41],59:[2,41],62:[2,41],66:[2,41],69:[2,41],74:[2,41],75:[2,41],76:[2,41],77:[2,41],78:[2,41],79:[2,41],81:[2,41]},{52:[1,97]},{52:[2,78],59:[2,78],66:[2,78],74:[2,78],75:[2,78],76:[2,78],77:[2,78],78:[2,78],79:[2,78]},{52:[2,80]},{5:[2,12],13:[2,12],14:[2,12],17:[2,12],27:[2,12],32:[2,12],37:[2,12],42:[2,12],45:[2,12],46:[2,12],49:[2,12],53:[2,12]},{18:98,66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{36:50,37:[1,52],41:51,42:[1,53],43:100,44:99,45:[2,71]},{31:[2,65],38:101,59:[2,65],66:[2,65],69:[2,65],74:[2,65],75:[2,65],76:[2,65],77:[2,65],78:[2,65],79:[2,65]},{45:[2,17]},{5:[2,13],13:[2,13],14:[2,13],17:[2,13],27:[2,13],32:[2,13],37:[2,13],42:[2,13],45:[2,13],46:[2,13],49:[2,13],53:[2,13]},{31:[1,102]},{31:[2,82],59:[2,82],66:[2,82],74:[2,82],75:[2,82],76:[2,82],77:[2,82],78:[2,82],79:[2,82]},{31:[2,84]},{18:65,57:104,58:66,59:[1,40],61:103,62:[2,87],63:105,64:67,65:68,66:[1,69],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{30:106,31:[2,57],68:107,69:[1,108]},{31:[2,54],59:[2,54],66:[2,54],69:[2,54],74:[2,54],75:[2,54],76:[2,54],77:[2,54],78:[2,54],79:[2,54]},{31:[2,56],69:[2,56]},{31:[2,63],35:109,68:110,69:[1,108]},{31:[2,60],59:[2,60],66:[2,60],69:[2,60],74:[2,60],75:[2,60],76:[2,60],77:[2,60],78:[2,60],79:[2,60]},{31:[2,62],69:[2,62]},{21:[1,111]},{21:[2,46],59:[2,46],66:[2,46],74:[2,46],75:[2,46],76:[2,46],77:[2,46],78:[2,46],79:[2,46]},{21:[2,48]},{5:[2,21],13:[2,21],14:[2,21],17:[2,21],27:[2,21],32:[2,21],37:[2,21],42:[2,21],45:[2,21],46:[2,21],49:[2,21],53:[2,21]},{21:[2,90],31:[2,90],52:[2,90],62:[2,90],66:[2,90],69:[2,90]},{67:[1,96]},{18:65,57:112,58:66,59:[1,40],66:[1,32],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{5:[2,22],13:[2,22],14:[2,22],17:[2,22],27:[2,22],32:[2,22],37:[2,22],42:[2,22],45:[2,22],46:[2,22],49:[2,22],53:[2,22]},{31:[1,113]},{45:[2,18]},{45:[2,72]},{18:65,31:[2,67],39:114,57:115,58:66,59:[1,40],63:116,64:67,65:68,66:[1,69],69:[2,67],72:23,73:24,74:[1,25],75:[1,26],76:[1,27],77:[1,28],78:[1,29],79:[1,31],80:30},{5:[2,23],13:[2,23],14:[2,23],17:[2,23],27:[2,23],32:[2,23],37:[2,23],42:[2,23],45:[2,23],46:[2,23],49:[2,23],53:[2,23]},{62:[1,117]},{59:[2,86],62:[2,86],66:[2,86],74:[2,86],75:[2,86],76:[2,86],77:[2,86],78:[2,86],79:[2,86]},{62:[2,88]},{31:[1,118]},{31:[2,58]},{66:[1,120],70:119},{31:[1,121]},{31:[2,64]},{14:[2,11]},{21:[2,28],31:[2,28],52:[2,28],62:[2,28],66:[2,28],69:[2,28]},{5:[2,20],13:[2,20],14:[2,20],17:[2,20],27:[2,20],32:[2,20],37:[2,20],42:[2,20],45:[2,20],46:[2,20],49:[2,20],53:[2,20]},{31:[2,69],40:122,68:123,69:[1,108]},{31:[2,66],59:[2,66],66:[2,66],69:[2,66],74:[2,66],75:[2,66],76:[2,66],77:[2,66],78:[2,66],79:[2,66]},{31:[2,68],69:[2,68]},{21:[2,26],31:[2,26],52:[2,26],59:[2,26],62:[2,26],66:[2,26],69:[2,26],74:[2,26],75:[2,26],76:[2,26],77:[2,26],78:[2,26],79:[2,26]},{13:[2,14],14:[2,14],17:[2,14],27:[2,14],32:[2,14],37:[2,14],42:[2,14],45:[2,14],46:[2,14],49:[2,14],53:[2,14]},{66:[1,125],71:[1,124]},{66:[2,91],71:[2,91]},{13:[2,15],14:[2,15],17:[2,15],27:[2,15],32:[2,15],42:[2,15],45:[2,15],46:[2,15],49:[2,15],53:[2,15]},{31:[1,126]},{31:[2,70]},{31:[2,29]},{66:[2,92],71:[2,92]},{13:[2,16],14:[2,16],17:[2,16],27:[2,16],32:[2,16],37:[2,16],42:[2,16],45:[2,16],46:[2,16],49:[2,16],53:[2,16]}],defaultActions:{4:[2,1],49:[2,50],51:[2,19],55:[2,52],64:[2,76],73:[2,80],78:[2,17],82:[2,84],92:[2,48],99:[2,18],100:[2,72],105:[2,88],107:[2,58],110:[2,64],111:[2,11],123:[2,70],124:[2,29]},parseError:function(a){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:((null===n||"undefined"==typeof n)&&(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 14;break;case 1:return 14;case 2:return this.popState(),14;case 3:return b.yytext=b.yytext.substr(5,b.yyleng-9),this.popState(),16;case 4:return 14;case 5:return this.popState(),13;case 6:return 59;case 7:return 62;case 8:return 17;case 9:return this.popState(),this.begin("raw"),21;case 10:return 53;case 11:return 27;case 12:return 45;case 13:return this.popState(),42;case 14:return this.popState(),42;case 15:return 32;case 16:return 37;case 17:return 49;case 18:return 46;case 19:this.unput(b.yytext),this.popState(),this.begin("com");break;case 20:return this.popState(),13;case 21:return 46;case 22:return 67;case 23:return 66;case 24:return 66;case 25:return 81;case 26:break;case 27:return this.popState(),52;case 28:return this.popState(),31;case 29:return b.yytext=e(1,2).replace(/\\"/g,'"'),74;case 30:return b.yytext=e(1,2).replace(/\\'/g,"'"),74;case 31:return 79;case 32:return 76;case 33:return 76;case 34:return 77;case 35:return 78;case 36:return 75;case 37:return 69;case 38:return 71;case 39:return 66;case 40:return 66;case 41:return"INVALID";case 42:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]*?(?=(\{\{\{\{\/)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[5],inclusive:!1},raw:{rules:[3,4],inclusive:!1},INITIAL:{rules:[0,1,42],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(8)["default"];b.__esModule=!0;var j=c(6),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.isRootSeen;this.isRootSeen=!0;for(var c=a.body,d=0,i=c.length;i>d;d++){var j=c[d],k=this.accept(j);if(k){var l=e(c,d,b),m=f(c,d,b),n=k.openStandalone&&l,o=k.closeStandalone&&m,p=k.inlineStandalone&&l&&m;k.close&&g(c,d,!0),k.open&&h(c,d,!0),p&&(g(c,d),h(c,d)&&"PartialStatement"===j.type&&(j.indent=/([ \t]+$)/.exec(c[d-1].original)[1])),n&&(g((j.program||j.inverse).body),h(c,d)),o&&(g(c,d),h((j.inverse||j.program).body))}}return a},d.prototype.BlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function e(a){return/^\[.*\]$/.test(a)?a.substr(1,a.length-2):a}function f(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function g(a){return a.replace(/^\{\{~?\!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function h(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g="",h=0,i=b.length;i>h;h++){var j=b[h].part,k=b[h].original!==j;if(d+=(b[h].separator||"")+j,k||".."!==j&&"."!==j&&"this"!==j)e.push(j);else{if(e.length>0)throw new n["default"]("Invalid path: "+d,{loc:c});".."===j&&(f++,g+="../")}}return new this.PathExpression(a,f,e,d,c)}function i(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g;return new this.MustacheStatement(a,b,c,h,e,this.locInfo(f))}function j(a,b,c,d){if(a.path.original!==c){var e={loc:a.path.loc};throw new n["default"](a.path.original+" doesn't match "+c,e)}d=this.locInfo(d);var f=new this.Program([b],null,{},d);return new this.BlockStatement(a.path,a.params,a.hash,f,void 0,{},{},{},d)}function k(a,b,c,d,e,f){if(d&&d.path&&a.path.original!==d.path.original){var g={loc:a.path.loc};throw new n["default"](a.path.original+" doesn't match "+d.path.original,g)}b.blockParams=a.blockParams;var h=void 0,i=void 0;return c&&(c.chain&&(c.program.body[0].closeStrip=d.strip),i=c.strip,h=c.program),e&&(e=h,h=b,b=e),new this.BlockStatement(a.path,a.params,a.hash,b,h,a.strip,i,d&&d.strip,this.locInfo(f))}var l=c(8)["default"];b.__esModule=!0,b.SourceLocation=d,b.id=e,b.stripFlags=f,b.stripComment=g,b.preparePath=h,b.prepareMustache=i,b.prepareRawBlock=j,b.prepareBlock=k;var m=c(11),n=l(m)},function(a,b,c){"use strict";function d(a,b,c){if(f.isArray(a)){for(var d=[],e=0,g=a.length;g>e;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}b.__esModule=!0;var f=c(12),g=void 0;try{}catch(h){}g||(g=function(a,b,c,d){this.src="",d&&this.add(d)},g.prototype={add:function(a){f.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){f.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add(["  ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;c>b;b++)a(this.source[b])},empty:function(){var a=void 0===arguments[0]?this.currentLocation||{start:{}}:arguments[0];return new g(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof g?a:(a=d(a,this,b),new g(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=[];for(var c in a)if(a.hasOwnProperty(c)){var e=d(a[c],this);"undefined"!==e&&b.push([this.quotedString(c),":",e])
}var f=this.generateList(b);return f.prepend("{"),f.add("}"),f},generateList:function(a,b){for(var c=this.empty(b),e=0,f=a.length;f>e;e++)e&&c.add(","),c.add(d(a[e],this,b));return c},generateArray:function(a,b){var c=this.generateList(a,b);return c.prepend("["),c.add("]"),c}},b["default"]=e,a.exports=b["default"]}])});;
//! moment.js
//! version : 2.10.3
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function(){"use strict";function a(){return Dc.apply(null,arguments)}function b(a){Dc=a}function c(a){return"[object Array]"===Object.prototype.toString.call(a)}function d(a){return a instanceof Date||"[object Date]"===Object.prototype.toString.call(a)}function e(a,b){var c,d=[];for(c=0;c<a.length;++c)d.push(b(a[c],c));return d}function f(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function g(a,b){for(var c in b)f(b,c)&&(a[c]=b[c]);return f(b,"toString")&&(a.toString=b.toString),f(b,"valueOf")&&(a.valueOf=b.valueOf),a}function h(a,b,c,d){return za(a,b,c,d,!0).utc()}function i(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1}}function j(a){return null==a._pf&&(a._pf=i()),a._pf}function k(a){if(null==a._isValid){var b=j(a);a._isValid=!isNaN(a._d.getTime())&&b.overflow<0&&!b.empty&&!b.invalidMonth&&!b.nullInput&&!b.invalidFormat&&!b.userInvalidated,a._strict&&(a._isValid=a._isValid&&0===b.charsLeftOver&&0===b.unusedTokens.length&&void 0===b.bigHour)}return a._isValid}function l(a){var b=h(0/0);return null!=a?g(j(b),a):j(b).userInvalidated=!0,b}function m(a,b){var c,d,e;if("undefined"!=typeof b._isAMomentObject&&(a._isAMomentObject=b._isAMomentObject),"undefined"!=typeof b._i&&(a._i=b._i),"undefined"!=typeof b._f&&(a._f=b._f),"undefined"!=typeof b._l&&(a._l=b._l),"undefined"!=typeof b._strict&&(a._strict=b._strict),"undefined"!=typeof b._tzm&&(a._tzm=b._tzm),"undefined"!=typeof b._isUTC&&(a._isUTC=b._isUTC),"undefined"!=typeof b._offset&&(a._offset=b._offset),"undefined"!=typeof b._pf&&(a._pf=j(b)),"undefined"!=typeof b._locale&&(a._locale=b._locale),Fc.length>0)for(c in Fc)d=Fc[c],e=b[d],"undefined"!=typeof e&&(a[d]=e);return a}function n(b){m(this,b),this._d=new Date(+b._d),Gc===!1&&(Gc=!0,a.updateOffset(this),Gc=!1)}function o(a){return a instanceof n||null!=a&&null!=a._isAMomentObject}function p(a){var b=+a,c=0;return 0!==b&&isFinite(b)&&(c=b>=0?Math.floor(b):Math.ceil(b)),c}function q(a,b,c){var d,e=Math.min(a.length,b.length),f=Math.abs(a.length-b.length),g=0;for(d=0;e>d;d++)(c&&a[d]!==b[d]||!c&&p(a[d])!==p(b[d]))&&g++;return g+f}function r(){}function s(a){return a?a.toLowerCase().replace("_","-"):a}function t(a){for(var b,c,d,e,f=0;f<a.length;){for(e=s(a[f]).split("-"),b=e.length,c=s(a[f+1]),c=c?c.split("-"):null;b>0;){if(d=u(e.slice(0,b).join("-")))return d;if(c&&c.length>=b&&q(e,c,!0)>=b-1)break;b--}f++}return null}function u(a){var b=null;if(!Hc[a]&&"undefined"!=typeof module&&module&&module.exports)try{b=Ec._abbr,require("./locale/"+a),v(b)}catch(c){}return Hc[a]}function v(a,b){var c;return a&&(c="undefined"==typeof b?x(a):w(a,b),c&&(Ec=c)),Ec._abbr}function w(a,b){return null!==b?(b.abbr=a,Hc[a]||(Hc[a]=new r),Hc[a].set(b),v(a),Hc[a]):(delete Hc[a],null)}function x(a){var b;if(a&&a._locale&&a._locale._abbr&&(a=a._locale._abbr),!a)return Ec;if(!c(a)){if(b=u(a))return b;a=[a]}return t(a)}function y(a,b){var c=a.toLowerCase();Ic[c]=Ic[c+"s"]=Ic[b]=a}function z(a){return"string"==typeof a?Ic[a]||Ic[a.toLowerCase()]:void 0}function A(a){var b,c,d={};for(c in a)f(a,c)&&(b=z(c),b&&(d[b]=a[c]));return d}function B(b,c){return function(d){return null!=d?(D(this,b,d),a.updateOffset(this,c),this):C(this,b)}}function C(a,b){return a._d["get"+(a._isUTC?"UTC":"")+b]()}function D(a,b,c){return a._d["set"+(a._isUTC?"UTC":"")+b](c)}function E(a,b){var c;if("object"==typeof a)for(c in a)this.set(c,a[c]);else if(a=z(a),"function"==typeof this[a])return this[a](b);return this}function F(a,b,c){for(var d=""+Math.abs(a),e=a>=0;d.length<b;)d="0"+d;return(e?c?"+":"":"-")+d}function G(a,b,c,d){var e=d;"string"==typeof d&&(e=function(){return this[d]()}),a&&(Mc[a]=e),b&&(Mc[b[0]]=function(){return F(e.apply(this,arguments),b[1],b[2])}),c&&(Mc[c]=function(){return this.localeData().ordinal(e.apply(this,arguments),a)})}function H(a){return a.match(/\[[\s\S]/)?a.replace(/^\[|\]$/g,""):a.replace(/\\/g,"")}function I(a){var b,c,d=a.match(Jc);for(b=0,c=d.length;c>b;b++)Mc[d[b]]?d[b]=Mc[d[b]]:d[b]=H(d[b]);return function(e){var f="";for(b=0;c>b;b++)f+=d[b]instanceof Function?d[b].call(e,a):d[b];return f}}function J(a,b){return a.isValid()?(b=K(b,a.localeData()),Lc[b]||(Lc[b]=I(b)),Lc[b](a)):a.localeData().invalidDate()}function K(a,b){function c(a){return b.longDateFormat(a)||a}var d=5;for(Kc.lastIndex=0;d>=0&&Kc.test(a);)a=a.replace(Kc,c),Kc.lastIndex=0,d-=1;return a}function L(a,b,c){_c[a]="function"==typeof b?b:function(a){return a&&c?c:b}}function M(a,b){return f(_c,a)?_c[a](b._strict,b._locale):new RegExp(N(a))}function N(a){return a.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(a,b,c,d,e){return b||c||d||e}).replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function O(a,b){var c,d=b;for("string"==typeof a&&(a=[a]),"number"==typeof b&&(d=function(a,c){c[b]=p(a)}),c=0;c<a.length;c++)ad[a[c]]=d}function P(a,b){O(a,function(a,c,d,e){d._w=d._w||{},b(a,d._w,d,e)})}function Q(a,b,c){null!=b&&f(ad,a)&&ad[a](b,c._a,c,a)}function R(a,b){return new Date(Date.UTC(a,b+1,0)).getUTCDate()}function S(a){return this._months[a.month()]}function T(a){return this._monthsShort[a.month()]}function U(a,b,c){var d,e,f;for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),d=0;12>d;d++){if(e=h([2e3,d]),c&&!this._longMonthsParse[d]&&(this._longMonthsParse[d]=new RegExp("^"+this.months(e,"").replace(".","")+"$","i"),this._shortMonthsParse[d]=new RegExp("^"+this.monthsShort(e,"").replace(".","")+"$","i")),c||this._monthsParse[d]||(f="^"+this.months(e,"")+"|^"+this.monthsShort(e,""),this._monthsParse[d]=new RegExp(f.replace(".",""),"i")),c&&"MMMM"===b&&this._longMonthsParse[d].test(a))return d;if(c&&"MMM"===b&&this._shortMonthsParse[d].test(a))return d;if(!c&&this._monthsParse[d].test(a))return d}}function V(a,b){var c;return"string"==typeof b&&(b=a.localeData().monthsParse(b),"number"!=typeof b)?a:(c=Math.min(a.date(),R(a.year(),b)),a._d["set"+(a._isUTC?"UTC":"")+"Month"](b,c),a)}function W(b){return null!=b?(V(this,b),a.updateOffset(this,!0),this):C(this,"Month")}function X(){return R(this.year(),this.month())}function Y(a){var b,c=a._a;return c&&-2===j(a).overflow&&(b=c[cd]<0||c[cd]>11?cd:c[dd]<1||c[dd]>R(c[bd],c[cd])?dd:c[ed]<0||c[ed]>24||24===c[ed]&&(0!==c[fd]||0!==c[gd]||0!==c[hd])?ed:c[fd]<0||c[fd]>59?fd:c[gd]<0||c[gd]>59?gd:c[hd]<0||c[hd]>999?hd:-1,j(a)._overflowDayOfYear&&(bd>b||b>dd)&&(b=dd),j(a).overflow=b),a}function Z(b){a.suppressDeprecationWarnings===!1&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+b)}function $(a,b){var c=!0,d=a+"\n"+(new Error).stack;return g(function(){return c&&(Z(d),c=!1),b.apply(this,arguments)},b)}function _(a,b){kd[a]||(Z(b),kd[a]=!0)}function aa(a){var b,c,d=a._i,e=ld.exec(d);if(e){for(j(a).iso=!0,b=0,c=md.length;c>b;b++)if(md[b][1].exec(d)){a._f=md[b][0]+(e[6]||" ");break}for(b=0,c=nd.length;c>b;b++)if(nd[b][1].exec(d)){a._f+=nd[b][0];break}d.match(Yc)&&(a._f+="Z"),ta(a)}else a._isValid=!1}function ba(b){var c=od.exec(b._i);return null!==c?void(b._d=new Date(+c[1])):(aa(b),void(b._isValid===!1&&(delete b._isValid,a.createFromInputFallback(b))))}function ca(a,b,c,d,e,f,g){var h=new Date(a,b,c,d,e,f,g);return 1970>a&&h.setFullYear(a),h}function da(a){var b=new Date(Date.UTC.apply(null,arguments));return 1970>a&&b.setUTCFullYear(a),b}function ea(a){return fa(a)?366:365}function fa(a){return a%4===0&&a%100!==0||a%400===0}function ga(){return fa(this.year())}function ha(a,b,c){var d,e=c-b,f=c-a.day();return f>e&&(f-=7),e-7>f&&(f+=7),d=Aa(a).add(f,"d"),{week:Math.ceil(d.dayOfYear()/7),year:d.year()}}function ia(a){return ha(a,this._week.dow,this._week.doy).week}function ja(){return this._week.dow}function ka(){return this._week.doy}function la(a){var b=this.localeData().week(this);return null==a?b:this.add(7*(a-b),"d")}function ma(a){var b=ha(this,1,4).week;return null==a?b:this.add(7*(a-b),"d")}function na(a,b,c,d,e){var f,g,h=da(a,0,1).getUTCDay();return h=0===h?7:h,c=null!=c?c:e,f=e-h+(h>d?7:0)-(e>h?7:0),g=7*(b-1)+(c-e)+f+1,{year:g>0?a:a-1,dayOfYear:g>0?g:ea(a-1)+g}}function oa(a){var b=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==a?b:this.add(a-b,"d")}function pa(a,b,c){return null!=a?a:null!=b?b:c}function qa(a){var b=new Date;return a._useUTC?[b.getUTCFullYear(),b.getUTCMonth(),b.getUTCDate()]:[b.getFullYear(),b.getMonth(),b.getDate()]}function ra(a){var b,c,d,e,f=[];if(!a._d){for(d=qa(a),a._w&&null==a._a[dd]&&null==a._a[cd]&&sa(a),a._dayOfYear&&(e=pa(a._a[bd],d[bd]),a._dayOfYear>ea(e)&&(j(a)._overflowDayOfYear=!0),c=da(e,0,a._dayOfYear),a._a[cd]=c.getUTCMonth(),a._a[dd]=c.getUTCDate()),b=0;3>b&&null==a._a[b];++b)a._a[b]=f[b]=d[b];for(;7>b;b++)a._a[b]=f[b]=null==a._a[b]?2===b?1:0:a._a[b];24===a._a[ed]&&0===a._a[fd]&&0===a._a[gd]&&0===a._a[hd]&&(a._nextDay=!0,a._a[ed]=0),a._d=(a._useUTC?da:ca).apply(null,f),null!=a._tzm&&a._d.setUTCMinutes(a._d.getUTCMinutes()-a._tzm),a._nextDay&&(a._a[ed]=24)}}function sa(a){var b,c,d,e,f,g,h;b=a._w,null!=b.GG||null!=b.W||null!=b.E?(f=1,g=4,c=pa(b.GG,a._a[bd],ha(Aa(),1,4).year),d=pa(b.W,1),e=pa(b.E,1)):(f=a._locale._week.dow,g=a._locale._week.doy,c=pa(b.gg,a._a[bd],ha(Aa(),f,g).year),d=pa(b.w,1),null!=b.d?(e=b.d,f>e&&++d):e=null!=b.e?b.e+f:f),h=na(c,d,e,g,f),a._a[bd]=h.year,a._dayOfYear=h.dayOfYear}function ta(b){if(b._f===a.ISO_8601)return void aa(b);b._a=[],j(b).empty=!0;var c,d,e,f,g,h=""+b._i,i=h.length,k=0;for(e=K(b._f,b._locale).match(Jc)||[],c=0;c<e.length;c++)f=e[c],d=(h.match(M(f,b))||[])[0],d&&(g=h.substr(0,h.indexOf(d)),g.length>0&&j(b).unusedInput.push(g),h=h.slice(h.indexOf(d)+d.length),k+=d.length),Mc[f]?(d?j(b).empty=!1:j(b).unusedTokens.push(f),Q(f,d,b)):b._strict&&!d&&j(b).unusedTokens.push(f);j(b).charsLeftOver=i-k,h.length>0&&j(b).unusedInput.push(h),j(b).bigHour===!0&&b._a[ed]<=12&&b._a[ed]>0&&(j(b).bigHour=void 0),b._a[ed]=ua(b._locale,b._a[ed],b._meridiem),ra(b),Y(b)}function ua(a,b,c){var d;return null==c?b:null!=a.meridiemHour?a.meridiemHour(b,c):null!=a.isPM?(d=a.isPM(c),d&&12>b&&(b+=12),d||12!==b||(b=0),b):b}function va(a){var b,c,d,e,f;if(0===a._f.length)return j(a).invalidFormat=!0,void(a._d=new Date(0/0));for(e=0;e<a._f.length;e++)f=0,b=m({},a),null!=a._useUTC&&(b._useUTC=a._useUTC),b._f=a._f[e],ta(b),k(b)&&(f+=j(b).charsLeftOver,f+=10*j(b).unusedTokens.length,j(b).score=f,(null==d||d>f)&&(d=f,c=b));g(a,c||b)}function wa(a){if(!a._d){var b=A(a._i);a._a=[b.year,b.month,b.day||b.date,b.hour,b.minute,b.second,b.millisecond],ra(a)}}function xa(a){var b,e=a._i,f=a._f;return a._locale=a._locale||x(a._l),null===e||void 0===f&&""===e?l({nullInput:!0}):("string"==typeof e&&(a._i=e=a._locale.preparse(e)),o(e)?new n(Y(e)):(c(f)?va(a):f?ta(a):d(e)?a._d=e:ya(a),b=new n(Y(a)),b._nextDay&&(b.add(1,"d"),b._nextDay=void 0),b))}function ya(b){var f=b._i;void 0===f?b._d=new Date:d(f)?b._d=new Date(+f):"string"==typeof f?ba(b):c(f)?(b._a=e(f.slice(0),function(a){return parseInt(a,10)}),ra(b)):"object"==typeof f?wa(b):"number"==typeof f?b._d=new Date(f):a.createFromInputFallback(b)}function za(a,b,c,d,e){var f={};return"boolean"==typeof c&&(d=c,c=void 0),f._isAMomentObject=!0,f._useUTC=f._isUTC=e,f._l=c,f._i=a,f._f=b,f._strict=d,xa(f)}function Aa(a,b,c,d){return za(a,b,c,d,!1)}function Ba(a,b){var d,e;if(1===b.length&&c(b[0])&&(b=b[0]),!b.length)return Aa();for(d=b[0],e=1;e<b.length;++e)b[e][a](d)&&(d=b[e]);return d}function Ca(){var a=[].slice.call(arguments,0);return Ba("isBefore",a)}function Da(){var a=[].slice.call(arguments,0);return Ba("isAfter",a)}function Ea(a){var b=A(a),c=b.year||0,d=b.quarter||0,e=b.month||0,f=b.week||0,g=b.day||0,h=b.hour||0,i=b.minute||0,j=b.second||0,k=b.millisecond||0;this._milliseconds=+k+1e3*j+6e4*i+36e5*h,this._days=+g+7*f,this._months=+e+3*d+12*c,this._data={},this._locale=x(),this._bubble()}function Fa(a){return a instanceof Ea}function Ga(a,b){G(a,0,0,function(){var a=this.utcOffset(),c="+";return 0>a&&(a=-a,c="-"),c+F(~~(a/60),2)+b+F(~~a%60,2)})}function Ha(a){var b=(a||"").match(Yc)||[],c=b[b.length-1]||[],d=(c+"").match(td)||["-",0,0],e=+(60*d[1])+p(d[2]);return"+"===d[0]?e:-e}function Ia(b,c){var e,f;return c._isUTC?(e=c.clone(),f=(o(b)||d(b)?+b:+Aa(b))-+e,e._d.setTime(+e._d+f),a.updateOffset(e,!1),e):Aa(b).local();return c._isUTC?Aa(b).zone(c._offset||0):Aa(b).local()}function Ja(a){return 15*-Math.round(a._d.getTimezoneOffset()/15)}function Ka(b,c){var d,e=this._offset||0;return null!=b?("string"==typeof b&&(b=Ha(b)),Math.abs(b)<16&&(b=60*b),!this._isUTC&&c&&(d=Ja(this)),this._offset=b,this._isUTC=!0,null!=d&&this.add(d,"m"),e!==b&&(!c||this._changeInProgress?$a(this,Va(b-e,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,a.updateOffset(this,!0),this._changeInProgress=null)),this):this._isUTC?e:Ja(this)}function La(a,b){return null!=a?("string"!=typeof a&&(a=-a),this.utcOffset(a,b),this):-this.utcOffset()}function Ma(a){return this.utcOffset(0,a)}function Na(a){return this._isUTC&&(this.utcOffset(0,a),this._isUTC=!1,a&&this.subtract(Ja(this),"m")),this}function Oa(){return this._tzm?this.utcOffset(this._tzm):"string"==typeof this._i&&this.utcOffset(Ha(this._i)),this}function Pa(a){return a=a?Aa(a).utcOffset():0,(this.utcOffset()-a)%60===0}function Qa(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Ra(){if(this._a){var a=this._isUTC?h(this._a):Aa(this._a);return this.isValid()&&q(this._a,a.toArray())>0}return!1}function Sa(){return!this._isUTC}function Ta(){return this._isUTC}function Ua(){return this._isUTC&&0===this._offset}function Va(a,b){var c,d,e,g=a,h=null;return Fa(a)?g={ms:a._milliseconds,d:a._days,M:a._months}:"number"==typeof a?(g={},b?g[b]=a:g.milliseconds=a):(h=ud.exec(a))?(c="-"===h[1]?-1:1,g={y:0,d:p(h[dd])*c,h:p(h[ed])*c,m:p(h[fd])*c,s:p(h[gd])*c,ms:p(h[hd])*c}):(h=vd.exec(a))?(c="-"===h[1]?-1:1,g={y:Wa(h[2],c),M:Wa(h[3],c),d:Wa(h[4],c),h:Wa(h[5],c),m:Wa(h[6],c),s:Wa(h[7],c),w:Wa(h[8],c)}):null==g?g={}:"object"==typeof g&&("from"in g||"to"in g)&&(e=Ya(Aa(g.from),Aa(g.to)),g={},g.ms=e.milliseconds,g.M=e.months),d=new Ea(g),Fa(a)&&f(a,"_locale")&&(d._locale=a._locale),d}function Wa(a,b){var c=a&&parseFloat(a.replace(",","."));return(isNaN(c)?0:c)*b}function Xa(a,b){var c={milliseconds:0,months:0};return c.months=b.month()-a.month()+12*(b.year()-a.year()),a.clone().add(c.months,"M").isAfter(b)&&--c.months,c.milliseconds=+b-+a.clone().add(c.months,"M"),c}function Ya(a,b){var c;return b=Ia(b,a),a.isBefore(b)?c=Xa(a,b):(c=Xa(b,a),c.milliseconds=-c.milliseconds,c.months=-c.months),c}function Za(a,b){return function(c,d){var e,f;return null===d||isNaN(+d)||(_(b,"moment()."+b+"(period, number) is deprecated. Please use moment()."+b+"(number, period)."),f=c,c=d,d=f),c="string"==typeof c?+c:c,e=Va(c,d),$a(this,e,a),this}}function $a(b,c,d,e){var f=c._milliseconds,g=c._days,h=c._months;e=null==e?!0:e,f&&b._d.setTime(+b._d+f*d),g&&D(b,"Date",C(b,"Date")+g*d),h&&V(b,C(b,"Month")+h*d),e&&a.updateOffset(b,g||h)}function _a(a){var b=a||Aa(),c=Ia(b,this).startOf("day"),d=this.diff(c,"days",!0),e=-6>d?"sameElse":-1>d?"lastWeek":0>d?"lastDay":1>d?"sameDay":2>d?"nextDay":7>d?"nextWeek":"sameElse";return this.format(this.localeData().calendar(e,this,Aa(b)))}function ab(){return new n(this)}function bb(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+this>+a):(c=o(a)?+a:+Aa(a),c<+this.clone().startOf(b))}function cb(a,b){var c;return b=z("undefined"!=typeof b?b:"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+a>+this):(c=o(a)?+a:+Aa(a),+this.clone().endOf(b)<c)}function db(a,b,c){return this.isAfter(a,c)&&this.isBefore(b,c)}function eb(a,b){var c;return b=z(b||"millisecond"),"millisecond"===b?(a=o(a)?a:Aa(a),+this===+a):(c=+Aa(a),+this.clone().startOf(b)<=c&&c<=+this.clone().endOf(b))}function fb(a){return 0>a?Math.ceil(a):Math.floor(a)}function gb(a,b,c){var d,e,f=Ia(a,this),g=6e4*(f.utcOffset()-this.utcOffset());return b=z(b),"year"===b||"month"===b||"quarter"===b?(e=hb(this,f),"quarter"===b?e/=3:"year"===b&&(e/=12)):(d=this-f,e="second"===b?d/1e3:"minute"===b?d/6e4:"hour"===b?d/36e5:"day"===b?(d-g)/864e5:"week"===b?(d-g)/6048e5:d),c?e:fb(e)}function hb(a,b){var c,d,e=12*(b.year()-a.year())+(b.month()-a.month()),f=a.clone().add(e,"months");return 0>b-f?(c=a.clone().add(e-1,"months"),d=(b-f)/(f-c)):(c=a.clone().add(e+1,"months"),d=(b-f)/(c-f)),-(e+d)}function ib(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function jb(){var a=this.clone().utc();return 0<a.year()&&a.year()<=9999?"function"==typeof Date.prototype.toISOString?this.toDate().toISOString():J(a,"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]"):J(a,"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]")}function kb(b){var c=J(this,b||a.defaultFormat);return this.localeData().postformat(c)}function lb(a,b){return this.isValid()?Va({to:this,from:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function mb(a){return this.from(Aa(),a)}function nb(a,b){return this.isValid()?Va({from:this,to:a}).locale(this.locale()).humanize(!b):this.localeData().invalidDate()}function ob(a){return this.to(Aa(),a)}function pb(a){var b;return void 0===a?this._locale._abbr:(b=x(a),null!=b&&(this._locale=b),this)}function qb(){return this._locale}function rb(a){switch(a=z(a)){case"year":this.month(0);case"quarter":case"month":this.date(1);case"week":case"isoWeek":case"day":this.hours(0);case"hour":this.minutes(0);case"minute":this.seconds(0);case"second":this.milliseconds(0)}return"week"===a&&this.weekday(0),"isoWeek"===a&&this.isoWeekday(1),"quarter"===a&&this.month(3*Math.floor(this.month()/3)),this}function sb(a){return a=z(a),void 0===a||"millisecond"===a?this:this.startOf(a).add(1,"isoWeek"===a?"week":a).subtract(1,"ms")}function tb(){return+this._d-6e4*(this._offset||0)}function ub(){return Math.floor(+this/1e3)}function vb(){return this._offset?new Date(+this):this._d}function wb(){var a=this;return[a.year(),a.month(),a.date(),a.hour(),a.minute(),a.second(),a.millisecond()]}function xb(){return k(this)}function yb(){return g({},j(this))}function zb(){return j(this).overflow}function Ab(a,b){G(0,[a,a.length],0,b)}function Bb(a,b,c){return ha(Aa([a,11,31+b-c]),b,c).week}function Cb(a){var b=ha(this,this.localeData()._week.dow,this.localeData()._week.doy).year;return null==a?b:this.add(a-b,"y")}function Db(a){var b=ha(this,1,4).year;return null==a?b:this.add(a-b,"y")}function Eb(){return Bb(this.year(),1,4)}function Fb(){var a=this.localeData()._week;return Bb(this.year(),a.dow,a.doy)}function Gb(a){return null==a?Math.ceil((this.month()+1)/3):this.month(3*(a-1)+this.month()%3)}function Hb(a,b){if("string"==typeof a)if(isNaN(a)){if(a=b.weekdaysParse(a),"number"!=typeof a)return null}else a=parseInt(a,10);return a}function Ib(a){return this._weekdays[a.day()]}function Jb(a){return this._weekdaysShort[a.day()]}function Kb(a){return this._weekdaysMin[a.day()]}function Lb(a){var b,c,d;for(this._weekdaysParse||(this._weekdaysParse=[]),b=0;7>b;b++)if(this._weekdaysParse[b]||(c=Aa([2e3,1]).day(b),d="^"+this.weekdays(c,"")+"|^"+this.weekdaysShort(c,"")+"|^"+this.weekdaysMin(c,""),this._weekdaysParse[b]=new RegExp(d.replace(".",""),"i")),this._weekdaysParse[b].test(a))return b}function Mb(a){var b=this._isUTC?this._d.getUTCDay():this._d.getDay();return null!=a?(a=Hb(a,this.localeData()),this.add(a-b,"d")):b}function Nb(a){var b=(this.day()+7-this.localeData()._week.dow)%7;return null==a?b:this.add(a-b,"d")}function Ob(a){return null==a?this.day()||7:this.day(this.day()%7?a:a-7)}function Pb(a,b){G(a,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),b)})}function Qb(a,b){return b._meridiemParse}function Rb(a){return"p"===(a+"").toLowerCase().charAt(0)}function Sb(a,b,c){return a>11?c?"pm":"PM":c?"am":"AM"}function Tb(a){G(0,[a,3],0,"millisecond")}function Ub(){return this._isUTC?"UTC":""}function Vb(){return this._isUTC?"Coordinated Universal Time":""}function Wb(a){return Aa(1e3*a)}function Xb(){return Aa.apply(null,arguments).parseZone()}function Yb(a,b,c){var d=this._calendar[a];return"function"==typeof d?d.call(b,c):d}function Zb(a){var b=this._longDateFormat[a];return!b&&this._longDateFormat[a.toUpperCase()]&&(b=this._longDateFormat[a.toUpperCase()].replace(/MMMM|MM|DD|dddd/g,function(a){return a.slice(1)}),this._longDateFormat[a]=b),b}function $b(){return this._invalidDate}function _b(a){return this._ordinal.replace("%d",a)}function ac(a){return a}function bc(a,b,c,d){var e=this._relativeTime[c];return"function"==typeof e?e(a,b,c,d):e.replace(/%d/i,a)}function cc(a,b){var c=this._relativeTime[a>0?"future":"past"];return"function"==typeof c?c(b):c.replace(/%s/i,b)}function dc(a){var b,c;for(c in a)b=a[c],"function"==typeof b?this[c]=b:this["_"+c]=b;this._ordinalParseLenient=new RegExp(this._ordinalParse.source+"|"+/\d{1,2}/.source)}function ec(a,b,c,d){var e=x(),f=h().set(d,b);return e[c](f,a)}function fc(a,b,c,d,e){if("number"==typeof a&&(b=a,a=void 0),a=a||"",null!=b)return ec(a,b,c,e);var f,g=[];for(f=0;d>f;f++)g[f]=ec(a,f,c,e);return g}function gc(a,b){return fc(a,b,"months",12,"month")}function hc(a,b){return fc(a,b,"monthsShort",12,"month")}function ic(a,b){return fc(a,b,"weekdays",7,"day")}function jc(a,b){return fc(a,b,"weekdaysShort",7,"day")}function kc(a,b){return fc(a,b,"weekdaysMin",7,"day")}function lc(){var a=this._data;return this._milliseconds=Rd(this._milliseconds),this._days=Rd(this._days),this._months=Rd(this._months),a.milliseconds=Rd(a.milliseconds),a.seconds=Rd(a.seconds),a.minutes=Rd(a.minutes),a.hours=Rd(a.hours),a.months=Rd(a.months),a.years=Rd(a.years),this}function mc(a,b,c,d){var e=Va(b,c);return a._milliseconds+=d*e._milliseconds,a._days+=d*e._days,a._months+=d*e._months,a._bubble()}function nc(a,b){return mc(this,a,b,1)}function oc(a,b){return mc(this,a,b,-1)}function pc(){var a,b,c,d=this._milliseconds,e=this._days,f=this._months,g=this._data,h=0;return g.milliseconds=d%1e3,a=fb(d/1e3),g.seconds=a%60,b=fb(a/60),g.minutes=b%60,c=fb(b/60),g.hours=c%24,e+=fb(c/24),h=fb(qc(e)),e-=fb(rc(h)),f+=fb(e/30),e%=30,h+=fb(f/12),f%=12,g.days=e,g.months=f,g.years=h,this}function qc(a){return 400*a/146097}function rc(a){return 146097*a/400}function sc(a){var b,c,d=this._milliseconds;if(a=z(a),"month"===a||"year"===a)return b=this._days+d/864e5,c=this._months+12*qc(b),"month"===a?c:c/12;switch(b=this._days+Math.round(rc(this._months/12)),a){case"week":return b/7+d/6048e5;case"day":return b+d/864e5;case"hour":return 24*b+d/36e5;case"minute":return 1440*b+d/6e4;case"second":return 86400*b+d/1e3;case"millisecond":return Math.floor(864e5*b)+d;default:throw new Error("Unknown unit "+a)}}function tc(){return this._milliseconds+864e5*this._days+this._months%12*2592e6+31536e6*p(this._months/12)}function uc(a){return function(){return this.as(a)}}function vc(a){return a=z(a),this[a+"s"]()}function wc(a){return function(){return this._data[a]}}function xc(){return fb(this.days()/7)}function yc(a,b,c,d,e){return e.relativeTime(b||1,!!c,a,d)}function zc(a,b,c){var d=Va(a).abs(),e=fe(d.as("s")),f=fe(d.as("m")),g=fe(d.as("h")),h=fe(d.as("d")),i=fe(d.as("M")),j=fe(d.as("y")),k=e<ge.s&&["s",e]||1===f&&["m"]||f<ge.m&&["mm",f]||1===g&&["h"]||g<ge.h&&["hh",g]||1===h&&["d"]||h<ge.d&&["dd",h]||1===i&&["M"]||i<ge.M&&["MM",i]||1===j&&["y"]||["yy",j];return k[2]=b,k[3]=+a>0,k[4]=c,yc.apply(null,k)}function Ac(a,b){return void 0===ge[a]?!1:void 0===b?ge[a]:(ge[a]=b,!0)}function Bc(a){var b=this.localeData(),c=zc(this,!a,b);return a&&(c=b.pastFuture(+this,c)),b.postformat(c)}function Cc(){var a=he(this.years()),b=he(this.months()),c=he(this.days()),d=he(this.hours()),e=he(this.minutes()),f=he(this.seconds()+this.milliseconds()/1e3),g=this.asSeconds();return g?(0>g?"-":"")+"P"+(a?a+"Y":"")+(b?b+"M":"")+(c?c+"D":"")+(d||e||f?"T":"")+(d?d+"H":"")+(e?e+"M":"")+(f?f+"S":""):"P0D"}var Dc,Ec,Fc=a.momentProperties=[],Gc=!1,Hc={},Ic={},Jc=/(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g,Kc=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Lc={},Mc={},Nc=/\d/,Oc=/\d\d/,Pc=/\d{3}/,Qc=/\d{4}/,Rc=/[+-]?\d{6}/,Sc=/\d\d?/,Tc=/\d{1,3}/,Uc=/\d{1,4}/,Vc=/[+-]?\d{1,6}/,Wc=/\d+/,Xc=/[+-]?\d+/,Yc=/Z|[+-]\d\d:?\d\d/gi,Zc=/[+-]?\d+(\.\d{1,3})?/,$c=/[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i,_c={},ad={},bd=0,cd=1,dd=2,ed=3,fd=4,gd=5,hd=6;G("M",["MM",2],"Mo",function(){return this.month()+1}),G("MMM",0,0,function(a){return this.localeData().monthsShort(this,a)}),G("MMMM",0,0,function(a){return this.localeData().months(this,a)}),y("month","M"),L("M",Sc),L("MM",Sc,Oc),L("MMM",$c),L("MMMM",$c),O(["M","MM"],function(a,b){b[cd]=p(a)-1}),O(["MMM","MMMM"],function(a,b,c,d){var e=c._locale.monthsParse(a,d,c._strict);null!=e?b[cd]=e:j(c).invalidMonth=a});var id="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),jd="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),kd={};a.suppressDeprecationWarnings=!1;var ld=/^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/,md=[["YYYYYY-MM-DD",/[+-]\d{6}-\d{2}-\d{2}/],["YYYY-MM-DD",/\d{4}-\d{2}-\d{2}/],["GGGG-[W]WW-E",/\d{4}-W\d{2}-\d/],["GGGG-[W]WW",/\d{4}-W\d{2}/],["YYYY-DDD",/\d{4}-\d{3}/]],nd=[["HH:mm:ss.SSSS",/(T| )\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss",/(T| )\d\d:\d\d:\d\d/],["HH:mm",/(T| )\d\d:\d\d/],["HH",/(T| )\d\d/]],od=/^\/?Date\((\-?\d+)/i;a.createFromInputFallback=$("moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.",function(a){a._d=new Date(a._i+(a._useUTC?" UTC":""))}),G(0,["YY",2],0,function(){return this.year()%100}),G(0,["YYYY",4],0,"year"),G(0,["YYYYY",5],0,"year"),G(0,["YYYYYY",6,!0],0,"year"),y("year","y"),L("Y",Xc),L("YY",Sc,Oc),L("YYYY",Uc,Qc),L("YYYYY",Vc,Rc),L("YYYYYY",Vc,Rc),O(["YYYY","YYYYY","YYYYYY"],bd),O("YY",function(b,c){c[bd]=a.parseTwoDigitYear(b)}),a.parseTwoDigitYear=function(a){return p(a)+(p(a)>68?1900:2e3)};var pd=B("FullYear",!1);G("w",["ww",2],"wo","week"),G("W",["WW",2],"Wo","isoWeek"),y("week","w"),y("isoWeek","W"),L("w",Sc),L("ww",Sc,Oc),L("W",Sc),L("WW",Sc,Oc),P(["w","ww","W","WW"],function(a,b,c,d){b[d.substr(0,1)]=p(a)});var qd={dow:0,doy:6};G("DDD",["DDDD",3],"DDDo","dayOfYear"),y("dayOfYear","DDD"),L("DDD",Tc),L("DDDD",Pc),O(["DDD","DDDD"],function(a,b,c){c._dayOfYear=p(a)}),a.ISO_8601=function(){};var rd=$("moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548",function(){var a=Aa.apply(null,arguments);return this>a?this:a}),sd=$("moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548",function(){var a=Aa.apply(null,arguments);return a>this?this:a});Ga("Z",":"),Ga("ZZ",""),L("Z",Yc),L("ZZ",Yc),O(["Z","ZZ"],function(a,b,c){c._useUTC=!0,c._tzm=Ha(a)});var td=/([\+\-]|\d\d)/gi;a.updateOffset=function(){};var ud=/(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/,vd=/^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/;Va.fn=Ea.prototype;var wd=Za(1,"add"),xd=Za(-1,"subtract");a.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";var yd=$("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(a){return void 0===a?this.localeData():this.locale(a)});G(0,["gg",2],0,function(){return this.weekYear()%100}),G(0,["GG",2],0,function(){return this.isoWeekYear()%100}),Ab("gggg","weekYear"),Ab("ggggg","weekYear"),Ab("GGGG","isoWeekYear"),Ab("GGGGG","isoWeekYear"),y("weekYear","gg"),y("isoWeekYear","GG"),L("G",Xc),L("g",Xc),L("GG",Sc,Oc),L("gg",Sc,Oc),L("GGGG",Uc,Qc),L("gggg",Uc,Qc),L("GGGGG",Vc,Rc),L("ggggg",Vc,Rc),P(["gggg","ggggg","GGGG","GGGGG"],function(a,b,c,d){b[d.substr(0,2)]=p(a)}),P(["gg","GG"],function(b,c,d,e){c[e]=a.parseTwoDigitYear(b)}),G("Q",0,0,"quarter"),y("quarter","Q"),L("Q",Nc),O("Q",function(a,b){b[cd]=3*(p(a)-1)}),G("D",["DD",2],"Do","date"),y("date","D"),L("D",Sc),L("DD",Sc,Oc),L("Do",function(a,b){return a?b._ordinalParse:b._ordinalParseLenient}),O(["D","DD"],dd),O("Do",function(a,b){b[dd]=p(a.match(Sc)[0],10)});var zd=B("Date",!0);G("d",0,"do","day"),G("dd",0,0,function(a){return this.localeData().weekdaysMin(this,a)}),G("ddd",0,0,function(a){return this.localeData().weekdaysShort(this,a)}),G("dddd",0,0,function(a){return this.localeData().weekdays(this,a)}),G("e",0,0,"weekday"),G("E",0,0,"isoWeekday"),y("day","d"),y("weekday","e"),y("isoWeekday","E"),L("d",Sc),L("e",Sc),L("E",Sc),L("dd",$c),L("ddd",$c),L("dddd",$c),P(["dd","ddd","dddd"],function(a,b,c){var d=c._locale.weekdaysParse(a);null!=d?b.d=d:j(c).invalidWeekday=a}),P(["d","e","E"],function(a,b,c,d){b[d]=p(a)});var Ad="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Bd="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Cd="Su_Mo_Tu_We_Th_Fr_Sa".split("_");G("H",["HH",2],0,"hour"),G("h",["hh",2],0,function(){return this.hours()%12||12}),Pb("a",!0),Pb("A",!1),y("hour","h"),L("a",Qb),L("A",Qb),L("H",Sc),L("h",Sc),L("HH",Sc,Oc),L("hh",Sc,Oc),O(["H","HH"],ed),O(["a","A"],function(a,b,c){c._isPm=c._locale.isPM(a),c._meridiem=a}),O(["h","hh"],function(a,b,c){b[ed]=p(a),j(c).bigHour=!0});var Dd=/[ap]\.?m?\.?/i,Ed=B("Hours",!0);G("m",["mm",2],0,"minute"),y("minute","m"),L("m",Sc),L("mm",Sc,Oc),O(["m","mm"],fd);var Fd=B("Minutes",!1);G("s",["ss",2],0,"second"),y("second","s"),L("s",Sc),L("ss",Sc,Oc),O(["s","ss"],gd);var Gd=B("Seconds",!1);G("S",0,0,function(){return~~(this.millisecond()/100)}),G(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),Tb("SSS"),Tb("SSSS"),y("millisecond","ms"),L("S",Tc,Nc),L("SS",Tc,Oc),L("SSS",Tc,Pc),L("SSSS",Wc),O(["S","SS","SSS","SSSS"],function(a,b){b[hd]=p(1e3*("0."+a))});var Hd=B("Milliseconds",!1);G("z",0,0,"zoneAbbr"),G("zz",0,0,"zoneName");var Id=n.prototype;Id.add=wd,Id.calendar=_a,Id.clone=ab,Id.diff=gb,Id.endOf=sb,Id.format=kb,Id.from=lb,Id.fromNow=mb,Id.to=nb,Id.toNow=ob,Id.get=E,Id.invalidAt=zb,Id.isAfter=bb,Id.isBefore=cb,Id.isBetween=db,Id.isSame=eb,Id.isValid=xb,Id.lang=yd,Id.locale=pb,Id.localeData=qb,Id.max=sd,Id.min=rd,Id.parsingFlags=yb,Id.set=E,Id.startOf=rb,Id.subtract=xd,Id.toArray=wb,Id.toDate=vb,Id.toISOString=jb,Id.toJSON=jb,Id.toString=ib,Id.unix=ub,Id.valueOf=tb,Id.year=pd,Id.isLeapYear=ga,Id.weekYear=Cb,Id.isoWeekYear=Db,Id.quarter=Id.quarters=Gb,Id.month=W,Id.daysInMonth=X,Id.week=Id.weeks=la,Id.isoWeek=Id.isoWeeks=ma,Id.weeksInYear=Fb,Id.isoWeeksInYear=Eb,Id.date=zd,Id.day=Id.days=Mb,Id.weekday=Nb,Id.isoWeekday=Ob,Id.dayOfYear=oa,Id.hour=Id.hours=Ed,Id.minute=Id.minutes=Fd,Id.second=Id.seconds=Gd,Id.millisecond=Id.milliseconds=Hd,Id.utcOffset=Ka,Id.utc=Ma,Id.local=Na,Id.parseZone=Oa,Id.hasAlignedHourOffset=Pa,Id.isDST=Qa,Id.isDSTShifted=Ra,Id.isLocal=Sa,Id.isUtcOffset=Ta,Id.isUtc=Ua,Id.isUTC=Ua,Id.zoneAbbr=Ub,Id.zoneName=Vb,Id.dates=$("dates accessor is deprecated. Use date instead.",zd),Id.months=$("months accessor is deprecated. Use month instead",W),Id.years=$("years accessor is deprecated. Use year instead",pd),Id.zone=$("moment().zone is deprecated, use moment().utcOffset instead. https://github.com/moment/moment/issues/1779",La);var Jd=Id,Kd={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},Ld={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY LT",LLLL:"dddd, MMMM D, YYYY LT"},Md="Invalid date",Nd="%d",Od=/\d{1,2}/,Pd={future:"in %s",past:"%s ago",s:"a few seconds",m:"a minute",mm:"%d minutes",h:"an hour",
hh:"%d hours",d:"a day",dd:"%d days",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},Qd=r.prototype;Qd._calendar=Kd,Qd.calendar=Yb,Qd._longDateFormat=Ld,Qd.longDateFormat=Zb,Qd._invalidDate=Md,Qd.invalidDate=$b,Qd._ordinal=Nd,Qd.ordinal=_b,Qd._ordinalParse=Od,Qd.preparse=ac,Qd.postformat=ac,Qd._relativeTime=Pd,Qd.relativeTime=bc,Qd.pastFuture=cc,Qd.set=dc,Qd.months=S,Qd._months=id,Qd.monthsShort=T,Qd._monthsShort=jd,Qd.monthsParse=U,Qd.week=ia,Qd._week=qd,Qd.firstDayOfYear=ka,Qd.firstDayOfWeek=ja,Qd.weekdays=Ib,Qd._weekdays=Ad,Qd.weekdaysMin=Kb,Qd._weekdaysMin=Cd,Qd.weekdaysShort=Jb,Qd._weekdaysShort=Bd,Qd.weekdaysParse=Lb,Qd.isPM=Rb,Qd._meridiemParse=Dd,Qd.meridiem=Sb,v("en",{ordinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(a){var b=a%10,c=1===p(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th";return a+c}}),a.lang=$("moment.lang is deprecated. Use moment.locale instead.",v),a.langData=$("moment.langData is deprecated. Use moment.localeData instead.",x);var Rd=Math.abs,Sd=uc("ms"),Td=uc("s"),Ud=uc("m"),Vd=uc("h"),Wd=uc("d"),Xd=uc("w"),Yd=uc("M"),Zd=uc("y"),$d=wc("milliseconds"),_d=wc("seconds"),ae=wc("minutes"),be=wc("hours"),ce=wc("days"),de=wc("months"),ee=wc("years"),fe=Math.round,ge={s:45,m:45,h:22,d:26,M:11},he=Math.abs,ie=Ea.prototype;ie.abs=lc,ie.add=nc,ie.subtract=oc,ie.as=sc,ie.asMilliseconds=Sd,ie.asSeconds=Td,ie.asMinutes=Ud,ie.asHours=Vd,ie.asDays=Wd,ie.asWeeks=Xd,ie.asMonths=Yd,ie.asYears=Zd,ie.valueOf=tc,ie._bubble=pc,ie.get=vc,ie.milliseconds=$d,ie.seconds=_d,ie.minutes=ae,ie.hours=be,ie.days=ce,ie.weeks=xc,ie.months=de,ie.years=ee,ie.humanize=Bc,ie.toISOString=Cc,ie.toString=Cc,ie.toJSON=Cc,ie.locale=pb,ie.localeData=qb,ie.toIsoString=$("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Cc),ie.lang=yd,G("X",0,0,"unix"),G("x",0,0,"valueOf"),L("x",Xc),L("X",Zc),O("X",function(a,b,c){c._d=new Date(1e3*parseFloat(a,10))}),O("x",function(a,b,c){c._d=new Date(p(a))}),a.version="2.10.3",b(Aa),a.fn=Jd,a.min=Ca,a.max=Da,a.utc=h,a.unix=Wb,a.months=gc,a.isDate=d,a.locale=v,a.invalid=l,a.duration=Va,a.isMoment=o,a.weekdays=ic,a.parseZone=Xb,a.localeData=x,a.isDuration=Fa,a.monthsShort=hc,a.weekdaysMin=kc,a.defineLocale=w,a.weekdaysShort=jc,a.normalizeUnits=z,a.relativeTimeThreshold=Ac;var je=a;return je});;
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c<
f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&&
(j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r=
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length,
t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
"string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/,
q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g,
"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a),
a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value",
m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m=
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue=
j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],
H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),
["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",
/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes",
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b=
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m,
250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",
PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
;
/*! Respond.js v1.4.2: min/max-width media query polyfill
 * Copyright 2014 Scott Jehl
 * Licensed under MIT
 * http://j.mp/respondjs */

/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
(function(w) {
  "use strict";
  w.matchMedia = w.matchMedia || function(doc, undefined) {
    var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, fakeBody = doc.createElement("body"), div = doc.createElement("div");
    div.id = "mq-test-1";
    div.style.cssText = "position:absolute;top:-100em";
    fakeBody.style.background = "none";
    fakeBody.appendChild(div);
    return function(q) {
      div.innerHTML = '&shy;<style media="' + q + '"> #mq-test-1 { width: 42px; }</style>';
      docElem.insertBefore(fakeBody, refNode);
      bool = div.offsetWidth === 42;
      docElem.removeChild(fakeBody);
      return {
        matches: bool,
        media: q
      };
    };
  }(w.document);
})(this);

/*! matchMedia() polyfill addListener/removeListener extension. Author & copyright (c) 2012: Scott Jehl. Dual MIT/BSD license */
(function(w) {
  "use strict";
  if (w.matchMedia && w.matchMedia("all").addListener) {
    return false;
  }
  var localMatchMedia = w.matchMedia, hasMediaQueries = localMatchMedia("only all").matches, isListening = false, timeoutID = 0, queries = [], handleChange = function(evt) {
    w.clearTimeout(timeoutID);
    timeoutID = w.setTimeout(function() {
      for (var i = 0, il = queries.length; i < il; i++) {
        var mql = queries[i].mql, listeners = queries[i].listeners || [], matches = localMatchMedia(mql.media).matches;
        if (matches !== mql.matches) {
          mql.matches = matches;
          for (var j = 0, jl = listeners.length; j < jl; j++) {
            listeners[j].call(w, mql);
          }
        }
      }
    }, 30);
  };
  w.matchMedia = function(media) {
    var mql = localMatchMedia(media), listeners = [], index = 0;
    mql.addListener = function(listener) {
      if (!hasMediaQueries) {
        return;
      }
      if (!isListening) {
        isListening = true;
        w.addEventListener("resize", handleChange, true);
      }
      if (index === 0) {
        index = queries.push({
          mql: mql,
          listeners: listeners
        });
      }
      listeners.push(listener);
    };
    mql.removeListener = function(listener) {
      for (var i = 0, il = listeners.length; i < il; i++) {
        if (listeners[i] === listener) {
          listeners.splice(i, 1);
        }
      }
    };
    return mql;
  };
})(this);

(function(w) {
  "use strict";
  var respond = {};
  w.respond = respond;
  respond.update = function() {};
  var requestQueue = [], xmlHttp = function() {
    var xmlhttpmethod = false;
    try {
      xmlhttpmethod = new w.XMLHttpRequest();
    } catch (e) {
      xmlhttpmethod = new w.ActiveXObject("Microsoft.XMLHTTP");
    }
    return function() {
      return xmlhttpmethod;
    };
  }(), ajax = function(url, callback) {
    var req = xmlHttp();
    if (!req) {
      return;
    }
    req.open("GET", url, true);
    req.onreadystatechange = function() {
      if (req.readyState !== 4 || req.status !== 200 && req.status !== 304) {
        return;
      }
      callback(req.responseText);
    };
    if (req.readyState === 4) {
      return;
    }
    req.send(null);
  }, isUnsupportedMediaQuery = function(query) {
    return query.replace(respond.regex.minmaxwh, "").match(respond.regex.other);
  };
  respond.ajax = ajax;
  respond.queue = requestQueue;
  respond.unsupportedmq = isUnsupportedMediaQuery;
  respond.regex = {
    media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi,
    keyframes: /@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi,
    comments: /\/\*[^*]*\*+([^/][^*]*\*+)*\//gi,
    urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,
    findStyles: /@media *([^\{]+)\{([\S\s]+?)$/,
    only: /(only\s+)?([a-zA-Z]+)\s?/,
    minw: /\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/,
    maxw: /\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/,
    minmaxwh: /\(\s*m(in|ax)\-(height|width)\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/gi,
    other: /\([^\)]*\)/g
  };
  respond.mediaQueriesSupported = w.matchMedia && w.matchMedia("only all") !== null && w.matchMedia("only all").matches;
  if (respond.mediaQueriesSupported) {
    return;
  }
  var doc = w.document, docElem = doc.documentElement, mediastyles = [], rules = [], appendedEls = [], parsedSheets = {}, resizeThrottle = 30, head = doc.getElementsByTagName("head")[0] || docElem, base = doc.getElementsByTagName("base")[0], links = head.getElementsByTagName("link"), lastCall, resizeDefer, eminpx, getEmValue = function() {
    var ret, div = doc.createElement("div"), body = doc.body, originalHTMLFontSize = docElem.style.fontSize, originalBodyFontSize = body && body.style.fontSize, fakeUsed = false;
    div.style.cssText = "position:absolute;font-size:1em;width:1em";
    if (!body) {
      body = fakeUsed = doc.createElement("body");
      body.style.background = "none";
    }
    docElem.style.fontSize = "100%";
    body.style.fontSize = "100%";
    body.appendChild(div);
    if (fakeUsed) {
      docElem.insertBefore(body, docElem.firstChild);
    }
    ret = div.offsetWidth;
    if (fakeUsed) {
      docElem.removeChild(body);
    } else {
      body.removeChild(div);
    }
    docElem.style.fontSize = originalHTMLFontSize;
    if (originalBodyFontSize) {
      body.style.fontSize = originalBodyFontSize;
    }
    ret = eminpx = parseFloat(ret);
    return ret;
  }, applyMedia = function(fromResize) {
    var name = "clientWidth", docElemProp = docElem[name], currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[name] || docElemProp, styleBlocks = {}, lastLink = links[links.length - 1], now = new Date().getTime();
    if (fromResize && lastCall && now - lastCall < resizeThrottle) {
      w.clearTimeout(resizeDefer);
      resizeDefer = w.setTimeout(applyMedia, resizeThrottle);
      return;
    } else {
      lastCall = now;
    }
    for (var i in mediastyles) {
      if (mediastyles.hasOwnProperty(i)) {
        var thisstyle = mediastyles[i], min = thisstyle.minw, max = thisstyle.maxw, minnull = min === null, maxnull = max === null, em = "em";
        if (!!min) {
          min = parseFloat(min) * (min.indexOf(em) > -1 ? eminpx || getEmValue() : 1);
        }
        if (!!max) {
          max = parseFloat(max) * (max.indexOf(em) > -1 ? eminpx || getEmValue() : 1);
        }
        if (!thisstyle.hasquery || (!minnull || !maxnull) && (minnull || currWidth >= min) && (maxnull || currWidth <= max)) {
          if (!styleBlocks[thisstyle.media]) {
            styleBlocks[thisstyle.media] = [];
          }
          styleBlocks[thisstyle.media].push(rules[thisstyle.rules]);
        }
      }
    }
    for (var j in appendedEls) {
      if (appendedEls.hasOwnProperty(j)) {
        if (appendedEls[j] && appendedEls[j].parentNode === head) {
          head.removeChild(appendedEls[j]);
        }
      }
    }
    appendedEls.length = 0;
    for (var k in styleBlocks) {
      if (styleBlocks.hasOwnProperty(k)) {
        var ss = doc.createElement("style"), css = styleBlocks[k].join("\n");
        ss.type = "text/css";
        ss.media = k;
        head.insertBefore(ss, lastLink.nextSibling);
        if (ss.styleSheet) {
          ss.styleSheet.cssText = css;
        } else {
          ss.appendChild(doc.createTextNode(css));
        }
        appendedEls.push(ss);
      }
    }
  }, translate = function(styles, href, media) {
    var qs = styles.replace(respond.regex.comments, "").replace(respond.regex.keyframes, "").match(respond.regex.media), ql = qs && qs.length || 0;
    href = href.substring(0, href.lastIndexOf("/"));
    var repUrls = function(css) {
      return css.replace(respond.regex.urls, "$1" + href + "$2$3");
    }, useMedia = !ql && media;
    if (href.length) {
      href += "/";
    }
    if (useMedia) {
      ql = 1;
    }
    for (var i = 0; i < ql; i++) {
      var fullq, thisq, eachq, eql;
      if (useMedia) {
        fullq = media;
        rules.push(repUrls(styles));
      } else {
        fullq = qs[i].match(respond.regex.findStyles) && RegExp.$1;
        rules.push(RegExp.$2 && repUrls(RegExp.$2));
      }
      eachq = fullq.split(",");
      eql = eachq.length;
      for (var j = 0; j < eql; j++) {
        thisq = eachq[j];
        if (isUnsupportedMediaQuery(thisq)) {
          continue;
        }
        mediastyles.push({
          media: thisq.split("(")[0].match(respond.regex.only) && RegExp.$2 || "all",
          rules: rules.length - 1,
          hasquery: thisq.indexOf("(") > -1,
          minw: thisq.match(respond.regex.minw) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
          maxw: thisq.match(respond.regex.maxw) && parseFloat(RegExp.$1) + (RegExp.$2 || "")
        });
      }
    }
    applyMedia();
  }, makeRequests = function() {
    if (requestQueue.length) {
      var thisRequest = requestQueue.shift();
      ajax(thisRequest.href, function(styles) {
        translate(styles, thisRequest.href, thisRequest.media);
        parsedSheets[thisRequest.href] = true;
        w.setTimeout(function() {
          makeRequests();
        }, 0);
      });
    }
  }, ripCSS = function() {
    for (var i = 0; i < links.length; i++) {
      var sheet = links[i], href = sheet.href, media = sheet.media, isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
      if (!!href && isCSS && !parsedSheets[href]) {
        if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
          translate(sheet.styleSheet.rawCssText, href, media);
          parsedSheets[href] = true;
        } else {
          if (!/^([a-zA-Z:]*\/\/)/.test(href) && !base || href.replace(RegExp.$1, "").split("/")[0] === w.location.host) {
            if (href.substring(0, 2) === "//") {
              href = w.location.protocol + href;
            }
            requestQueue.push({
              href: href,
              media: media
            });
          }
        }
      }
    }
    makeRequests();
  };
  ripCSS();
  respond.update = ripCSS;
  respond.getEmValue = getEmValue;
  function callMedia() {
    applyMedia(true);
  }
  if (w.addEventListener) {
    w.addEventListener("resize", callMedia, false);
  } else if (w.attachEvent) {
    w.attachEvent("onresize", callMedia);
  }
})(this);;
/*! Respond.js v1.4.2: min/max-width media query polyfill
 * Copyright 2014 Scott Jehl
 * Licensed under MIT
 * http://j.mp/respondjs */

/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
(function(w) {
  "use strict";
  w.matchMedia = w.matchMedia || function(doc, undefined) {
    var bool, docElem = doc.documentElement, refNode = docElem.firstElementChild || docElem.firstChild, fakeBody = doc.createElement("body"), div = doc.createElement("div");
    div.id = "mq-test-1";
    div.style.cssText = "position:absolute;top:-100em";
    fakeBody.style.background = "none";
    fakeBody.appendChild(div);
    return function(q) {
      div.innerHTML = '&shy;<style media="' + q + '"> #mq-test-1 { width: 42px; }</style>';
      docElem.insertBefore(fakeBody, refNode);
      bool = div.offsetWidth === 42;
      docElem.removeChild(fakeBody);
      return {
        matches: bool,
        media: q
      };
    };
  }(w.document);
})(this);

(function(w) {
  "use strict";
  var respond = {};
  w.respond = respond;
  respond.update = function() {};
  var requestQueue = [], xmlHttp = function() {
    var xmlhttpmethod = false;
    try {
      xmlhttpmethod = new w.XMLHttpRequest();
    } catch (e) {
      xmlhttpmethod = new w.ActiveXObject("Microsoft.XMLHTTP");
    }
    return function() {
      return xmlhttpmethod;
    };
  }(), ajax = function(url, callback) {
    var req = xmlHttp();
    if (!req) {
      return;
    }
    req.open("GET", url, true);
    req.onreadystatechange = function() {
      if (req.readyState !== 4 || req.status !== 200 && req.status !== 304) {
        return;
      }
      callback(req.responseText);
    };
    if (req.readyState === 4) {
      return;
    }
    req.send(null);
  }, isUnsupportedMediaQuery = function(query) {
    return query.replace(respond.regex.minmaxwh, "").match(respond.regex.other);
  };
  respond.ajax = ajax;
  respond.queue = requestQueue;
  respond.unsupportedmq = isUnsupportedMediaQuery;
  respond.regex = {
    media: /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi,
    keyframes: /@(?:\-(?:o|moz|webkit)\-)?keyframes[^\{]+\{(?:[^\{\}]*\{[^\}\{]*\})+[^\}]*\}/gi,
    comments: /\/\*[^*]*\*+([^/][^*]*\*+)*\//gi,
    urls: /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,
    findStyles: /@media *([^\{]+)\{([\S\s]+?)$/,
    only: /(only\s+)?([a-zA-Z]+)\s?/,
    minw: /\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/,
    maxw: /\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/,
    minmaxwh: /\(\s*m(in|ax)\-(height|width)\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/gi,
    other: /\([^\)]*\)/g
  };
  respond.mediaQueriesSupported = w.matchMedia && w.matchMedia("only all") !== null && w.matchMedia("only all").matches;
  if (respond.mediaQueriesSupported) {
    return;
  }
  var doc = w.document, docElem = doc.documentElement, mediastyles = [], rules = [], appendedEls = [], parsedSheets = {}, resizeThrottle = 30, head = doc.getElementsByTagName("head")[0] || docElem, base = doc.getElementsByTagName("base")[0], links = head.getElementsByTagName("link"), lastCall, resizeDefer, eminpx, getEmValue = function() {
    var ret, div = doc.createElement("div"), body = doc.body, originalHTMLFontSize = docElem.style.fontSize, originalBodyFontSize = body && body.style.fontSize, fakeUsed = false;
    div.style.cssText = "position:absolute;font-size:1em;width:1em";
    if (!body) {
      body = fakeUsed = doc.createElement("body");
      body.style.background = "none";
    }
    docElem.style.fontSize = "100%";
    body.style.fontSize = "100%";
    body.appendChild(div);
    if (fakeUsed) {
      docElem.insertBefore(body, docElem.firstChild);
    }
    ret = div.offsetWidth;
    if (fakeUsed) {
      docElem.removeChild(body);
    } else {
      body.removeChild(div);
    }
    docElem.style.fontSize = originalHTMLFontSize;
    if (originalBodyFontSize) {
      body.style.fontSize = originalBodyFontSize;
    }
    ret = eminpx = parseFloat(ret);
    return ret;
  }, applyMedia = function(fromResize) {
    var name = "clientWidth", docElemProp = docElem[name], currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[name] || docElemProp, styleBlocks = {}, lastLink = links[links.length - 1], now = new Date().getTime();
    if (fromResize && lastCall && now - lastCall < resizeThrottle) {
      w.clearTimeout(resizeDefer);
      resizeDefer = w.setTimeout(applyMedia, resizeThrottle);
      return;
    } else {
      lastCall = now;
    }
    for (var i in mediastyles) {
      if (mediastyles.hasOwnProperty(i)) {
        var thisstyle = mediastyles[i], min = thisstyle.minw, max = thisstyle.maxw, minnull = min === null, maxnull = max === null, em = "em";
        if (!!min) {
          min = parseFloat(min) * (min.indexOf(em) > -1 ? eminpx || getEmValue() : 1);
        }
        if (!!max) {
          max = parseFloat(max) * (max.indexOf(em) > -1 ? eminpx || getEmValue() : 1);
        }
        if (!thisstyle.hasquery || (!minnull || !maxnull) && (minnull || currWidth >= min) && (maxnull || currWidth <= max)) {
          if (!styleBlocks[thisstyle.media]) {
            styleBlocks[thisstyle.media] = [];
          }
          styleBlocks[thisstyle.media].push(rules[thisstyle.rules]);
        }
      }
    }
    for (var j in appendedEls) {
      if (appendedEls.hasOwnProperty(j)) {
        if (appendedEls[j] && appendedEls[j].parentNode === head) {
          head.removeChild(appendedEls[j]);
        }
      }
    }
    appendedEls.length = 0;
    for (var k in styleBlocks) {
      if (styleBlocks.hasOwnProperty(k)) {
        var ss = doc.createElement("style"), css = styleBlocks[k].join("\n");
        ss.type = "text/css";
        ss.media = k;
        head.insertBefore(ss, lastLink.nextSibling);
        if (ss.styleSheet) {
          ss.styleSheet.cssText = css;
        } else {
          ss.appendChild(doc.createTextNode(css));
        }
        appendedEls.push(ss);
      }
    }
  }, translate = function(styles, href, media) {
    var qs = styles.replace(respond.regex.comments, "").replace(respond.regex.keyframes, "").match(respond.regex.media), ql = qs && qs.length || 0;
    href = href.substring(0, href.lastIndexOf("/"));
    var repUrls = function(css) {
      return css.replace(respond.regex.urls, "$1" + href + "$2$3");
    }, useMedia = !ql && media;
    if (href.length) {
      href += "/";
    }
    if (useMedia) {
      ql = 1;
    }
    for (var i = 0; i < ql; i++) {
      var fullq, thisq, eachq, eql;
      if (useMedia) {
        fullq = media;
        rules.push(repUrls(styles));
      } else {
        fullq = qs[i].match(respond.regex.findStyles) && RegExp.$1;
        rules.push(RegExp.$2 && repUrls(RegExp.$2));
      }
      eachq = fullq.split(",");
      eql = eachq.length;
      for (var j = 0; j < eql; j++) {
        thisq = eachq[j];
        if (isUnsupportedMediaQuery(thisq)) {
          continue;
        }
        mediastyles.push({
          media: thisq.split("(")[0].match(respond.regex.only) && RegExp.$2 || "all",
          rules: rules.length - 1,
          hasquery: thisq.indexOf("(") > -1,
          minw: thisq.match(respond.regex.minw) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
          maxw: thisq.match(respond.regex.maxw) && parseFloat(RegExp.$1) + (RegExp.$2 || "")
        });
      }
    }
    applyMedia();
  }, makeRequests = function() {
    if (requestQueue.length) {
      var thisRequest = requestQueue.shift();
      ajax(thisRequest.href, function(styles) {
        translate(styles, thisRequest.href, thisRequest.media);
        parsedSheets[thisRequest.href] = true;
        w.setTimeout(function() {
          makeRequests();
        }, 0);
      });
    }
  }, ripCSS = function() {
    for (var i = 0; i < links.length; i++) {
      var sheet = links[i], href = sheet.href, media = sheet.media, isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
      if (!!href && isCSS && !parsedSheets[href]) {
        if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
          translate(sheet.styleSheet.rawCssText, href, media);
          parsedSheets[href] = true;
        } else {
          if (!/^([a-zA-Z:]*\/\/)/.test(href) && !base || href.replace(RegExp.$1, "").split("/")[0] === w.location.host) {
            if (href.substring(0, 2) === "//") {
              href = w.location.protocol + href;
            }
            requestQueue.push({
              href: href,
              media: media
            });
          }
        }
      }
    }
    makeRequests();
  };
  ripCSS();
  respond.update = ripCSS;
  respond.getEmValue = getEmValue;
  function callMedia() {
    applyMedia(true);
  }
  if (w.addEventListener) {
    w.addEventListener("resize", callMedia, false);
  } else if (w.attachEvent) {
    w.attachEvent("onresize", callMedia);
  }
})(this);;
/*
Copyright 2014 Igor Vaynberg

Version: 3.5.1 Timestamp: Tue Jul 22 18:58:56 EDT 2014

This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
General Public License version 2 (the "GPL License"). You may choose either license to govern your
use of this software only upon the condition that you accept all of the terms of either the Apache
License or the GPL License.

You may obtain a copy of the Apache License and the GPL License at:

http://www.apache.org/licenses/LICENSE-2.0
http://www.gnu.org/licenses/gpl-2.0.html

Unless required by applicable law or agreed to in writing, software distributed under the Apache License
or the GPL Licesnse is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the Apache License and the GPL License for the specific language governing
permissions and limitations under the Apache License and the GPL License.
*/
!function(a){"undefined"==typeof a.fn.each2&&a.extend(a.fn,{each2:function(b){for(var c=a([0]),d=-1,e=this.length;++d<e&&(c.context=c[0]=this[d])&&b.call(c[0],d,c)!==!1;);return this}})}(jQuery),function(a,b){"use strict";function n(b){var c=a(document.createTextNode(""));b.before(c),c.before(b),c.remove()}function o(a){function b(a){return m[a]||a}return a.replace(/[^\u0000-\u007E]/g,b)}function p(a,b){for(var c=0,d=b.length;d>c;c+=1)if(r(a,b[c]))return c;return-1}function q(){var b=a(l);b.appendTo("body");var c={width:b.width()-b[0].clientWidth,height:b.height()-b[0].clientHeight};return b.remove(),c}function r(a,c){return a===c?!0:a===b||c===b?!1:null===a||null===c?!1:a.constructor===String?a+""==c+"":c.constructor===String?c+""==a+"":!1}function s(b,c){var d,e,f;if(null===b||b.length<1)return[];for(d=b.split(c),e=0,f=d.length;f>e;e+=1)d[e]=a.trim(d[e]);return d}function t(a){return a.outerWidth(!1)-a.width()}function u(c){var d="keyup-change-value";c.on("keydown",function(){a.data(c,d)===b&&a.data(c,d,c.val())}),c.on("keyup",function(){var e=a.data(c,d);e!==b&&c.val()!==e&&(a.removeData(c,d),c.trigger("keyup-change"))})}function v(c){c.on("mousemove",function(c){var d=i;(d===b||d.x!==c.pageX||d.y!==c.pageY)&&a(c.target).trigger("mousemove-filtered",c)})}function w(a,c,d){d=d||b;var e;return function(){var b=arguments;window.clearTimeout(e),e=window.setTimeout(function(){c.apply(d,b)},a)}}function x(a,b){var c=w(a,function(a){b.trigger("scroll-debounced",a)});b.on("scroll",function(a){p(a.target,b.get())>=0&&c(a)})}function y(a){a[0]!==document.activeElement&&window.setTimeout(function(){var d,b=a[0],c=a.val().length;a.focus();var e=b.offsetWidth>0||b.offsetHeight>0;e&&b===document.activeElement&&(b.setSelectionRange?b.setSelectionRange(c,c):b.createTextRange&&(d=b.createTextRange(),d.collapse(!1),d.select()))},0)}function z(b){b=a(b)[0];var c=0,d=0;if("selectionStart"in b)c=b.selectionStart,d=b.selectionEnd-c;else if("selection"in document){b.focus();var e=document.selection.createRange();d=document.selection.createRange().text.length,e.moveStart("character",-b.value.length),c=e.text.length-d}return{offset:c,length:d}}function A(a){a.preventDefault(),a.stopPropagation()}function B(a){a.preventDefault(),a.stopImmediatePropagation()}function C(b){if(!h){var c=b[0].currentStyle||window.getComputedStyle(b[0],null);h=a(document.createElement("div")).css({position:"absolute",left:"-10000px",top:"-10000px",display:"none",fontSize:c.fontSize,fontFamily:c.fontFamily,fontStyle:c.fontStyle,fontWeight:c.fontWeight,letterSpacing:c.letterSpacing,textTransform:c.textTransform,whiteSpace:"nowrap"}),h.attr("class","select2-sizer"),a("body").append(h)}return h.text(b.val()),h.width()}function D(b,c,d){var e,g,f=[];e=a.trim(b.attr("class")),e&&(e=""+e,a(e.split(/\s+/)).each2(function(){0===this.indexOf("select2-")&&f.push(this)})),e=a.trim(c.attr("class")),e&&(e=""+e,a(e.split(/\s+/)).each2(function(){0!==this.indexOf("select2-")&&(g=d(this),g&&f.push(g))})),b.attr("class",f.join(" "))}function E(a,b,c,d){var e=o(a.toUpperCase()).indexOf(o(b.toUpperCase())),f=b.length;return 0>e?(c.push(d(a)),void 0):(c.push(d(a.substring(0,e))),c.push("<span class='select2-match'>"),c.push(d(a.substring(e,e+f))),c.push("</span>"),c.push(d(a.substring(e+f,a.length))),void 0)}function F(a){var b={"\\":"&#92;","&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#47;"};return String(a).replace(/[&<>"'\/\\]/g,function(a){return b[a]})}function G(c){var d,e=null,f=c.quietMillis||100,g=c.url,h=this;return function(i){window.clearTimeout(d),d=window.setTimeout(function(){var d=c.data,f=g,j=c.transport||a.fn.select2.ajaxDefaults.transport,k={type:c.type||"GET",cache:c.cache||!1,jsonpCallback:c.jsonpCallback||b,dataType:c.dataType||"json"},l=a.extend({},a.fn.select2.ajaxDefaults.params,k);d=d?d.call(h,i.term,i.page,i.context):null,f="function"==typeof f?f.call(h,i.term,i.page,i.context):f,e&&"function"==typeof e.abort&&e.abort(),c.params&&(a.isFunction(c.params)?a.extend(l,c.params.call(h)):a.extend(l,c.params)),a.extend(l,{url:f,dataType:c.dataType,data:d,success:function(a){var b=c.results(a,i.page,i);i.callback(b)},error:function(a,b,c){var d={hasError:!0,jqXHR:a,textStatus:b,errorThrown:c};i.callback(d)}}),e=j.call(h,l)},f)}}function H(b){var d,e,c=b,f=function(a){return""+a.text};a.isArray(c)&&(e=c,c={results:e}),a.isFunction(c)===!1&&(e=c,c=function(){return e});var g=c();return g.text&&(f=g.text,a.isFunction(f)||(d=g.text,f=function(a){return a[d]})),function(b){var g,d=b.term,e={results:[]};return""===d?(b.callback(c()),void 0):(g=function(c,e){var h,i;if(c=c[0],c.children){h={};for(i in c)c.hasOwnProperty(i)&&(h[i]=c[i]);h.children=[],a(c.children).each2(function(a,b){g(b,h.children)}),(h.children.length||b.matcher(d,f(h),c))&&e.push(h)}else b.matcher(d,f(c),c)&&e.push(c)},a(c().results).each2(function(a,b){g(b,e.results)}),b.callback(e),void 0)}}function I(c){var d=a.isFunction(c);return function(e){var f=e.term,g={results:[]},h=d?c(e):c;a.isArray(h)&&(a(h).each(function(){var a=this.text!==b,c=a?this.text:this;(""===f||e.matcher(f,c))&&g.results.push(a?this:{id:this,text:this})}),e.callback(g))}}function J(b,c){if(a.isFunction(b))return!0;if(!b)return!1;if("string"==typeof b)return!0;throw new Error(c+" must be a string, function, or falsy value")}function K(b,c){if(a.isFunction(b)){var d=Array.prototype.slice.call(arguments,2);return b.apply(c,d)}return b}function L(b){var c=0;return a.each(b,function(a,b){b.children?c+=L(b.children):c++}),c}function M(a,c,d,e){var h,i,j,k,l,f=a,g=!1;if(!e.createSearchChoice||!e.tokenSeparators||e.tokenSeparators.length<1)return b;for(;;){for(i=-1,j=0,k=e.tokenSeparators.length;k>j&&(l=e.tokenSeparators[j],i=a.indexOf(l),!(i>=0));j++);if(0>i)break;if(h=a.substring(0,i),a=a.substring(i+l.length),h.length>0&&(h=e.createSearchChoice.call(this,h,c),h!==b&&null!==h&&e.id(h)!==b&&null!==e.id(h))){for(g=!1,j=0,k=c.length;k>j;j++)if(r(e.id(h),e.id(c[j]))){g=!0;break}g||d(h)}}return f!==a?a:void 0}function N(){var b=this;a.each(arguments,function(a,c){b[c].remove(),b[c]=null})}function O(b,c){var d=function(){};return d.prototype=new b,d.prototype.constructor=d,d.prototype.parent=b.prototype,d.prototype=a.extend(d.prototype,c),d}if(window.Select2===b){var c,d,e,f,g,h,j,k,i={x:0,y:0},c={TAB:9,ENTER:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,SHIFT:16,CTRL:17,ALT:18,PAGE_UP:33,PAGE_DOWN:34,HOME:36,END:35,BACKSPACE:8,DELETE:46,isArrow:function(a){switch(a=a.which?a.which:a){case c.LEFT:case c.RIGHT:case c.UP:case c.DOWN:return!0}return!1},isControl:function(a){var b=a.which;switch(b){case c.SHIFT:case c.CTRL:case c.ALT:return!0}return a.metaKey?!0:!1},isFunctionKey:function(a){return a=a.which?a.which:a,a>=112&&123>=a}},l="<div class='select2-measure-scrollbar'></div>",m={"\u24b6":"A","\uff21":"A","\xc0":"A","\xc1":"A","\xc2":"A","\u1ea6":"A","\u1ea4":"A","\u1eaa":"A","\u1ea8":"A","\xc3":"A","\u0100":"A","\u0102":"A","\u1eb0":"A","\u1eae":"A","\u1eb4":"A","\u1eb2":"A","\u0226":"A","\u01e0":"A","\xc4":"A","\u01de":"A","\u1ea2":"A","\xc5":"A","\u01fa":"A","\u01cd":"A","\u0200":"A","\u0202":"A","\u1ea0":"A","\u1eac":"A","\u1eb6":"A","\u1e00":"A","\u0104":"A","\u023a":"A","\u2c6f":"A","\ua732":"AA","\xc6":"AE","\u01fc":"AE","\u01e2":"AE","\ua734":"AO","\ua736":"AU","\ua738":"AV","\ua73a":"AV","\ua73c":"AY","\u24b7":"B","\uff22":"B","\u1e02":"B","\u1e04":"B","\u1e06":"B","\u0243":"B","\u0182":"B","\u0181":"B","\u24b8":"C","\uff23":"C","\u0106":"C","\u0108":"C","\u010a":"C","\u010c":"C","\xc7":"C","\u1e08":"C","\u0187":"C","\u023b":"C","\ua73e":"C","\u24b9":"D","\uff24":"D","\u1e0a":"D","\u010e":"D","\u1e0c":"D","\u1e10":"D","\u1e12":"D","\u1e0e":"D","\u0110":"D","\u018b":"D","\u018a":"D","\u0189":"D","\ua779":"D","\u01f1":"DZ","\u01c4":"DZ","\u01f2":"Dz","\u01c5":"Dz","\u24ba":"E","\uff25":"E","\xc8":"E","\xc9":"E","\xca":"E","\u1ec0":"E","\u1ebe":"E","\u1ec4":"E","\u1ec2":"E","\u1ebc":"E","\u0112":"E","\u1e14":"E","\u1e16":"E","\u0114":"E","\u0116":"E","\xcb":"E","\u1eba":"E","\u011a":"E","\u0204":"E","\u0206":"E","\u1eb8":"E","\u1ec6":"E","\u0228":"E","\u1e1c":"E","\u0118":"E","\u1e18":"E","\u1e1a":"E","\u0190":"E","\u018e":"E","\u24bb":"F","\uff26":"F","\u1e1e":"F","\u0191":"F","\ua77b":"F","\u24bc":"G","\uff27":"G","\u01f4":"G","\u011c":"G","\u1e20":"G","\u011e":"G","\u0120":"G","\u01e6":"G","\u0122":"G","\u01e4":"G","\u0193":"G","\ua7a0":"G","\ua77d":"G","\ua77e":"G","\u24bd":"H","\uff28":"H","\u0124":"H","\u1e22":"H","\u1e26":"H","\u021e":"H","\u1e24":"H","\u1e28":"H","\u1e2a":"H","\u0126":"H","\u2c67":"H","\u2c75":"H","\ua78d":"H","\u24be":"I","\uff29":"I","\xcc":"I","\xcd":"I","\xce":"I","\u0128":"I","\u012a":"I","\u012c":"I","\u0130":"I","\xcf":"I","\u1e2e":"I","\u1ec8":"I","\u01cf":"I","\u0208":"I","\u020a":"I","\u1eca":"I","\u012e":"I","\u1e2c":"I","\u0197":"I","\u24bf":"J","\uff2a":"J","\u0134":"J","\u0248":"J","\u24c0":"K","\uff2b":"K","\u1e30":"K","\u01e8":"K","\u1e32":"K","\u0136":"K","\u1e34":"K","\u0198":"K","\u2c69":"K","\ua740":"K","\ua742":"K","\ua744":"K","\ua7a2":"K","\u24c1":"L","\uff2c":"L","\u013f":"L","\u0139":"L","\u013d":"L","\u1e36":"L","\u1e38":"L","\u013b":"L","\u1e3c":"L","\u1e3a":"L","\u0141":"L","\u023d":"L","\u2c62":"L","\u2c60":"L","\ua748":"L","\ua746":"L","\ua780":"L","\u01c7":"LJ","\u01c8":"Lj","\u24c2":"M","\uff2d":"M","\u1e3e":"M","\u1e40":"M","\u1e42":"M","\u2c6e":"M","\u019c":"M","\u24c3":"N","\uff2e":"N","\u01f8":"N","\u0143":"N","\xd1":"N","\u1e44":"N","\u0147":"N","\u1e46":"N","\u0145":"N","\u1e4a":"N","\u1e48":"N","\u0220":"N","\u019d":"N","\ua790":"N","\ua7a4":"N","\u01ca":"NJ","\u01cb":"Nj","\u24c4":"O","\uff2f":"O","\xd2":"O","\xd3":"O","\xd4":"O","\u1ed2":"O","\u1ed0":"O","\u1ed6":"O","\u1ed4":"O","\xd5":"O","\u1e4c":"O","\u022c":"O","\u1e4e":"O","\u014c":"O","\u1e50":"O","\u1e52":"O","\u014e":"O","\u022e":"O","\u0230":"O","\xd6":"O","\u022a":"O","\u1ece":"O","\u0150":"O","\u01d1":"O","\u020c":"O","\u020e":"O","\u01a0":"O","\u1edc":"O","\u1eda":"O","\u1ee0":"O","\u1ede":"O","\u1ee2":"O","\u1ecc":"O","\u1ed8":"O","\u01ea":"O","\u01ec":"O","\xd8":"O","\u01fe":"O","\u0186":"O","\u019f":"O","\ua74a":"O","\ua74c":"O","\u01a2":"OI","\ua74e":"OO","\u0222":"OU","\u24c5":"P","\uff30":"P","\u1e54":"P","\u1e56":"P","\u01a4":"P","\u2c63":"P","\ua750":"P","\ua752":"P","\ua754":"P","\u24c6":"Q","\uff31":"Q","\ua756":"Q","\ua758":"Q","\u024a":"Q","\u24c7":"R","\uff32":"R","\u0154":"R","\u1e58":"R","\u0158":"R","\u0210":"R","\u0212":"R","\u1e5a":"R","\u1e5c":"R","\u0156":"R","\u1e5e":"R","\u024c":"R","\u2c64":"R","\ua75a":"R","\ua7a6":"R","\ua782":"R","\u24c8":"S","\uff33":"S","\u1e9e":"S","\u015a":"S","\u1e64":"S","\u015c":"S","\u1e60":"S","\u0160":"S","\u1e66":"S","\u1e62":"S","\u1e68":"S","\u0218":"S","\u015e":"S","\u2c7e":"S","\ua7a8":"S","\ua784":"S","\u24c9":"T","\uff34":"T","\u1e6a":"T","\u0164":"T","\u1e6c":"T","\u021a":"T","\u0162":"T","\u1e70":"T","\u1e6e":"T","\u0166":"T","\u01ac":"T","\u01ae":"T","\u023e":"T","\ua786":"T","\ua728":"TZ","\u24ca":"U","\uff35":"U","\xd9":"U","\xda":"U","\xdb":"U","\u0168":"U","\u1e78":"U","\u016a":"U","\u1e7a":"U","\u016c":"U","\xdc":"U","\u01db":"U","\u01d7":"U","\u01d5":"U","\u01d9":"U","\u1ee6":"U","\u016e":"U","\u0170":"U","\u01d3":"U","\u0214":"U","\u0216":"U","\u01af":"U","\u1eea":"U","\u1ee8":"U","\u1eee":"U","\u1eec":"U","\u1ef0":"U","\u1ee4":"U","\u1e72":"U","\u0172":"U","\u1e76":"U","\u1e74":"U","\u0244":"U","\u24cb":"V","\uff36":"V","\u1e7c":"V","\u1e7e":"V","\u01b2":"V","\ua75e":"V","\u0245":"V","\ua760":"VY","\u24cc":"W","\uff37":"W","\u1e80":"W","\u1e82":"W","\u0174":"W","\u1e86":"W","\u1e84":"W","\u1e88":"W","\u2c72":"W","\u24cd":"X","\uff38":"X","\u1e8a":"X","\u1e8c":"X","\u24ce":"Y","\uff39":"Y","\u1ef2":"Y","\xdd":"Y","\u0176":"Y","\u1ef8":"Y","\u0232":"Y","\u1e8e":"Y","\u0178":"Y","\u1ef6":"Y","\u1ef4":"Y","\u01b3":"Y","\u024e":"Y","\u1efe":"Y","\u24cf":"Z","\uff3a":"Z","\u0179":"Z","\u1e90":"Z","\u017b":"Z","\u017d":"Z","\u1e92":"Z","\u1e94":"Z","\u01b5":"Z","\u0224":"Z","\u2c7f":"Z","\u2c6b":"Z","\ua762":"Z","\u24d0":"a","\uff41":"a","\u1e9a":"a","\xe0":"a","\xe1":"a","\xe2":"a","\u1ea7":"a","\u1ea5":"a","\u1eab":"a","\u1ea9":"a","\xe3":"a","\u0101":"a","\u0103":"a","\u1eb1":"a","\u1eaf":"a","\u1eb5":"a","\u1eb3":"a","\u0227":"a","\u01e1":"a","\xe4":"a","\u01df":"a","\u1ea3":"a","\xe5":"a","\u01fb":"a","\u01ce":"a","\u0201":"a","\u0203":"a","\u1ea1":"a","\u1ead":"a","\u1eb7":"a","\u1e01":"a","\u0105":"a","\u2c65":"a","\u0250":"a","\ua733":"aa","\xe6":"ae","\u01fd":"ae","\u01e3":"ae","\ua735":"ao","\ua737":"au","\ua739":"av","\ua73b":"av","\ua73d":"ay","\u24d1":"b","\uff42":"b","\u1e03":"b","\u1e05":"b","\u1e07":"b","\u0180":"b","\u0183":"b","\u0253":"b","\u24d2":"c","\uff43":"c","\u0107":"c","\u0109":"c","\u010b":"c","\u010d":"c","\xe7":"c","\u1e09":"c","\u0188":"c","\u023c":"c","\ua73f":"c","\u2184":"c","\u24d3":"d","\uff44":"d","\u1e0b":"d","\u010f":"d","\u1e0d":"d","\u1e11":"d","\u1e13":"d","\u1e0f":"d","\u0111":"d","\u018c":"d","\u0256":"d","\u0257":"d","\ua77a":"d","\u01f3":"dz","\u01c6":"dz","\u24d4":"e","\uff45":"e","\xe8":"e","\xe9":"e","\xea":"e","\u1ec1":"e","\u1ebf":"e","\u1ec5":"e","\u1ec3":"e","\u1ebd":"e","\u0113":"e","\u1e15":"e","\u1e17":"e","\u0115":"e","\u0117":"e","\xeb":"e","\u1ebb":"e","\u011b":"e","\u0205":"e","\u0207":"e","\u1eb9":"e","\u1ec7":"e","\u0229":"e","\u1e1d":"e","\u0119":"e","\u1e19":"e","\u1e1b":"e","\u0247":"e","\u025b":"e","\u01dd":"e","\u24d5":"f","\uff46":"f","\u1e1f":"f","\u0192":"f","\ua77c":"f","\u24d6":"g","\uff47":"g","\u01f5":"g","\u011d":"g","\u1e21":"g","\u011f":"g","\u0121":"g","\u01e7":"g","\u0123":"g","\u01e5":"g","\u0260":"g","\ua7a1":"g","\u1d79":"g","\ua77f":"g","\u24d7":"h","\uff48":"h","\u0125":"h","\u1e23":"h","\u1e27":"h","\u021f":"h","\u1e25":"h","\u1e29":"h","\u1e2b":"h","\u1e96":"h","\u0127":"h","\u2c68":"h","\u2c76":"h","\u0265":"h","\u0195":"hv","\u24d8":"i","\uff49":"i","\xec":"i","\xed":"i","\xee":"i","\u0129":"i","\u012b":"i","\u012d":"i","\xef":"i","\u1e2f":"i","\u1ec9":"i","\u01d0":"i","\u0209":"i","\u020b":"i","\u1ecb":"i","\u012f":"i","\u1e2d":"i","\u0268":"i","\u0131":"i","\u24d9":"j","\uff4a":"j","\u0135":"j","\u01f0":"j","\u0249":"j","\u24da":"k","\uff4b":"k","\u1e31":"k","\u01e9":"k","\u1e33":"k","\u0137":"k","\u1e35":"k","\u0199":"k","\u2c6a":"k","\ua741":"k","\ua743":"k","\ua745":"k","\ua7a3":"k","\u24db":"l","\uff4c":"l","\u0140":"l","\u013a":"l","\u013e":"l","\u1e37":"l","\u1e39":"l","\u013c":"l","\u1e3d":"l","\u1e3b":"l","\u017f":"l","\u0142":"l","\u019a":"l","\u026b":"l","\u2c61":"l","\ua749":"l","\ua781":"l","\ua747":"l","\u01c9":"lj","\u24dc":"m","\uff4d":"m","\u1e3f":"m","\u1e41":"m","\u1e43":"m","\u0271":"m","\u026f":"m","\u24dd":"n","\uff4e":"n","\u01f9":"n","\u0144":"n","\xf1":"n","\u1e45":"n","\u0148":"n","\u1e47":"n","\u0146":"n","\u1e4b":"n","\u1e49":"n","\u019e":"n","\u0272":"n","\u0149":"n","\ua791":"n","\ua7a5":"n","\u01cc":"nj","\u24de":"o","\uff4f":"o","\xf2":"o","\xf3":"o","\xf4":"o","\u1ed3":"o","\u1ed1":"o","\u1ed7":"o","\u1ed5":"o","\xf5":"o","\u1e4d":"o","\u022d":"o","\u1e4f":"o","\u014d":"o","\u1e51":"o","\u1e53":"o","\u014f":"o","\u022f":"o","\u0231":"o","\xf6":"o","\u022b":"o","\u1ecf":"o","\u0151":"o","\u01d2":"o","\u020d":"o","\u020f":"o","\u01a1":"o","\u1edd":"o","\u1edb":"o","\u1ee1":"o","\u1edf":"o","\u1ee3":"o","\u1ecd":"o","\u1ed9":"o","\u01eb":"o","\u01ed":"o","\xf8":"o","\u01ff":"o","\u0254":"o","\ua74b":"o","\ua74d":"o","\u0275":"o","\u01a3":"oi","\u0223":"ou","\ua74f":"oo","\u24df":"p","\uff50":"p","\u1e55":"p","\u1e57":"p","\u01a5":"p","\u1d7d":"p","\ua751":"p","\ua753":"p","\ua755":"p","\u24e0":"q","\uff51":"q","\u024b":"q","\ua757":"q","\ua759":"q","\u24e1":"r","\uff52":"r","\u0155":"r","\u1e59":"r","\u0159":"r","\u0211":"r","\u0213":"r","\u1e5b":"r","\u1e5d":"r","\u0157":"r","\u1e5f":"r","\u024d":"r","\u027d":"r","\ua75b":"r","\ua7a7":"r","\ua783":"r","\u24e2":"s","\uff53":"s","\xdf":"s","\u015b":"s","\u1e65":"s","\u015d":"s","\u1e61":"s","\u0161":"s","\u1e67":"s","\u1e63":"s","\u1e69":"s","\u0219":"s","\u015f":"s","\u023f":"s","\ua7a9":"s","\ua785":"s","\u1e9b":"s","\u24e3":"t","\uff54":"t","\u1e6b":"t","\u1e97":"t","\u0165":"t","\u1e6d":"t","\u021b":"t","\u0163":"t","\u1e71":"t","\u1e6f":"t","\u0167":"t","\u01ad":"t","\u0288":"t","\u2c66":"t","\ua787":"t","\ua729":"tz","\u24e4":"u","\uff55":"u","\xf9":"u","\xfa":"u","\xfb":"u","\u0169":"u","\u1e79":"u","\u016b":"u","\u1e7b":"u","\u016d":"u","\xfc":"u","\u01dc":"u","\u01d8":"u","\u01d6":"u","\u01da":"u","\u1ee7":"u","\u016f":"u","\u0171":"u","\u01d4":"u","\u0215":"u","\u0217":"u","\u01b0":"u","\u1eeb":"u","\u1ee9":"u","\u1eef":"u","\u1eed":"u","\u1ef1":"u","\u1ee5":"u","\u1e73":"u","\u0173":"u","\u1e77":"u","\u1e75":"u","\u0289":"u","\u24e5":"v","\uff56":"v","\u1e7d":"v","\u1e7f":"v","\u028b":"v","\ua75f":"v","\u028c":"v","\ua761":"vy","\u24e6":"w","\uff57":"w","\u1e81":"w","\u1e83":"w","\u0175":"w","\u1e87":"w","\u1e85":"w","\u1e98":"w","\u1e89":"w","\u2c73":"w","\u24e7":"x","\uff58":"x","\u1e8b":"x","\u1e8d":"x","\u24e8":"y","\uff59":"y","\u1ef3":"y","\xfd":"y","\u0177":"y","\u1ef9":"y","\u0233":"y","\u1e8f":"y","\xff":"y","\u1ef7":"y","\u1e99":"y","\u1ef5":"y","\u01b4":"y","\u024f":"y","\u1eff":"y","\u24e9":"z","\uff5a":"z","\u017a":"z","\u1e91":"z","\u017c":"z","\u017e":"z","\u1e93":"z","\u1e95":"z","\u01b6":"z","\u0225":"z","\u0240":"z","\u2c6c":"z","\ua763":"z","\u0386":"\u0391","\u0388":"\u0395","\u0389":"\u0397","\u038a":"\u0399","\u03aa":"\u0399","\u038c":"\u039f","\u038e":"\u03a5","\u03ab":"\u03a5","\u038f":"\u03a9","\u03ac":"\u03b1","\u03ad":"\u03b5","\u03ae":"\u03b7","\u03af":"\u03b9","\u03ca":"\u03b9","\u0390":"\u03b9","\u03cc":"\u03bf","\u03cd":"\u03c5","\u03cb":"\u03c5","\u03b0":"\u03c5","\u03c9":"\u03c9","\u03c2":"\u03c3"};j=a(document),g=function(){var a=1;return function(){return a++}}(),d=O(Object,{bind:function(a){var b=this;return function(){a.apply(b,arguments)}},init:function(c){var d,e,f=".select2-results";this.opts=c=this.prepareOpts(c),this.id=c.id,c.element.data("select2")!==b&&null!==c.element.data("select2")&&c.element.data("select2").destroy(),this.container=this.createContainer(),this.liveRegion=a("<span>",{role:"status","aria-live":"polite"}).addClass("select2-hidden-accessible").appendTo(document.body),this.containerId="s2id_"+(c.element.attr("id")||"autogen"+g()),this.containerEventName=this.containerId.replace(/([.])/g,"_").replace(/([;&,\-\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g,"\\$1"),this.container.attr("id",this.containerId),this.container.attr("title",c.element.attr("title")),this.body=a("body"),D(this.container,this.opts.element,this.opts.adaptContainerCssClass),this.container.attr("style",c.element.attr("style")),this.container.css(K(c.containerCss,this.opts.element)),this.container.addClass(K(c.containerCssClass,this.opts.element)),this.elementTabIndex=this.opts.element.attr("tabindex"),this.opts.element.data("select2",this).attr("tabindex","-1").before(this.container).on("click.select2",A),this.container.data("select2",this),this.dropdown=this.container.find(".select2-drop"),D(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass),this.dropdown.addClass(K(c.dropdownCssClass,this.opts.element)),this.dropdown.data("select2",this),this.dropdown.on("click",A),this.results=d=this.container.find(f),this.search=e=this.container.find("input.select2-input"),this.queryCount=0,this.resultsPage=0,this.context=null,this.initContainer(),this.container.on("click",A),v(this.results),this.dropdown.on("mousemove-filtered",f,this.bind(this.highlightUnderEvent)),this.dropdown.on("touchstart touchmove touchend",f,this.bind(function(a){this._touchEvent=!0,this.highlightUnderEvent(a)})),this.dropdown.on("touchmove",f,this.bind(this.touchMoved)),this.dropdown.on("touchstart touchend",f,this.bind(this.clearTouchMoved)),this.dropdown.on("click",this.bind(function(){this._touchEvent&&(this._touchEvent=!1,this.selectHighlighted())})),x(80,this.results),this.dropdown.on("scroll-debounced",f,this.bind(this.loadMoreIfNeeded)),a(this.container).on("change",".select2-input",function(a){a.stopPropagation()}),a(this.dropdown).on("change",".select2-input",function(a){a.stopPropagation()}),a.fn.mousewheel&&d.mousewheel(function(a,b,c,e){var f=d.scrollTop();e>0&&0>=f-e?(d.scrollTop(0),A(a)):0>e&&d.get(0).scrollHeight-d.scrollTop()+e<=d.height()&&(d.scrollTop(d.get(0).scrollHeight-d.height()),A(a))}),u(e),e.on("keyup-change input paste",this.bind(this.updateResults)),e.on("focus",function(){e.addClass("select2-focused")}),e.on("blur",function(){e.removeClass("select2-focused")}),this.dropdown.on("mouseup",f,this.bind(function(b){a(b.target).closest(".select2-result-selectable").length>0&&(this.highlightUnderEvent(b),this.selectHighlighted(b))})),this.dropdown.on("click mouseup mousedown touchstart touchend focusin",function(a){a.stopPropagation()}),this.nextSearchTerm=b,a.isFunction(this.opts.initSelection)&&(this.initSelection(),this.monitorSource()),null!==c.maximumInputLength&&this.search.attr("maxlength",c.maximumInputLength);var h=c.element.prop("disabled");h===b&&(h=!1),this.enable(!h);var i=c.element.prop("readonly");i===b&&(i=!1),this.readonly(i),k=k||q(),this.autofocus=c.element.prop("autofocus"),c.element.prop("autofocus",!1),this.autofocus&&this.focus(),this.search.attr("placeholder",c.searchInputPlaceholder)},destroy:function(){var a=this.opts.element,c=a.data("select2"),d=this;this.close(),a.length&&a[0].detachEvent&&a.each(function(){this.detachEvent("onpropertychange",d._sync)}),this.propertyObserver&&(this.propertyObserver.disconnect(),this.propertyObserver=null),this._sync=null,c!==b&&(c.container.remove(),c.liveRegion.remove(),c.dropdown.remove(),a.removeClass("select2-offscreen").removeData("select2").off(".select2").prop("autofocus",this.autofocus||!1),this.elementTabIndex?a.attr({tabindex:this.elementTabIndex}):a.removeAttr("tabindex"),a.show()),N.call(this,"container","liveRegion","dropdown","results","search")},optionToData:function(a){return a.is("option")?{id:a.prop("value"),text:a.text(),element:a.get(),css:a.attr("class"),disabled:a.prop("disabled"),locked:r(a.attr("locked"),"locked")||r(a.data("locked"),!0)}:a.is("optgroup")?{text:a.attr("label"),children:[],element:a.get(),css:a.attr("class")}:void 0},prepareOpts:function(c){var d,e,f,h,i=this;if(d=c.element,"select"===d.get(0).tagName.toLowerCase()&&(this.select=e=c.element),e&&a.each(["id","multiple","ajax","query","createSearchChoice","initSelection","data","tags"],function(){if(this in c)throw new Error("Option '"+this+"' is not allowed for Select2 when attached to a <select> element.")}),c=a.extend({},{populateResults:function(d,e,f){var h,j=this.opts.id,k=this.liveRegion;h=function(d,e,l){var m,n,o,p,q,r,s,t,u,v;d=c.sortResults(d,e,f);var w=[];for(m=0,n=d.length;n>m;m+=1)o=d[m],q=o.disabled===!0,p=!q&&j(o)!==b,r=o.children&&o.children.length>0,s=a("<li></li>"),s.addClass("select2-results-dept-"+l),s.addClass("select2-result"),s.addClass(p?"select2-result-selectable":"select2-result-unselectable"),q&&s.addClass("select2-disabled"),r&&s.addClass("select2-result-with-children"),s.addClass(i.opts.formatResultCssClass(o)),s.attr("role","presentation"),t=a(document.createElement("div")),t.addClass("select2-result-label"),t.attr("id","select2-result-label-"+g()),t.attr("role","option"),v=c.formatResult(o,t,f,i.opts.escapeMarkup),v!==b&&(t.html(v),s.append(t)),r&&(u=a("<ul></ul>"),u.addClass("select2-result-sub"),h(o.children,u,l+1),s.append(u)),s.data("select2-data",o),w.push(s[0]);e.append(w),k.text(c.formatMatches(d.length))},h(e,d,0)}},a.fn.select2.defaults,c),"function"!=typeof c.id&&(f=c.id,c.id=function(a){return a[f]}),a.isArray(c.element.data("select2Tags"))){if("tags"in c)throw"tags specified as both an attribute 'data-select2-tags' and in options of Select2 "+c.element.attr("id");c.tags=c.element.data("select2Tags")}if(e?(c.query=this.bind(function(a){var f,g,h,c={results:[],more:!1},e=a.term;h=function(b,c){var d;b.is("option")?a.matcher(e,b.text(),b)&&c.push(i.optionToData(b)):b.is("optgroup")&&(d=i.optionToData(b),b.children().each2(function(a,b){h(b,d.children)}),d.children.length>0&&c.push(d))},f=d.children(),this.getPlaceholder()!==b&&f.length>0&&(g=this.getPlaceholderOption(),g&&(f=f.not(g))),f.each2(function(a,b){h(b,c.results)}),a.callback(c)}),c.id=function(a){return a.id}):"query"in c||("ajax"in c?(h=c.element.data("ajax-url"),h&&h.length>0&&(c.ajax.url=h),c.query=G.call(c.element,c.ajax)):"data"in c?c.query=H(c.data):"tags"in c&&(c.query=I(c.tags),c.createSearchChoice===b&&(c.createSearchChoice=function(b){return{id:a.trim(b),text:a.trim(b)}}),c.initSelection===b&&(c.initSelection=function(b,d){var e=[];a(s(b.val(),c.separator)).each(function(){var b={id:this,text:this},d=c.tags;a.isFunction(d)&&(d=d()),a(d).each(function(){return r(this.id,b.id)?(b=this,!1):void 0}),e.push(b)}),d(e)}))),"function"!=typeof c.query)throw"query function not defined for Select2 "+c.element.attr("id");if("top"===c.createSearchChoicePosition)c.createSearchChoicePosition=function(a,b){a.unshift(b)};else if("bottom"===c.createSearchChoicePosition)c.createSearchChoicePosition=function(a,b){a.push(b)};else if("function"!=typeof c.createSearchChoicePosition)throw"invalid createSearchChoicePosition option must be 'top', 'bottom' or a custom function";return c},monitorSource:function(){var d,c=this.opts.element,e=this;c.on("change.select2",this.bind(function(){this.opts.element.data("select2-change-triggered")!==!0&&this.initSelection()})),this._sync=this.bind(function(){var a=c.prop("disabled");a===b&&(a=!1),this.enable(!a);var d=c.prop("readonly");d===b&&(d=!1),this.readonly(d),D(this.container,this.opts.element,this.opts.adaptContainerCssClass),this.container.addClass(K(this.opts.containerCssClass,this.opts.element)),D(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass),this.dropdown.addClass(K(this.opts.dropdownCssClass,this.opts.element))}),c.length&&c[0].attachEvent&&c.each(function(){this.attachEvent("onpropertychange",e._sync)}),d=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver,d!==b&&(this.propertyObserver&&(delete this.propertyObserver,this.propertyObserver=null),this.propertyObserver=new d(function(b){a.each(b,e._sync)}),this.propertyObserver.observe(c.get(0),{attributes:!0,subtree:!1}))},triggerSelect:function(b){var c=a.Event("select2-selecting",{val:this.id(b),object:b,choice:b});return this.opts.element.trigger(c),!c.isDefaultPrevented()},triggerChange:function(b){b=b||{},b=a.extend({},b,{type:"change",val:this.val()}),this.opts.element.data("select2-change-triggered",!0),this.opts.element.trigger(b),this.opts.element.data("select2-change-triggered",!1),this.opts.element.click(),this.opts.blurOnChange&&this.opts.element.blur()},isInterfaceEnabled:function(){return this.enabledInterface===!0},enableInterface:function(){var a=this._enabled&&!this._readonly,b=!a;return a===this.enabledInterface?!1:(this.container.toggleClass("select2-container-disabled",b),this.close(),this.enabledInterface=a,!0)},enable:function(a){a===b&&(a=!0),this._enabled!==a&&(this._enabled=a,this.opts.element.prop("disabled",!a),this.enableInterface())},disable:function(){this.enable(!1)},readonly:function(a){a===b&&(a=!1),this._readonly!==a&&(this._readonly=a,this.opts.element.prop("readonly",a),this.enableInterface())},opened:function(){return this.container?this.container.hasClass("select2-dropdown-open"):!1},positionDropdown:function(){var t,u,v,w,x,b=this.dropdown,c=this.container.offset(),d=this.container.outerHeight(!1),e=this.container.outerWidth(!1),f=b.outerHeight(!1),g=a(window),h=g.width(),i=g.height(),j=g.scrollLeft()+h,l=g.scrollTop()+i,m=c.top+d,n=c.left,o=l>=m+f,p=c.top-f>=g.scrollTop(),q=b.outerWidth(!1),r=j>=n+q,s=b.hasClass("select2-drop-above");s?(u=!0,!p&&o&&(v=!0,u=!1)):(u=!1,!o&&p&&(v=!0,u=!0)),v&&(b.hide(),c=this.container.offset(),d=this.container.outerHeight(!1),e=this.container.outerWidth(!1),f=b.outerHeight(!1),j=g.scrollLeft()+h,l=g.scrollTop()+i,m=c.top+d,n=c.left,q=b.outerWidth(!1),r=j>=n+q,b.show(),this.focusSearch()),this.opts.dropdownAutoWidth?(x=a(".select2-results",b)[0],b.addClass("select2-drop-auto-width"),b.css("width",""),q=b.outerWidth(!1)+(x.scrollHeight===x.clientHeight?0:k.width),q>e?e=q:q=e,f=b.outerHeight(!1),r=j>=n+q):this.container.removeClass("select2-drop-auto-width"),"static"!==this.body.css("position")&&(t=this.body.offset(),m-=t.top,n-=t.left),r||(n=c.left+this.container.outerWidth(!1)-q),w={left:n,width:e},u?(w.top=c.top-f,w.bottom="auto",this.container.addClass("select2-drop-above"),b.addClass("select2-drop-above")):(w.top=m,w.bottom="auto",this.container.removeClass("select2-drop-above"),b.removeClass("select2-drop-above")),w=a.extend(w,K(this.opts.dropdownCss,this.opts.element)),b.css(w)},shouldOpen:function(){var b;return this.opened()?!1:this._enabled===!1||this._readonly===!0?!1:(b=a.Event("select2-opening"),this.opts.element.trigger(b),!b.isDefaultPrevented())},clearDropdownAlignmentPreference:function(){this.container.removeClass("select2-drop-above"),this.dropdown.removeClass("select2-drop-above")},open:function(){return this.shouldOpen()?(this.opening(),j.on("mousemove.select2Event",function(a){i.x=a.pageX,i.y=a.pageY}),!0):!1},opening:function(){var f,b=this.containerEventName,c="scroll."+b,d="resize."+b,e="orientationchange."+b;this.container.addClass("select2-dropdown-open").addClass("select2-container-active"),this.clearDropdownAlignmentPreference(),this.dropdown[0]!==this.body.children().last()[0]&&this.dropdown.detach().appendTo(this.body),f=a("#select2-drop-mask"),0==f.length&&(f=a(document.createElement("div")),f.attr("id","select2-drop-mask").attr("class","select2-drop-mask"),f.hide(),f.appendTo(this.body),f.on("mousedown touchstart click",function(b){n(f);var d,c=a("#select2-drop");c.length>0&&(d=c.data("select2"),d.opts.selectOnBlur&&d.selectHighlighted({noFocus:!0}),d.close(),b.preventDefault(),b.stopPropagation())})),this.dropdown.prev()[0]!==f[0]&&this.dropdown.before(f),a("#select2-drop").removeAttr("id"),this.dropdown.attr("id","select2-drop"),f.show(),this.positionDropdown(),this.dropdown.show(),this.positionDropdown(),this.dropdown.addClass("select2-drop-active");var g=this;this.container.parents().add(window).each(function(){a(this).on(d+" "+c+" "+e,function(){g.opened()&&g.positionDropdown()})})},close:function(){if(this.opened()){var b=this.containerEventName,c="scroll."+b,d="resize."+b,e="orientationchange."+b;this.container.parents().add(window).each(function(){a(this).off(c).off(d).off(e)}),this.clearDropdownAlignmentPreference(),a("#select2-drop-mask").hide(),this.dropdown.removeAttr("id"),this.dropdown.hide(),this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active"),this.results.empty(),j.off("mousemove.select2Event"),this.clearSearch(),this.search.removeClass("select2-active"),this.opts.element.trigger(a.Event("select2-close"))}},externalSearch:function(a){this.open(),this.search.val(a),this.updateResults(!1)},clearSearch:function(){},getMaximumSelectionSize:function(){return K(this.opts.maximumSelectionSize,this.opts.element)},ensureHighlightVisible:function(){var c,d,e,f,g,h,i,j,b=this.results;if(d=this.highlight(),!(0>d)){if(0==d)return b.scrollTop(0),void 0;c=this.findHighlightableChoices().find(".select2-result-label"),e=a(c[d]),j=(e.offset()||{}).top||0,f=j+e.outerHeight(!0),d===c.length-1&&(i=b.find("li.select2-more-results"),i.length>0&&(f=i.offset().top+i.outerHeight(!0))),g=b.offset().top+b.outerHeight(!0),f>g&&b.scrollTop(b.scrollTop()+(f-g)),h=j-b.offset().top,0>h&&"none"!=e.css("display")&&b.scrollTop(b.scrollTop()+h)}},findHighlightableChoices:function(){return this.results.find(".select2-result-selectable:not(.select2-disabled):not(.select2-selected)")},moveHighlight:function(b){for(var c=this.findHighlightableChoices(),d=this.highlight();d>-1&&d<c.length;){d+=b;var e=a(c[d]);if(e.hasClass("select2-result-selectable")&&!e.hasClass("select2-disabled")&&!e.hasClass("select2-selected")){this.highlight(d);
break}}},highlight:function(b){var d,e,c=this.findHighlightableChoices();return 0===arguments.length?p(c.filter(".select2-highlighted")[0],c.get()):(b>=c.length&&(b=c.length-1),0>b&&(b=0),this.removeHighlight(),d=a(c[b]),d.addClass("select2-highlighted"),this.search.attr("aria-activedescendant",d.find(".select2-result-label").attr("id")),this.ensureHighlightVisible(),this.liveRegion.text(d.text()),e=d.data("select2-data"),e&&this.opts.element.trigger({type:"select2-highlight",val:this.id(e),choice:e}),void 0)},removeHighlight:function(){this.results.find(".select2-highlighted").removeClass("select2-highlighted")},touchMoved:function(){this._touchMoved=!0},clearTouchMoved:function(){this._touchMoved=!1},countSelectableResults:function(){return this.findHighlightableChoices().length},highlightUnderEvent:function(b){var c=a(b.target).closest(".select2-result-selectable");if(c.length>0&&!c.is(".select2-highlighted")){var d=this.findHighlightableChoices();this.highlight(d.index(c))}else 0==c.length&&this.removeHighlight()},loadMoreIfNeeded:function(){var c,a=this.results,b=a.find("li.select2-more-results"),d=this.resultsPage+1,e=this,f=this.search.val(),g=this.context;0!==b.length&&(c=b.offset().top-a.offset().top-a.height(),c<=this.opts.loadMorePadding&&(b.addClass("select2-active"),this.opts.query({element:this.opts.element,term:f,page:d,context:g,matcher:this.opts.matcher,callback:this.bind(function(c){e.opened()&&(e.opts.populateResults.call(this,a,c.results,{term:f,page:d,context:g}),e.postprocessResults(c,!1,!1),c.more===!0?(b.detach().appendTo(a).text(K(e.opts.formatLoadMore,e.opts.element,d+1)),window.setTimeout(function(){e.loadMoreIfNeeded()},10)):b.remove(),e.positionDropdown(),e.resultsPage=d,e.context=c.context,this.opts.element.trigger({type:"select2-loaded",items:c}))})})))},tokenize:function(){},updateResults:function(c){function m(){d.removeClass("select2-active"),h.positionDropdown(),e.find(".select2-no-results,.select2-selection-limit,.select2-searching").length?h.liveRegion.text(e.text()):h.liveRegion.text(h.opts.formatMatches(e.find(".select2-result-selectable").length))}function n(a){e.html(a),m()}var g,i,l,d=this.search,e=this.results,f=this.opts,h=this,j=d.val(),k=a.data(this.container,"select2-last-term");if((c===!0||!k||!r(j,k))&&(a.data(this.container,"select2-last-term",j),c===!0||this.showSearchInput!==!1&&this.opened())){l=++this.queryCount;var o=this.getMaximumSelectionSize();if(o>=1&&(g=this.data(),a.isArray(g)&&g.length>=o&&J(f.formatSelectionTooBig,"formatSelectionTooBig")))return n("<li class='select2-selection-limit'>"+K(f.formatSelectionTooBig,f.element,o)+"</li>"),void 0;if(d.val().length<f.minimumInputLength)return J(f.formatInputTooShort,"formatInputTooShort")?n("<li class='select2-no-results'>"+K(f.formatInputTooShort,f.element,d.val(),f.minimumInputLength)+"</li>"):n(""),c&&this.showSearch&&this.showSearch(!0),void 0;if(f.maximumInputLength&&d.val().length>f.maximumInputLength)return J(f.formatInputTooLong,"formatInputTooLong")?n("<li class='select2-no-results'>"+K(f.formatInputTooLong,f.element,d.val(),f.maximumInputLength)+"</li>"):n(""),void 0;f.formatSearching&&0===this.findHighlightableChoices().length&&n("<li class='select2-searching'>"+K(f.formatSearching,f.element)+"</li>"),d.addClass("select2-active"),this.removeHighlight(),i=this.tokenize(),i!=b&&null!=i&&d.val(i),this.resultsPage=1,f.query({element:f.element,term:d.val(),page:this.resultsPage,context:null,matcher:f.matcher,callback:this.bind(function(g){var i;if(l==this.queryCount){if(!this.opened())return this.search.removeClass("select2-active"),void 0;if(g.hasError!==b&&J(f.formatAjaxError,"formatAjaxError"))return n("<li class='select2-ajax-error'>"+K(f.formatAjaxError,f.element,g.jqXHR,g.textStatus,g.errorThrown)+"</li>"),void 0;if(this.context=g.context===b?null:g.context,this.opts.createSearchChoice&&""!==d.val()&&(i=this.opts.createSearchChoice.call(h,d.val(),g.results),i!==b&&null!==i&&h.id(i)!==b&&null!==h.id(i)&&0===a(g.results).filter(function(){return r(h.id(this),h.id(i))}).length&&this.opts.createSearchChoicePosition(g.results,i)),0===g.results.length&&J(f.formatNoMatches,"formatNoMatches"))return n("<li class='select2-no-results'>"+K(f.formatNoMatches,f.element,d.val())+"</li>"),void 0;e.empty(),h.opts.populateResults.call(this,e,g.results,{term:d.val(),page:this.resultsPage,context:null}),g.more===!0&&J(f.formatLoadMore,"formatLoadMore")&&(e.append("<li class='select2-more-results'>"+f.escapeMarkup(K(f.formatLoadMore,f.element,this.resultsPage))+"</li>"),window.setTimeout(function(){h.loadMoreIfNeeded()},10)),this.postprocessResults(g,c),m(),this.opts.element.trigger({type:"select2-loaded",items:g})}})})}},cancel:function(){this.close()},blur:function(){this.opts.selectOnBlur&&this.selectHighlighted({noFocus:!0}),this.close(),this.container.removeClass("select2-container-active"),this.search[0]===document.activeElement&&this.search.blur(),this.clearSearch(),this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus")},focusSearch:function(){y(this.search)},selectHighlighted:function(a){if(this._touchMoved)return this.clearTouchMoved(),void 0;var b=this.highlight(),c=this.results.find(".select2-highlighted"),d=c.closest(".select2-result").data("select2-data");d?(this.highlight(b),this.onSelect(d,a)):a&&a.noFocus&&this.close()},getPlaceholder:function(){var a;return this.opts.element.attr("placeholder")||this.opts.element.attr("data-placeholder")||this.opts.element.data("placeholder")||this.opts.placeholder||((a=this.getPlaceholderOption())!==b?a.text():b)},getPlaceholderOption:function(){if(this.select){var c=this.select.children("option").first();if(this.opts.placeholderOption!==b)return"first"===this.opts.placeholderOption&&c||"function"==typeof this.opts.placeholderOption&&this.opts.placeholderOption(this.select);if(""===a.trim(c.text())&&""===c.val())return c}},initContainerWidth:function(){function c(){var c,d,e,f,g,h;if("off"===this.opts.width)return null;if("element"===this.opts.width)return 0===this.opts.element.outerWidth(!1)?"auto":this.opts.element.outerWidth(!1)+"px";if("copy"===this.opts.width||"resolve"===this.opts.width){if(c=this.opts.element.attr("style"),c!==b)for(d=c.split(";"),f=0,g=d.length;g>f;f+=1)if(h=d[f].replace(/\s/g,""),e=h.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i),null!==e&&e.length>=1)return e[1];return"resolve"===this.opts.width?(c=this.opts.element.css("width"),c.indexOf("%")>0?c:0===this.opts.element.outerWidth(!1)?"auto":this.opts.element.outerWidth(!1)+"px"):null}return a.isFunction(this.opts.width)?this.opts.width():this.opts.width}var d=c.call(this);null!==d&&this.container.css("width",d)}}),e=O(d,{createContainer:function(){var b=a(document.createElement("div")).attr({"class":"select2-container"}).html(["<a href='javascript:void(0)' class='select2-choice' tabindex='-1'>","   <span class='select2-chosen'>&#160;</span><abbr class='select2-search-choice-close'></abbr>","   <span class='select2-arrow' role='presentation'><b role='presentation'></b></span>","</a>","<label for='' class='select2-offscreen'></label>","<input class='select2-focusser select2-offscreen' type='text' aria-haspopup='true' role='button' />","<div class='select2-drop select2-display-none'>","   <div class='select2-search'>","       <label for='' class='select2-offscreen'></label>","       <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input' role='combobox' aria-expanded='true'","       aria-autocomplete='list' />","   </div>","   <ul class='select2-results' role='listbox'>","   </ul>","</div>"].join(""));return b},enableInterface:function(){this.parent.enableInterface.apply(this,arguments)&&this.focusser.prop("disabled",!this.isInterfaceEnabled())},opening:function(){var c,d,e;this.opts.minimumResultsForSearch>=0&&this.showSearch(!0),this.parent.opening.apply(this,arguments),this.showSearchInput!==!1&&this.search.val(this.focusser.val()),this.opts.shouldFocusInput(this)&&(this.search.focus(),c=this.search.get(0),c.createTextRange?(d=c.createTextRange(),d.collapse(!1),d.select()):c.setSelectionRange&&(e=this.search.val().length,c.setSelectionRange(e,e))),""===this.search.val()&&this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.search.select()),this.focusser.prop("disabled",!0).val(""),this.updateResults(!0),this.opts.element.trigger(a.Event("select2-open"))},close:function(){this.opened()&&(this.parent.close.apply(this,arguments),this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus())},focus:function(){this.opened()?this.close():(this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus())},isFocused:function(){return this.container.hasClass("select2-container-active")},cancel:function(){this.parent.cancel.apply(this,arguments),this.focusser.prop("disabled",!1),this.opts.shouldFocusInput(this)&&this.focusser.focus()},destroy:function(){a("label[for='"+this.focusser.attr("id")+"']").attr("for",this.opts.element.attr("id")),this.parent.destroy.apply(this,arguments),N.call(this,"selection","focusser")},initContainer:function(){var b,h,d=this.container,e=this.dropdown,f=g();this.opts.minimumResultsForSearch<0?this.showSearch(!1):this.showSearch(!0),this.selection=b=d.find(".select2-choice"),this.focusser=d.find(".select2-focusser"),b.find(".select2-chosen").attr("id","select2-chosen-"+f),this.focusser.attr("aria-labelledby","select2-chosen-"+f),this.results.attr("id","select2-results-"+f),this.search.attr("aria-owns","select2-results-"+f),this.focusser.attr("id","s2id_autogen"+f),h=a("label[for='"+this.opts.element.attr("id")+"']"),this.focusser.prev().text(h.text()).attr("for",this.focusser.attr("id"));var i=this.opts.element.attr("title");this.opts.element.attr("title",i||h.text()),this.focusser.attr("tabindex",this.elementTabIndex),this.search.attr("id",this.focusser.attr("id")+"_search"),this.search.prev().text(a("label[for='"+this.focusser.attr("id")+"']").text()).attr("for",this.search.attr("id")),this.search.on("keydown",this.bind(function(a){if(this.isInterfaceEnabled()&&229!=a.keyCode){if(a.which===c.PAGE_UP||a.which===c.PAGE_DOWN)return A(a),void 0;switch(a.which){case c.UP:case c.DOWN:return this.moveHighlight(a.which===c.UP?-1:1),A(a),void 0;case c.ENTER:return this.selectHighlighted(),A(a),void 0;case c.TAB:return this.selectHighlighted({noFocus:!0}),void 0;case c.ESC:return this.cancel(a),A(a),void 0}}})),this.search.on("blur",this.bind(function(){document.activeElement===this.body.get(0)&&window.setTimeout(this.bind(function(){this.opened()&&this.search.focus()}),0)})),this.focusser.on("keydown",this.bind(function(a){if(this.isInterfaceEnabled()&&a.which!==c.TAB&&!c.isControl(a)&&!c.isFunctionKey(a)&&a.which!==c.ESC){if(this.opts.openOnEnter===!1&&a.which===c.ENTER)return A(a),void 0;if(a.which==c.DOWN||a.which==c.UP||a.which==c.ENTER&&this.opts.openOnEnter){if(a.altKey||a.ctrlKey||a.shiftKey||a.metaKey)return;return this.open(),A(a),void 0}return a.which==c.DELETE||a.which==c.BACKSPACE?(this.opts.allowClear&&this.clear(),A(a),void 0):void 0}})),u(this.focusser),this.focusser.on("keyup-change input",this.bind(function(a){if(this.opts.minimumResultsForSearch>=0){if(a.stopPropagation(),this.opened())return;this.open()}})),b.on("mousedown touchstart","abbr",this.bind(function(a){this.isInterfaceEnabled()&&(this.clear(),B(a),this.close(),this.selection.focus())})),b.on("mousedown touchstart",this.bind(function(c){n(b),this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.opened()?this.close():this.isInterfaceEnabled()&&this.open(),A(c)})),e.on("mousedown touchstart",this.bind(function(){this.opts.shouldFocusInput(this)&&this.search.focus()})),b.on("focus",this.bind(function(a){A(a)})),this.focusser.on("focus",this.bind(function(){this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active")})).on("blur",this.bind(function(){this.opened()||(this.container.removeClass("select2-container-active"),this.opts.element.trigger(a.Event("select2-blur")))})),this.search.on("focus",this.bind(function(){this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active")})),this.initContainerWidth(),this.opts.element.addClass("select2-offscreen"),this.setPlaceholder()},clear:function(b){var c=this.selection.data("select2-data");if(c){var d=a.Event("select2-clearing");if(this.opts.element.trigger(d),d.isDefaultPrevented())return;var e=this.getPlaceholderOption();this.opts.element.val(e?e.val():""),this.selection.find(".select2-chosen").empty(),this.selection.removeData("select2-data"),this.setPlaceholder(),b!==!1&&(this.opts.element.trigger({type:"select2-removed",val:this.id(c),choice:c}),this.triggerChange({removed:c}))}},initSelection:function(){if(this.isPlaceholderOptionSelected())this.updateSelection(null),this.close(),this.setPlaceholder();else{var c=this;this.opts.initSelection.call(null,this.opts.element,function(a){a!==b&&null!==a&&(c.updateSelection(a),c.close(),c.setPlaceholder(),c.nextSearchTerm=c.opts.nextSearchTerm(a,c.search.val()))})}},isPlaceholderOptionSelected:function(){var a;return this.getPlaceholder()===b?!1:(a=this.getPlaceholderOption())!==b&&a.prop("selected")||""===this.opts.element.val()||this.opts.element.val()===b||null===this.opts.element.val()},prepareOpts:function(){var b=this.parent.prepareOpts.apply(this,arguments),c=this;return"select"===b.element.get(0).tagName.toLowerCase()?b.initSelection=function(a,b){var d=a.find("option").filter(function(){return this.selected&&!this.disabled});b(c.optionToData(d))}:"data"in b&&(b.initSelection=b.initSelection||function(c,d){var e=c.val(),f=null;b.query({matcher:function(a,c,d){var g=r(e,b.id(d));return g&&(f=d),g},callback:a.isFunction(d)?function(){d(f)}:a.noop})}),b},getPlaceholder:function(){return this.select&&this.getPlaceholderOption()===b?b:this.parent.getPlaceholder.apply(this,arguments)},setPlaceholder:function(){var a=this.getPlaceholder();if(this.isPlaceholderOptionSelected()&&a!==b){if(this.select&&this.getPlaceholderOption()===b)return;this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(a)),this.selection.addClass("select2-default"),this.container.removeClass("select2-allowclear")}},postprocessResults:function(a,b,c){var d=0,e=this;if(this.findHighlightableChoices().each2(function(a,b){return r(e.id(b.data("select2-data")),e.opts.element.val())?(d=a,!1):void 0}),c!==!1&&(b===!0&&d>=0?this.highlight(d):this.highlight(0)),b===!0){var g=this.opts.minimumResultsForSearch;g>=0&&this.showSearch(L(a.results)>=g)}},showSearch:function(b){this.showSearchInput!==b&&(this.showSearchInput=b,this.dropdown.find(".select2-search").toggleClass("select2-search-hidden",!b),this.dropdown.find(".select2-search").toggleClass("select2-offscreen",!b),a(this.dropdown,this.container).toggleClass("select2-with-searchbox",b))},onSelect:function(a,b){if(this.triggerSelect(a)){var c=this.opts.element.val(),d=this.data();this.opts.element.val(this.id(a)),this.updateSelection(a),this.opts.element.trigger({type:"select2-selected",val:this.id(a),choice:a}),this.nextSearchTerm=this.opts.nextSearchTerm(a,this.search.val()),this.close(),b&&b.noFocus||!this.opts.shouldFocusInput(this)||this.focusser.focus(),r(c,this.id(a))||this.triggerChange({added:a,removed:d})}},updateSelection:function(a){var d,e,c=this.selection.find(".select2-chosen");this.selection.data("select2-data",a),c.empty(),null!==a&&(d=this.opts.formatSelection(a,c,this.opts.escapeMarkup)),d!==b&&c.append(d),e=this.opts.formatSelectionCssClass(a,c),e!==b&&c.addClass(e),this.selection.removeClass("select2-default"),this.opts.allowClear&&this.getPlaceholder()!==b&&this.container.addClass("select2-allowclear")},val:function(){var a,c=!1,d=null,e=this,f=this.data();if(0===arguments.length)return this.opts.element.val();if(a=arguments[0],arguments.length>1&&(c=arguments[1]),this.select)this.select.val(a).find("option").filter(function(){return this.selected}).each2(function(a,b){return d=e.optionToData(b),!1}),this.updateSelection(d),this.setPlaceholder(),c&&this.triggerChange({added:d,removed:f});else{if(!a&&0!==a)return this.clear(c),void 0;if(this.opts.initSelection===b)throw new Error("cannot call val() if initSelection() is not defined");this.opts.element.val(a),this.opts.initSelection(this.opts.element,function(a){e.opts.element.val(a?e.id(a):""),e.updateSelection(a),e.setPlaceholder(),c&&e.triggerChange({added:a,removed:f})})}},clearSearch:function(){this.search.val(""),this.focusser.val("")},data:function(a){var c,d=!1;return 0===arguments.length?(c=this.selection.data("select2-data"),c==b&&(c=null),c):(arguments.length>1&&(d=arguments[1]),a?(c=this.data(),this.opts.element.val(a?this.id(a):""),this.updateSelection(a),d&&this.triggerChange({added:a,removed:c})):this.clear(d),void 0)}}),f=O(d,{createContainer:function(){var b=a(document.createElement("div")).attr({"class":"select2-container select2-container-multi"}).html(["<ul class='select2-choices'>","  <li class='select2-search-field'>","    <label for='' class='select2-offscreen'></label>","    <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>","  </li>","</ul>","<div class='select2-drop select2-drop-multi select2-display-none'>","   <ul class='select2-results'>","   </ul>","</div>"].join(""));return b},prepareOpts:function(){var b=this.parent.prepareOpts.apply(this,arguments),c=this;return"select"===b.element.get(0).tagName.toLowerCase()?b.initSelection=function(a,b){var d=[];a.find("option").filter(function(){return this.selected&&!this.disabled}).each2(function(a,b){d.push(c.optionToData(b))}),b(d)}:"data"in b&&(b.initSelection=b.initSelection||function(c,d){var e=s(c.val(),b.separator),f=[];b.query({matcher:function(c,d,g){var h=a.grep(e,function(a){return r(a,b.id(g))}).length;return h&&f.push(g),h},callback:a.isFunction(d)?function(){for(var a=[],c=0;c<e.length;c++)for(var g=e[c],h=0;h<f.length;h++){var i=f[h];if(r(g,b.id(i))){a.push(i),f.splice(h,1);break}}d(a)}:a.noop})}),b},selectChoice:function(a){var b=this.container.find(".select2-search-choice-focus");b.length&&a&&a[0]==b[0]||(b.length&&this.opts.element.trigger("choice-deselected",b),b.removeClass("select2-search-choice-focus"),a&&a.length&&(this.close(),a.addClass("select2-search-choice-focus"),this.opts.element.trigger("choice-selected",a)))},destroy:function(){a("label[for='"+this.search.attr("id")+"']").attr("for",this.opts.element.attr("id")),this.parent.destroy.apply(this,arguments),N.call(this,"searchContainer","selection")},initContainer:function(){var d,b=".select2-choices";this.searchContainer=this.container.find(".select2-search-field"),this.selection=d=this.container.find(b);var e=this;this.selection.on("click",".select2-search-choice:not(.select2-locked)",function(){e.search[0].focus(),e.selectChoice(a(this))}),this.search.attr("id","s2id_autogen"+g()),this.search.prev().text(a("label[for='"+this.opts.element.attr("id")+"']").text()).attr("for",this.search.attr("id")),this.search.on("input paste",this.bind(function(){this.search.attr("placeholder")&&0==this.search.val().length||this.isInterfaceEnabled()&&(this.opened()||this.open())})),this.search.attr("tabindex",this.elementTabIndex),this.keydowns=0,this.search.on("keydown",this.bind(function(a){if(this.isInterfaceEnabled()){++this.keydowns;var b=d.find(".select2-search-choice-focus"),e=b.prev(".select2-search-choice:not(.select2-locked)"),f=b.next(".select2-search-choice:not(.select2-locked)"),g=z(this.search);if(b.length&&(a.which==c.LEFT||a.which==c.RIGHT||a.which==c.BACKSPACE||a.which==c.DELETE||a.which==c.ENTER)){var h=b;return a.which==c.LEFT&&e.length?h=e:a.which==c.RIGHT?h=f.length?f:null:a.which===c.BACKSPACE?this.unselect(b.first())&&(this.search.width(10),h=e.length?e:f):a.which==c.DELETE?this.unselect(b.first())&&(this.search.width(10),h=f.length?f:null):a.which==c.ENTER&&(h=null),this.selectChoice(h),A(a),h&&h.length||this.open(),void 0}if((a.which===c.BACKSPACE&&1==this.keydowns||a.which==c.LEFT)&&0==g.offset&&!g.length)return this.selectChoice(d.find(".select2-search-choice:not(.select2-locked)").last()),A(a),void 0;if(this.selectChoice(null),this.opened())switch(a.which){case c.UP:case c.DOWN:return this.moveHighlight(a.which===c.UP?-1:1),A(a),void 0;case c.ENTER:return this.selectHighlighted(),A(a),void 0;case c.TAB:return this.selectHighlighted({noFocus:!0}),this.close(),void 0;case c.ESC:return this.cancel(a),A(a),void 0}if(a.which!==c.TAB&&!c.isControl(a)&&!c.isFunctionKey(a)&&a.which!==c.BACKSPACE&&a.which!==c.ESC){if(a.which===c.ENTER){if(this.opts.openOnEnter===!1)return;if(a.altKey||a.ctrlKey||a.shiftKey||a.metaKey)return}this.open(),(a.which===c.PAGE_UP||a.which===c.PAGE_DOWN)&&A(a),a.which===c.ENTER&&A(a)}}})),this.search.on("keyup",this.bind(function(){this.keydowns=0,this.resizeSearch()})),this.search.on("blur",this.bind(function(b){this.container.removeClass("select2-container-active"),this.search.removeClass("select2-focused"),this.selectChoice(null),this.opened()||this.clearSearch(),b.stopImmediatePropagation(),this.opts.element.trigger(a.Event("select2-blur"))})),this.container.on("click",b,this.bind(function(b){this.isInterfaceEnabled()&&(a(b.target).closest(".select2-search-choice").length>0||(this.selectChoice(null),this.clearPlaceholder(),this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.open(),this.focusSearch(),b.preventDefault()))})),this.container.on("focus",b,this.bind(function(){this.isInterfaceEnabled()&&(this.container.hasClass("select2-container-active")||this.opts.element.trigger(a.Event("select2-focus")),this.container.addClass("select2-container-active"),this.dropdown.addClass("select2-drop-active"),this.clearPlaceholder())})),this.initContainerWidth(),this.opts.element.addClass("select2-offscreen"),this.clearSearch()},enableInterface:function(){this.parent.enableInterface.apply(this,arguments)&&this.search.prop("disabled",!this.isInterfaceEnabled())},initSelection:function(){if(""===this.opts.element.val()&&""===this.opts.element.text()&&(this.updateSelection([]),this.close(),this.clearSearch()),this.select||""!==this.opts.element.val()){var c=this;this.opts.initSelection.call(null,this.opts.element,function(a){a!==b&&null!==a&&(c.updateSelection(a),c.close(),c.clearSearch())})}},clearSearch:function(){var a=this.getPlaceholder(),c=this.getMaxSearchWidth();a!==b&&0===this.getVal().length&&this.search.hasClass("select2-focused")===!1?(this.search.val(a).addClass("select2-default"),this.search.width(c>0?c:this.container.css("width"))):this.search.val("").width(10)},clearPlaceholder:function(){this.search.hasClass("select2-default")&&this.search.val("").removeClass("select2-default")},opening:function(){this.clearPlaceholder(),this.resizeSearch(),this.parent.opening.apply(this,arguments),this.focusSearch(),""===this.search.val()&&this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.search.select()),this.updateResults(!0),this.opts.shouldFocusInput(this)&&this.search.focus(),this.opts.element.trigger(a.Event("select2-open"))},close:function(){this.opened()&&this.parent.close.apply(this,arguments)},focus:function(){this.close(),this.search.focus()},isFocused:function(){return this.search.hasClass("select2-focused")},updateSelection:function(b){var c=[],d=[],e=this;a(b).each(function(){p(e.id(this),c)<0&&(c.push(e.id(this)),d.push(this))}),b=d,this.selection.find(".select2-search-choice").remove(),a(b).each(function(){e.addSelectedChoice(this)}),e.postprocessResults()},tokenize:function(){var a=this.search.val();a=this.opts.tokenizer.call(this,a,this.data(),this.bind(this.onSelect),this.opts),null!=a&&a!=b&&(this.search.val(a),a.length>0&&this.open())},onSelect:function(a,c){this.triggerSelect(a)&&""!==a.text&&(this.addSelectedChoice(a),this.opts.element.trigger({type:"selected",val:this.id(a),choice:a}),this.nextSearchTerm=this.opts.nextSearchTerm(a,this.search.val()),this.clearSearch(),this.updateResults(),(this.select||!this.opts.closeOnSelect)&&this.postprocessResults(a,!1,this.opts.closeOnSelect===!0),this.opts.closeOnSelect?(this.close(),this.search.width(10)):this.countSelectableResults()>0?(this.search.width(10),this.resizeSearch(),this.getMaximumSelectionSize()>0&&this.val().length>=this.getMaximumSelectionSize()?this.updateResults(!0):this.nextSearchTerm!=b&&(this.search.val(this.nextSearchTerm),this.updateResults(),this.search.select()),this.positionDropdown()):(this.close(),this.search.width(10)),this.triggerChange({added:a}),c&&c.noFocus||this.focusSearch())},cancel:function(){this.close(),this.focusSearch()},addSelectedChoice:function(c){var j,k,d=!c.locked,e=a("<li class='select2-search-choice'>    <div></div>    <a href='#' class='select2-search-choice-close' tabindex='-1'></a></li>"),f=a("<li class='select2-search-choice select2-locked'><div></div></li>"),g=d?e:f,h=this.id(c),i=this.getVal();j=this.opts.formatSelection(c,g.find("div"),this.opts.escapeMarkup),j!=b&&g.find("div").replaceWith("<div>"+j+"</div>"),k=this.opts.formatSelectionCssClass(c,g.find("div")),k!=b&&g.addClass(k),d&&g.find(".select2-search-choice-close").on("mousedown",A).on("click dblclick",this.bind(function(b){this.isInterfaceEnabled()&&(this.unselect(a(b.target)),this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"),A(b),this.close(),this.focusSearch())})).on("focus",this.bind(function(){this.isInterfaceEnabled()&&(this.container.addClass("select2-container-active"),this.dropdown.addClass("select2-drop-active"))})),g.data("select2-data",c),g.insertBefore(this.searchContainer),i.push(h),this.setVal(i)},unselect:function(b){var d,e,c=this.getVal();if(b=b.closest(".select2-search-choice"),0===b.length)throw"Invalid argument: "+b+". Must be .select2-search-choice";if(d=b.data("select2-data")){var f=a.Event("select2-removing");if(f.val=this.id(d),f.choice=d,this.opts.element.trigger(f),f.isDefaultPrevented())return!1;for(;(e=p(this.id(d),c))>=0;)c.splice(e,1),this.setVal(c),this.select&&this.postprocessResults();return b.remove(),this.opts.element.trigger({type:"select2-removed",val:this.id(d),choice:d}),this.triggerChange({removed:d}),!0}},postprocessResults:function(a,b,c){var d=this.getVal(),e=this.results.find(".select2-result"),f=this.results.find(".select2-result-with-children"),g=this;e.each2(function(a,b){var c=g.id(b.data("select2-data"));p(c,d)>=0&&(b.addClass("select2-selected"),b.find(".select2-result-selectable").addClass("select2-selected"))}),f.each2(function(a,b){b.is(".select2-result-selectable")||0!==b.find(".select2-result-selectable:not(.select2-selected)").length||b.addClass("select2-selected")}),-1==this.highlight()&&c!==!1&&g.highlight(0),!this.opts.createSearchChoice&&!e.filter(".select2-result:not(.select2-selected)").length>0&&(!a||a&&!a.more&&0===this.results.find(".select2-no-results").length)&&J(g.opts.formatNoMatches,"formatNoMatches")&&this.results.append("<li class='select2-no-results'>"+K(g.opts.formatNoMatches,g.opts.element,g.search.val())+"</li>")},getMaxSearchWidth:function(){return this.selection.width()-t(this.search)},resizeSearch:function(){var a,b,c,d,e,f=t(this.search);a=C(this.search)+10,b=this.search.offset().left,c=this.selection.width(),d=this.selection.offset().left,e=c-(b-d)-f,a>e&&(e=c-f),40>e&&(e=c-f),0>=e&&(e=a),this.search.width(Math.floor(e))},getVal:function(){var a;return this.select?(a=this.select.val(),null===a?[]:a):(a=this.opts.element.val(),s(a,this.opts.separator))},setVal:function(b){var c;this.select?this.select.val(b):(c=[],a(b).each(function(){p(this,c)<0&&c.push(this)}),this.opts.element.val(0===c.length?"":c.join(this.opts.separator)))},buildChangeDetails:function(a,b){for(var b=b.slice(0),a=a.slice(0),c=0;c<b.length;c++)for(var d=0;d<a.length;d++)r(this.opts.id(b[c]),this.opts.id(a[d]))&&(b.splice(c,1),c>0&&c--,a.splice(d,1),d--);return{added:b,removed:a}},val:function(c,d){var e,f=this;if(0===arguments.length)return this.getVal();if(e=this.data(),e.length||(e=[]),!c&&0!==c)return this.opts.element.val(""),this.updateSelection([]),this.clearSearch(),d&&this.triggerChange({added:this.data(),removed:e}),void 0;if(this.setVal(c),this.select)this.opts.initSelection(this.select,this.bind(this.updateSelection)),d&&this.triggerChange(this.buildChangeDetails(e,this.data()));else{if(this.opts.initSelection===b)throw new Error("val() cannot be called if initSelection() is not defined");this.opts.initSelection(this.opts.element,function(b){var c=a.map(b,f.id);f.setVal(c),f.updateSelection(b),f.clearSearch(),d&&f.triggerChange(f.buildChangeDetails(e,f.data()))})}this.clearSearch()},onSortStart:function(){if(this.select)throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");this.search.width(0),this.searchContainer.hide()},onSortEnd:function(){var b=[],c=this;this.searchContainer.show(),this.searchContainer.appendTo(this.searchContainer.parent()),this.resizeSearch(),this.selection.find(".select2-search-choice").each(function(){b.push(c.opts.id(a(this).data("select2-data")))}),this.setVal(b),this.triggerChange()},data:function(b,c){var e,f,d=this;return 0===arguments.length?this.selection.children(".select2-search-choice").map(function(){return a(this).data("select2-data")}).get():(f=this.data(),b||(b=[]),e=a.map(b,function(a){return d.opts.id(a)}),this.setVal(e),this.updateSelection(b),this.clearSearch(),c&&this.triggerChange(this.buildChangeDetails(f,this.data())),void 0)}}),a.fn.select2=function(){var d,e,f,g,h,c=Array.prototype.slice.call(arguments,0),i=["val","destroy","opened","open","close","focus","isFocused","container","dropdown","onSortStart","onSortEnd","enable","disable","readonly","positionDropdown","data","search"],j=["opened","isFocused","container","dropdown"],k=["val","data"],l={search:"externalSearch"};return this.each(function(){if(0===c.length||"object"==typeof c[0])d=0===c.length?{}:a.extend({},c[0]),d.element=a(this),"select"===d.element.get(0).tagName.toLowerCase()?h=d.element.prop("multiple"):(h=d.multiple||!1,"tags"in d&&(d.multiple=h=!0)),e=h?new window.Select2["class"].multi:new window.Select2["class"].single,e.init(d);else{if("string"!=typeof c[0])throw"Invalid arguments to select2 plugin: "+c;if(p(c[0],i)<0)throw"Unknown method: "+c[0];if(g=b,e=a(this).data("select2"),e===b)return;if(f=c[0],"container"===f?g=e.container:"dropdown"===f?g=e.dropdown:(l[f]&&(f=l[f]),g=e[f].apply(e,c.slice(1))),p(c[0],j)>=0||p(c[0],k)>=0&&1==c.length)return!1}}),g===b?this:g},a.fn.select2.defaults={width:"copy",loadMorePadding:0,closeOnSelect:!0,openOnEnter:!0,containerCss:{},dropdownCss:{},containerCssClass:"",dropdownCssClass:"",formatResult:function(a,b,c,d){var e=[];return E(a.text,c.term,e,d),e.join("")},formatSelection:function(a,c,d){return a?d(a.text):b},sortResults:function(a){return a},formatResultCssClass:function(a){return a.css},formatSelectionCssClass:function(){return b},minimumResultsForSearch:0,minimumInputLength:0,maximumInputLength:null,maximumSelectionSize:0,id:function(a){return a==b?null:a.id},matcher:function(a,b){return o(""+b).toUpperCase().indexOf(o(""+a).toUpperCase())>=0},separator:",",tokenSeparators:[],tokenizer:M,escapeMarkup:F,blurOnChange:!1,selectOnBlur:!1,adaptContainerCssClass:function(a){return a},adaptDropdownCssClass:function(){return null},nextSearchTerm:function(){return b},searchInputPlaceholder:"",createSearchChoicePosition:"top",shouldFocusInput:function(a){var b="ontouchstart"in window||navigator.msMaxTouchPoints>0;return b?a.opts.minimumResultsForSearch<0?!1:!0:!0}},a.fn.select2.locales=[],a.fn.select2.locales.en={formatMatches:function(a){return 1===a?"One result is available, press enter to select it.":a+" results are available, use up and down arrow keys to navigate."
},formatNoMatches:function(){return"No matches found"},formatAjaxError:function(){return"Loading failed"},formatInputTooShort:function(a,b){var c=b-a.length;return"Please enter "+c+" or more character"+(1==c?"":"s")},formatInputTooLong:function(a,b){var c=a.length-b;return"Please delete "+c+" character"+(1==c?"":"s")},formatSelectionTooBig:function(a){return"You can only select "+a+" item"+(1==a?"":"s")},formatLoadMore:function(){return"Loading more results\u2026"},formatSearching:function(){return"Searching\u2026"}},a.extend(a.fn.select2.defaults,a.fn.select2.locales.en),a.fn.select2.ajaxDefaults={transport:a.ajax,params:{type:"GET",cache:!1,dataType:"json"}},window.Select2={query:{ajax:G,local:H,tags:I},util:{debounce:w,markMatch:E,escapeMarkup:F,stripDiacritics:o},"class":{"abstract":d,single:e,multi:f}}}}(jQuery);;
/**
 * @preserve
 *
 * slippry v1.2.1 - Simple responsive content slider
 * http://slippry.com
 *
 * Author(s): Lukas Jakob Hafner - @saftsaak 
 *
 * Copyright 2013, booncon oy - http://booncon.com
 *
 * Thanks @ http://bxslider.com for the inspiration!
 *
 * Released under the MIT license - http://opensource.org/licenses/MIT
 */

(function ($) {
  "use strict";
  var defaults;

  defaults = {
    // general elements & wrapper
    slippryWrapper: '<div class="sy-box" />', // wrapper to wrap everything, including pager
    slideWrapper: '<div class="sy-slides-wrap" />', // wrapper to wrap sildes & controls
    slideCrop: '<div class="sy-slides-crop" />', //additional wrapper around just the slides
    boxClass: 'sy-list', // class that goes to original element
    elements: 'li', // elments cointaining slide content
    activeClass: 'sy-active', // class for current slide
    fillerClass: 'sy-filler', // class for element that acts as intrinsic placholder
    loadingClass: 'sy-loading',

    // options
    adaptiveHeight: true, // height of the sliders adapts to current slide
    start: 1, // num (starting from 1), random
    loop: true, // first -> last & last -> first arrows
    captionsSrc: 'img', // img, el [img takes caption from alt or title, el from title of slide element]
    captions: 'overlay', // Position: overlay, below, custom, false
    captionsEl: '.sy-caption', // $ selector for captions wrapper
    initSingle: true, // initialise even if there is only one slide
    responsive: true,
    preload: 'visible', // visible, all | resources to wait for until showing slider

    // pager
    pager: true,
    pagerClass: 'sy-pager',

    // controls
    controls: true,
    controlClass: 'sy-controls',
    prevClass: 'sy-prev',
    prevText: 'Previous',
    nextClass: 'sy-next',
    nextText: 'Next',
    hideOnEnd: true,

    // transitions
    transition: 'fade', // fade, horizontal, vertical, kenburns, false
    kenZoom: 120, // max zoom for kenburns (in %)
    slideMargin: 0, // spacing between slides (in %)
    transClass: 'transition', // [Class applied to [element] while a transition is taking place.]
    speed: 800, // time the transition takes (ms)
    easing: 'swing', // easing to use in the animation [(see... [jquery www])]
    continuous: true, // seamless first/ last transistion, only works with loop
    useCSS: true, // true, false -> fallback to js if no browser support

    //slideshow
    auto: true,
    autoDirection: 'next',
    autoHover: true,
    autoHoverDelay: 100,
    autoDelay: 500,
    pause: 4000,

    // callback functions
    onSliderLoad: function () { // when slider loaded
      return this;
    },
    onSlideBefore: function () { // before page transition starts
      return this;
    },
    onSlideAfter: function () {  // after page transition happened
      return this;
    }
  };

  $.fn.slippry = function (options) {
    var slip, el, prepareFiller, getFillerProportions, init, updateCaption, initPager, initControls, ready, transitionDone, whichTransitionEvent,
      initCaptions, updatePager, setFillerProportions, doTransition, updateSlide, updateControls, updatePos, supports, preload, start, elFromSel, doKens;

    // reference to the object calling the function
    el = this;

    // if no elements just stop
    if (el.length === 0) {
      return this;
    }
    // support mutltiple elements
    if (el.length > 1) {
      el.each(function () {
        $(this).slippry(options);
      });
      return this;
    }

    // variable to access the slider settings across the plugin
    slip = {};
    slip.vars = {};

    whichTransitionEvent = function () { // Thanks! http://stackoverflow.com/a/18672988
      var t, div, transitions;
      div = document.createElement('div');
      transitions = {
        'WebkitTransition' : 'webkitTransitionEnd',
        'MozTransition'    : 'transitionend',
        'MSTransition'     : 'msTransitionEnd',
        'OTransition'      : 'oTransitionEnd',
        'transition'       : 'transitionEnd transitionend'
      };
      for (t in transitions) {
        if (div.style[t] !== undefined) {
          return transitions[t];
        }
      }
    };

    supports = (function () {  // Thanks! http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-detect-css-support-in-browsers-with-javascript/
      var div = document.createElement('div'),
        vendors = ['Khtml', 'Ms', 'O', 'Moz', 'Webkit'],
        len = vendors.length;
      return function (prop) {
        if (prop in div.style) {
          return true;
        }
        prop = prop.replace(/^[a-z]/, function (val) {
          return val.toUpperCase();
        });
        while (len--) {
          if (vendors[len] + prop in div.style) {
            return true;
          }
        }
        return false;
      };
    }());

    elFromSel = function (sel, prop) {
      var props, newelement, id, className;
      props = prop.split('.');
      newelement = $(sel);
      id = '';
      className = '';
      $.each(props, function (i, val) {
        if (val.indexOf('#') >= 0) {
          id += val.replace(/^#/, '');
        } else {
          className += val + ' ';
        }
      });
      if (id.length) {
        newelement.attr('id', id);
      }
      if (className.length) {
        newelement.attr('class', $.trim(className));
      }
      return newelement;
    };

    doKens = function () {
      var kenStart, kenTime, animProp, cssProp;
      animProp = {};
      cssProp = {};
      kenStart = 100 - slip.settings.kenZoom;
      cssProp.width = slip.settings.kenZoom + '%';
      if (slip.vars.active.index() % 2 === 0) {
        cssProp.left = kenStart + '%';
        cssProp.top = kenStart + '%';
        animProp.left = '0%';
        animProp.top = '0%';
      } else {
        cssProp.left = '0%';
        cssProp.top = '0%';
        animProp.left = kenStart + '%';
        animProp.top = kenStart + '%';
      }
      kenTime = slip.settings.pause + slip.settings.speed * 2;
      slip.vars.active.css(cssProp);
      slip.vars.active.animate(animProp, {duration: kenTime, easing: slip.settings.easing, queue: false});
    };

    ready = function () {
      if (slip.vars.fresh) {
        slip.vars.slippryWrapper.removeClass(slip.settings.loadingClass);
        slip.vars.fresh = false;
        if (slip.settings.auto) {
          el.startAuto();
        }
        if (!slip.settings.useCSS && slip.settings.transition === 'kenburns') {
          doKens();
        }
        slip.settings.onSliderLoad.call(undefined, slip.vars.active.index());
      } else {
        $('.' + slip.settings.fillerClass, slip.vars.slideWrapper).addClass('ready');
      }
    };

    setFillerProportions = function (width, height) {
      var ratio, p_top, $filler;
      ratio = width / height;
      p_top = 1 / ratio * 100 + '%';  //cool intrinsic trick: http://alistapart.com/article/creating-intrinsic-ratios-for-video
      $filler = $('.' + slip.settings.fillerClass, slip.vars.slideWrapper);
      $filler.css({paddingTop: p_top}); // resizing without the need of js, true responsiveness :)
      ready();
    };

    // gets the aspect ratio of the filler element
    getFillerProportions = function ($slide) {
      var width, height;
      if (($('img', $slide).attr("src") !== undefined)) {
        $("<img />").load(function () {
          width = $slide.width();
          height = $slide.height();
          setFillerProportions(width, height);
        }).attr("src", $('img', $slide).attr("src"));
      } else {
        width = $slide.width();
        height = $slide.height();
        setFillerProportions(width, height);
      }
    };

    // prepares a div to occupy the needed space
    prepareFiller = function () {
      if ($('.' + slip.settings.fillerClass, slip.vars.slideWrapper).length === 0) {
        slip.vars.slideWrapper.append($('<div class="' + slip.settings.fillerClass + '" />'));
      }
      if (slip.settings.adaptiveHeight === true) {  // if the slides shoud alwas adapt to their content
        getFillerProportions($('.' + slip.settings.activeClass, el));  // set the filler height on the active element
      } else {  // otherwise get the highest element
        var $highest, height, loop;
        height = 0;
        loop = 0;
        $(slip.vars.slides).each(function () {
          if ($(this).height() > height) {
            $highest = $(this);
            height = $highest.height();
          }
          loop = loop + 1;
          if (loop === slip.vars.count) {
            if ($highest === undefined) {
              $highest = $($(slip.vars.slides)[0]);
            }
            getFillerProportions($highest);
          }
        });
      }
    };

    updatePager = function () {
      if (slip.settings.pager) {
        $('.' + slip.settings.pagerClass + ' li', slip.vars.slippryWrapper).removeClass(slip.settings.activeClass);
        $($('.' + slip.settings.pagerClass + ' li', slip.vars.slippryWrapper)[slip.vars.active.index()]).addClass(slip.settings.activeClass);
      }
    };

    updateControls = function () {
      if (!slip.settings.loop && slip.settings.hideOnEnd) {
        $('.' + slip.settings.prevClass, slip.vars.slippryWrapper)[slip.vars.first ? 'hide' : 'show']();
        $('.' + slip.settings.nextClass, slip.vars.slippryWrapper)[slip.vars.last ? 'hide' : 'show']();
      }
    };

    updateCaption = function () {
      var caption, wrapper;
      if (slip.settings.captions !== false) {
        if (slip.settings.captionsSrc !== 'img') {
          caption = slip.vars.active.attr('title');
        } else {
          caption = $('img', slip.vars.active).attr('title') !== undefined ? $('img', slip.vars.active).attr('title') : $('img', slip.vars.active).attr('alt');
        }
        if (slip.settings.captions !== 'custom') {
          wrapper = $(slip.settings.captionsEl, slip.vars.slippryWrapper);
        } else {
          wrapper = $(slip.settings.captionsEl);
        }
        if ((caption !== undefined) && (caption !== '')) {
          wrapper.html(caption).show();
        } else {
          wrapper.hide();
        }
      }
    };

    el.startAuto = function () {
      if ((slip.vars.timer === undefined) && (slip.vars.delay === undefined)) {
        slip.vars.delay = window.setTimeout(function () {
          slip.vars.autodelay = false;
          slip.vars.timer = window.setInterval(function () {
            slip.vars.trigger = 'auto';
            el.goToSlide(slip.settings.autoDirection);
          }, slip.settings.pause);
        }, slip.vars.autodelay ? slip.settings.autoHoverDelay : slip.settings.autoDelay);
      }
      if (slip.settings.autoHover) {
        slip.vars.slideWrapper.unbind('mouseenter').unbind('mouseleave').bind('mouseenter', function () {
          if (slip.vars.timer !== undefined) {
            slip.vars.hoverStop = true;
            el.stopAuto();
          } else {
            slip.vars.hoverStop = false;
          }
        }).bind('mouseleave', function () {
          if (slip.vars.hoverStop) {
            slip.vars.autodelay = true;
            el.startAuto();
          }
        });
      }
    };

    el.stopAuto = function () {
      window.clearInterval(slip.vars.timer);
      slip.vars.timer = undefined;
      window.clearTimeout(slip.vars.delay);
      slip.vars.delay = undefined;
    };

    // refreshes the already initialised slider
    el.refresh = function () {
      slip.vars.slides.removeClass(slip.settings.activeClass);
      slip.vars.active.addClass(slip.settings.activeClass);
      if (slip.settings.responsive) {
        prepareFiller();
      } else {
        ready();
      }
      updateControls();
      updatePager();
      updateCaption();
    };

    updateSlide = function () {
      el.refresh();
    };

    transitionDone = function () {
      slip.vars.moving = false;
      slip.vars.active.removeClass(slip.settings.transClass);
      if (!slip.vars.fresh) {
        slip.vars.old.removeClass('sy-ken');
      }
      slip.vars.old.removeClass(slip.settings.transClass);
      slip.settings.onSlideAfter.call(undefined, slip.vars.active, slip.vars.old.index(), slip.vars.active.index());
    };

    doTransition = function () {
      var pos, jump, old_left, old_pos, kenTime, ref, cssProp;
      slip.settings.onSlideBefore.call(undefined, slip.vars.active, slip.vars.old.index(), slip.vars.active.index());
      if (slip.settings.transition !== false) {
        slip.vars.moving = true;
        if ((slip.settings.transition === 'fade') || (slip.settings.transition === 'kenburns')) {
          if (slip.vars.fresh) {
            if (slip.settings.useCSS) {
              slip.vars.slides.css({transitionDuration: slip.settings.speed + 'ms', opacity: 0});
            } else {
              slip.vars.slides.css({opacity: 0});
            }
            slip.vars.active.css('opacity', 1);
            if (slip.settings.transition === 'kenburns') {
              if (slip.settings.useCSS) {
                kenTime = slip.settings.pause + slip.settings.speed * 2;
                slip.vars.slides.css({animationDuration: kenTime + 'ms'});
                slip.vars.active.addClass('sy-ken');
              }
            }
            transitionDone();
          } else {
            if (slip.settings.useCSS) {
              slip.vars.old.addClass(slip.settings.transClass).css('opacity', 0);
              slip.vars.active.addClass(slip.settings.transClass).css('opacity', 1);
              if (slip.settings.transition === 'kenburns') {
                slip.vars.active.addClass('sy-ken');
              }
              $(window).off('focus').on('focus', function () { // bugfix for safari 7 which doesn't always trigger ontransitionend when switching tab
                if (slip.vars.moving) {
                  slip.vars.old.trigger(slip.vars.transition);
                }
              });
              slip.vars.old.one(slip.vars.transition, function () {
                transitionDone();
                return this;
              });
            } else {
              if (slip.settings.transition === 'kenburns') {
                doKens();
              }
              slip.vars.old.addClass(slip.settings.transClass).animate({
                opacity: 0
              }, slip.settings.speed, slip.settings.easing, function () {
                transitionDone();
              });
              slip.vars.active.addClass(slip.settings.transClass).css('opacity', 0).animate({
                opacity: 1
              }, slip.settings.speed, slip.settings.easing);
            }
          }
          updateSlide();
        } else if ((slip.settings.transition === 'horizontal') || (slip.settings.transition === 'vertical')) {
          ref = (slip.settings.transition === 'horizontal') ? 'left' : 'top';
          pos = '-' + slip.vars.active.index() * (100 + slip.settings.slideMargin) + '%';
          if (slip.vars.fresh) {
            el.css(ref, pos);
            transitionDone();
          } else {
            cssProp = {};
            if (slip.settings.continuous) {
              if (slip.vars.jump && ((slip.vars.trigger === 'controls') || (slip.vars.trigger === 'auto'))) {
                jump = true;
                old_pos = pos;
                if (slip.vars.first) {
                  old_left = 0;
                  slip.vars.active.css(ref, slip.vars.count * (100 + slip.settings.slideMargin) + '%');
                  pos = '-' + slip.vars.count * (100 + slip.settings.slideMargin) + '%';
                } else {
                  old_left = (slip.vars.count - 1) * (100 + slip.settings.slideMargin) + '%';
                  slip.vars.active.css(ref, -(100 + slip.settings.slideMargin) + '%');
                  pos = (100 + slip.settings.slideMargin) + '%';
                }
              }
            }
            slip.vars.active.addClass(slip.settings.transClass);
            if (slip.settings.useCSS) {
              cssProp[ref] = pos;
              cssProp.transitionDuration = slip.settings.speed + 'ms';
              el.addClass(slip.settings.transition);
              el.css(cssProp);
              $(window).off('focus').on('focus', function () { // bugfix for safari 7 which doesn't always trigger ontransitionend when switching tab
                if (slip.vars.moving) {
                  el.trigger(slip.vars.transition);
                }
              });
              el.one(slip.vars.transition, function () {
                el.removeClass(slip.settings.transition);
                if (jump) {
                  slip.vars.active.css(ref, old_left);
                  cssProp[ref] = old_pos;
                  cssProp.transitionDuration = '0ms';
                  el.css(cssProp);
                }
                transitionDone();
                return this;
              });
            } else {
              cssProp[ref] = pos;
              el.stop().animate(cssProp, slip.settings.speed, slip.settings.easing, function () {
                if (jump) {
                  slip.vars.active.css(ref, old_left);
                  el.css(ref, old_pos);
                }
                transitionDone();
                return this;
              });
            }
          }
          updateSlide();
        }
      } else {
        updateSlide();
        transitionDone();
      }
    };

    updatePos = function (slide) {
      slip.vars.first = false;
      slip.vars.last = false;
      if ((slide === 'prev') || (slide === 0)) {
        slip.vars.first = true;
      } else if ((slide === 'next') || (slide === slip.vars.count - 1)) {
        slip.vars.last = true;
      }
    };

    el.goToSlide = function (slide) {
      var current;
      if (!slip.vars.moving) {
        current = slip.vars.active.index();
        if (slide === 'prev') {
          if (current > 0) {
            slide = current - 1;
          } else if (slip.settings.loop) {
            slide = slip.vars.count - 1;
          }
        } else if (slide === 'next') {
          if (current < slip.vars.count - 1) {
            slide = current + 1;
          } else if (slip.settings.loop) {
            slide = 0;
          }
        } else {
          slide = slide - 1;
        }
        slip.vars.jump = false;
        if ((slide !== 'prev') && (slide !== 'next') && ((slide !== current) || (slip.vars.fresh))) {
          updatePos(slide);
          slip.vars.old = slip.vars.active;
          slip.vars.active = $(slip.vars.slides[slide]);
          if (((current === 0) && (slide === slip.vars.count - 1)) || ((current === slip.vars.count - 1) && (slide === 0))) {
            slip.vars.jump = true;
          }
          doTransition();
        }
      }
    };

    el.goToNextSlide = function () {
      el.goToSlide('next');
    };

    el.goToPrevSlide = function () {
      el.goToSlide('prev');
    };

    initPager = function () {
      if ((slip.settings.pager) && (slip.vars.count > 1)) {
        var count, loop, pager;
        count = slip.vars.slides.length;
        pager = $('<ul class="' + slip.settings.pagerClass + '" />');
        for (loop = 1; loop < count + 1; loop = loop + 1) {
          pager.append($('<li />').append($('<a href="#' + loop + '">' + loop + '</a>')));
        }
        slip.vars.slippryWrapper.append(pager);
        $('.' + slip.settings.pagerClass + ' a', slip.vars.slippryWrapper).click(function () {
          slip.vars.trigger = 'pager';
          el.goToSlide(parseInt(this.hash.split('#')[1], 10));
          return false;
        });
        updatePager();
      }
    };

    initControls = function () {
      if ((slip.settings.controls) && (slip.vars.count > 1)) {
        slip.vars.slideWrapper.append(
          $('<ul class="' + slip.settings.controlClass + '" />')
            .append('<li class="' + slip.settings.prevClass + '"><a href="#prev">' + slip.settings.prevText + '</a></li>')
            .append('<li class="' + slip.settings.nextClass + '"><a href="#next">' + slip.settings.nextText + '</a></li>')
        );
        $('.' + slip.settings.controlClass + ' a', slip.vars.slippryWrapper).click(function () {
          slip.vars.trigger = 'controls';
          el.goToSlide(this.hash.split('#')[1]);
          return false;
        });
        updateControls();
      }
    };

    initCaptions = function () {
      if (slip.settings.captions !== false) {
        if (slip.settings.captions === 'overlay') {
          slip.vars.slideWrapper.append($('<div class="sy-caption-wrap" />').html(elFromSel('<div />', slip.settings.captionsEl)));
        } else if (slip.settings.captions === 'below') {
          slip.vars.slippryWrapper.append($('<div class="sy-caption-wrap" />').html(elFromSel('<div />', slip.settings.captionsEl)));
        }
      }
    };

    // actually show the first slide
    start = function () {
      el.goToSlide(slip.vars.active.index() + 1);
    };

    // wait for images, iframes to be loaded
    preload = function (slides) {
      var count, loop, elements, container;
      container = (slip.settings.preload === 'all') ? slides : slip.vars.active;
      elements = $('img, iframe', container);
      count = elements.length;
      if (count === 0) {
        start();
        return;
      }
      loop = 0;
      elements.each(function () {
        $(this).one('load error', function () {
          if (++loop === count) {
            start();
          }
        }).each(function () {
          if (this.complete) {
            $(this).load();
          }
        });
      });
    };

    el.getCurrentSlide = function () {
      return slip.vars.active;
    };

    el.getSlideCount = function () {
      return slip.vars.count;
    };

    el.destroySlider = function () {
      if (slip.vars.fresh === false) {
        el.stopAuto();
        slip.vars.moving = false;
        slip.vars.slides.each(function () {
          if ($(this).data("sy-cssBckup") !== undefined) {
            $(this).attr("style", $(this).data("sy-cssBckup"));
          } else {
            $(this).removeAttr('style');
          }
          if ($(this).data("sy-classBckup") !== undefined) {
            $(this).attr("class", $(this).data("sy-classBckup"));
          } else {
            $(this).removeAttr('class');
          }
        });
        if (el.data("sy-cssBckup") !== undefined) {
          el.attr("style", el.data("sy-cssBckup"));
        } else {
          el.removeAttr('style');
        }
        if (el.data("sy-classBckup") !== undefined) {
          el.attr("class", el.data("sy-classBckup"));
        } else {
          el.removeAttr('class');
        }
        slip.vars.slippryWrapper.before(el);
        slip.vars.slippryWrapper.remove();
        slip.vars.fresh = undefined;
      }
    };

    el.reloadSlider = function () {
      el.destroySlider();
      init();
    };

    // initialises the slider, creates needed markup
    init = function () {
      var first;
      slip.settings = $.extend({}, defaults, options);
      slip.vars.slides = $(slip.settings.elements, el);
      slip.vars.count = slip.vars.slides.length;
      if (slip.settings.useCSS) { // deactivate css transitions on unsupported browsers
        if (!supports('transition')) {
          slip.settings.useCSS = false;
        }
        slip.vars.transition = whichTransitionEvent();
      }
      el.data('sy-cssBckup', el.attr('style'));
      el.data('sy-classBackup', el.attr('class'));
      el.addClass(slip.settings.boxClass).wrap(slip.settings.slippryWrapper).wrap(slip.settings.slideWrapper).wrap(slip.settings.slideCrop);
      slip.vars.slideWrapper = el.parent().parent();
      slip.vars.slippryWrapper = slip.vars.slideWrapper.parent().addClass(slip.settings.loadingClass);
      slip.vars.fresh = true;
      slip.vars.slides.each(function () {
        $(this).addClass('sy-slide ' + slip.settings.transition);
        if (slip.settings.useCSS) {
          $(this).addClass('useCSS');
        }
        if (slip.settings.transition === 'horizontal') {
          $(this).css('left', $(this).index() * (100 + slip.settings.slideMargin) + '%');
        } else if (slip.settings.transition === 'vertical') {
          $(this).css('top', $(this).index() * (100 + slip.settings.slideMargin) + '%');
        }
      });
      if ((slip.vars.count > 1) || (slip.settings.initSingle)) {
        if ($('.' + slip.settings.activeClass, el).index() === -1) {
          if (slip.settings.start === 'random') {
            first = Math.round(Math.random() * (slip.vars.count - 1));
          } else if (slip.settings.start > 0 && slip.settings.start <= slip.vars.count) {
            first = slip.settings.start - 1;
          } else {
            first = 0;
          }
          slip.vars.active = $(slip.vars.slides[first]).addClass(slip.settings.activeClass);
        } else {
          slip.vars.active = $('.' + slip.settings.activeClass, el);
        }
        initControls();
        initPager();
        initCaptions();
        preload(slip.vars.slides);
      } else {
        return this;
      }
    };

    init(); // on startup initialise the slider

    return this;
  };
}(jQuery));;
/*

	Supersized - Fullscreen Slideshow jQuery Plugin
	Version : 3.2.7
	Site	: www.buildinternet.com/project/supersized
	
	Author	: Sam Dunn
	Company : One Mighty Roar (www.onemightyroar.com)
	License : MIT License / GPL License
	
*/

(function($){

	/* Place Supersized Elements
	----------------------------*/
	$(document).ready(function() {
		$('body').append('<ul id="supersized"></ul>');
	});
    
    
    $.supersized = function(options){
    	
    	/* Variables
		----------------------------*/
    	var el = '#supersized',
        	base = this;
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        vars = $.supersized.vars;
        // Add a reverse reference to the DOM object
        base.$el.data("supersized", base);
        api = base.$el.data('supersized');
		
		base.init = function(){
        	// Combine options and vars
        	$.supersized.vars = $.extend($.supersized.vars, $.supersized.themeVars);
        	$.supersized.vars.options = $.extend({},$.supersized.defaultOptions, $.supersized.themeOptions, options);
            base.options = $.supersized.vars.options;
            
            base._build();
        };
        
        
        /* Build Elements
		----------------------------*/
        base._build = function(){
        	// Add in slide markers
        	var thisSlide = 0,
        		slideSet = '',
				markers = '',
				markerContent,
				thumbMarkers = '',
				thumbImage;
				
			while(thisSlide <= base.options.slides.length-1){
				//Determine slide link content
				switch(base.options.slide_links){
					case 'num':
						markerContent = thisSlide;
						break;
					case 'name':
						markerContent = base.options.slides[thisSlide].title;
						break;
					case 'blank':
						markerContent = '';
						break;
				}
				
				slideSet = slideSet+'<li class="slide-'+thisSlide+'"></li>';
				
				if(thisSlide == base.options.start_slide-1){
					// Slide links
					if (base.options.slide_links)markers = markers+'<li class="slide-link-'+thisSlide+' current-slide"><a>'+markerContent+'</a></li>';
					// Slide Thumbnail Links
					if (base.options.thumb_links){
						base.options.slides[thisSlide].thumb ? thumbImage = base.options.slides[thisSlide].thumb : thumbImage = base.options.slides[thisSlide].image;
						thumbMarkers = thumbMarkers+'<li class="thumb'+thisSlide+' current-thumb"><img src="'+thumbImage+'"/></li>';
					};
				}else{
					// Slide links
					if (base.options.slide_links) markers = markers+'<li class="slide-link-'+thisSlide+'" ><a>'+markerContent+'</a></li>';
					// Slide Thumbnail Links
					if (base.options.thumb_links){
						base.options.slides[thisSlide].thumb ? thumbImage = base.options.slides[thisSlide].thumb : thumbImage = base.options.slides[thisSlide].image;
						thumbMarkers = thumbMarkers+'<li class="thumb'+thisSlide+'"><img src="'+thumbImage+'"/></li>';
					};
				}
				thisSlide++;
			}
			
			if (base.options.slide_links) $(vars.slide_list).html(markers);
			if (base.options.thumb_links && vars.thumb_tray.length){
				$(vars.thumb_tray).append('<ul id="'+vars.thumb_list.replace('#','')+'">'+thumbMarkers+'</ul>');
			}
			
			$(base.el).append(slideSet);
			
			// Add in thumbnails
			if (base.options.thumbnail_navigation){
				// Load previous thumbnail
				vars.current_slide - 1 < 0  ? prevThumb = base.options.slides.length - 1 : prevThumb = vars.current_slide - 1;
				$(vars.prev_thumb).show().html($("<img/>").attr("src", base.options.slides[prevThumb].image));
				
				// Load next thumbnail
				vars.current_slide == base.options.slides.length - 1 ? nextThumb = 0 : nextThumb = vars.current_slide + 1;
				$(vars.next_thumb).show().html($("<img/>").attr("src", base.options.slides[nextThumb].image));
			}
			
            base._start(); // Get things started
        };
        
        
        /* Initialize
		----------------------------*/
    	base._start = function(){
			
			// Determine if starting slide random
			if (base.options.start_slide){
				vars.current_slide = base.options.start_slide - 1;
			}else{
				vars.current_slide = Math.floor(Math.random()*base.options.slides.length);	// Generate random slide number
			}
			
			// If links should open in new window
			var linkTarget = base.options.new_window ? ' target="_blank"' : '';
			
			// Set slideshow quality (Supported only in FF and IE, no Webkit)
			if (base.options.performance == 3){
				base.$el.addClass('speed'); 		// Faster transitions
			} else if ((base.options.performance == 1) || (base.options.performance == 2)){
				base.$el.addClass('quality');	// Higher image quality
			}
						
			// Shuffle slide order if needed		
			if (base.options.random){
				arr = base.options.slides;
				for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);	// Fisher-Yates shuffle algorithm (jsfromhell.com/array/shuffle)
			    base.options.slides = arr;
			}
			
			/*-----Load initial set of images-----*/
	
			if (base.options.slides.length > 1){
				if(base.options.slides.length > 2){
					// Set previous image
					vars.current_slide - 1 < 0  ? loadPrev = base.options.slides.length - 1 : loadPrev = vars.current_slide - 1;	// If slide is 1, load last slide as previous
					var imageLink = (base.options.slides[loadPrev].url) ? "href='" + base.options.slides[loadPrev].url + "'" : "";
				
					var imgPrev = $('<img src="'+base.options.slides[loadPrev].image+'"/>');
					var slidePrev = base.el+' li:eq('+loadPrev+')';
					imgPrev.appendTo(slidePrev).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading prevslide');
				
					imgPrev.load(function(){
						$(this).data('origWidth', $(this).width()).data('origHeight', $(this).height());
						base.resizeNow();	// Resize background image
					});	// End Load
				}
			} else {
				// Slideshow turned off if there is only one slide
				base.options.slideshow = 0;
			}
			
			// Set current image
			imageLink = (api.getField('url')) ? "href='" + api.getField('url') + "'" : "";
			var img = $('<img src="'+api.getField('image')+'"/>');
			
			var slideCurrent= base.el+' li:eq('+vars.current_slide+')';
			img.appendTo(slideCurrent).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading activeslide');
			
			img.load(function(){
				base._origDim($(this));
				base.resizeNow();	// Resize background image
				base.launch();
				if( typeof theme != 'undefined' && typeof theme._init == "function" ) theme._init();	// Load Theme
			});
			
			if (base.options.slides.length > 1){
				// Set next image
				vars.current_slide == base.options.slides.length - 1 ? loadNext = 0 : loadNext = vars.current_slide + 1;	// If slide is last, load first slide as next
				imageLink = (base.options.slides[loadNext].url) ? "href='" + base.options.slides[loadNext].url + "'" : "";
				
				var imgNext = $('<img src="'+base.options.slides[loadNext].image+'"/>');
				var slideNext = base.el+' li:eq('+loadNext+')';
				imgNext.appendTo(slideNext).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading');
				
				imgNext.load(function(){
					$(this).data('origWidth', $(this).width()).data('origHeight', $(this).height());
					base.resizeNow();	// Resize background image
				});	// End Load
			}
			/*-----End load initial images-----*/
			
			//  Hide elements to be faded in
			base.$el.css('visibility','hidden');
			$('.load-item').hide();
			
    	};
		
		
		/* Launch Supersized
		----------------------------*/
		base.launch = function(){
		
			base.$el.css('visibility','visible');
			$('#supersized-loader').remove();		//Hide loading animation
			
			// Call theme function for before slide transition
			if( typeof theme != 'undefined' && typeof theme.beforeAnimation == "function" ) theme.beforeAnimation('next');
			$('.load-item').show();
			
			// Keyboard Navigation
			if (base.options.keyboard_nav){
				$(document.documentElement).keyup(function (event) {
				
					if(vars.in_animation) return false;		// Abort if currently animating
					if($(document.activeElement).is("input, textarea")) return false; // Abort if active element is an input or a textarea.
					
					// Left Arrow or Down Arrow
					if ((event.keyCode == 37) || (event.keyCode == 40)) {
						clearInterval(vars.slideshow_interval);	// Stop slideshow, prevent buildup
						base.prevSlide();
					
					// Right Arrow or Up Arrow
					} else if ((event.keyCode == 39) || (event.keyCode == 38)) {
						clearInterval(vars.slideshow_interval);	// Stop slideshow, prevent buildup
						base.nextSlide();
					
					// Spacebar	
					} else if (event.keyCode == 32 && !vars.hover_pause) {
						clearInterval(vars.slideshow_interval);	// Stop slideshow, prevent buildup
						base.playToggle();
					}
				
				});
			}
			
			// Pause when hover on image
			if (base.options.slideshow && base.options.pause_hover){
				$(base.el).hover(function() {
					if(vars.in_animation) return false;		// Abort if currently animating
			   			vars.hover_pause = true;	// Mark slideshow paused from hover
			   			if(!vars.is_paused){
			   				vars.hover_pause = 'resume';	// It needs to resume afterwards
			   				base.playToggle();
			   			}
			   	}, function() {
					if(vars.hover_pause == 'resume'){
						base.playToggle();
						vars.hover_pause = false;
					}
			   	});
			}
			
			if (base.options.slide_links){
				// Slide marker clicked
				$(vars.slide_list+'> li').click(function(){
				
					index = $(vars.slide_list+'> li').index(this);
					targetSlide = index + 1;
					
					base.goTo(targetSlide);
					return false;
					
				});
			}
			
			// Thumb marker clicked
			if (base.options.thumb_links){
				$(vars.thumb_list+'> li').click(function(){
				
					index = $(vars.thumb_list+'> li').index(this);
					targetSlide = index + 1;
					
					api.goTo(targetSlide);
					return false;
					
				});
			}
			
			// Start slideshow if enabled
			if (base.options.slideshow && base.options.slides.length > 1){
	    		
	    		// Start slideshow if autoplay enabled
	    		if (base.options.autoplay && base.options.slides.length > 1){
	    			vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);	// Initiate slide interval
				}else{
					vars.is_paused = true;	// Mark as paused
				}
				
				//Prevent navigation items from being dragged					
				$('.load-item img').bind("contextmenu mousedown",function(){
					return false;
				});
								
			}
			
			// Adjust image when browser is resized
			$(window).resize(function(){
	    		base.resizeNow();
			});
    		
    	};
        
        
        /* Resize Images
		----------------------------*/
		base.resizeNow = function(){
			
			return base.$el.each(function() {
		  		//  Resize each image seperately
		  		$('img', base.el).each(function(){
		  			
					thisSlide = $(this);
					var ratio = (thisSlide.data('origHeight')/thisSlide.data('origWidth')).toFixed(2);	// Define image ratio
					
					// Gather browser size
					var browserwidth = base.$el.width(),
						browserheight = base.$el.height(),
						offset;
					
					/*-----Resize Image-----*/
					if (base.options.fit_always){	// Fit always is enabled
						if ((browserheight/browserwidth) > ratio){
							resizeWidth();
						} else {
							resizeHeight();
						}
					}else{	// Normal Resize
						if ((browserheight <= base.options.min_height) && (browserwidth <= base.options.min_width)){	// If window smaller than minimum width and height
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth(true) : resizeHeight(true);	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight(true) : resizeWidth(true);		// If portraits are set to fit
							}
						
						} else if (browserwidth <= base.options.min_width){		// If window only smaller than minimum width
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth(true) : resizeHeight();	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight() : resizeWidth(true);		// If portraits are set to fit
							}
							
						} else if (browserheight <= base.options.min_height){	// If window only smaller than minimum height
						
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth() : resizeHeight(true);	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight(true) : resizeWidth();		// If portraits are set to fit
							}
						
						} else {	// If larger than minimums
							
							if ((browserheight/browserwidth) > ratio){
								base.options.fit_landscape && ratio < 1 ? resizeWidth() : resizeHeight();	// If landscapes are set to fit
							} else {
								base.options.fit_portrait && ratio >= 1 ? resizeHeight() : resizeWidth();		// If portraits are set to fit
							}
							
						}
					}
					/*-----End Image Resize-----*/
					
					
					/*-----Resize Functions-----*/
					
					function resizeWidth(minimum){
						if (minimum){	// If minimum height needs to be considered
							if(thisSlide.width() < browserwidth || thisSlide.width() < base.options.min_width ){
								if (thisSlide.width() * ratio >= base.options.min_height){
									thisSlide.width(base.options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
						    	}else{
						    		resizeHeight();
						    	}
						    }
						}else{
							if (base.options.min_height >= browserheight && !base.options.fit_landscape){	// If minimum height needs to be considered
								if (browserwidth * ratio >= base.options.min_height || (browserwidth * ratio >= base.options.min_height && ratio <= 1)){	// If resizing would push below minimum height or image is a landscape
									thisSlide.width(browserwidth);
									thisSlide.height(browserwidth * ratio);
								} else if (ratio > 1){		// Else the image is portrait
									thisSlide.height(base.options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								} else if (thisSlide.width() < browserwidth) {
									thisSlide.width(browserwidth);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	// Otherwise, resize as normal
								thisSlide.width(browserwidth);
								thisSlide.height(browserwidth * ratio);
							}
						}
					};
					
					function resizeHeight(minimum){
						if (minimum){	// If minimum height needs to be considered
							if(thisSlide.height() < browserheight){
								if (thisSlide.height() / ratio >= base.options.min_width){
									thisSlide.height(base.options.min_height);
									thisSlide.width(thisSlide.height() / ratio);
								}else{
									resizeWidth(true);
								}
							}
						}else{	// Otherwise, resized as normal
							if (base.options.min_width >= browserwidth){	// If minimum width needs to be considered
								if (browserheight / ratio >= base.options.min_width || ratio > 1){	// If resizing would push below minimum width or image is a portrait
									thisSlide.height(browserheight);
									thisSlide.width(browserheight / ratio);
								} else if (ratio <= 1){		// Else the image is landscape
									thisSlide.width(base.options.min_width);
						    		thisSlide.height(thisSlide.width() * ratio);
								}
							}else{	// Otherwise, resize as normal
								thisSlide.height(browserheight);
								thisSlide.width(browserheight / ratio);
							}
						}
					};
					
					/*-----End Resize Functions-----*/
					
					if (thisSlide.parents('li').hasClass('image-loading')){
						$('.image-loading').removeClass('image-loading');
					}
					
					// Horizontally Center
					if (base.options.horizontal_center){
						$(this).css('left', (browserwidth - $(this).width())/2);
					}
					
					// Vertically Center
					if (base.options.vertical_center){
						$(this).css('top', (browserheight - $(this).height())/2);
					}
					
				});
				
				// Basic image drag and right click protection
				if (base.options.image_protect){
					
					$('img', base.el).bind("contextmenu mousedown",function(){
						return false;
					});
				
				}
				
				return false;
				
			});
			
		};
        
        
        /* Next Slide
		----------------------------*/
		base.nextSlide = function(){
			
			if(vars.in_animation || !api.options.slideshow) return false;		// Abort if currently animating
				else vars.in_animation = true;		// Otherwise set animation marker
				
		    clearInterval(vars.slideshow_interval);	// Stop slideshow
		    
		    var slides = base.options.slides,					// Pull in slides array
				liveslide = base.$el.find('.activeslide');		// Find active slide
				$('.prevslide').removeClass('prevslide');
				liveslide.removeClass('activeslide').addClass('prevslide');	// Remove active class & update previous slide
					
			// Get the slide number of new slide
			vars.current_slide + 1 == base.options.slides.length ? vars.current_slide = 0 : vars.current_slide++;
			
		    var nextslide = $(base.el+' li:eq('+vars.current_slide+')'),
		    	prevslide = base.$el.find('.prevslide');
			
			// If hybrid mode is on drop quality for transition
			if (base.options.performance == 1) base.$el.removeClass('quality').addClass('speed');	
			
			
			/*-----Load Image-----*/
			
			loadSlide = false;

			vars.current_slide == base.options.slides.length - 1 ? loadSlide = 0 : loadSlide = vars.current_slide + 1;	// Determine next slide

			var targetList = base.el+' li:eq('+loadSlide+')';
			if (!$(targetList).html()){
				
				// If links should open in new window
				var linkTarget = base.options.new_window ? ' target="_blank"' : '';
				
				imageLink = (base.options.slides[loadSlide].url) ? "href='" + base.options.slides[loadSlide].url + "'" : "";	// If link exists, build it
				var img = $('<img src="'+base.options.slides[loadSlide].image+'"/>'); 
				
				img.appendTo(targetList).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading').css('visibility','hidden');
				
				img.load(function(){
					base._origDim($(this));
					base.resizeNow();
				});	// End Load
			};
						
			// Update thumbnails (if enabled)
			if (base.options.thumbnail_navigation == 1){
			
				// Load previous thumbnail
				vars.current_slide - 1 < 0  ? prevThumb = base.options.slides.length - 1 : prevThumb = vars.current_slide - 1;
				$(vars.prev_thumb).html($("<img/>").attr("src", base.options.slides[prevThumb].image));
			
				// Load next thumbnail
				nextThumb = loadSlide;
				$(vars.next_thumb).html($("<img/>").attr("src", base.options.slides[nextThumb].image));
				
			}
			
			
			
			/*-----End Load Image-----*/
			
			
			// Call theme function for before slide transition
			if( typeof theme != 'undefined' && typeof theme.beforeAnimation == "function" ) theme.beforeAnimation('next');
			
			//Update slide markers
			if (base.options.slide_links){
				$('.current-slide').removeClass('current-slide');
				$(vars.slide_list +'> li' ).eq(vars.current_slide).addClass('current-slide');
			}
		    
		    nextslide.css('visibility','hidden').addClass('activeslide');	// Update active slide
		    
	    	switch(base.options.transition){
	    		case 0: case 'none':	// No transition
	    		    nextslide.css('visibility','visible'); vars.in_animation = false; base.afterAnimation();
	    		    break;
	    		case 1: case 'fade':	// Fade
	    		    nextslide.css({opacity : 0, 'visibility': 'visible'}).animate({opacity : 1, avoidTransforms : false}, base.options.transition_speed, function(){ base.afterAnimation(); });
	    		    break;
	    		case 2: case 'slideTop':	// Slide Top
	    		    nextslide.css({top : -base.$el.height(), 'visibility': 'visible'}).animate({ top:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    		    break;
	    		case 3: case 'slideRight':	// Slide Right
	    			nextslide.css({left : base.$el.width(), 'visibility': 'visible'}).animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 4: case 'slideBottom': // Slide Bottom
	    			nextslide.css({top : base.$el.height(), 'visibility': 'visible'}).animate({ top:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 5: case 'slideLeft':  // Slide Left
	    			nextslide.css({left : -base.$el.width(), 'visibility': 'visible'}).animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 6: case 'carouselRight':	// Carousel Right
	    			nextslide.css({left : base.$el.width(), 'visibility': 'visible'}).animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
					liveslide.animate({ left: -base.$el.width(), avoidTransforms : false }, base.options.transition_speed );
	    			break;
	    		case 7: case 'carouselLeft':   // Carousel Left
	    			nextslide.css({left : -base.$el.width(), 'visibility': 'visible'}).animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
					liveslide.animate({ left: base.$el.width(), avoidTransforms : false }, base.options.transition_speed );
	    			break;
	    	}
		    return false;	
		};
		
		
		/* Previous Slide
		----------------------------*/
		base.prevSlide = function(){
		
			if(vars.in_animation || !api.options.slideshow) return false;		// Abort if currently animating
				else vars.in_animation = true;		// Otherwise set animation marker
			
			clearInterval(vars.slideshow_interval);	// Stop slideshow
			
			var slides = base.options.slides,					// Pull in slides array
				liveslide = base.$el.find('.activeslide');		// Find active slide
				$('.prevslide').removeClass('prevslide');
				liveslide.removeClass('activeslide').addClass('prevslide');		// Remove active class & update previous slide
			
			// Get current slide number
			vars.current_slide == 0 ?  vars.current_slide = base.options.slides.length - 1 : vars.current_slide-- ;
				
		    var nextslide =  $(base.el+' li:eq('+vars.current_slide+')'),
		    	prevslide =  base.$el.find('.prevslide');
			
			// If hybrid mode is on drop quality for transition
			if (base.options.performance == 1) base.$el.removeClass('quality').addClass('speed');	
			
			
			/*-----Load Image-----*/
			
			loadSlide = vars.current_slide;
			
			var targetList = base.el+' li:eq('+loadSlide+')';
			if (!$(targetList).html()){
				// If links should open in new window
				var linkTarget = base.options.new_window ? ' target="_blank"' : '';
				imageLink = (base.options.slides[loadSlide].url) ? "href='" + base.options.slides[loadSlide].url + "'" : "";	// If link exists, build it
				var img = $('<img src="'+base.options.slides[loadSlide].image+'"/>'); 
				
				img.appendTo(targetList).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading').css('visibility','hidden');
				
				img.load(function(){
					base._origDim($(this));
					base.resizeNow();
				});	// End Load
			};
			
			// Update thumbnails (if enabled)
			if (base.options.thumbnail_navigation == 1){
			
				// Load previous thumbnail
				//prevThumb = loadSlide;
				loadSlide == 0 ? prevThumb = base.options.slides.length - 1 : prevThumb = loadSlide - 1;
				$(vars.prev_thumb).html($("<img/>").attr("src", base.options.slides[prevThumb].image));
				
				// Load next thumbnail
				vars.current_slide == base.options.slides.length - 1 ? nextThumb = 0 : nextThumb = vars.current_slide + 1;
				$(vars.next_thumb).html($("<img/>").attr("src", base.options.slides[nextThumb].image));
			}
			
			/*-----End Load Image-----*/
			
			
			// Call theme function for before slide transition
			if( typeof theme != 'undefined' && typeof theme.beforeAnimation == "function" ) theme.beforeAnimation('prev');
			
			//Update slide markers
			if (base.options.slide_links){
				$('.current-slide').removeClass('current-slide');
				$(vars.slide_list +'> li' ).eq(vars.current_slide).addClass('current-slide');
			}
			
		    nextslide.css('visibility','hidden').addClass('activeslide');	// Update active slide
		    
		    switch(base.options.transition){
	    		case 0: case 'none':	// No transition
	    		    nextslide.css('visibility','visible'); vars.in_animation = false; base.afterAnimation();
	    		    break;
	    		case 1: case 'fade':	// Fade
	    		  	nextslide.css({opacity : 0, 'visibility': 'visible'}).animate({opacity : 1, avoidTransforms : false}, base.options.transition_speed, function(){ base.afterAnimation(); });
	    		    break;
	    		case 2: case 'slideTop':	// Slide Top (reverse)
	    		    nextslide.css({top : base.$el.height(), 'visibility': 'visible'}).animate({ top:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    		    break;
	    		case 3: case 'slideRight':	// Slide Right (reverse)
	    			nextslide.css({left : -base.$el.width(), 'visibility': 'visible'}).animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 4: case 'slideBottom': // Slide Bottom (reverse)
	    			nextslide.css({top : -base.$el.height(), 'visibility': 'visible'}).animate({ top:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 5: case 'slideLeft':  // Slide Left (reverse)
	    			nextslide.css({left : base.$el.width(), 'visibility': 'visible'}).animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
	    			break;
	    		case 6: case 'carouselRight':	// Carousel Right (reverse)
	    			nextslide.css({left : -base.$el.width(), 'visibility': 'visible'}).animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
					liveslide.css({left : 0}).animate({ left: base.$el.width(), avoidTransforms : false}, base.options.transition_speed );
	    			break;
	    		case 7: case 'carouselLeft':   // Carousel Left (reverse)
	    			nextslide.css({left : base.$el.width(), 'visibility': 'visible'}).animate({ left:0, avoidTransforms : false }, base.options.transition_speed, function(){ base.afterAnimation(); });
					liveslide.css({left : 0}).animate({ left: -base.$el.width(), avoidTransforms : false }, base.options.transition_speed );
	    			break;
	    	}
		    return false;	
		};
		
		
		/* Play/Pause Toggle
		----------------------------*/
		base.playToggle = function(){
		
			if (vars.in_animation || !api.options.slideshow) return false;		// Abort if currently animating
			
			if (vars.is_paused){
				
				vars.is_paused = false;
				
				// Call theme function for play
				if( typeof theme != 'undefined' && typeof theme.playToggle == "function" ) theme.playToggle('play');
				
				// Resume slideshow
	        	vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);
	        	  
        	}else{
        		
        		vars.is_paused = true;
        		
        		// Call theme function for pause
        		if( typeof theme != 'undefined' && typeof theme.playToggle == "function" ) theme.playToggle('pause');
        		
        		// Stop slideshow
        		clearInterval(vars.slideshow_interval);	
       		
       		}
		    
		    return false;
    		
    	};
    	
    	
    	/* Go to specific slide
		----------------------------*/
    	base.goTo = function(targetSlide){
			if (vars.in_animation || !api.options.slideshow) return false;		// Abort if currently animating
			
			var totalSlides = base.options.slides.length;
			
			// If target outside range
			if(targetSlide < 0){
				targetSlide = totalSlides;
			}else if(targetSlide > totalSlides){
				targetSlide = 1;
			}
			targetSlide = totalSlides - targetSlide + 1;
			
			clearInterval(vars.slideshow_interval);	// Stop slideshow, prevent buildup
			
			// Call theme function for goTo trigger
			if (typeof theme != 'undefined' && typeof theme.goTo == "function" ) theme.goTo();
			
			if (vars.current_slide == totalSlides - targetSlide){
				if(!(vars.is_paused)){
					vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);
				} 
				return false;
			}
			
			// If ahead of current position
			if(totalSlides - targetSlide > vars.current_slide ){
				
				// Adjust for new next slide
				vars.current_slide = totalSlides-targetSlide-1;
				vars.update_images = 'next';
				base._placeSlide(vars.update_images);
				
			//Otherwise it's before current position
			}else if(totalSlides - targetSlide < vars.current_slide){
				
				// Adjust for new prev slide
				vars.current_slide = totalSlides-targetSlide+1;
				vars.update_images = 'prev';
			    base._placeSlide(vars.update_images);
			    
			}
			
			// set active markers
			if (base.options.slide_links){
				$(vars.slide_list +'> .current-slide').removeClass('current-slide');
				$(vars.slide_list +'> li').eq((totalSlides-targetSlide)).addClass('current-slide');
			}
			
			if (base.options.thumb_links){
				$(vars.thumb_list +'> .current-thumb').removeClass('current-thumb');
				$(vars.thumb_list +'> li').eq((totalSlides-targetSlide)).addClass('current-thumb');
			}
			
		};
        
        
        /* Place Slide
		----------------------------*/
        base._placeSlide = function(place){
    			
			// If links should open in new window
			var linkTarget = base.options.new_window ? ' target="_blank"' : '';
			
			loadSlide = false;
			
			if (place == 'next'){
				
				vars.current_slide == base.options.slides.length - 1 ? loadSlide = 0 : loadSlide = vars.current_slide + 1;	// Determine next slide
				
				var targetList = base.el+' li:eq('+loadSlide+')';
				
				if (!$(targetList).html()){
					// If links should open in new window
					var linkTarget = base.options.new_window ? ' target="_blank"' : '';
					
					imageLink = (base.options.slides[loadSlide].url) ? "href='" + base.options.slides[loadSlide].url + "'" : "";	// If link exists, build it
					var img = $('<img src="'+base.options.slides[loadSlide].image+'"/>'); 
					
					img.appendTo(targetList).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading').css('visibility','hidden');
					
					img.load(function(){
						base._origDim($(this));
						base.resizeNow();
					});	// End Load
				};
				
				base.nextSlide();
				
			}else if (place == 'prev'){
			
				vars.current_slide - 1 < 0  ? loadSlide = base.options.slides.length - 1 : loadSlide = vars.current_slide - 1;	// Determine next slide
				
				var targetList = base.el+' li:eq('+loadSlide+')';
				
				if (!$(targetList).html()){
					// If links should open in new window
					var linkTarget = base.options.new_window ? ' target="_blank"' : '';
					
					imageLink = (base.options.slides[loadSlide].url) ? "href='" + base.options.slides[loadSlide].url + "'" : "";	// If link exists, build it
					var img = $('<img src="'+base.options.slides[loadSlide].image+'"/>'); 
					
					img.appendTo(targetList).wrap('<a ' + imageLink + linkTarget + '></a>').parent().parent().addClass('image-loading').css('visibility','hidden');
					
					img.load(function(){
						base._origDim($(this));
						base.resizeNow();
					});	// End Load
				};
				base.prevSlide();
			}
			
		};
		
		
		/* Get Original Dimensions
		----------------------------*/
		base._origDim = function(targetSlide){
			targetSlide.data('origWidth', targetSlide.width()).data('origHeight', targetSlide.height());
		};
		
		
		/* After Slide Animation
		----------------------------*/
		base.afterAnimation = function(){
			
			// If hybrid mode is on swap back to higher image quality
			if (base.options.performance == 1){
		    	base.$el.removeClass('speed').addClass('quality');
			}
			
			// Update previous slide
			if (vars.update_images){
				vars.current_slide - 1 < 0  ? setPrev = base.options.slides.length - 1 : setPrev = vars.current_slide-1;
				vars.update_images = false;
				$('.prevslide').removeClass('prevslide');
				$(base.el+' li:eq('+setPrev+')').addClass('prevslide');
			}
			
			vars.in_animation = false;
			
			// Resume slideshow
			if (!vars.is_paused && base.options.slideshow){
				vars.slideshow_interval = setInterval(base.nextSlide, base.options.slide_interval);
				if (base.options.stop_loop && vars.current_slide == base.options.slides.length - 1 ) base.playToggle();
			}
			
			// Call theme function for after slide transition
			if (typeof theme != 'undefined' && typeof theme.afterAnimation == "function" ) theme.afterAnimation();
			
			return false;
		
		};
		
		base.getField = function(field){
			return base.options.slides[vars.current_slide][field];
		};
		
        // Make it go!
        base.init();
	};
	
	
	/* Global Variables
	----------------------------*/
	$.supersized.vars = {
	
		// Elements							
		thumb_tray			:	'#thumb-tray',	// Thumbnail tray
		thumb_list			:	'#thumb-list',	// Thumbnail list
		slide_list          :   '#slide-list',	// Slide link list
		
		// Internal variables
		current_slide			:	0,			// Current slide number
		in_animation 			:	false,		// Prevents animations from stacking
		is_paused 				: 	false,		// Tracks paused on/off
		hover_pause				:	false,		// If slideshow is paused from hover
		slideshow_interval		:	false,		// Stores slideshow timer					
		update_images 			: 	false,		// Trigger to update images after slide jump
		options					:	{}			// Stores assembled options list
		
	};
	
	
	/* Default Options
	----------------------------*/
	$.supersized.defaultOptions = {
    
    	// Functionality
		slideshow               :   1,			// Slideshow on/off
		autoplay				:	1,			// Slideshow starts playing automatically
		start_slide             :   1,			// Start slide (0 is random)
		stop_loop				:	0,			// Stops slideshow on last slide
		random					: 	0,			// Randomize slide order (Ignores start slide)
		slide_interval          :   5000,		// Length between transitions
		transition              :   1, 			// 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
		transition_speed		:	750,		// Speed of transition
		new_window				:	1,			// Image links open in new window/tab
		pause_hover             :   0,			// Pause slideshow on hover
		keyboard_nav            :   1,			// Keyboard navigation on/off
		performance				:	1,			// 0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed //  (Only works for Firefox/IE, not Webkit)
		image_protect			:	1,			// Disables image dragging and right click with Javascript
												   
		// Size & Position
		fit_always				:	0,			// Image will never exceed browser width or height (Ignores min. dimensions)
		fit_landscape			:   0,			// Landscape images will not exceed browser width
		fit_portrait         	:   1,			// Portrait images will not exceed browser height  			   
		min_width		        :   0,			// Min width allowed (in pixels)
		min_height		        :   0,			// Min height allowed (in pixels)
		horizontal_center       :   1,			// Horizontally center background
		vertical_center         :   1,			// Vertically center background
		
												   
		// Components							
		slide_links				:	1,			// Individual links for each slide (Options: false, 'num', 'name', 'blank')
		thumb_links				:	1,			// Individual thumb links for each slide
		thumbnail_navigation    :   0			// Thumbnail navigation
    	
    };
    
    $.fn.supersized = function(options){
        return this.each(function(){
            (new $.supersized(options));
        });
    };
		
})(jQuery);

;
// Generated by CoffeeScript 1.6.3
/*
Copyright 2013 Marco Braak

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/


(function() {
	var $,
		BorderDropHint,
		DragAndDropHandler,
		DragElement,
		FolderElement,
		GhostDropHint,
		HitAreasGenerator,
		JqTreeWidget,
		KeyHandler,
		MouseWidget,
		Node,
		NodeElement,
		Position,
		SaveStateHandler,
		ScrollHandler,
		SelectNodeHandler,
		SimpleWidget,
		VisibleNodeIterator,
		html_escape,
		indexOf,
		json_escapable,
		json_meta,
		json_quote,
		json_str,
		_indexOf,
		_ref,
		_ref1,
		_ref2,
		__slice = [].slice,
		__hasProp = {}.hasOwnProperty,
		__extends = function(child, parent) {
			for (var key in parent) {
				if (__hasProp.call(parent, key)) child[key] = parent[key];
			}

			function ctor() { this.constructor = child; }

			ctor.prototype = parent.prototype;
			child.prototype = new ctor();
			child.__super__ = parent.prototype;
			return child;
		};

	$ = this.jQuery;

	SimpleWidget = (function() {
		SimpleWidget.prototype.defaults = {};

		function SimpleWidget(el, options) {
			this.$el = $(el);
			this.options = $.extend({}, this.defaults, options);
		}

		SimpleWidget.prototype.destroy = function() {
			return this._deinit();
		};

		SimpleWidget.prototype._init = function() {
			return null;
		};

		SimpleWidget.prototype._deinit = function() {
			return null;
		};

		SimpleWidget.register = function(widget_class, widget_name) {
			var callFunction, createWidget, destroyWidget, getDataKey;
			getDataKey = function() {
				return "simple_widget_" + widget_name;
			};
			createWidget = function($el, options) {
				var data_key, el, widget, _i, _len;
				data_key = getDataKey();
				for (_i = 0, _len = $el.length; _i < _len; _i++) {
					el = $el[_i];
					widget = new widget_class(el, options);
					if (!$.data(el, data_key)) {
						$.data(el, data_key, widget);
					}
					widget._init();
				}
				return $el;
			};
			destroyWidget = function($el) {
				var data_key, el, widget, _i, _len, _results;
				data_key = getDataKey();
				_results = [];
				for (_i = 0, _len = $el.length; _i < _len; _i++) {
					el = $el[_i];
					widget = $.data(el, data_key);
					if (widget && (widget instanceof SimpleWidget)) {
						widget.destroy();
					}
					_results.push($.removeData(el, data_key));
				}
				return _results;
			};
			callFunction = function($el, function_name, args) {
				var el, result, widget, widget_function, _i, _len;
				result = null;
				for (_i = 0, _len = $el.length; _i < _len; _i++) {
					el = $el[_i];
					widget = $.data(el, getDataKey());
					if (widget && (widget instanceof SimpleWidget)) {
						widget_function = widget[function_name];
						if (widget_function && (typeof widget_function === 'function')) {
							result = widget_function.apply(widget, args);
						}
					}
				}
				return result;
			};
			return $.fn[widget_name] = function() {
				var $el, args, argument1, function_name, options;
				argument1 = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
				$el = this;
				if (argument1 === void 0 || typeof argument1 === 'object') {
					options = argument1;
					return createWidget($el, options);
				} else if (typeof argument1 === 'string' && argument1[0] !== '_') {
					function_name = argument1;
					if (function_name === 'destroy') {
						return destroyWidget($el);
					} else {
						return callFunction($el, function_name, args);
					}
				}
			};
		};

		return SimpleWidget;

	})();

	this.SimpleWidget = SimpleWidget;

	/*
  This widget does the same a the mouse widget in jqueryui.
  */


	MouseWidget = (function(_super) {
		__extends(MouseWidget, _super);

		function MouseWidget() {
			_ref = MouseWidget.__super__.constructor.apply(this, arguments);
			return _ref;
		}

		MouseWidget.is_mouse_handled = false;

		MouseWidget.prototype._init = function() {
			this.$el.bind('mousedown.mousewidget', $.proxy(this._mouseDown, this));
			this.$el.bind('touchstart.mousewidget', $.proxy(this._touchStart, this));
			this.is_mouse_started = false;
			this.mouse_delay = 0;
			this._mouse_delay_timer = null;
			this._is_mouse_delay_met = true;
			return this.mouse_down_info = null;
		};

		MouseWidget.prototype._deinit = function() {
			var $document;
			this.$el.unbind('mousedown.mousewidget');
			this.$el.unbind('touchstart.mousewidget');
			$document = $(document);
			$document.unbind('mousemove.mousewidget');
			return $document.unbind('mouseup.mousewidget');
		};

		MouseWidget.prototype._mouseDown = function(e) {
			var result;
			if (e.which !== 1) {
				return;
			}
			result = this._handleMouseDown(e, this._getPositionInfo(e));
			if (result) {
				e.preventDefault();
			}
			return result;
		};

		MouseWidget.prototype._handleMouseDown = function(e, position_info) {
			if (MouseWidget.is_mouse_handled) {
				return;
			}
			if (this.is_mouse_started) {
				this._handleMouseUp(position_info);
			}
			this.mouse_down_info = position_info;
			if (!this._mouseCapture(position_info)) {
				return;
			}
			this._handleStartMouse();
			this.is_mouse_handled = true;
			return true;
		};

		MouseWidget.prototype._handleStartMouse = function() {
			var $document;
			$document = $(document);
			$document.bind('mousemove.mousewidget', $.proxy(this._mouseMove, this));
			$document.bind('touchmove.mousewidget', $.proxy(this._touchMove, this));
			$document.bind('mouseup.mousewidget', $.proxy(this._mouseUp, this));
			$document.bind('touchend.mousewidget', $.proxy(this._touchEnd, this));
			if (this.mouse_delay) {
				return this._startMouseDelayTimer();
			}
		};

		MouseWidget.prototype._startMouseDelayTimer = function() {
			var _this = this;
			if (this._mouse_delay_timer) {
				clearTimeout(this._mouse_delay_timer);
			}
			this._mouse_delay_timer = setTimeout(function() {
				return _this._is_mouse_delay_met = true;
			}, this.mouse_delay);
			return this._is_mouse_delay_met = false;
		};

		MouseWidget.prototype._mouseMove = function(e) {
			return this._handleMouseMove(e, this._getPositionInfo(e));
		};

		MouseWidget.prototype._handleMouseMove = function(e, position_info) {
			if (this.is_mouse_started) {
				this._mouseDrag(position_info);
				return e.preventDefault();
			}
			if (this.mouse_delay && !this._is_mouse_delay_met) {
				return true;
			}
			this.is_mouse_started = this._mouseStart(this.mouse_down_info) !== false;
			if (this.is_mouse_started) {
				this._mouseDrag(position_info);
			} else {
				this._handleMouseUp(position_info);
			}
			return !this.is_mouse_started;
		};

		MouseWidget.prototype._getPositionInfo = function(e) {
			return {
				page_x: e.pageX,
				page_y: e.pageY,
				target: e.target,
				original_event: e
			};
		};

		MouseWidget.prototype._mouseUp = function(e) {
			return this._handleMouseUp(this._getPositionInfo(e));
		};

		MouseWidget.prototype._handleMouseUp = function(position_info) {
			var $document;
			$document = $(document);
			$document.unbind('mousemove.mousewidget');
			$document.unbind('touchmove.mousewidget');
			$document.unbind('mouseup.mousewidget');
			$document.unbind('touchend.mousewidget');
			if (this.is_mouse_started) {
				this.is_mouse_started = false;
				this._mouseStop(position_info);
			}
		};

		MouseWidget.prototype._mouseCapture = function(position_info) {
			return true;
		};

		MouseWidget.prototype._mouseStart = function(position_info) {
			return null;
		};

		MouseWidget.prototype._mouseDrag = function(position_info) {
			return null;
		};

		MouseWidget.prototype._mouseStop = function(position_info) {
			return null;
		};

		MouseWidget.prototype.setMouseDelay = function(mouse_delay) {
			return this.mouse_delay = mouse_delay;
		};

		MouseWidget.prototype._touchStart = function(e) {
			var touch;
			if (e.originalEvent.touches.length > 1) {
				return;
			}
			touch = e.originalEvent.changedTouches[0];
			return this._handleMouseDown(e, this._getPositionInfo(touch));
		};

		MouseWidget.prototype._touchMove = function(e) {
			var touch;
			if (e.originalEvent.touches.length > 1) {
				return;
			}
			touch = e.originalEvent.changedTouches[0];
			return this._handleMouseMove(e, this._getPositionInfo(touch));
		};

		MouseWidget.prototype._touchEnd = function(e) {
			var touch;
			if (e.originalEvent.touches.length > 1) {
				return;
			}
			touch = e.originalEvent.changedTouches[0];
			return this._handleMouseUp(this._getPositionInfo(touch));
		};

		return MouseWidget;

	})(SimpleWidget);

	this.Tree = {};

	$ = this.jQuery;

	Position = {
		getName: function(position) {
			return Position.strings[position - 1];
		},
		nameToIndex: function(name) {
			var i, _i, _ref1;
			for (i = _i = 1, _ref1 = Position.strings.length; 1 <= _ref1 ? _i <= _ref1 : _i >= _ref1; i = 1 <= _ref1 ? ++_i : --_i) {
				if (Position.strings[i - 1] === name) {
					return i;
				}
			}
			return 0;
		}
	};

	Position.BEFORE = 1;

	Position.AFTER = 2;

	Position.INSIDE = 3;

	Position.NONE = 4;

	Position.strings = ['before', 'after', 'inside', 'none'];

	this.Tree.Position = Position;

	Node = (function() {
		function Node(o, is_root, node_class) {
			if (is_root == null) {
				is_root = false;
			}
			if (node_class == null) {
				node_class = Node;
			}
			this.setData(o);
			this.children = [];
			this.parent = null;
			if (is_root) {
				this.id_mapping = {};
				this.tree = this;
				this.node_class = node_class;
			}
		}

		Node.prototype.setData = function(o) {
			var key, value, _results;
			if (typeof o !== 'object') {
				return this.name = o;
			} else {
				_results = [];
				for (key in o) {
					value = o[key];
					if (key === 'label') {
						_results.push(this.name = value);
					} else {
						_results.push(this[key] = value);
					}
				}
				return _results;
			}
		};

		Node.prototype.initFromData = function(data) {
			var addChildren,
				addNode,
				_this = this;
			addNode = function(node_data) {
				_this.setData(node_data);
				if (node_data.children) {
					return addChildren(node_data.children);
				}
			};
			addChildren = function(children_data) {
				var child, node, _i, _len;
				for (_i = 0, _len = children_data.length; _i < _len; _i++) {
					child = children_data[_i];
					node = new _this.tree.node_class('');
					node.initFromData(child);
					_this.addChild(node);
				}
				return null;
			};
			addNode(data);
			return null;
		};

		/*
    Create tree from data.
    
    Structure of data is:
    [
        {
            label: 'node1',
            children: [
                { label: 'child1' },
                { label: 'child2' }
            ]
        },
        {
            label: 'node2'
        }
    ]
    */


		Node.prototype.loadFromData = function(data) {
			var node, o, _i, _len;
			this.removeChildren();
			for (_i = 0, _len = data.length; _i < _len; _i++) {
				o = data[_i];
				node = new this.tree.node_class(o);
				this.addChild(node);
				if (typeof o === 'object' && o.children) {
					node.loadFromData(o.children);
				}
			}
			return null;
		};

		/*
    Add child.
    
    tree.addChild(
        new Node('child1')
    );
    */


		Node.prototype.addChild = function(node) {
			this.children.push(node);
			return node._setParent(this);
		};

		/*
    Add child at position. Index starts at 0.
    
    tree.addChildAtPosition(
        new Node('abc'),
        1
    );
    */


		Node.prototype.addChildAtPosition = function(node, index) {
			this.children.splice(index, 0, node);
			return node._setParent(this);
		};

		Node.prototype._setParent = function(parent) {
			this.parent = parent;
			this.tree = parent.tree;
			return this.tree.addNodeToIndex(this);
		};

		/*
    Remove child. This also removes the children of the node.
    
    tree.removeChild(tree.children[0]);
    */


		Node.prototype.removeChild = function(node) {
			node.removeChildren();
			return this._removeChild(node);
		};

		Node.prototype._removeChild = function(node) {
			this.children.splice(this.getChildIndex(node), 1);
			return this.tree.removeNodeFromIndex(node);
		};

		/*
    Get child index.
    
    var index = getChildIndex(node);
    */


		Node.prototype.getChildIndex = function(node) {
			return $.inArray(node, this.children);
		};

		/*
    Does the tree have children?
    
    if (tree.hasChildren()) {
        //
    }
    */


		Node.prototype.hasChildren = function() {
			return this.children.length !== 0;
		};

		Node.prototype.isFolder = function() {
			return this.hasChildren() || this.load_on_demand;
		};

		/*
    Iterate over all the nodes in the tree.
    
    Calls callback with (node, level).
    
    The callback must return true to continue the iteration on current node.
    
    tree.iterate(
        function(node, level) {
           console.log(node.name);
    
           // stop iteration after level 2
           return (level <= 2);
        }
    );
    */


		Node.prototype.iterate = function(callback) {
			var _iterate,
				_this = this;
			_iterate = function(node, level) {
				var child, result, _i, _len, _ref1;
				if (node.children) {
					_ref1 = node.children;
					for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
						child = _ref1[_i];
						result = callback(child, level);
						if (_this.hasChildren() && result) {
							_iterate(child, level + 1);
						}
					}
					return null;
				}
			};
			_iterate(this, 0);
			return null;
		};

		/*
    Move node relative to another node.
    
    Argument position: Position.BEFORE, Position.AFTER or Position.Inside
    
    // move node1 after node2
    tree.moveNode(node1, node2, Position.AFTER);
    */


		Node.prototype.moveNode = function(moved_node, target_node, position) {
			if (moved_node.isParentOf(target_node)) {
				return;
			}
			moved_node.parent._removeChild(moved_node);
			if (position === Position.AFTER) {
				return target_node.parent.addChildAtPosition(moved_node, target_node.parent.getChildIndex(target_node) + 1);
			} else if (position === Position.BEFORE) {
				return target_node.parent.addChildAtPosition(moved_node, target_node.parent.getChildIndex(target_node));
			} else if (position === Position.INSIDE) {
				return target_node.addChildAtPosition(moved_node, 0);
			}
		};

		/*
    Get the tree as data.
    */


		Node.prototype.getData = function() {
			var getDataFromNodes,
				_this = this;
			getDataFromNodes = function(nodes) {
				var data, k, node, tmp_node, v, _i, _len;
				data = [];
				for (_i = 0, _len = nodes.length; _i < _len; _i++) {
					node = nodes[_i];
					tmp_node = {};
					for (k in node) {
						v = node[k];
						if ((k !== 'parent' && k !== 'children' && k !== 'element' && k !== 'tree') && Object.prototype.hasOwnProperty.call(node, k)) {
							tmp_node[k] = v;
						}
					}
					if (node.hasChildren()) {
						tmp_node.children = getDataFromNodes(node.children);
					}
					data.push(tmp_node);
				}
				return data;
			};
			return getDataFromNodes(this.children);
		};

		Node.prototype.getNodeByName = function(name) {
			var result;
			result = null;
			this.iterate(function(node) {
				if (node.name === name) {
					result = node;
					return false;
				} else {
					return true;
				}
			});
			return result;
		};

		Node.prototype.addAfter = function(node_info) {
			var child_index, node;
			if (!this.parent) {
				return null;
			} else {
				node = new this.tree.node_class(node_info);
				child_index = this.parent.getChildIndex(this);
				this.parent.addChildAtPosition(node, child_index + 1);
				return node;
			}
		};

		Node.prototype.addBefore = function(node_info) {
			var child_index, node;
			if (!this.parent) {
				return null;
			} else {
				node = new this.tree.node_class(node_info);
				child_index = this.parent.getChildIndex(this);
				this.parent.addChildAtPosition(node, child_index);
				return node;
			}
		};

		Node.prototype.addParent = function(node_info) {
			var child, new_parent, original_parent, _i, _len, _ref1;
			if (!this.parent) {
				return null;
			} else {
				new_parent = new this.tree.node_class(node_info);
				new_parent._setParent(this.tree);
				original_parent = this.parent;
				_ref1 = original_parent.children;
				for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
					child = _ref1[_i];
					new_parent.addChild(child);
				}
				original_parent.children = [];
				original_parent.addChild(new_parent);
				return new_parent;
			}
		};

		Node.prototype.remove = function() {
			if (this.parent) {
				this.parent.removeChild(this);
				return this.parent = null;
			}
		};

		Node.prototype.append = function(node_info) {
			var node;
			node = new this.tree.node_class(node_info);
			this.addChild(node);
			return node;
		};

		Node.prototype.prepend = function(node_info) {
			var node;
			node = new this.tree.node_class(node_info);
			this.addChildAtPosition(node, 0);
			return node;
		};

		Node.prototype.isParentOf = function(node) {
			var parent;
			parent = node.parent;
			while (parent) {
				if (parent === this) {
					return true;
				}
				parent = parent.parent;
			}
			return false;
		};

		Node.prototype.getLevel = function() {
			var level, node;
			level = 0;
			node = this;
			while (node.parent) {
				level += 1;
				node = node.parent;
			}
			return level;
		};

		Node.prototype.getNodeById = function(node_id) {
			return this.id_mapping[node_id];
		};

		Node.prototype.addNodeToIndex = function(node) {
			if (node.id != null) {
				return this.id_mapping[node.id] = node;
			}
		};

		Node.prototype.removeNodeFromIndex = function(node) {
			if (node.id != null) {
				return delete this.id_mapping[node.id];
			}
		};

		Node.prototype.removeChildren = function() {
			var _this = this;
			this.iterate(function(child) {
				_this.tree.removeNodeFromIndex(child);
				return true;
			});
			return this.children = [];
		};

		Node.prototype.getPreviousSibling = function() {
			var previous_index;
			if (!this.parent) {
				return null;
			} else {
				previous_index = this.parent.getChildIndex(this) - 1;
				if (previous_index >= 0) {
					return this.parent.children[previous_index];
				} else {
					return null;
				}
			}
		};

		Node.prototype.getNextSibling = function() {
			var next_index;
			if (!this.parent) {
				return null;
			} else {
				next_index = this.parent.getChildIndex(this) + 1;
				if (next_index < this.parent.children.length) {
					return this.parent.children[next_index];
				} else {
					return null;
				}
			}
		};

		return Node;

	})();

	this.Tree.Node = Node;

	/*
  Copyright 2013 Marco Braak
  
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
      http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  */


	JqTreeWidget = (function(_super) {
		__extends(JqTreeWidget, _super);

		function JqTreeWidget() {
			_ref1 = JqTreeWidget.__super__.constructor.apply(this, arguments);
			return _ref1;
		}

		JqTreeWidget.prototype.defaults = {
			autoOpen: false,
			saveState: false,
			dragAndDrop: false,
			selectable: true,
			useContextMenu: true,
			onCanSelectNode: null,
			onSetStateFromStorage: null,
			onGetStateFromStorage: null,
			onCreateLi: null,
			onIsMoveHandle: null,
			onCanMove: null,
			onCanMoveTo: null,
			onLoadFailed: null,
			autoEscape: true,
			dataUrl: null,
			closedIcon: '&#x25ba;',
			openedIcon: '&#x25bc;',
			slide: true,
			nodeClass: Node,
			dataFilter: null,
			keyboardSupport: true,
			openFolderDelay: 500
		};

		JqTreeWidget.prototype.toggle = function(node, slide) {
			if (slide == null) {
				slide = true;
			}
			if (node.is_open) {
				return this.closeNode(node, slide);
			} else {
				return this.openNode(node, slide);
			}
		};

		JqTreeWidget.prototype.getTree = function() {
			return this.tree;
		};

		JqTreeWidget.prototype.selectNode = function(node) {
			return this._selectNode(node, false);
		};

		JqTreeWidget.prototype._selectNode = function(node, must_toggle) {
			var canSelect,
				deselected_node,
				openParents,
				saveState,
				_this = this;
			if (must_toggle == null) {
				must_toggle = false;
			}
			if (!this.select_node_handler) {
				return;
			}
			canSelect = function() {
				if (_this.options.onCanSelectNode) {
					return _this.options.selectable && _this.options.onCanSelectNode(node);
				} else {
					return _this.options.selectable;
				}
			};
			openParents = function() {
				var parent;
				parent = node.parent;
				if (parent && parent.parent && !parent.is_open) {
					return _this.openNode(parent, false);
				}
			};
			saveState = function() {
				if (_this.options.saveState) {
					return _this.save_state_handler.saveState();
				}
			};
			if (!node) {
				this._deselectCurrentNode();
				saveState();
				return;
			}
			if (!canSelect()) {
				return;
			}
			if (this.select_node_handler.isNodeSelected(node)) {
				if (must_toggle) {
					this._deselectCurrentNode();
					this._triggerEvent('tree.select', {
						node: null,
						previous_node: node
					});
				}
			} else {
				deselected_node = this.getSelectedNode();
				this._deselectCurrentNode();
				this.addToSelection(node);
				this._triggerEvent('tree.select', {
					node: node,
					deselected_node: deselected_node
				});
				openParents();
			}
			return saveState();
		};

		JqTreeWidget.prototype.getSelectedNode = function() {
			return this.select_node_handler.getSelectedNode();
		};

		JqTreeWidget.prototype.toJson = function() {
			return JSON.stringify(this.tree.getData());
		};

		JqTreeWidget.prototype.loadData = function(data, parent_node) {
			return this._loadData(data, parent_node);
		};

		JqTreeWidget.prototype.loadDataFromUrl = function(url, parent_node, on_finished) {
			if ($.type(url) !== 'string') {
				on_finished = parent_node;
				parent_node = url;
				url = null;
			}
			return this._loadDataFromUrl(url, parent_node, on_finished);
		};

		JqTreeWidget.prototype._loadDataFromUrl = function(url_info, parent_node, on_finished) {
			var $el,
				addLoadingClass,
				parseUrlInfo,
				removeLoadingClass,
				_this = this;
			$el = null;
			addLoadingClass = function() {
				var folder_element;
				if (!parent_node) {
					$el = _this.element;
				} else {
					folder_element = new FolderElement(parent_node, _this);
					$el = folder_element.getLi();
				}
				return $el.addClass('jqtree-loading');
			};
			removeLoadingClass = function() {
				if ($el) {
					return $el.removeClass('jqtree-loading');
				}
			};
			parseUrlInfo = function() {
				if ($.type(url_info) === 'string') {
					url_info = {
						url: url_info
					};
				}
				if (!url_info.method) {
					return url_info.method = 'get';
				}
			};
			addLoadingClass();
			if (!url_info) {
				url_info = this._getDataUrlInfo(parent_node);
			}
			parseUrlInfo();
			return $.ajax({
				url: url_info.url,
				data: url_info.data,
				type: url_info.method.toUpperCase(),
				cache: false,
				dataType: 'json',
				success: function(response) {
					var data;
					if ($.isArray(response) || typeof response === 'object') {
						data = response;
					} else {
						data = $.parseJSON(response);
					}
					if (_this.options.dataFilter) {
						data = _this.options.dataFilter(data);
					}
					removeLoadingClass();
					_this._loadData(data, parent_node);
					if (on_finished && $.isFunction(on_finished)) {
						return on_finished();
					}
				},
				error: function(response) {
					removeLoadingClass();
					if (_this.options.onLoadFailed) {
						return _this.options.onLoadFailed(response);
					}
				}
			});
		};

		JqTreeWidget.prototype._loadData = function(data, parent_node) {
			var n, selected_nodes_under_parent, _i, _len;
			if (!data) {
				return;
			}
			this._triggerEvent('tree.load_data', {
				tree_data: data
			});
			if (!parent_node) {
				this._initTree(data);
			} else {
				selected_nodes_under_parent = this.select_node_handler.getSelectedNodes(parent_node);
				for (_i = 0, _len = selected_nodes_under_parent.length; _i < _len; _i++) {
					n = selected_nodes_under_parent[_i];
					this.select_node_handler.removeFromSelection(n);
				}
				parent_node.loadFromData(data);
				parent_node.load_on_demand = false;
				this._refreshElements(parent_node.parent);
			}
			if (this.is_dragging) {
				return this.dnd_handler.refreshHitAreas();
			}
		};

		JqTreeWidget.prototype.getNodeById = function(node_id) {
			return this.tree.getNodeById(node_id);
		};

		JqTreeWidget.prototype.getNodeByName = function(name) {
			return this.tree.getNodeByName(name);
		};

		JqTreeWidget.prototype.openNode = function(node, slide) {
			if (slide == null) {
				slide = true;
			}
			return this._openNode(node, slide);
		};

		JqTreeWidget.prototype._openNode = function(node, slide, on_finished) {
			var doOpenNode,
				parent,
				_this = this;
			if (slide == null) {
				slide = true;
			}
			doOpenNode = function(_node, _slide, _on_finished) {
				var folder_element;
				folder_element = new FolderElement(_node, _this);
				return folder_element.open(_on_finished, _slide);
			};
			if (node.isFolder()) {
				if (node.load_on_demand) {
					return this._loadFolderOnDemand(node, slide, on_finished);
				} else {
					parent = node.parent;
					while (parent && !parent.is_open) {
						if (parent.parent) {
							doOpenNode(parent, false, null);
						}
						parent = parent.parent;
					}
					doOpenNode(node, slide, on_finished);
					return this._saveState();
				}
			}
		};

		JqTreeWidget.prototype._loadFolderOnDemand = function(node, slide, on_finished) {
			var _this = this;
			if (slide == null) {
				slide = true;
			}
			return this._loadDataFromUrl(null, node, function() {
				return _this._openNode(node, slide, on_finished);
			});
		};

		JqTreeWidget.prototype.closeNode = function(node, slide) {
			if (slide == null) {
				slide = true;
			}
			if (node.isFolder()) {
				new FolderElement(node, this).close(slide);
				return this._saveState();
			}
		};

		JqTreeWidget.prototype.isDragging = function() {
			return this.is_dragging;
		};

		JqTreeWidget.prototype.refreshHitAreas = function() {
			return this.dnd_handler.refreshHitAreas();
		};

		JqTreeWidget.prototype.addNodeAfter = function(new_node_info, existing_node) {
			var new_node;
			new_node = existing_node.addAfter(new_node_info);
			this._refreshElements(existing_node.parent);
			return new_node;
		};

		JqTreeWidget.prototype.addNodeBefore = function(new_node_info, existing_node) {
			var new_node;
			new_node = existing_node.addBefore(new_node_info);
			this._refreshElements(existing_node.parent);
			return new_node;
		};

		JqTreeWidget.prototype.addParentNode = function(new_node_info, existing_node) {
			var new_node;
			new_node = existing_node.addParent(new_node_info);
			this._refreshElements(new_node.parent);
			return new_node;
		};

		JqTreeWidget.prototype.removeNode = function(node) {
			var parent;
			parent = node.parent;
			if (parent) {
				this.select_node_handler.removeFromSelection(node, true);
				node.remove();
				return this._refreshElements(parent.parent);
			}
		};

		JqTreeWidget.prototype.appendNode = function(new_node_info, parent_node) {
			var is_already_folder_node, node;
			if (!parent_node) {
				parent_node = this.tree;
			}
			is_already_folder_node = parent_node.isFolder();
			node = parent_node.append(new_node_info);
			if (is_already_folder_node) {
				this._refreshElements(parent_node);
			} else {
				this._refreshElements(parent_node.parent);
			}
			return node;
		};

		JqTreeWidget.prototype.prependNode = function(new_node_info, parent_node) {
			var node;
			if (!parent_node) {
				parent_node = this.tree;
			}
			node = parent_node.prepend(new_node_info);
			this._refreshElements(parent_node);
			return node;
		};

		JqTreeWidget.prototype.updateNode = function(node, data) {
			var id_is_changed;
			id_is_changed = data.id && data.id !== node.id;
			if (id_is_changed) {
				this.tree.removeNodeFromIndex(node);
			}
			node.setData(data);
			if (id_is_changed) {
				this.tree.addNodeToIndex(node);
			}
			this._refreshElements(node.parent);
			return this._selectCurrentNode();
		};

		JqTreeWidget.prototype.moveNode = function(node, target_node, position) {
			var position_index;
			position_index = Position.nameToIndex(position);
			this.tree.moveNode(node, target_node, position_index);
			return this._refreshElements();
		};

		JqTreeWidget.prototype.getStateFromStorage = function() {
			return this.save_state_handler.getStateFromStorage();
		};

		JqTreeWidget.prototype.addToSelection = function(node) {
			this.select_node_handler.addToSelection(node);
			return this._getNodeElementForNode(node).select();
		};

		JqTreeWidget.prototype.getSelectedNodes = function() {
			return this.select_node_handler.getSelectedNodes();
		};

		JqTreeWidget.prototype.isNodeSelected = function(node) {
			return this.select_node_handler.isNodeSelected(node);
		};

		JqTreeWidget.prototype.removeFromSelection = function(node) {
			this.select_node_handler.removeFromSelection(node);
			return this._getNodeElementForNode(node).deselect();
		};

		JqTreeWidget.prototype.scrollToNode = function(node) {
			var $element, top;
			$element = $(node.element);
			top = $element.offset().top - this.$el.offset().top;
			return this.scroll_handler.scrollTo(top);
		};

		JqTreeWidget.prototype.getState = function() {
			return this.save_state_handler.getState();
		};

		JqTreeWidget.prototype.setState = function(state) {
			this.save_state_handler.setState(state);
			return this._refreshElements();
		};

		JqTreeWidget.prototype._init = function() {
			JqTreeWidget.__super__._init.call(this);
			this.element = this.$el;
			this.mouse_delay = 300;
			this.is_initialized = false;
			if (typeof SaveStateHandler !== "undefined" && SaveStateHandler !== null) {
				this.save_state_handler = new SaveStateHandler(this);
			} else {
				this.options.saveState = false;
			}
			if (typeof SelectNodeHandler !== "undefined" && SelectNodeHandler !== null) {
				this.select_node_handler = new SelectNodeHandler(this);
			}
			if (typeof DragAndDropHandler !== "undefined" && DragAndDropHandler !== null) {
				this.dnd_handler = new DragAndDropHandler(this);
			} else {
				this.options.dragAndDrop = false;
			}
			if (typeof ScrollHandler !== "undefined" && ScrollHandler !== null) {
				this.scroll_handler = new ScrollHandler(this);
			}
			if ((typeof KeyHandler !== "undefined" && KeyHandler !== null) && (typeof SelectNodeHandler !== "undefined" && SelectNodeHandler !== null)) {
				this.key_handler = new KeyHandler(this);
			}
			this._initData();
			this.element.click($.proxy(this._click, this));
			this.element.dblclick($.proxy(this._dblclick, this));
			if (this.options.useContextMenu) {
				return this.element.bind('contextmenu', $.proxy(this._contextmenu, this));
			}
		};

		JqTreeWidget.prototype._deinit = function() {
			this.element.empty();
			this.element.unbind();
			this.key_handler.deinit();
			this.tree = null;
			return JqTreeWidget.__super__._deinit.call(this);
		};

		JqTreeWidget.prototype._initData = function() {
			if (this.options.data) {
				return this._loadData(this.options.data);
			} else {
				return this._loadDataFromUrl(this._getDataUrlInfo());
			}
		};

		JqTreeWidget.prototype._getDataUrlInfo = function(node) {
			var data_url,
				getUrlFromString,
				_this = this;
			data_url = this.options.dataUrl || this.element.data('url');
			getUrlFromString = function() {
				var data, selected_node_id, url_info;
				url_info = {
					url: data_url
				};
				if (node && node.id) {
					data = {
						node: node.id
					};
					url_info['data'] = data;
				} else {
					selected_node_id = _this._getNodeIdToBeSelected();
					if (selected_node_id) {
						data = {
							selected_node: selected_node_id
						};
						url_info['data'] = data;
					}
				}
				return url_info;
			};
			if ($.isFunction(data_url)) {
				return data_url(node);
			} else if ($.type(data_url) === 'string') {
				return getUrlFromString();
			} else {
				return data_url;
			}
		};

		JqTreeWidget.prototype._getNodeIdToBeSelected = function() {
			if (this.options.saveState) {
				return this.save_state_handler.getNodeIdToBeSelected();
			} else {
				return null;
			}
		};

		JqTreeWidget.prototype._initTree = function(data) {
			this.tree = new this.options.nodeClass(null, true, this.options.nodeClass);
			if (this.select_node_handler) {
				this.select_node_handler.clear();
			}
			this.tree.loadFromData(data);
			this._openNodes();
			this._refreshElements();
			if (!this.is_initialized) {
				this.is_initialized = true;
				return this._triggerEvent('tree.init');
			}
		};

		JqTreeWidget.prototype._openNodes = function() {
			var max_level;
			if (this.options.saveState) {
				if (this.save_state_handler.restoreState()) {
					return;
				}
			}
			if (this.options.autoOpen === false) {
				return;
			} else if (this.options.autoOpen === true) {
				max_level = -1;
			} else {
				max_level = parseInt(this.options.autoOpen);
			}
			return this.tree.iterate(function(node, level) {
				if (node.hasChildren()) {
					node.is_open = true;
				}
				return level !== max_level;
			});
		};

		JqTreeWidget.prototype._refreshElements = function(from_node) {
			var $element,
				createFolderLi,
				createLi,
				createNodeLi,
				createUl,
				doCreateDomElements,
				escapeIfNecessary,
				is_root_node,
				node_element,
				_this = this;
			if (from_node == null) {
				from_node = null;
			}
			escapeIfNecessary = function(value) {
				if (_this.options.autoEscape) {
					return html_escape(value);
				} else {
					return value;
				}
			};
			createUl = function(is_root_node) {
				var class_string;
				if (is_root_node) {
					class_string = 'jqtree-tree nav nav-stacked';
				} else {
					class_string = '';
				}
				return $("<ul class=\"jqtree_common " + class_string + "\"></ul>");
			};
			createLi = function(node) {
				var $li;
				if (node.isFolder()) {
					$li = createFolderLi(node);
				} else {
					$li = createNodeLi(node);
				}
				if (_this.options.onCreateLi) {
					_this.options.onCreateLi(node, $li);
				}
				return $li;
			};
			createNodeLi = function(node) {
				var class_string, escaped_name, li_classes;
				li_classes = ['jqtree_common'];
				if (_this.select_node_handler && _this.select_node_handler.isNodeSelected(node)) {
					li_classes.push('jqtree-selected');
				}
				class_string = li_classes.join(' ');
				escaped_name = escapeIfNecessary(node.name);
				return $("<li class=\"" + class_string + "\"><div class=\"jqtree-element jqtree_common\"><span class=\"jqtree-title jqtree_common\">" + escaped_name + "</span></div></li>");
			};
			createFolderLi = function(node) {
				var button_char, button_classes, escaped_name, folder_classes, getButtonClasses, getFolderClasses;
				getButtonClasses = function() {
					var classes;
					classes = ['jqtree-toggler'];
					if (!node.is_open) {
						classes.push('jqtree-closed');
					}
					return classes.join(' ');
				};
				getFolderClasses = function() {
					var classes;
					classes = ['jqtree-folder'];
					if (!node.is_open) {
						classes.push('jqtree-closed');
					}
					if (_this.select_node_handler && _this.select_node_handler.isNodeSelected(node)) {
						classes.push('jqtree-selected');
					}
					return classes.join(' ');
				};
				button_classes = getButtonClasses();
				folder_classes = getFolderClasses();
				escaped_name = escapeIfNecessary(node.name);
				if (node.is_open) {
					button_char = _this.options.openedIcon;
				} else {
					button_char = _this.options.closedIcon;
				}
				return $("<li class=\"jqtree_common " + folder_classes + "\"><div class=\"jqtree-element jqtree_common\"><a class=\"jqtree_common " + button_classes + "\">" + button_char + "</a><span class=\"jqtree_common jqtree-title\">" + escaped_name + "</span></div></li>");
			};
			doCreateDomElements = function($element, children, is_root_node, is_open) {
				var $li, $ul, child, _i, _len;
				$ul = createUl(is_root_node);
				$element.append($ul);
				for (_i = 0, _len = children.length; _i < _len; _i++) {
					child = children[_i];
					$li = createLi(child);
					$ul.append($li);
					child.element = $li[0];
					$li.data('node', child);
					if (child.hasChildren()) {
						doCreateDomElements($li, child.children, false, child.is_open);
					}
				}
				return null;
			};
			if (from_node && from_node.parent) {
				is_root_node = false;
				node_element = this._getNodeElementForNode(from_node);
				node_element.getUl().remove();
				$element = node_element.$element;
			} else {
				from_node = this.tree;
				$element = this.element;
				$element.empty();
				is_root_node = true;
			}
			doCreateDomElements($element, from_node.children, is_root_node, is_root_node);
			return this._triggerEvent('tree.refresh');
		};

		JqTreeWidget.prototype._click = function(e) {
			var click_target, event, node;
			click_target = this._getClickTarget(e.target);
			if (click_target) {
				if (click_target.type === 'button') {
					this.toggle(click_target.node, this.options.slide);
					e.preventDefault();
					return e.stopPropagation();
				} else if (click_target.type === 'label') {
					node = click_target.node;
					event = this._triggerEvent('tree.click', {
						node: node,
						click_event: e
					});
					if (!event.isDefaultPrevented()) {
						return this._selectNode(node, true);
					}
				}
			}
		};

		JqTreeWidget.prototype._dblclick = function(e) {
			var click_target;
			click_target = this._getClickTarget(e.target);
			if (click_target && click_target.type === 'label') {
				return this._triggerEvent('tree.dblclick', {
					node: click_target.node,
					click_event: e
				});
			}
		};

		JqTreeWidget.prototype._getClickTarget = function(element) {
			var $button, $el, $target, node;
			$target = $(element);
			$button = $target.closest('.jqtree-toggler');
			if ($button.length) {
				node = this._getNode($button);
				if (node) {
					return {
						type: 'button',
						node: node
					};
				}
			} else {
				$el = $target.closest('.jqtree-element');
				if ($el.length) {
					node = this._getNode($el);
					if (node) {
						return {
							type: 'label',
							node: node
						};
					}
				}
			}
			return null;
		};

		JqTreeWidget.prototype._getNode = function($element) {
			var $li;
			$li = $element.closest('li');
			if ($li.length === 0) {
				return null;
			} else {
				return $li.data('node');
			}
		};

		JqTreeWidget.prototype._getNodeElementForNode = function(node) {
			if (node.isFolder()) {
				return new FolderElement(node, this);
			} else {
				return new NodeElement(node, this);
			}
		};

		JqTreeWidget.prototype._getNodeElement = function($element) {
			var node;
			node = this._getNode($element);
			if (node) {
				return this._getNodeElementForNode(node);
			} else {
				return null;
			}
		};

		JqTreeWidget.prototype._contextmenu = function(e) {
			var $div, node;
			$div = $(e.target).closest('ul.jqtree-tree .jqtree-element');
			if ($div.length) {
				node = this._getNode($div);
				if (node) {
					e.preventDefault();
					e.stopPropagation();
					this._triggerEvent('tree.contextmenu', {
						node: node,
						click_event: e
					});
					return false;
				}
			}
		};

		JqTreeWidget.prototype._saveState = function() {
			if (this.options.saveState) {
				return this.save_state_handler.saveState();
			}
		};

		JqTreeWidget.prototype._mouseCapture = function(position_info) {
			if (this.options.dragAndDrop) {
				return this.dnd_handler.mouseCapture(position_info);
			} else {
				return false;
			}
		};

		JqTreeWidget.prototype._mouseStart = function(position_info) {
			if (this.options.dragAndDrop) {
				return this.dnd_handler.mouseStart(position_info);
			} else {
				return false;
			}
		};

		JqTreeWidget.prototype._mouseDrag = function(position_info) {
			var result;
			if (this.options.dragAndDrop) {
				result = this.dnd_handler.mouseDrag(position_info);
				if (this.scroll_handler) {
					this.scroll_handler.checkScrolling();
				}
				return result;
			} else {
				return false;
			}
		};

		JqTreeWidget.prototype._mouseStop = function(position_info) {
			if (this.options.dragAndDrop) {
				return this.dnd_handler.mouseStop(position_info);
			} else {
				return false;
			}
		};

		JqTreeWidget.prototype._triggerEvent = function(event_name, values) {
			var event;
			event = $.Event(event_name);
			$.extend(event, values);
			this.element.trigger(event);
			return event;
		};

		JqTreeWidget.prototype.testGenerateHitAreas = function(moving_node) {
			this.dnd_handler.current_item = this._getNodeElementForNode(moving_node);
			this.dnd_handler.generateHitAreas();
			return this.dnd_handler.hit_areas;
		};

		JqTreeWidget.prototype._selectCurrentNode = function() {
			var node, node_element;
			node = this.getSelectedNode();
			if (node) {
				node_element = this._getNodeElementForNode(node);
				if (node_element) {
					return node_element.select();
				}
			}
		};

		JqTreeWidget.prototype._deselectCurrentNode = function() {
			var node;
			node = this.getSelectedNode();
			if (node) {
				return this.removeFromSelection(node);
			}
		};

		return JqTreeWidget;

	})(MouseWidget);

	SimpleWidget.register(JqTreeWidget, 'tree');

	NodeElement = (function() {
		function NodeElement(node, tree_widget) {
			this.init(node, tree_widget);
		}

		NodeElement.prototype.init = function(node, tree_widget) {
			this.node = node;
			this.tree_widget = tree_widget;
			return this.$element = $(node.element);
		};

		NodeElement.prototype.getUl = function() {
			return this.$element.children('ul:first');
		};

		NodeElement.prototype.getSpan = function() {
			return this.$element.children('.jqtree-element').find('span.jqtree-title');
		};

		NodeElement.prototype.getLi = function() {
			return this.$element;
		};

		NodeElement.prototype.addDropHint = function(position) {
			if (position === Position.INSIDE) {
				return new BorderDropHint(this.$element);
			} else {
				return new GhostDropHint(this.node, this.$element, position);
			}
		};

		NodeElement.prototype.select = function() {
			return this.getLi().addClass('jqtree-selected');
		};

		NodeElement.prototype.deselect = function() {
			return this.getLi().removeClass('jqtree-selected');
		};

		return NodeElement;

	})();

	FolderElement = (function(_super) {
		__extends(FolderElement, _super);

		function FolderElement() {
			_ref2 = FolderElement.__super__.constructor.apply(this, arguments);
			return _ref2;
		}

		FolderElement.prototype.open = function(on_finished, slide) {
			var $button,
				doOpen,
				_this = this;
			if (slide == null) {
				slide = true;
			}
			if (!this.node.is_open) {
				this.node.is_open = true;
				$button = this.getButton();
				$button.removeClass('jqtree-closed');
				$button.html(this.tree_widget.options.openedIcon);
				doOpen = function() {
					_this.getLi().removeClass('jqtree-closed');
					if (on_finished) {
						on_finished();
					}
					return _this.tree_widget._triggerEvent('tree.open', {
						node: _this.node
					});
				};
				if (slide) {
					return this.getUl().slideDown('fast', doOpen);
				} else {
					this.getUl().show();
					return doOpen();
				}
			}
		};

		FolderElement.prototype.close = function(slide) {
			var $button,
				doClose,
				_this = this;
			if (slide == null) {
				slide = true;
			}
			if (this.node.is_open) {
				this.node.is_open = false;
				$button = this.getButton();
				$button.addClass('jqtree-closed');
				$button.html(this.tree_widget.options.closedIcon);
				doClose = function() {
					_this.getLi().addClass('jqtree-closed');
					return _this.tree_widget._triggerEvent('tree.close', {
						node: _this.node
					});
				};
				if (slide) {
					return this.getUl().slideUp('fast', doClose);
				} else {
					this.getUl().hide();
					return doClose();
				}
			}
		};

		FolderElement.prototype.getButton = function() {
			return this.$element.children('.jqtree-element').find('a.jqtree-toggler');
		};

		FolderElement.prototype.addDropHint = function(position) {
			if (!this.node.is_open && position === Position.INSIDE) {
				return new BorderDropHint(this.$element);
			} else {
				return new GhostDropHint(this.node, this.$element, position);
			}
		};

		return FolderElement;

	})(NodeElement);

	html_escape = function(string) {
		return ('' + string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g, '&#x2F;');
	};

	_indexOf = function(array, item) {
		var i, value, _i, _len;
		for (i = _i = 0, _len = array.length; _i < _len; i = ++_i) {
			value = array[i];
			if (value === item) {
				return i;
			}
		}
		return -1;
	};

	indexOf = function(array, item) {
		if (array.indexOf) {
			return array.indexOf(item);
		} else {
			return _indexOf(array, item);
		}
	};

	this.Tree.indexOf = indexOf;

	this.Tree._indexOf = _indexOf;

	if (!((this.JSON != null) && (this.JSON.stringify != null) && typeof this.JSON.stringify === 'function')) {
		json_escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
		json_meta = {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"': '\\"',
			'\\': '\\\\'
		};
		json_quote = function(string) {
			json_escapable.lastIndex = 0;
			if (json_escapable.test(string)) {
				return '"' + string.replace(json_escapable, function(a) {
					var c;
					c = json_meta[a];
					return (typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4));
				}) + '"';
			} else {
				return '"' + string + '"';
			}
		};
		json_str = function(key, holder) {
			var i, k, partial, v, value, _i, _len;
			value = holder[key];
			switch (typeof value) {
			case 'string':
				return json_quote(value);
			case 'number':
				if (isFinite(value)) {
					return String(value);
				} else {
					return 'null';
				}
			case 'boolean':
			case 'null':
				return String(value);
			case 'object':
				if (!value) {
					return 'null';
				}
				partial = [];
				if (Object.prototype.toString.apply(value) === '[object Array]') {
					for (i = _i = 0, _len = value.length; _i < _len; i = ++_i) {
						v = value[i];
						partial[i] = json_str(i, value) || 'null';
					}
					return (partial.length === 0 ? '[]' : '[' + partial.join(',') + ']');
				}
				for (k in value) {
					if (Object.prototype.hasOwnProperty.call(value, k)) {
						v = json_str(k, value);
						if (v) {
							partial.push(json_quote(k) + ':' + v);
						}
					}
				}
				return (partial.length === 0 ? '{}' : '{' + partial.join(',') + '}');
			}
		};
		if (this.JSON == null) {
			this.JSON = {};
		}
		this.JSON.stringify = function(value) {
			return json_str('', {
				'': value
			});
		};
	}

	SaveStateHandler = (function() {
		function SaveStateHandler(tree_widget) {
			this.tree_widget = tree_widget;
		}

		SaveStateHandler.prototype.saveState = function() {
			var state;
			state = JSON.stringify(this.getState());
			if (this.tree_widget.options.onSetStateFromStorage) {
				return this.tree_widget.options.onSetStateFromStorage(state);
			} else if (this.supportsLocalStorage()) {
				return localStorage.setItem(this.getCookieName(), state);
			} else if ($.cookie) {
				$.cookie.raw = true;
				return $.cookie(this.getCookieName(), state, {
					path: '/'
				});
			}
		};

		SaveStateHandler.prototype.restoreState = function() {
			var state;
			state = this.getStateFromStorage();
			if (state) {
				this.setState($.parseJSON(state));
				return true;
			} else {
				return false;
			}
		};

		SaveStateHandler.prototype.getStateFromStorage = function() {
			if (this.tree_widget.options.onGetStateFromStorage) {
				return this.tree_widget.options.onGetStateFromStorage();
			} else if (this.supportsLocalStorage()) {
				return localStorage.getItem(this.getCookieName());
			} else if ($.cookie) {
				$.cookie.raw = true;
				return $.cookie(this.getCookieName());
			} else {
				return null;
			}
		};

		SaveStateHandler.prototype.getState = function() {
			var open_nodes,
				selected_node,
				selected_node_id,
				_this = this;
			open_nodes = [];
			this.tree_widget.tree.iterate(function(node) {
				if (node.is_open && node.id && node.hasChildren()) {
					open_nodes.push(node.id);
				}
				return true;
			});
			selected_node = this.tree_widget.getSelectedNode();
			if (selected_node) {
				selected_node_id = selected_node.id;
			} else {
				selected_node_id = '';
			}
			return {
				open_nodes: open_nodes,
				selected_node: selected_node_id
			};
		};

		SaveStateHandler.prototype.setState = function(state) {
			var open_nodes,
				selected_node,
				selected_node_id,
				_this = this;
			if (state) {
				open_nodes = state.open_nodes;
				selected_node_id = state.selected_node;
				this.tree_widget.tree.iterate(function(node) {
					node.is_open = node.id && node.hasChildren() && (indexOf(open_nodes, node.id) >= 0);
					return true;
				});
				if (selected_node_id && this.tree_widget.select_node_handler) {
					this.tree_widget.select_node_handler.clear();
					selected_node = this.tree_widget.getNodeById(selected_node_id);
					if (selected_node) {
						return this.tree_widget.select_node_handler.addToSelection(selected_node);
					}
				}
			}
		};

		SaveStateHandler.prototype.getCookieName = function() {
			if (typeof this.tree_widget.options.saveState === 'string') {
				return this.tree_widget.options.saveState;
			} else {
				return 'tree';
			}
		};

		SaveStateHandler.prototype.supportsLocalStorage = function() {
			var testSupport;
			testSupport = function() {
				var error, key;
				if (typeof localStorage === "undefined" || localStorage === null) {
					return false;
				} else {
					try {
						key = '_storage_test';
						sessionStorage.setItem(key, true);
						sessionStorage.removeItem(key);
					} catch (_error) {
						error = _error;
						return false;
					}
					return true;
				}
			};
			if (this._supportsLocalStorage == null) {
				this._supportsLocalStorage = testSupport();
			}
			return this._supportsLocalStorage;
		};

		SaveStateHandler.prototype.getNodeIdToBeSelected = function() {
			var state, state_json;
			state_json = this.getStateFromStorage();
			if (state_json) {
				state = $.parseJSON(state_json);
				return state.selected_node;
			} else {
				return null;
			}
		};

		return SaveStateHandler;

	})();

	SelectNodeHandler = (function() {
		function SelectNodeHandler(tree_widget) {
			this.tree_widget = tree_widget;
			this.clear();
		}

		SelectNodeHandler.prototype.getSelectedNode = function() {
			var selected_nodes;
			selected_nodes = this.getSelectedNodes();
			if (selected_nodes.length) {
				return selected_nodes[0];
			} else {
				return false;
			}
		};

		SelectNodeHandler.prototype.getSelectedNodes = function() {
			var id, node, selected_nodes;
			if (this.selected_single_node) {
				return [this.selected_single_node];
			} else {
				selected_nodes = [];
				for (id in this.selected_nodes) {
					node = this.tree_widget.getNodeById(id);
					if (node) {
						selected_nodes.push(node);
					}
				}
				return selected_nodes;
			}
		};

		SelectNodeHandler.prototype.isNodeSelected = function(node) {
			if (node.id) {
				return this.selected_nodes[node.id];
			} else if (this.selected_single_node) {
				return this.selected_single_node.element === node.element;
			} else {
				return false;
			}
		};

		SelectNodeHandler.prototype.clear = function() {
			this.selected_nodes = {};
			return this.selected_single_node = null;
		};

		SelectNodeHandler.prototype.removeFromSelection = function(node, include_children) {
			var _this = this;
			if (include_children == null) {
				include_children = false;
			}
			if (!node.id) {
				if (this.selected_single_node && node.element === this.selected_single_node.element) {
					return this.selected_single_node = null;
				}
			} else {
				delete this.selected_nodes[node.id];
				if (include_children) {
					return node.iterate(function(n) {
						delete _this.selected_nodes[node.id];
						return true;
					});
				}
			}
		};

		SelectNodeHandler.prototype.addToSelection = function(node) {
			if (node.id) {
				return this.selected_nodes[node.id] = true;
			} else {
				return this.selected_single_node = node;
			}
		};

		return SelectNodeHandler;

	})();

	DragAndDropHandler = (function() {
		function DragAndDropHandler(tree_widget) {
			this.tree_widget = tree_widget;
			this.hovered_area = null;
			this.$ghost = null;
			this.hit_areas = [];
			this.is_dragging = false;
		}

		DragAndDropHandler.prototype.mouseCapture = function(position_info) {
			var $element, node_element;
			$element = $(position_info.target);
			if (this.tree_widget.options.onIsMoveHandle && !this.tree_widget.options.onIsMoveHandle($element)) {
				return null;
			}
			node_element = this.tree_widget._getNodeElement($element);
			if (node_element && this.tree_widget.options.onCanMove) {
				if (!this.tree_widget.options.onCanMove(node_element.node)) {
					node_element = null;
				}
			}
			this.current_item = node_element;
			return this.current_item !== null;
		};

		DragAndDropHandler.prototype.mouseStart = function(position_info) {
			var offset;
			this.refreshHitAreas();
			offset = $(position_info.target).offset();
			this.drag_element = new DragElement(this.current_item.node, position_info.page_x - offset.left, position_info.page_y - offset.top, this.tree_widget.element);
			this.is_dragging = true;
			this.current_item.$element.addClass('jqtree-moving');
			return true;
		};

		DragAndDropHandler.prototype.mouseDrag = function(position_info) {
			var area, can_move_to;
			this.drag_element.move(position_info.page_x, position_info.page_y);
			area = this.findHoveredArea(position_info.page_x, position_info.page_y);
			can_move_to = this.canMoveToArea(area);
			if (area) {
				if (this.hovered_area !== area) {
					this.hovered_area = area;
					if (this.mustOpenFolderTimer(area)) {
						this.startOpenFolderTimer(area.node);
					}
					if (can_move_to) {
						this.updateDropHint();
					}
				}
			} else {
				this.removeHover();
				this.removeDropHint();
				this.stopOpenFolderTimer();
			}
			return true;
		};

		DragAndDropHandler.prototype.canMoveToArea = function(area) {
			var position_name;
			if (!area) {
				return false;
			} else if (this.tree_widget.options.onCanMoveTo) {
				position_name = Position.getName(area.position);
				return this.tree_widget.options.onCanMoveTo(this.current_item.node, area.node, position_name);
			} else {
				return true;
			}
		};

		DragAndDropHandler.prototype.mouseStop = function(position_info) {
			this.moveItem(position_info);
			this.clear();
			this.removeHover();
			this.removeDropHint();
			this.removeHitAreas();
			if (this.current_item) {
				this.current_item.$element.removeClass('jqtree-moving');
			}
			this.is_dragging = false;
			return false;
		};

		DragAndDropHandler.prototype.refreshHitAreas = function() {
			this.removeHitAreas();
			return this.generateHitAreas();
		};

		DragAndDropHandler.prototype.removeHitAreas = function() {
			return this.hit_areas = [];
		};

		DragAndDropHandler.prototype.clear = function() {
			this.drag_element.remove();
			return this.drag_element = null;
		};

		DragAndDropHandler.prototype.removeDropHint = function() {
			if (this.previous_ghost) {
				return this.previous_ghost.remove();
			}
		};

		DragAndDropHandler.prototype.removeHover = function() {
			return this.hovered_area = null;
		};

		DragAndDropHandler.prototype.generateHitAreas = function() {
			var hit_areas_generator;
			hit_areas_generator = new HitAreasGenerator(this.tree_widget.tree, this.current_item.node, this.getTreeDimensions().bottom);
			return this.hit_areas = hit_areas_generator.generate();
		};

		DragAndDropHandler.prototype.findHoveredArea = function(x, y) {
			var area, dimensions, high, low, mid;
			dimensions = this.getTreeDimensions();
			if (x < dimensions.left || y < dimensions.top || x > dimensions.right || y > dimensions.bottom) {
				return null;
			}
			low = 0;
			high = this.hit_areas.length;
			while (low < high) {
				mid = (low + high) >> 1;
				area = this.hit_areas[mid];
				if (y < area.top) {
					high = mid;
				} else if (y > area.bottom) {
					low = mid + 1;
				} else {
					return area;
				}
			}
			return null;
		};

		DragAndDropHandler.prototype.mustOpenFolderTimer = function(area) {
			var node;
			node = area.node;
			return node.isFolder() && !node.is_open && area.position === Position.INSIDE;
		};

		DragAndDropHandler.prototype.updateDropHint = function() {
			var node_element;
			if (!this.hovered_area) {
				return;
			}
			this.removeDropHint();
			node_element = this.tree_widget._getNodeElementForNode(this.hovered_area.node);
			return this.previous_ghost = node_element.addDropHint(this.hovered_area.position);
		};

		DragAndDropHandler.prototype.startOpenFolderTimer = function(folder) {
			var openFolder,
				_this = this;
			openFolder = function() {
				return _this.tree_widget._openNode(folder, _this.tree_widget.options.slide, function() {
					_this.refreshHitAreas();
					return _this.updateDropHint();
				});
			};
			this.stopOpenFolderTimer();
			return this.open_folder_timer = setTimeout(openFolder, this.tree_widget.options.openFolderDelay);
		};

		DragAndDropHandler.prototype.stopOpenFolderTimer = function() {
			if (this.open_folder_timer) {
				clearTimeout(this.open_folder_timer);
				return this.open_folder_timer = null;
			}
		};

		DragAndDropHandler.prototype.moveItem = function(position_info) {
			var doMove,
				event,
				moved_node,
				position,
				previous_parent,
				target_node,
				_this = this;
			if (this.hovered_area && this.hovered_area.position !== Position.NONE && this.canMoveToArea(this.hovered_area)) {
				moved_node = this.current_item.node;
				target_node = this.hovered_area.node;
				position = this.hovered_area.position;
				previous_parent = moved_node.parent;
				if (position === Position.INSIDE) {
					this.hovered_area.node.is_open = true;
				}
				doMove = function() {
					_this.tree_widget.tree.moveNode(moved_node, target_node, position);
					_this.tree_widget.element.empty();
					return _this.tree_widget._refreshElements();
				};
				event = this.tree_widget._triggerEvent('tree.move', {
					move_info: {
						moved_node: moved_node,
						target_node: target_node,
						position: Position.getName(position),
						previous_parent: previous_parent,
						do_move: doMove,
						original_event: position_info.original_event
					}
				});
				if (!event.isDefaultPrevented()) {
					return doMove();
				}
			}
		};

		DragAndDropHandler.prototype.getTreeDimensions = function() {
			var offset;
			offset = this.tree_widget.element.offset();
			return {
				left: offset.left,
				top: offset.top,
				right: offset.left + this.tree_widget.element.width(),
				bottom: offset.top + this.tree_widget.element.height() + 16
			};
		};

		return DragAndDropHandler;

	})();

	VisibleNodeIterator = (function() {
		function VisibleNodeIterator(tree) {
			this.tree = tree;
		}

		VisibleNodeIterator.prototype.iterate = function() {
			var is_first_node,
				_iterateNode,
				_this = this;
			is_first_node = true;
			_iterateNode = function(node, next_node) {
				var $element, child, children_length, i, must_iterate_inside, _i, _len, _ref3, _results;
				must_iterate_inside = (node.is_open || !node.element) && node.hasChildren();
				if (node.element) {
					$element = $(node.element);
					if (!$element.is(':visible')) {
						return;
					}
					if (is_first_node) {
						_this.handleFirstNode(node, $element);
						is_first_node = false;
					}
					if (!node.hasChildren()) {
						_this.handleNode(node, next_node, $element);
					} else if (node.is_open) {
						if (!_this.handleOpenFolder(node, $element)) {
							must_iterate_inside = false;
						}
					} else {
						_this.handleClosedFolder(node, next_node, $element);
					}
				}
				if (must_iterate_inside) {
					children_length = node.children.length;
					_ref3 = node.children;
					_results = [];
					for (i = _i = 0, _len = _ref3.length; _i < _len; i = ++_i) {
						child = _ref3[i];
						if (i === (children_length - 1)) {
							_results.push(_iterateNode(node.children[i], null));
						} else {
							_results.push(_iterateNode(node.children[i], node.children[i + 1]));
						}
					}
					return _results;
				}
			};
			return _iterateNode(this.tree, null);
		};

		VisibleNodeIterator.prototype.handleNode = function(node, next_node, $element) {};

		VisibleNodeIterator.prototype.handleOpenFolder = function(node, $element) {};

		VisibleNodeIterator.prototype.handleClosedFolder = function(node, next_node, $element) {};

		VisibleNodeIterator.prototype.handleFirstNode = function(node, $element) {};

		return VisibleNodeIterator;

	})();

	HitAreasGenerator = (function(_super) {
		__extends(HitAreasGenerator, _super);

		function HitAreasGenerator(tree, current_node, tree_bottom) {
			HitAreasGenerator.__super__.constructor.call(this, tree);
			this.current_node = current_node;
			this.tree_bottom = tree_bottom;
		}

		HitAreasGenerator.prototype.generate = function() {
			this.positions = [];
			this.last_top = 0;
			this.iterate();
			return this.generateHitAreas(this.positions);
		};

		HitAreasGenerator.prototype.getTop = function($element) {
			return $element.offset().top;
		};

		HitAreasGenerator.prototype.addPosition = function(node, position, top) {
			this.positions.push({
				top: top,
				node: node,
				position: position
			});
			return this.last_top = top;
		};

		HitAreasGenerator.prototype.handleNode = function(node, next_node, $element) {
			var top;
			top = this.getTop($element);
			if (node === this.current_node) {
				this.addPosition(node, Position.NONE, top);
			} else {
				this.addPosition(node, Position.INSIDE, top);
			}
			if (next_node === this.current_node || node === this.current_node) {
				return this.addPosition(node, Position.NONE, top);
			} else {
				return this.addPosition(node, Position.AFTER, top);
			}
		};

		HitAreasGenerator.prototype.handleOpenFolder = function(node, $element) {
			if (node === this.current_node) {
				return false;
			}
			if (node.children[0] !== this.current_node) {
				this.addPosition(node, Position.INSIDE, this.getTop($element));
			}
			return true;
		};

		HitAreasGenerator.prototype.handleClosedFolder = function(node, next_node, $element) {
			var top;
			top = this.getTop($element);
			if (node === this.current_node) {
				return this.addPosition(node, Position.NONE, top);
			} else {
				this.addPosition(node, Position.INSIDE, top);
				if (next_node !== this.current_node) {
					return this.addPosition(node, Position.AFTER, top);
				}
			}
		};

		HitAreasGenerator.prototype.handleFirstNode = function(node, $element) {
			if (node !== this.current_node) {
				return this.addPosition(node, Position.BEFORE, this.getTop($(node.element)));
			}
		};

		HitAreasGenerator.prototype.generateHitAreas = function(positions) {
			var group, hit_areas, position, previous_top, _i, _len;
			previous_top = -1;
			group = [];
			hit_areas = [];
			for (_i = 0, _len = positions.length; _i < _len; _i++) {
				position = positions[_i];
				if (position.top !== previous_top && group.length) {
					if (group.length) {
						this.generateHitAreasForGroup(hit_areas, group, previous_top, position.top);
					}
					previous_top = position.top;
					group = [];
				}
				group.push(position);
			}
			this.generateHitAreasForGroup(hit_areas, group, previous_top, this.tree_bottom);
			return hit_areas;
		};

		HitAreasGenerator.prototype.generateHitAreasForGroup = function(hit_areas, positions_in_group, top, bottom) {
			var area_height, area_top, position, _i, _len;
			area_height = (bottom - top) / positions_in_group.length;
			area_top = top;
			for (_i = 0, _len = positions_in_group.length; _i < _len; _i++) {
				position = positions_in_group[_i];
				hit_areas.push({
					top: area_top,
					bottom: area_top + area_height,
					node: position.node,
					position: position.position
				});
				area_top += area_height;
			}
			return null;
		};

		return HitAreasGenerator;

	})(VisibleNodeIterator);

	DragElement = (function() {
		function DragElement(node, offset_x, offset_y, $tree) {
			this.offset_x = offset_x;
			this.offset_y = offset_y;
			this.$element = $("<span class=\"jqtree-title jqtree-dragging\">" + node.name + "</span>");
			this.$element.css("position", "absolute");
			$tree.append(this.$element);
		}

		DragElement.prototype.move = function(page_x, page_y) {
			return this.$element.offset({
				left: page_x - this.offset_x,
				top: page_y - this.offset_y
			});
		};

		DragElement.prototype.remove = function() {
			return this.$element.remove();
		};

		return DragElement;

	})();

	GhostDropHint = (function() {
		function GhostDropHint(node, $element, position) {
			this.$element = $element;
			this.node = node;
			this.$ghost = $('<li class="jqtree_common jqtree-ghost"><span class="jqtree_common jqtree-circle"></span><span class="jqtree_common jqtree-line"></span></li>');
			if (position === Position.AFTER) {
				this.moveAfter();
			} else if (position === Position.BEFORE) {
				this.moveBefore();
			} else if (position === Position.INSIDE) {
				if (node.isFolder() && node.is_open) {
					this.moveInsideOpenFolder();
				} else {
					this.moveInside();
				}
			}
		}

		GhostDropHint.prototype.remove = function() {
			return this.$ghost.remove();
		};

		GhostDropHint.prototype.moveAfter = function() {
			return this.$element.after(this.$ghost);
		};

		GhostDropHint.prototype.moveBefore = function() {
			return this.$element.before(this.$ghost);
		};

		GhostDropHint.prototype.moveInsideOpenFolder = function() {
			return $(this.node.children[0].element).before(this.$ghost);
		};

		GhostDropHint.prototype.moveInside = function() {
			this.$element.after(this.$ghost);
			return this.$ghost.addClass('jqtree-inside');
		};

		return GhostDropHint;

	})();

	BorderDropHint = (function() {
		function BorderDropHint($element) {
			var $div, width;
			$div = $element.children('.jqtree-element');
			width = $element.width() - 4;
			this.$hint = $('<span class="jqtree-border"></span>');
			$div.append(this.$hint);
			this.$hint.css({
				width: width,
				height: $div.height() - 4
			});
		}

		BorderDropHint.prototype.remove = function() {
			return this.$hint.remove();
		};

		return BorderDropHint;

	})();

	ScrollHandler = (function() {
		function ScrollHandler(tree_widget) {
			this.tree_widget = tree_widget;
			this.previous_top = -1;
			this._initScrollParent();
		}

		ScrollHandler.prototype._initScrollParent = function() {
			var $scroll_parent,
				getParentWithOverflow,
				setDocumentAsScrollParent,
				_this = this;
			getParentWithOverflow = function() {
				var css_values, el, hasOverFlow, _i, _len, _ref3;
				css_values = ['overflow', 'overflow-y'];
				hasOverFlow = function(el) {
					var css_value, _i, _len, _ref3;
					for (_i = 0, _len = css_values.length; _i < _len; _i++) {
						css_value = css_values[_i];
						if ((_ref3 = $.css(el, css_value)) === 'auto' || _ref3 === 'scroll') {
							return true;
						}
					}
					return false;
				};
				if (hasOverFlow(_this.tree_widget.$el[0])) {
					return _this.tree_widget.$el;
				}
				_ref3 = _this.tree_widget.$el.parents();
				for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
					el = _ref3[_i];
					if (hasOverFlow(el)) {
						return $(el);
					}
				}
				return null;
			};
			setDocumentAsScrollParent = function() {
				_this.scroll_parent_top = 0;
				return _this.$scroll_parent = null;
			};
			if (this.tree_widget.$el.css('position') === 'fixed') {
				setDocumentAsScrollParent();
			}
			$scroll_parent = getParentWithOverflow();
			if ($scroll_parent && $scroll_parent.length && $scroll_parent[0].tagName !== 'HTML') {
				this.$scroll_parent = $scroll_parent;
				return this.scroll_parent_top = this.$scroll_parent.offset().top;
			} else {
				return setDocumentAsScrollParent();
			}
		};

		ScrollHandler.prototype.checkScrolling = function() {
			var hovered_area;
			hovered_area = this.tree_widget.dnd_handler.hovered_area;
			if (hovered_area && hovered_area.top !== this.previous_top) {
				this.previous_top = hovered_area.top;
				if (this.$scroll_parent) {
					return this._handleScrollingWithScrollParent(hovered_area);
				} else {
					return this._handleScrollingWithDocument(hovered_area);
				}
			}
		};

		ScrollHandler.prototype._handleScrollingWithScrollParent = function(area) {
			var distance_bottom;
			distance_bottom = this.scroll_parent_top + this.$scroll_parent[0].offsetHeight - area.bottom;
			if (distance_bottom < 20) {
				this.$scroll_parent[0].scrollTop += 20;
				this.tree_widget.refreshHitAreas();
				return this.previous_top = -1;
			} else if ((area.top - this.scroll_parent_top) < 20) {
				this.$scroll_parent[0].scrollTop -= 20;
				this.tree_widget.refreshHitAreas();
				return this.previous_top = -1;
			}
		};

		ScrollHandler.prototype._handleScrollingWithDocument = function(area) {
			var distance_top;
			distance_top = area.top - $(document).scrollTop();
			if (distance_top < 20) {
				return $(document).scrollTop($(document).scrollTop() - 20);
			} else if ($(window).height() - (area.bottom - $(document).scrollTop()) < 20) {
				return $(document).scrollTop($(document).scrollTop() + 20);
			}
		};

		ScrollHandler.prototype.scrollTo = function(top) {
			var tree_top;
			if (this.$scroll_parent) {
				return this.$scroll_parent[0].scrollTop = top;
			} else {
				tree_top = this.tree_widget.$el.offset().top;
				return $(document).scrollTop(top + tree_top);
			}
		};

		ScrollHandler.prototype.isScrolledIntoView = function(element) {
			var $element, element_bottom, element_top, view_bottom, view_top;
			$element = $(element);
			if (this.$scroll_parent) {
				view_top = 0;
				view_bottom = this.$scroll_parent.height();
				element_top = $element.offset().top - this.scroll_parent_top;
				element_bottom = element_top + $element.height();
			} else {
				view_top = $(window).scrollTop();
				view_bottom = view_top + $(window).height();
				element_top = $element.offset().top;
				element_bottom = element_top + $element.height();
			}
			return (element_bottom <= view_bottom) && (element_top >= view_top);
		};

		return ScrollHandler;

	})();

	KeyHandler = (function() {
		var DOWN, LEFT, RIGHT, UP;

		LEFT = 37;

		UP = 38;

		RIGHT = 39;

		DOWN = 40;

		function KeyHandler(tree_widget) {
			this.tree_widget = tree_widget;
			if (tree_widget.options.keyboardSupport) {
				$(document).bind('keydown.jqtree', $.proxy(this.handleKeyDown, this));
			}
		}

		KeyHandler.prototype.deinit = function() {
			return $(document).unbind('keydown.jqtree');
		};

		KeyHandler.prototype.handleKeyDown = function(e) {
			var current_node,
				key,
				moveDown,
				moveLeft,
				moveRight,
				moveUp,
				selectNode,
				_this = this;
			if ($(document.activeElement).is('textarea, input')) {
				return true;
			}
			current_node = this.tree_widget.getSelectedNode();
			selectNode = function(node) {
				if (node) {
					_this.tree_widget.selectNode(node);
					if (_this.tree_widget.scroll_handler && (!_this.tree_widget.scroll_handler.isScrolledIntoView($(node.element).find('.jqtree-element')))) {
						_this.tree_widget.scrollToNode(node);
					}
					return false;
				} else {
					return true;
				}
			};
			moveDown = function() {
				return selectNode(_this.getNextNode(current_node));
			};
			moveUp = function() {
				return selectNode(_this.getPreviousNode(current_node));
			};
			moveRight = function() {
				if (current_node.hasChildren() && !current_node.is_open) {
					_this.tree_widget.openNode(current_node);
					return false;
				} else {
					return true;
				}
			};
			moveLeft = function() {
				if (current_node.hasChildren() && current_node.is_open) {
					_this.tree_widget.closeNode(current_node);
					return false;
				} else {
					return true;
				}
			};
			if (!current_node) {
				return true;
			} else {
				key = e.which;
				switch (key) {
				case DOWN:
					return moveDown();
				case UP:
					return moveUp();
				case RIGHT:
					return moveRight();
				case LEFT:
					return moveLeft();
				}
			}
		};

		KeyHandler.prototype.getNextNode = function(node, include_children) {
			var next_sibling;
			if (include_children == null) {
				include_children = true;
			}
			if (include_children && node.hasChildren() && node.is_open) {
				return node.children[0];
			} else {
				if (!node.parent) {
					return null;
				} else {
					next_sibling = node.getNextSibling();
					if (next_sibling) {
						return next_sibling;
					} else {
						return this.getNextNode(node.parent, false);
					}
				}
			}
		};

		KeyHandler.prototype.getPreviousNode = function(node) {
			var previous_sibling;
			if (!node.parent) {
				return null;
			} else {
				previous_sibling = node.getPreviousSibling();
				if (previous_sibling) {
					if (!previous_sibling.hasChildren() || !previous_sibling.is_open) {
						return previous_sibling;
					} else {
						return this.getLastChild(previous_sibling);
					}
				} else {
					if (node.parent.parent) {
						return node.parent;
					} else {
						return null;
					}
				}
			}
		};

		KeyHandler.prototype.getLastChild = function(node) {
			var last_child;
			if (!node.hasChildren()) {
				return null;
			} else {
				last_child = node.children[node.children.length - 1];
				if (!last_child.hasChildren() || !last_child.is_open) {
					return last_child;
				} else {
					return this.getLastChild(last_child);
				}
			}
		};

		return KeyHandler;

	})();

}).call(this);;
/*!
 * typeahead.js 0.11.1
 * https://github.com/twitter/typeahead.js
 * Copyright 2013-2015 Twitter, Inc. and other contributors; Licensed MIT
 */

!function(a,b){"function"==typeof define&&define.amd?define("typeahead.js",["jquery"],function(a){return b(a)}):"object"==typeof exports?module.exports=b(require("jquery")):b(jQuery)}(this,function(a){var b=function(){"use strict";return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},isElement:function(a){return!(!a||1!==a.nodeType)},isJQuery:function(b){return b instanceof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,identity:function(a){return a},clone:function(b){return a.extend(!0,{},b)},getIdGenerator:function(){var a=0;return function(){return a++}},templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},stringify:function(a){return b.isString(a)?a:JSON.stringify(a)},noop:function(){}}}(),c=function(){"use strict";function a(a){var g,h;return h=b.mixin({},f,a),g={css:e(),classes:h,html:c(h),selectors:d(h)},{css:g.css,html:g.html,classes:g.classes,selectors:g.selectors,mixin:function(a){b.mixin(a,g)}}}function c(a){return{wrapper:'<span class="'+a.wrapper+'"></span>',menu:'<div class="'+a.menu+'"></div>'}}function d(a){var c={};return b.each(a,function(a,b){c[b]="."+a}),c}function e(){var a={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none",opacity:"1"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},menu:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};return b.isMsie()&&b.mixin(a.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),a}var f={wrapper:"twitter-typeahead",input:"tt-input",hint:"tt-hint",menu:"tt-menu",dataset:"tt-dataset",suggestion:"tt-suggestion",selectable:"tt-selectable",empty:"tt-empty",open:"tt-open",cursor:"tt-cursor",highlight:"tt-highlight"};return a}(),d=function(){"use strict";function c(b){b&&b.el||a.error("EventBus initialized without el"),this.$el=a(b.el)}var d,e;return d="typeahead:",e={render:"rendered",cursorchange:"cursorchanged",select:"selected",autocomplete:"autocompleted"},b.mixin(c.prototype,{_trigger:function(b,c){var e;return e=a.Event(d+b),(c=c||[]).unshift(e),this.$el.trigger.apply(this.$el,c),e},before:function(a){var b,c;return b=[].slice.call(arguments,1),c=this._trigger("before"+a,b),c.isDefaultPrevented()},trigger:function(a){var b;this._trigger(a,[].slice.call(arguments,1)),(b=e[a])&&this._trigger(b,[].slice.call(arguments,1))}}),c}(),e=function(){"use strict";function a(a,b,c,d){var e;if(!c)return this;for(b=b.split(i),c=d?h(c,d):c,this._callbacks=this._callbacks||{};e=b.shift();)this._callbacks[e]=this._callbacks[e]||{sync:[],async:[]},this._callbacks[e][a].push(c);return this}function b(b,c,d){return a.call(this,"async",b,c,d)}function c(b,c,d){return a.call(this,"sync",b,c,d)}function d(a){var b;if(!this._callbacks)return this;for(a=a.split(i);b=a.shift();)delete this._callbacks[b];return this}function e(a){var b,c,d,e,g;if(!this._callbacks)return this;for(a=a.split(i),d=[].slice.call(arguments,1);(b=a.shift())&&(c=this._callbacks[b]);)e=f(c.sync,this,[b].concat(d)),g=f(c.async,this,[b].concat(d)),e()&&j(g);return this}function f(a,b,c){function d(){for(var d,e=0,f=a.length;!d&&f>e;e+=1)d=a[e].apply(b,c)===!1;return!d}return d}function g(){var a;return a=window.setImmediate?function(a){setImmediate(function(){a()})}:function(a){setTimeout(function(){a()},0)}}function h(a,b){return a.bind?a.bind(b):function(){a.apply(b,[].slice.call(arguments,0))}}var i=/\s+/,j=g();return{onSync:c,onAsync:b,off:d,trigger:e}}(),f=function(a){"use strict";function c(a,c,d){for(var e,f=[],g=0,h=a.length;h>g;g++)f.push(b.escapeRegExChars(a[g]));return e=d?"\\b("+f.join("|")+")\\b":"("+f.join("|")+")",c?new RegExp(e):new RegExp(e,"i")}var d={node:null,pattern:null,tagName:"strong",className:null,wordsOnly:!1,caseSensitive:!1};return function(e){function f(b){var c,d,f;return(c=h.exec(b.data))&&(f=a.createElement(e.tagName),e.className&&(f.className=e.className),d=b.splitText(c.index),d.splitText(c[0].length),f.appendChild(d.cloneNode(!0)),b.parentNode.replaceChild(f,d)),!!c}function g(a,b){for(var c,d=3,e=0;e<a.childNodes.length;e++)c=a.childNodes[e],c.nodeType===d?e+=b(c)?1:0:g(c,b)}var h;e=b.mixin({},d,e),e.node&&e.pattern&&(e.pattern=b.isArray(e.pattern)?e.pattern:[e.pattern],h=c(e.pattern,e.caseSensitive,e.wordsOnly),g(e.node,f))}}(window.document),g=function(){"use strict";function c(c,e){c=c||{},c.input||a.error("input is missing"),e.mixin(this),this.$hint=a(c.hint),this.$input=a(c.input),this.query=this.$input.val(),this.queryWhenFocused=this.hasFocus()?this.query:null,this.$overflowHelper=d(this.$input),this._checkLanguageDirection(),0===this.$hint.length&&(this.setHint=this.getHint=this.clearHint=this.clearHintIfInvalid=b.noop)}function d(b){return a('<pre aria-hidden="true"></pre>').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:b.css("font-family"),fontSize:b.css("font-size"),fontStyle:b.css("font-style"),fontVariant:b.css("font-variant"),fontWeight:b.css("font-weight"),wordSpacing:b.css("word-spacing"),letterSpacing:b.css("letter-spacing"),textIndent:b.css("text-indent"),textRendering:b.css("text-rendering"),textTransform:b.css("text-transform")}).insertAfter(b)}function f(a,b){return c.normalizeQuery(a)===c.normalizeQuery(b)}function g(a){return a.altKey||a.ctrlKey||a.metaKey||a.shiftKey}var h;return h={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"},c.normalizeQuery=function(a){return b.toStr(a).replace(/^\s*/g,"").replace(/\s{2,}/g," ")},b.mixin(c.prototype,e,{_onBlur:function(){this.resetInputValue(),this.trigger("blurred")},_onFocus:function(){this.queryWhenFocused=this.query,this.trigger("focused")},_onKeydown:function(a){var b=h[a.which||a.keyCode];this._managePreventDefault(b,a),b&&this._shouldTrigger(b,a)&&this.trigger(b+"Keyed",a)},_onInput:function(){this._setQuery(this.getInputValue()),this.clearHintIfInvalid(),this._checkLanguageDirection()},_managePreventDefault:function(a,b){var c;switch(a){case"up":case"down":c=!g(b);break;default:c=!1}c&&b.preventDefault()},_shouldTrigger:function(a,b){var c;switch(a){case"tab":c=!g(b);break;default:c=!0}return c},_checkLanguageDirection:function(){var a=(this.$input.css("direction")||"ltr").toLowerCase();this.dir!==a&&(this.dir=a,this.$hint.attr("dir",a),this.trigger("langDirChanged",a))},_setQuery:function(a,b){var c,d;c=f(a,this.query),d=c?this.query.length!==a.length:!1,this.query=a,b||c?!b&&d&&this.trigger("whitespaceChanged",this.query):this.trigger("queryChanged",this.query)},bind:function(){var a,c,d,e,f=this;return a=b.bind(this._onBlur,this),c=b.bind(this._onFocus,this),d=b.bind(this._onKeydown,this),e=b.bind(this._onInput,this),this.$input.on("blur.tt",a).on("focus.tt",c).on("keydown.tt",d),!b.isMsie()||b.isMsie()>9?this.$input.on("input.tt",e):this.$input.on("keydown.tt keypress.tt cut.tt paste.tt",function(a){h[a.which||a.keyCode]||b.defer(b.bind(f._onInput,f,a))}),this},focus:function(){this.$input.focus()},blur:function(){this.$input.blur()},getLangDir:function(){return this.dir},getQuery:function(){return this.query||""},setQuery:function(a,b){this.setInputValue(a),this._setQuery(a,b)},hasQueryChangedSinceLastFocus:function(){return this.query!==this.queryWhenFocused},getInputValue:function(){return this.$input.val()},setInputValue:function(a){this.$input.val(a),this.clearHintIfInvalid(),this._checkLanguageDirection()},resetInputValue:function(){this.setInputValue(this.query)},getHint:function(){return this.$hint.val()},setHint:function(a){this.$hint.val(a)},clearHint:function(){this.setHint("")},clearHintIfInvalid:function(){var a,b,c,d;a=this.getInputValue(),b=this.getHint(),c=a!==b&&0===b.indexOf(a),d=""!==a&&c&&!this.hasOverflow(),!d&&this.clearHint()},hasFocus:function(){return this.$input.is(":focus")},hasOverflow:function(){var a=this.$input.width()-2;return this.$overflowHelper.text(this.getInputValue()),this.$overflowHelper.width()>=a},isCursorAtEnd:function(){var a,c,d;return a=this.$input.val().length,c=this.$input[0].selectionStart,b.isNumber(c)?c===a:document.selection?(d=document.selection.createRange(),d.moveStart("character",-a),a===d.text.length):!0},destroy:function(){this.$hint.off(".tt"),this.$input.off(".tt"),this.$overflowHelper.remove(),this.$hint=this.$input=this.$overflowHelper=a("<div>")}}),c}(),h=function(){"use strict";function c(c,e){c=c||{},c.templates=c.templates||{},c.templates.notFound=c.templates.notFound||c.templates.empty,c.source||a.error("missing source"),c.node||a.error("missing node"),c.name&&!h(c.name)&&a.error("invalid dataset name: "+c.name),e.mixin(this),this.highlight=!!c.highlight,this.name=c.name||j(),this.limit=c.limit||5,this.displayFn=d(c.display||c.displayKey),this.templates=g(c.templates,this.displayFn),this.source=c.source.__ttAdapter?c.source.__ttAdapter():c.source,this.async=b.isUndefined(c.async)?this.source.length>2:!!c.async,this._resetLastSuggestion(),this.$el=a(c.node).addClass(this.classes.dataset).addClass(this.classes.dataset+"-"+this.name)}function d(a){function c(b){return b[a]}return a=a||b.stringify,b.isFunction(a)?a:c}function g(c,d){function e(b){return a("<div>").text(d(b))}return{notFound:c.notFound&&b.templatify(c.notFound),pending:c.pending&&b.templatify(c.pending),header:c.header&&b.templatify(c.header),footer:c.footer&&b.templatify(c.footer),suggestion:c.suggestion||e}}function h(a){return/^[_a-zA-Z0-9-]+$/.test(a)}var i,j;return i={val:"tt-selectable-display",obj:"tt-selectable-object"},j=b.getIdGenerator(),c.extractData=function(b){var c=a(b);return c.data(i.obj)?{val:c.data(i.val)||"",obj:c.data(i.obj)||null}:null},b.mixin(c.prototype,e,{_overwrite:function(a,b){b=b||[],b.length?this._renderSuggestions(a,b):this.async&&this.templates.pending?this._renderPending(a):!this.async&&this.templates.notFound?this._renderNotFound(a):this._empty(),this.trigger("rendered",this.name,b,!1)},_append:function(a,b){b=b||[],b.length&&this.$lastSuggestion.length?this._appendSuggestions(a,b):b.length?this._renderSuggestions(a,b):!this.$lastSuggestion.length&&this.templates.notFound&&this._renderNotFound(a),this.trigger("rendered",this.name,b,!0)},_renderSuggestions:function(a,b){var c;c=this._getSuggestionsFragment(a,b),this.$lastSuggestion=c.children().last(),this.$el.html(c).prepend(this._getHeader(a,b)).append(this._getFooter(a,b))},_appendSuggestions:function(a,b){var c,d;c=this._getSuggestionsFragment(a,b),d=c.children().last(),this.$lastSuggestion.after(c),this.$lastSuggestion=d},_renderPending:function(a){var b=this.templates.pending;this._resetLastSuggestion(),b&&this.$el.html(b({query:a,dataset:this.name}))},_renderNotFound:function(a){var b=this.templates.notFound;this._resetLastSuggestion(),b&&this.$el.html(b({query:a,dataset:this.name}))},_empty:function(){this.$el.empty(),this._resetLastSuggestion()},_getSuggestionsFragment:function(c,d){var e,g=this;return e=document.createDocumentFragment(),b.each(d,function(b){var d,f;f=g._injectQuery(c,b),d=a(g.templates.suggestion(f)).data(i.obj,b).data(i.val,g.displayFn(b)).addClass(g.classes.suggestion+" "+g.classes.selectable),e.appendChild(d[0])}),this.highlight&&f({className:this.classes.highlight,node:e,pattern:c}),a(e)},_getFooter:function(a,b){return this.templates.footer?this.templates.footer({query:a,suggestions:b,dataset:this.name}):null},_getHeader:function(a,b){return this.templates.header?this.templates.header({query:a,suggestions:b,dataset:this.name}):null},_resetLastSuggestion:function(){this.$lastSuggestion=a()},_injectQuery:function(a,c){return b.isObject(c)?b.mixin({_query:a},c):c},update:function(b){function c(a){g||(g=!0,a=(a||[]).slice(0,e.limit),h=a.length,e._overwrite(b,a),h<e.limit&&e.async&&e.trigger("asyncRequested",b))}function d(c){c=c||[],!f&&h<e.limit&&(e.cancel=a.noop,h+=c.length,e._append(b,c.slice(0,e.limit-h)),e.async&&e.trigger("asyncReceived",b))}var e=this,f=!1,g=!1,h=0;this.cancel(),this.cancel=function(){f=!0,e.cancel=a.noop,e.async&&e.trigger("asyncCanceled",b)},this.source(b,c,d),!g&&c([])},cancel:a.noop,clear:function(){this._empty(),this.cancel(),this.trigger("cleared")},isEmpty:function(){return this.$el.is(":empty")},destroy:function(){this.$el=a("<div>")}}),c}(),i=function(){"use strict";function c(c,d){function e(b){var c=f.$node.find(b.node).first();return b.node=c.length?c:a("<div>").appendTo(f.$node),new h(b,d)}var f=this;c=c||{},c.node||a.error("node is required"),d.mixin(this),this.$node=a(c.node),this.query=null,this.datasets=b.map(c.datasets,e)}return b.mixin(c.prototype,e,{_onSelectableClick:function(b){this.trigger("selectableClicked",a(b.currentTarget))},_onRendered:function(a,b,c,d){this.$node.toggleClass(this.classes.empty,this._allDatasetsEmpty()),this.trigger("datasetRendered",b,c,d)},_onCleared:function(){this.$node.toggleClass(this.classes.empty,this._allDatasetsEmpty()),this.trigger("datasetCleared")},_propagate:function(){this.trigger.apply(this,arguments)},_allDatasetsEmpty:function(){function a(a){return a.isEmpty()}return b.every(this.datasets,a)},_getSelectables:function(){return this.$node.find(this.selectors.selectable)},_removeCursor:function(){var a=this.getActiveSelectable();a&&a.removeClass(this.classes.cursor)},_ensureVisible:function(a){var b,c,d,e;b=a.position().top,c=b+a.outerHeight(!0),d=this.$node.scrollTop(),e=this.$node.height()+parseInt(this.$node.css("paddingTop"),10)+parseInt(this.$node.css("paddingBottom"),10),0>b?this.$node.scrollTop(d+b):c>e&&this.$node.scrollTop(d+(c-e))},bind:function(){var a,c=this;return a=b.bind(this._onSelectableClick,this),this.$node.on("click.tt",this.selectors.selectable,a),b.each(this.datasets,function(a){a.onSync("asyncRequested",c._propagate,c).onSync("asyncCanceled",c._propagate,c).onSync("asyncReceived",c._propagate,c).onSync("rendered",c._onRendered,c).onSync("cleared",c._onCleared,c)}),this},isOpen:function(){return this.$node.hasClass(this.classes.open)},open:function(){this.$node.addClass(this.classes.open)},close:function(){this.$node.removeClass(this.classes.open),this._removeCursor()},setLanguageDirection:function(a){this.$node.attr("dir",a)},selectableRelativeToCursor:function(a){var b,c,d,e;return c=this.getActiveSelectable(),b=this._getSelectables(),d=c?b.index(c):-1,e=d+a,e=(e+1)%(b.length+1)-1,e=-1>e?b.length-1:e,-1===e?null:b.eq(e)},setCursor:function(a){this._removeCursor(),(a=a&&a.first())&&(a.addClass(this.classes.cursor),this._ensureVisible(a))},getSelectableData:function(a){return a&&a.length?h.extractData(a):null},getActiveSelectable:function(){var a=this._getSelectables().filter(this.selectors.cursor).first();return a.length?a:null},getTopSelectable:function(){var a=this._getSelectables().first();return a.length?a:null},update:function(a){function c(b){b.update(a)}var d=a!==this.query;return d&&(this.query=a,b.each(this.datasets,c)),d},empty:function(){function a(a){a.clear()}b.each(this.datasets,a),this.query=null,this.$node.addClass(this.classes.empty)},destroy:function(){function c(a){a.destroy()}this.$node.off(".tt"),this.$node=a("<div>"),b.each(this.datasets,c)}}),c}(),j=function(){"use strict";function a(){i.apply(this,[].slice.call(arguments,0))}var c=i.prototype;return b.mixin(a.prototype,i.prototype,{open:function(){return!this._allDatasetsEmpty()&&this._show(),c.open.apply(this,[].slice.call(arguments,0))},close:function(){return this._hide(),c.close.apply(this,[].slice.call(arguments,0))},_onRendered:function(){return this._allDatasetsEmpty()?this._hide():this.isOpen()&&this._show(),c._onRendered.apply(this,[].slice.call(arguments,0))},_onCleared:function(){return this._allDatasetsEmpty()?this._hide():this.isOpen()&&this._show(),c._onCleared.apply(this,[].slice.call(arguments,0))},setLanguageDirection:function(a){return this.$node.css("ltr"===a?this.css.ltr:this.css.rtl),c.setLanguageDirection.apply(this,[].slice.call(arguments,0))},_hide:function(){this.$node.hide()},_show:function(){this.$node.css("display","block")}}),a}(),k=function(){"use strict";function c(c,e){var f,g,h,i,j,k,l,m,n,o,p;c=c||{},c.input||a.error("missing input"),c.menu||a.error("missing menu"),c.eventBus||a.error("missing event bus"),e.mixin(this),this.eventBus=c.eventBus,this.minLength=b.isNumber(c.minLength)?c.minLength:1,this.input=c.input,this.menu=c.menu,this.enabled=!0,this.active=!1,this.input.hasFocus()&&this.activate(),this.dir=this.input.getLangDir(),this._hacks(),this.menu.bind().onSync("selectableClicked",this._onSelectableClicked,this).onSync("asyncRequested",this._onAsyncRequested,this).onSync("asyncCanceled",this._onAsyncCanceled,this).onSync("asyncReceived",this._onAsyncReceived,this).onSync("datasetRendered",this._onDatasetRendered,this).onSync("datasetCleared",this._onDatasetCleared,this),f=d(this,"activate","open","_onFocused"),g=d(this,"deactivate","_onBlurred"),h=d(this,"isActive","isOpen","_onEnterKeyed"),i=d(this,"isActive","isOpen","_onTabKeyed"),j=d(this,"isActive","_onEscKeyed"),k=d(this,"isActive","open","_onUpKeyed"),l=d(this,"isActive","open","_onDownKeyed"),m=d(this,"isActive","isOpen","_onLeftKeyed"),n=d(this,"isActive","isOpen","_onRightKeyed"),o=d(this,"_openIfActive","_onQueryChanged"),p=d(this,"_openIfActive","_onWhitespaceChanged"),this.input.bind().onSync("focused",f,this).onSync("blurred",g,this).onSync("enterKeyed",h,this).onSync("tabKeyed",i,this).onSync("escKeyed",j,this).onSync("upKeyed",k,this).onSync("downKeyed",l,this).onSync("leftKeyed",m,this).onSync("rightKeyed",n,this).onSync("queryChanged",o,this).onSync("whitespaceChanged",p,this).onSync("langDirChanged",this._onLangDirChanged,this)}function d(a){var c=[].slice.call(arguments,1);return function(){var d=[].slice.call(arguments);b.each(c,function(b){return a[b].apply(a,d)})}}return b.mixin(c.prototype,{_hacks:function(){var c,d;c=this.input.$input||a("<div>"),d=this.menu.$node||a("<div>"),c.on("blur.tt",function(a){var e,f,g;e=document.activeElement,f=d.is(e),g=d.has(e).length>0,b.isMsie()&&(f||g)&&(a.preventDefault(),a.stopImmediatePropagation(),b.defer(function(){c.focus()}))}),d.on("mousedown.tt",function(a){a.preventDefault()})},_onSelectableClicked:function(a,b){this.select(b)},_onDatasetCleared:function(){this._updateHint()},_onDatasetRendered:function(a,b,c,d){this._updateHint(),this.eventBus.trigger("render",c,d,b)},_onAsyncRequested:function(a,b,c){this.eventBus.trigger("asyncrequest",c,b)},_onAsyncCanceled:function(a,b,c){this.eventBus.trigger("asynccancel",c,b)},_onAsyncReceived:function(a,b,c){this.eventBus.trigger("asyncreceive",c,b)},_onFocused:function(){this._minLengthMet()&&this.menu.update(this.input.getQuery())},_onBlurred:function(){this.input.hasQueryChangedSinceLastFocus()&&this.eventBus.trigger("change",this.input.getQuery())},_onEnterKeyed:function(a,b){var c;(c=this.menu.getActiveSelectable())&&this.select(c)&&b.preventDefault()},_onTabKeyed:function(a,b){var c;(c=this.menu.getActiveSelectable())?this.select(c)&&b.preventDefault():(c=this.menu.getTopSelectable())&&this.autocomplete(c)&&b.preventDefault()},_onEscKeyed:function(){this.close()},_onUpKeyed:function(){this.moveCursor(-1)},_onDownKeyed:function(){this.moveCursor(1)},_onLeftKeyed:function(){"rtl"===this.dir&&this.input.isCursorAtEnd()&&this.autocomplete(this.menu.getTopSelectable())},_onRightKeyed:function(){"ltr"===this.dir&&this.input.isCursorAtEnd()&&this.autocomplete(this.menu.getTopSelectable())},_onQueryChanged:function(a,b){this._minLengthMet(b)?this.menu.update(b):this.menu.empty()},_onWhitespaceChanged:function(){this._updateHint()},_onLangDirChanged:function(a,b){this.dir!==b&&(this.dir=b,this.menu.setLanguageDirection(b))},_openIfActive:function(){this.isActive()&&this.open()},_minLengthMet:function(a){return a=b.isString(a)?a:this.input.getQuery()||"",a.length>=this.minLength},_updateHint:function(){var a,c,d,e,f,h,i;a=this.menu.getTopSelectable(),c=this.menu.getSelectableData(a),d=this.input.getInputValue(),!c||b.isBlankString(d)||this.input.hasOverflow()?this.input.clearHint():(e=g.normalizeQuery(d),f=b.escapeRegExChars(e),h=new RegExp("^(?:"+f+")(.+$)","i"),i=h.exec(c.val),i&&this.input.setHint(d+i[1]))},isEnabled:function(){return this.enabled},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},isActive:function(){return this.active},activate:function(){return this.isActive()?!0:!this.isEnabled()||this.eventBus.before("active")?!1:(this.active=!0,this.eventBus.trigger("active"),!0)},deactivate:function(){return this.isActive()?this.eventBus.before("idle")?!1:(this.active=!1,this.close(),this.eventBus.trigger("idle"),!0):!0},isOpen:function(){return this.menu.isOpen()},open:function(){return this.isOpen()||this.eventBus.before("open")||(this.menu.open(),this._updateHint(),this.eventBus.trigger("open")),this.isOpen()},close:function(){return this.isOpen()&&!this.eventBus.before("close")&&(this.menu.close(),this.input.clearHint(),this.input.resetInputValue(),this.eventBus.trigger("close")),!this.isOpen()},setVal:function(a){this.input.setQuery(b.toStr(a))},getVal:function(){return this.input.getQuery()},select:function(a){var b=this.menu.getSelectableData(a);return b&&!this.eventBus.before("select",b.obj)?(this.input.setQuery(b.val,!0),this.eventBus.trigger("select",b.obj),this.close(),!0):!1},autocomplete:function(a){var b,c,d;return b=this.input.getQuery(),c=this.menu.getSelectableData(a),d=c&&b!==c.val,d&&!this.eventBus.before("autocomplete",c.obj)?(this.input.setQuery(c.val),this.eventBus.trigger("autocomplete",c.obj),!0):!1},moveCursor:function(a){var b,c,d,e,f;return b=this.input.getQuery(),c=this.menu.selectableRelativeToCursor(a),d=this.menu.getSelectableData(c),e=d?d.obj:null,f=this._minLengthMet()&&this.menu.update(b),f||this.eventBus.before("cursorchange",e)?!1:(this.menu.setCursor(c),d?this.input.setInputValue(d.val):(this.input.resetInputValue(),this._updateHint()),this.eventBus.trigger("cursorchange",e),!0)},destroy:function(){this.input.destroy(),this.menu.destroy()}}),c}();!function(){"use strict";function e(b,c){b.each(function(){var b,d=a(this);(b=d.data(p.typeahead))&&c(b,d)})}function f(a,b){return a.clone().addClass(b.classes.hint).removeData().css(b.css.hint).css(l(a)).prop("readonly",!0).removeAttr("id name placeholder required").attr({autocomplete:"off",spellcheck:"false",tabindex:-1})}function h(a,b){a.data(p.attrs,{dir:a.attr("dir"),autocomplete:a.attr("autocomplete"),spellcheck:a.attr("spellcheck"),style:a.attr("style")}),a.addClass(b.classes.input).attr({autocomplete:"off",spellcheck:!1});try{!a.attr("dir")&&a.attr("dir","auto")}catch(c){}return a}function l(a){return{backgroundAttachment:a.css("background-attachment"),backgroundClip:a.css("background-clip"),backgroundColor:a.css("background-color"),backgroundImage:a.css("background-image"),backgroundOrigin:a.css("background-origin"),backgroundPosition:a.css("background-position"),backgroundRepeat:a.css("background-repeat"),backgroundSize:a.css("background-size")}}function m(a){var c,d;c=a.data(p.www),d=a.parent().filter(c.selectors.wrapper),b.each(a.data(p.attrs),function(c,d){b.isUndefined(c)?a.removeAttr(d):a.attr(d,c)}),a.removeData(p.typeahead).removeData(p.www).removeData(p.attr).removeClass(c.classes.input),d.length&&(a.detach().insertAfter(d),d.remove())}function n(c){var d,e;return d=b.isJQuery(c)||b.isElement(c),e=d?a(c).first():[],e.length?e:null}var o,p,q;o=a.fn.typeahead,p={www:"tt-www",attrs:"tt-attrs",typeahead:"tt-typeahead"},q={initialize:function(e,l){function m(){var c,m,q,r,s,t,u,v,w,x,y;b.each(l,function(a){a.highlight=!!e.highlight}),c=a(this),m=a(o.html.wrapper),q=n(e.hint),r=n(e.menu),s=e.hint!==!1&&!q,t=e.menu!==!1&&!r,s&&(q=f(c,o)),t&&(r=a(o.html.menu).css(o.css.menu)),q&&q.val(""),c=h(c,o),(s||t)&&(m.css(o.css.wrapper),c.css(s?o.css.input:o.css.inputWithNoHint),c.wrap(m).parent().prepend(s?q:null).append(t?r:null)),y=t?j:i,u=new d({el:c}),v=new g({hint:q,input:c},o),w=new y({node:r,datasets:l},o),x=new k({input:v,menu:w,eventBus:u,minLength:e.minLength},o),c.data(p.www,o),c.data(p.typeahead,x)}var o;return l=b.isArray(l)?l:[].slice.call(arguments,1),e=e||{},o=c(e.classNames),this.each(m)},isEnabled:function(){var a;return e(this.first(),function(b){a=b.isEnabled()}),a},enable:function(){return e(this,function(a){a.enable()}),this},disable:function(){return e(this,function(a){a.disable()}),this},isActive:function(){var a;return e(this.first(),function(b){a=b.isActive()}),a},activate:function(){return e(this,function(a){a.activate()}),this},deactivate:function(){return e(this,function(a){a.deactivate()}),this},isOpen:function(){var a;return e(this.first(),function(b){a=b.isOpen()}),a},open:function(){return e(this,function(a){a.open()}),this},close:function(){return e(this,function(a){a.close()}),this},select:function(b){var c=!1,d=a(b);return e(this.first(),function(a){c=a.select(d)}),c},autocomplete:function(b){var c=!1,d=a(b);return e(this.first(),function(a){c=a.autocomplete(d)}),c},moveCursor:function(a){var b=!1;return e(this.first(),function(c){b=c.moveCursor(a)}),b},val:function(a){var b;return arguments.length?(e(this,function(b){b.setVal(a)}),this):(e(this.first(),function(a){b=a.getVal()}),b)},destroy:function(){return e(this,function(a,b){m(b),a.destroy()}),this}},a.fn.typeahead=function(a){return q[a]?q[a].apply(this,[].slice.call(arguments,1)):q.initialize.apply(this,arguments)},a.fn.typeahead.noConflict=function(){return a.fn.typeahead=o,this}}()});;
!function (e) { "use strict"; if ("function" == typeof define && define.amd) define(["jquery", "moment"], e); else if ("object" == typeof exports) e(require("jquery"), require("moment")); else { if ("undefined" == typeof jQuery) throw "bootstrap-datetimepicker requires jQuery to be loaded first"; if ("undefined" == typeof moment) throw "bootstrap-datetimepicker requires Moment.js to be loaded first"; e(jQuery, moment) } }(function (e, t) {
    "use strict"; if (!t) throw new Error("bootstrap-datetimepicker requires Moment.js to be loaded first"); var a = function (a, n) {
        var r, i, o, s, d, l = {}, p = t().startOf("d"), c = p.clone(), u = !0, f = !1, m = !1, h = 0, g = [{ clsName: "days", navFnc: "M", navStep: 1 }, { clsName: "months", navFnc: "y", navStep: 1 }, { clsName: "years", navFnc: "y", navStep: 10 }, { clsName: "decades", navFnc: "y", navStep: 100 }], y = ["days", "months", "years", "decades"], b = ["top", "bottom", "auto"], w = ["left", "right", "auto"], v = ["default", "top", "bottom"], k = { up: 38, 38: "up", down: 40, 40: "down", left: 37, 37: "left", right: 39, 39: "right", tab: 9, 9: "tab", escape: 27, 27: "escape", enter: 13, 13: "enter", pageUp: 33, 33: "pageUp", pageDown: 34, 34: "pageDown", shift: 16, 16: "shift", control: 17, 17: "control", space: 32, 32: "space", t: 84, 84: "t", "delete": 46, 46: "delete" }, C = {}, x = function (e) { if ("string" != typeof e || e.length > 1) throw new TypeError("isEnabled expects a single character string parameter"); switch (e) { case "y": return -1 !== o.indexOf("Y"); case "M": return -1 !== o.indexOf("M"); case "d": return -1 !== o.toLowerCase().indexOf("d"); case "h": case "H": return -1 !== o.toLowerCase().indexOf("h"); case "m": return -1 !== o.indexOf("m"); case "s": return -1 !== o.indexOf("s"); default: return !1 } }, D = function () { return x("h") || x("m") || x("s") }, T = function () { return x("y") || x("M") || x("d") }, M = function () { var t = e("<thead>").append(e("<tr>").append(e("<th>").addClass("prev").attr("data-action", "previous").append(e("<span>").addClass(n.icons.previous))).append(e("<th>").addClass("picker-switch").attr("data-action", "pickerSwitch").attr("colspan", n.calendarWeeks ? "6" : "5")).append(e("<th>").addClass("next").attr("data-action", "next").append(e("<span>").addClass(n.icons.next)))), a = e("<tbody>").append(e("<tr>").append(e("<td>").attr("colspan", n.calendarWeeks ? "8" : "7"))); return [e("<div>").addClass("datepicker-days").append(e("<table>").addClass("table-condensed").append(t).append(e("<tbody>"))), e("<div>").addClass("datepicker-months").append(e("<table>").addClass("table-condensed").append(t.clone()).append(a.clone())), e("<div>").addClass("datepicker-years").append(e("<table>").addClass("table-condensed").append(t.clone()).append(a.clone())), e("<div>").addClass("datepicker-decades").append(e("<table>").addClass("table-condensed").append(t.clone()).append(a.clone()))] }, O = function () { var t = e("<tr>"), a = e("<tr>"), r = e("<tr>"); return x("h") && (t.append(e("<td>").append(e("<a>").attr({ href: "#", tabindex: "-1", title: "Increment Hour" }).addClass("btn").attr("data-action", "incrementHours").append(e("<span>").addClass(n.icons.up)))), a.append(e("<td>").append(e("<span>").addClass("timepicker-hour").attr({ "data-time-component": "hours", title: "Pick Hour" }).attr("data-action", "showHours"))), r.append(e("<td>").append(e("<a>").attr({ href: "#", tabindex: "-1", title: "Decrement Hour" }).addClass("btn").attr("data-action", "decrementHours").append(e("<span>").addClass(n.icons.down))))), x("m") && (x("h") && (t.append(e("<td>").addClass("separator")), a.append(e("<td>").addClass("separator").html(":")), r.append(e("<td>").addClass("separator"))), t.append(e("<td>").append(e("<a>").attr({ href: "#", tabindex: "-1", title: "Increment Minute" }).addClass("btn").attr("data-action", "incrementMinutes").append(e("<span>").addClass(n.icons.up)))), a.append(e("<td>").append(e("<span>").addClass("timepicker-minute").attr({ "data-time-component": "minutes", title: "Pick Minute" }).attr("data-action", "showMinutes"))), r.append(e("<td>").append(e("<a>").attr({ href: "#", tabindex: "-1", title: "Decrement Minute" }).addClass("btn").attr("data-action", "decrementMinutes").append(e("<span>").addClass(n.icons.down))))), x("s") && (x("m") && (t.append(e("<td>").addClass("separator")), a.append(e("<td>").addClass("separator").html(":")), r.append(e("<td>").addClass("separator"))), t.append(e("<td>").append(e("<a>").attr({ href: "#", tabindex: "-1", title: "Increment Second" }).addClass("btn").attr("data-action", "incrementSeconds").append(e("<span>").addClass(n.icons.up)))), a.append(e("<td>").append(e("<span>").addClass("timepicker-second").attr({ "data-time-component": "seconds", title: "Pick Second" }).attr("data-action", "showSeconds"))), r.append(e("<td>").append(e("<a>").attr({ href: "#", tabindex: "-1", title: "Decrement Second" }).addClass("btn").attr("data-action", "decrementSeconds").append(e("<span>").addClass(n.icons.down))))), i || (t.append(e("<td>").addClass("separator")), a.append(e("<td>").append(e("<button>").addClass("btn btn-primary").attr({ "data-action": "togglePeriod", tabindex: "-1", title: "Toggle Period" }))), r.append(e("<td>").addClass("separator"))), e("<div>").addClass("timepicker-picker").append(e("<table>").addClass("table-condensed").append([t, a, r])) }, S = function () { var t = e("<div>").addClass("timepicker-hours").append(e("<table>").addClass("table-condensed")), a = e("<div>").addClass("timepicker-minutes").append(e("<table>").addClass("table-condensed")), n = e("<div>").addClass("timepicker-seconds").append(e("<table>").addClass("table-condensed")), r = [O()]; return x("h") && r.push(t), x("m") && r.push(a), x("s") && r.push(n), r }, P = function () { var t = []; return n.showTodayButton && t.push(e("<td>").append(e("<a>").attr({ "data-action": "today", title: n.tooltips.today }).append(e("<span>").addClass(n.icons.today)))), !n.sideBySide && T() && D() && t.push(e("<td>").append(e("<a>").attr({ "data-action": "togglePicker", title: "Select Time" }).append(e("<span>").addClass(n.icons.time)))), n.showClear && t.push(e("<td>").append(e("<a>").attr({ "data-action": "clear", title: n.tooltips.clear }).append(e("<span>").addClass(n.icons.clear)))), n.showClose && t.push(e("<td>").append(e("<a>").attr({ "data-action": "close", title: n.tooltips.close }).append(e("<span>").addClass(n.icons.close)))), e("<table>").addClass("table-condensed").append(e("<tbody>").append(e("<tr>").append(t))) }, E = function () { var t = e("<div>").addClass("bootstrap-datetimepicker-widget dropdown-menu"), a = e("<div>").addClass("datepicker").append(M()), r = e("<div>").addClass("timepicker").append(S()), o = e("<ul>").addClass("list-unstyled"), s = e("<li>").addClass("picker-switch" + (n.collapse ? " accordion-toggle" : "")).append(P()); return n.inline && t.removeClass("dropdown-menu"), i && t.addClass("usetwentyfour"), x("s") && !i && t.addClass("wider"), n.sideBySide && T() && D() ? (t.addClass("timepicker-sbs"), "top" === n.toolbarPlacement && t.append(s), t.append(e("<div>").addClass("row").append(a.addClass("col-md-6")).append(r.addClass("col-md-6"))), "bottom" === n.toolbarPlacement && t.append(s), t) : ("top" === n.toolbarPlacement && o.append(s), T() && o.append(e("<li>").addClass(n.collapse && D() ? "collapse in" : "").append(a)), "default" === n.toolbarPlacement && o.append(s), D() && o.append(e("<li>").addClass(n.collapse && T() ? "collapse" : "").append(r)), "bottom" === n.toolbarPlacement && o.append(s), t.append(o)) }, I = function () { var t, r = {}; return t = a.is("input") || n.inline ? a.data() : a.find("input").data(), t.dateOptions && t.dateOptions instanceof Object && (r = e.extend(!0, r, t.dateOptions)), e.each(n, function (e) { var a = "date" + e.charAt(0).toUpperCase() + e.slice(1); void 0 !== t[a] && (r[e] = t[a]) }), r }, H = function () { var t, r = (f || a).position(), i = (f || a).offset(), o = n.widgetPositioning.vertical, s = n.widgetPositioning.horizontal; if (n.widgetParent) t = n.widgetParent.append(m); else if (a.is("input")) t = a.after(m).parent(); else { if (n.inline) return void (t = a.append(m)); t = a, a.children().first().after(m) } if ("auto" === o && (o = i.top + 1.5 * m.height() >= e(window).height() + e(window).scrollTop() && m.height() + a.outerHeight() < i.top ? "top" : "bottom"), "auto" === s && (s = t.width() < i.left + m.outerWidth() / 2 && i.left + m.outerWidth() > e(window).width() ? "right" : "left"), "top" === o ? m.addClass("top").removeClass("bottom") : m.addClass("bottom").removeClass("top"), "right" === s ? m.addClass("pull-right") : m.removeClass("pull-right"), "relative" !== t.css("position") && (t = t.parents().filter(function () { return "relative" === e(this).css("position") }).first()), 0 === t.length) throw new Error("datetimepicker component should be placed within a relative positioned container"); m.css({ top: "top" === o ? "auto" : r.top + a.outerHeight(), bottom: "top" === o ? r.top + a.outerHeight() : "auto", left: "left" === s ? t === a ? 0 : r.left : "auto", right: "left" === s ? "auto" : t.outerWidth() - a.outerWidth() - (t === a ? 0 : r.left) }) }, Y = function (e) { "dp.change" === e.type && (e.date && e.date.isSame(e.oldDate) || !e.date && !e.oldDate) || a.trigger(e) }, q = function (e) { "y" === e && (e = "YYYY"), Y({ type: "dp.update", change: e, viewDate: c.clone() }) }, B = function (e) { m && (e && (d = Math.max(h, Math.min(3, d + e))), m.find(".datepicker > div").hide().filter(".datepicker-" + g[d].clsName).show()) }, j = function () { var t = e("<tr>"), a = c.clone().startOf("w").startOf("d"); for (n.calendarWeeks === !0 && t.append(e("<th>").addClass("cw").text("#")) ; a.isBefore(c.clone().endOf("w")) ;) t.append(e("<th>").addClass("dow").text(a.format("dd"))), a.add(1, "d"); m.find(".datepicker-days thead").append(t) }, F = function (e) { return n.disabledDates[e.format("YYYY-MM-DD")] === !0 }, L = function (e) { return n.enabledDates[e.format("YYYY-MM-DD")] === !0 }, W = function (e) { return n.disabledHours[e.format("H")] === !0 }, A = function (e) { return n.enabledHours[e.format("H")] === !0 }, z = function (t, a) { if (!t.isValid()) return !1; if (n.disabledDates && "d" === a && F(t)) return !1; if (n.enabledDates && "d" === a && !L(t)) return !1; if (n.minDate && t.isBefore(n.minDate, a)) return !1; if (n.maxDate && t.isAfter(n.maxDate, a)) return !1; if (n.daysOfWeekDisabled && "d" === a && -1 !== n.daysOfWeekDisabled.indexOf(t.day())) return !1; if (n.disabledHours && ("h" === a || "m" === a || "s" === a) && W(t)) return !1; if (n.enabledHours && ("h" === a || "m" === a || "s" === a) && !A(t)) return !1; if (n.disabledTimeIntervals && ("h" === a || "m" === a || "s" === a)) { var r = !1; if (e.each(n.disabledTimeIntervals, function () { return t.isBetween(this[0], this[1]) ? (r = !0, !1) : void 0 }), r) return !1 } return !0 }, N = function () { for (var t = [], a = c.clone().startOf("y").startOf("d") ; a.isSame(c, "y") ;) t.push(e("<span>").attr("data-action", "selectMonth").addClass("month").text(a.format("MMM"))), a.add(1, "M"); m.find(".datepicker-months td").empty().append(t) }, V = function () { var t = m.find(".datepicker-months"), a = t.find("th"), r = t.find("tbody").find("span"); a.eq(0).find("span").attr("title", n.tooltips.prevYear), a.eq(1).attr("title", n.tooltips.selectYear), a.eq(2).find("span").attr("title", n.tooltips.nextYear), t.find(".disabled").removeClass("disabled"), z(c.clone().subtract(1, "y"), "y") || a.eq(0).addClass("disabled"), a.eq(1).text(c.year()), z(c.clone().add(1, "y"), "y") || a.eq(2).addClass("disabled"), r.removeClass("active"), p.isSame(c, "y") && !u && r.eq(p.month()).addClass("active"), r.each(function (t) { z(c.clone().month(t), "M") || e(this).addClass("disabled") }) }, R = function () { var e = m.find(".datepicker-years"), t = e.find("th"), a = c.clone().subtract(5, "y"), r = c.clone().add(6, "y"), i = ""; for (t.eq(0).find("span").attr("title", n.tooltips.nextDecade), t.eq(1).attr("title", n.tooltips.selectDecade), t.eq(2).find("span").attr("title", n.tooltips.prevDecade), e.find(".disabled").removeClass("disabled"), n.minDate && n.minDate.isAfter(a, "y") && t.eq(0).addClass("disabled"), t.eq(1).text(a.year() + "-" + r.year()), n.maxDate && n.maxDate.isBefore(r, "y") && t.eq(2).addClass("disabled") ; !a.isAfter(r, "y") ;) i += '<span data-action="selectYear" class="year' + (a.isSame(p, "y") && !u ? " active" : "") + (z(a, "y") ? "" : " disabled") + '">' + a.year() + "</span>", a.add(1, "y"); e.find("td").html(i) }, Q = function () { var e = m.find(".datepicker-decades"), a = e.find("th"), r = t(c.isBefore(t({ y: 1999 })) ? { y: 1899 } : { y: 1999 }), i = r.clone().add(100, "y"), o = ""; for (a.eq(0).find("span").attr("title", n.tooltips.prevCentury), a.eq(2).find("span").attr("title", n.tooltips.nextCentury), e.find(".disabled").removeClass("disabled"), (r.isSame(t({ y: 1900 })) || n.minDate && n.minDate.isAfter(r, "y")) && a.eq(0).addClass("disabled"), a.eq(1).text(r.year() + "-" + i.year()), (r.isSame(t({ y: 2e3 })) || n.maxDate && n.maxDate.isBefore(i, "y")) && a.eq(2).addClass("disabled") ; !r.isAfter(i, "y") ;) o += '<span data-action="selectDecade" class="decade' + (r.isSame(p, "y") ? " active" : "") + (z(r, "y") ? "" : " disabled") + '" data-selection="' + (r.year() + 6) + '">' + (r.year() + 1) + " - " + (r.year() + 12) + "</span>", r.add(12, "y"); o += "<span></span><span></span><span></span>", e.find("td").html(o) }, U = function () { var a, r, i, o, s = m.find(".datepicker-days"), d = s.find("th"), l = []; if (T()) { for (d.eq(0).find("span").attr("title", n.tooltips.prevMonth), d.eq(1).attr("title", n.tooltips.selectMonth), d.eq(2).find("span").attr("title", n.tooltips.nextMonth), s.find(".disabled").removeClass("disabled"), d.eq(1).text(c.format(n.dayViewHeaderFormat)), z(c.clone().subtract(1, "M"), "M") || d.eq(0).addClass("disabled"), z(c.clone().add(1, "M"), "M") || d.eq(2).addClass("disabled"), a = c.clone().startOf("M").startOf("w").startOf("d"), o = 0; 42 > o; o++) 0 === a.weekday() && (r = e("<tr>"), n.calendarWeeks && r.append('<td class="cw">' + a.week() + "</td>"), l.push(r)), i = "", a.isBefore(c, "M") && (i += " old"), a.isAfter(c, "M") && (i += " new"), a.isSame(p, "d") && !u && (i += " active"), z(a, "d") || (i += " disabled"), a.isSame(t(), "d") && (i += " today"), (0 === a.day() || 6 === a.day()) && (i += " weekend"), r.append('<td data-action="selectDay" data-day="' + a.format("L") + '" class="day' + i + '">' + a.date() + "</td>"), a.add(1, "d"); s.find("tbody").empty().append(l), V(), R(), Q() } }, G = function () { var t = m.find(".timepicker-hours table"), a = c.clone().startOf("d"), n = [], r = e("<tr>"); for (c.hour() > 11 && !i && a.hour(12) ; a.isSame(c, "d") && (i || c.hour() < 12 && a.hour() < 12 || c.hour() > 11) ;) a.hour() % 4 === 0 && (r = e("<tr>"), n.push(r)), r.append('<td data-action="selectHour" class="hour' + (z(a, "h") ? "" : " disabled") + '">' + a.format(i ? "HH" : "hh") + "</td>"), a.add(1, "h"); t.empty().append(n) }, J = function () { for (var t = m.find(".timepicker-minutes table"), a = c.clone().startOf("h"), r = [], i = e("<tr>"), o = 1 === n.stepping ? 5 : n.stepping; c.isSame(a, "h") ;) a.minute() % (4 * o) === 0 && (i = e("<tr>"), r.push(i)), i.append('<td data-action="selectMinute" class="minute' + (z(a, "m") ? "" : " disabled") + '">' + a.format("mm") + "</td>"), a.add(o, "m"); t.empty().append(r) }, K = function () { for (var t = m.find(".timepicker-seconds table"), a = c.clone().startOf("m"), n = [], r = e("<tr>") ; c.isSame(a, "m") ;) a.second() % 20 === 0 && (r = e("<tr>"), n.push(r)), r.append('<td data-action="selectSecond" class="second' + (z(a, "s") ? "" : " disabled") + '">' + a.format("ss") + "</td>"), a.add(5, "s"); t.empty().append(n) }, X = function () { var e, t, a = m.find(".timepicker span[data-time-component]"); i || (e = m.find(".timepicker [data-action=togglePeriod]"), t = p.clone().add(p.hours() >= 12 ? -12 : 12, "h"), e.text(p.format("A")), z(t, "h") ? e.removeClass("disabled") : e.addClass("disabled")), a.filter("[data-time-component=hours]").text(p.format(i ? "HH" : "hh")), a.filter("[data-time-component=minutes]").text(p.format("mm")), a.filter("[data-time-component=seconds]").text(p.format("ss")), G(), J(), K() }, Z = function () { m && (U(), X()) }, $ = function (e) { var t = u ? null : p; return e ? (e = e.clone().locale(n.locale), 1 !== n.stepping && e.minutes(Math.round(e.minutes() / n.stepping) * n.stepping % 60).seconds(0), void (z(e) ? (p = e, c = p.clone(), r.val(p.format(o)), a.data("date", p.format(o)), u = !1, Z(), Y({ type: "dp.change", date: p.clone(), oldDate: t })) : (n.keepInvalid || r.val(u ? "" : p.format(o)), Y({ type: "dp.error", date: e })))) : (u = !0, r.val(""), a.data("date", ""), Y({ type: "dp.change", date: !1, oldDate: t }), void Z()) }, _ = function () { var t = !1; return m ? (m.find(".collapse").each(function () { var a = e(this).data("collapse"); return a && a.transitioning ? (t = !0, !1) : !0 }), t ? l : (f && f.hasClass("btn") && f.toggleClass("active"), m.hide(), e(window).off("resize", H), m.off("click", "[data-action]"), m.off("mousedown", !1), m.remove(), m = !1, Y({ type: "dp.hide", date: p.clone() }), r.blur(), l)) : l }, ee = function () { $(null) }, te = { next: function () { var e = g[d].navFnc; c.add(g[d].navStep, e), U(), q(e) }, previous: function () { var e = g[d].navFnc; c.subtract(g[d].navStep, e), U(), q(e) }, pickerSwitch: function () { B(1) }, selectMonth: function (t) { var a = e(t.target).closest("tbody").find("span").index(e(t.target)); c.month(a), d === h ? ($(p.clone().year(c.year()).month(c.month())), n.inline || _()) : (B(-1), U()), q("M") }, selectYear: function (t) { var a = parseInt(e(t.target).text(), 10) || 0; c.year(a), d === h ? ($(p.clone().year(c.year())), n.inline || _()) : (B(-1), U()), q("YYYY") }, selectDecade: function (t) { var a = parseInt(e(t.target).data("selection"), 10) || 0; c.year(a), d === h ? ($(p.clone().year(c.year())), n.inline || _()) : (B(-1), U()), q("YYYY") }, selectDay: function (t) { var a = c.clone(); e(t.target).is(".old") && a.subtract(1, "M"), e(t.target).is(".new") && a.add(1, "M"), $(a.date(parseInt(e(t.target).text(), 10))), D() || n.keepOpen || n.inline || _() }, incrementHours: function () { var e = p.clone().add(1, "h"); z(e, "h") && $(e) }, incrementMinutes: function () { var e = p.clone().add(n.stepping, "m"); z(e, "m") && $(e) }, incrementSeconds: function () { var e = p.clone().add(1, "s"); z(e, "s") && $(e) }, decrementHours: function () { var e = p.clone().subtract(1, "h"); z(e, "h") && $(e) }, decrementMinutes: function () { var e = p.clone().subtract(n.stepping, "m"); z(e, "m") && $(e) }, decrementSeconds: function () { var e = p.clone().subtract(1, "s"); z(e, "s") && $(e) }, togglePeriod: function () { $(p.clone().add(p.hours() >= 12 ? -12 : 12, "h")) }, togglePicker: function (t) { var a, r = e(t.target), i = r.closest("ul"), o = i.find(".in"), s = i.find(".collapse:not(.in)"); if (o && o.length) { if (a = o.data("collapse"), a && a.transitioning) return; o.collapse ? (o.collapse("hide"), s.collapse("show")) : (o.removeClass("in"), s.addClass("in")), r.is("span") ? r.toggleClass(n.icons.time + " " + n.icons.date) : r.find("span").toggleClass(n.icons.time + " " + n.icons.date) } }, showPicker: function () { m.find(".timepicker > div:not(.timepicker-picker)").hide(), m.find(".timepicker .timepicker-picker").show() }, showHours: function () { m.find(".timepicker .timepicker-picker").hide(), m.find(".timepicker .timepicker-hours").show() }, showMinutes: function () { m.find(".timepicker .timepicker-picker").hide(), m.find(".timepicker .timepicker-minutes").show() }, showSeconds: function () { m.find(".timepicker .timepicker-picker").hide(), m.find(".timepicker .timepicker-seconds").show() }, selectHour: function (t) { var a = parseInt(e(t.target).text(), 10); i || (p.hours() >= 12 ? 12 !== a && (a += 12) : 12 === a && (a = 0)), $(p.clone().hours(a)), te.showPicker.call(l) }, selectMinute: function (t) { $(p.clone().minutes(parseInt(e(t.target).text(), 10))), te.showPicker.call(l) }, selectSecond: function (t) { $(p.clone().seconds(parseInt(e(t.target).text(), 10))), te.showPicker.call(l) }, clear: ee, today: function () { z(t(), "d") && $(t()) }, close: _ }, ae = function (t) { return e(t.currentTarget).is(".disabled") ? !1 : (te[e(t.currentTarget).data("action")].apply(l, arguments), !1) }, ne = function () { var a, i = { year: function (e) { return e.month(0).date(1).hours(0).seconds(0).minutes(0) }, month: function (e) { return e.date(1).hours(0).seconds(0).minutes(0) }, day: function (e) { return e.hours(0).seconds(0).minutes(0) }, hour: function (e) { return e.seconds(0).minutes(0) }, minute: function (e) { return e.seconds(0) } }; return r.prop("disabled") || !n.ignoreReadonly && r.prop("readonly") || m ? l : (void 0 !== r.val() && 0 !== r.val().trim().length ? $(ie(r.val().trim())) : n.useCurrent && u && (r.is("input") && 0 === r.val().trim().length || n.inline) && (a = t(), "string" == typeof n.useCurrent && (a = i[n.useCurrent](a)), $(a)), m = E(), j(), N(), m.find(".timepicker-hours").hide(), m.find(".timepicker-minutes").hide(), m.find(".timepicker-seconds").hide(), Z(), B(), e(window).on("resize", H), m.on("click", "[data-action]", ae), m.on("mousedown", !1), f && f.hasClass("btn") && f.toggleClass("active"), m.show(), H(), n.focusOnShow && !r.is(":focus") && r.focus(), Y({ type: "dp.show" }), l) }, re = function () { return m ? _() : ne() }, ie = function (e) { return e = void 0 === n.parseInputDate ? t.isMoment(e) || e instanceof Date ? t(e) : t(e, s, n.useStrict) : n.parseInputDate(e), e.locale(n.locale), e }, oe = function (e) { var t, a, r, i, o = null, s = [], d = {}, p = e.which, c = "p"; C[p] = c; for (t in C) C.hasOwnProperty(t) && C[t] === c && (s.push(t), parseInt(t, 10) !== p && (d[t] = !0)); for (t in n.keyBinds) if (n.keyBinds.hasOwnProperty(t) && "function" == typeof n.keyBinds[t] && (r = t.split(" "), r.length === s.length && k[p] === r[r.length - 1])) { for (i = !0, a = r.length - 2; a >= 0; a--) if (!(k[r[a]] in d)) { i = !1; break } if (i) { o = n.keyBinds[t]; break } } o && (o.call(l, m), e.stopPropagation(), e.preventDefault()) }, se = function (e) { C[e.which] = "r", e.stopPropagation(), e.preventDefault() }, de = function (t) { var a = e(t.target).val().trim(), n = a ? ie(a) : null; return $(n), t.stopImmediatePropagation(), !1 }, le = function () { r.on({ change: de, blur: n.debug ? "" : _, keydown: oe, keyup: se, focus: n.allowInputToggle ? ne : "" }), a.is("input") ? r.on({ focus: ne }) : f && (f.on("click", re), f.on("mousedown", !1)) }, pe = function () { r.off({ change: de, blur: blur, keydown: oe, keyup: se, focus: n.allowInputToggle ? _ : "" }), a.is("input") ? r.off({ focus: ne }) : f && (f.off("click", re), f.off("mousedown", !1)) }, ce = function (t) { var a = {}; return e.each(t, function () { var e = ie(this); e.isValid() && (a[e.format("YYYY-MM-DD")] = !0) }), Object.keys(a).length ? a : !1 }, ue = function (t) { var a = {}; return e.each(t, function () { a[this] = !0 }), Object.keys(a).length ? a : !1 }, fe = function () { var e = n.format || "L LT"; o = e.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (e) { var t = p.localeData().longDateFormat(e) || e; return t.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (e) { return p.localeData().longDateFormat(e) || e }) }), s = n.extraFormats ? n.extraFormats.slice() : [], s.indexOf(e) < 0 && s.indexOf(o) < 0 && s.push(o), i = o.toLowerCase().indexOf("a") < 1 && o.replace(/\[.*?\]/g, "").indexOf("h") < 1, x("y") && (h = 2), x("M") && (h = 1), x("d") && (h = 0), d = Math.max(h, d), u || $(p) }; if (l.destroy = function () { _(), pe(), a.removeData("DateTimePicker"), a.removeData("date") }, l.toggle = re, l.show = ne, l.hide = _, l.disable = function () { return _(), f && f.hasClass("btn") && f.addClass("disabled"), r.prop("disabled", !0), l }, l.enable = function () { return f && f.hasClass("btn") && f.removeClass("disabled"), r.prop("disabled", !1), l }, l.ignoreReadonly = function (e) { if (0 === arguments.length) return n.ignoreReadonly; if ("boolean" != typeof e) throw new TypeError("ignoreReadonly () expects a boolean parameter"); return n.ignoreReadonly = e, l }, l.options = function (t) { if (0 === arguments.length) return e.extend(!0, {}, n); if (!(t instanceof Object)) throw new TypeError("options() options parameter should be an object"); return e.extend(!0, n, t), e.each(n, function (e, t) { if (void 0 === l[e]) throw new TypeError("option " + e + " is not recognized!"); l[e](t) }), l }, l.date = function (e) { if (0 === arguments.length) return u ? null : p.clone(); if (!(null === e || "string" == typeof e || t.isMoment(e) || e instanceof Date)) throw new TypeError("date() parameter must be one of [null, string, moment or Date]"); return $(null === e ? null : ie(e)), l }, l.format = function (e) { if (0 === arguments.length) return n.format; if ("string" != typeof e && ("boolean" != typeof e || e !== !1)) throw new TypeError("format() expects a sting or boolean:false parameter " + e); return n.format = e, o && fe(), l }, l.dayViewHeaderFormat = function (e) { if (0 === arguments.length) return n.dayViewHeaderFormat; if ("string" != typeof e) throw new TypeError("dayViewHeaderFormat() expects a string parameter"); return n.dayViewHeaderFormat = e, l }, l.extraFormats = function (e) { if (0 === arguments.length) return n.extraFormats; if (e !== !1 && !(e instanceof Array)) throw new TypeError("extraFormats() expects an array or false parameter"); return n.extraFormats = e, s && fe(), l }, l.disabledDates = function (t) { if (0 === arguments.length) return n.disabledDates ? e.extend({}, n.disabledDates) : n.disabledDates; if (!t) return n.disabledDates = !1, Z(), l; if (!(t instanceof Array)) throw new TypeError("disabledDates() expects an array parameter"); return n.disabledDates = ce(t), n.enabledDates = !1, Z(), l }, l.enabledDates = function (t) { if (0 === arguments.length) return n.enabledDates ? e.extend({}, n.enabledDates) : n.enabledDates; if (!t) return n.enabledDates = !1, Z(), l; if (!(t instanceof Array)) throw new TypeError("enabledDates() expects an array parameter"); return n.enabledDates = ce(t), n.disabledDates = !1, Z(), l }, l.daysOfWeekDisabled = function (e) { if (0 === arguments.length) return n.daysOfWeekDisabled.splice(0); if ("boolean" == typeof e && !e) return n.daysOfWeekDisabled = !1, Z(), l; if (!(e instanceof Array)) throw new TypeError("daysOfWeekDisabled() expects an array parameter"); if (n.daysOfWeekDisabled = e.reduce(function (e, t) { return t = parseInt(t, 10), t > 6 || 0 > t || isNaN(t) ? e : (-1 === e.indexOf(t) && e.push(t), e) }, []).sort(), n.useCurrent && !n.keepInvalid) { for (var t = 0; !z(p, "d") ;) { if (p.add(1, "d"), 7 === t) throw "Tried 7 times to find a valid date"; t++ } $(p) } return Z(), l }, l.maxDate = function (e) { if (0 === arguments.length) return n.maxDate ? n.maxDate.clone() : n.maxDate; if ("boolean" == typeof e && e === !1) return n.maxDate = !1, Z(), l; "string" == typeof e && ("now" === e || "moment" === e) && (e = t()); var a = ie(e); if (!a.isValid()) throw new TypeError("maxDate() Could not parse date parameter: " + e); if (n.minDate && a.isBefore(n.minDate)) throw new TypeError("maxDate() date parameter is before options.minDate: " + a.format(o)); return n.maxDate = a, n.useCurrent && !n.keepInvalid && p.isAfter(e), c.isAfter(a) && (c = a.clone().subtract(n.stepping, "m")), Z(), l }, l.minDate = function (e) { if (0 === arguments.length) return n.minDate ? n.minDate.clone() : n.minDate; if ("boolean" == typeof e && e === !1) return n.minDate = !1, Z(), l; "string" == typeof e && ("now" === e || "moment" === e) && (e = t()); var a = ie(e); if (!a.isValid()) throw new TypeError("minDate() Could not parse date parameter: " + e); if (n.maxDate && a.isAfter(n.maxDate)) throw new TypeError("minDate() date parameter is after options.maxDate: " + a.format(o)); return n.minDate = a, n.useCurrent && !n.keepInvalid && p.isBefore(e) && $(n.minDate), c.isBefore(a) && (c = a.clone().add(n.stepping, "m")), Z(), l }, l.defaultDate = function (e) { if (0 === arguments.length) return n.defaultDate ? n.defaultDate.clone() : n.defaultDate; if (!e) return n.defaultDate = !1, l; "string" == typeof e && ("now" === e || "moment" === e) && (e = t()); var a = ie(e); if (!a.isValid()) throw new TypeError("defaultDate() Could not parse date parameter: " + e); if (!z(a)) throw new TypeError("defaultDate() date passed is invalid according to component setup validations"); return n.defaultDate = a, (n.defaultDate && n.inline || "" === r.val().trim() && void 0 === r.attr("placeholder")) && $(n.defaultDate), l }, l.locale = function (e) { if (0 === arguments.length) return n.locale; if (!t.localeData(e)) throw new TypeError("locale() locale " + e + " is not loaded from moment locales!"); return n.locale = e, p.locale(n.locale), c.locale(n.locale), o && fe(), m && (_(), ne()), l }, l.stepping = function (e) { return 0 === arguments.length ? n.stepping : (e = parseInt(e, 10), (isNaN(e) || 1 > e) && (e = 1), n.stepping = e, l) }, l.useCurrent = function (e) { var t = ["year", "month", "day", "hour", "minute"]; if (0 === arguments.length) return n.useCurrent; if ("boolean" != typeof e && "string" != typeof e) throw new TypeError("useCurrent() expects a boolean or string parameter"); if ("string" == typeof e && -1 === t.indexOf(e.toLowerCase())) throw new TypeError("useCurrent() expects a string parameter of " + t.join(", ")); return n.useCurrent = e, l }, l.collapse = function (e) { if (0 === arguments.length) return n.collapse; if ("boolean" != typeof e) throw new TypeError("collapse() expects a boolean parameter"); return n.collapse === e ? l : (n.collapse = e, m && (_(), ne()), l) }, l.icons = function (t) { if (0 === arguments.length) return e.extend({}, n.icons); if (!(t instanceof Object)) throw new TypeError("icons() expects parameter to be an Object"); return e.extend(n.icons, t), m && (_(), ne()), l }, l.tooltips = function (t) { if (0 === arguments.length) return e.extend({}, n.tooltips); if (!(t instanceof Object)) throw new TypeError("tooltips() expects parameter to be an Object"); return e.extend(n.tooltips, t), m && (_(), ne()), l }, l.useStrict = function (e) { if (0 === arguments.length) return n.useStrict; if ("boolean" != typeof e) throw new TypeError("useStrict() expects a boolean parameter"); return n.useStrict = e, l }, l.sideBySide = function (e) { if (0 === arguments.length) return n.sideBySide; if ("boolean" != typeof e) throw new TypeError("sideBySide() expects a boolean parameter"); return n.sideBySide = e, m && (_(), ne()), l }, l.viewMode = function (e) { if (0 === arguments.length) return n.viewMode; if ("string" != typeof e) throw new TypeError("viewMode() expects a string parameter"); if (-1 === y.indexOf(e)) throw new TypeError("viewMode() parameter must be one of (" + y.join(", ") + ") value"); return n.viewMode = e, d = Math.max(y.indexOf(e), h), B(), l }, l.toolbarPlacement = function (e) { if (0 === arguments.length) return n.toolbarPlacement; if ("string" != typeof e) throw new TypeError("toolbarPlacement() expects a string parameter"); if (-1 === v.indexOf(e)) throw new TypeError("toolbarPlacement() parameter must be one of (" + v.join(", ") + ") value"); return n.toolbarPlacement = e, m && (_(), ne()), l }, l.widgetPositioning = function (t) { if (0 === arguments.length) return e.extend({}, n.widgetPositioning); if ("[object Object]" !== {}.toString.call(t)) throw new TypeError("widgetPositioning() expects an object variable"); if (t.horizontal) { if ("string" != typeof t.horizontal) throw new TypeError("widgetPositioning() horizontal variable must be a string"); if (t.horizontal = t.horizontal.toLowerCase(), -1 === w.indexOf(t.horizontal)) throw new TypeError("widgetPositioning() expects horizontal parameter to be one of (" + w.join(", ") + ")"); n.widgetPositioning.horizontal = t.horizontal } if (t.vertical) { if ("string" != typeof t.vertical) throw new TypeError("widgetPositioning() vertical variable must be a string"); if (t.vertical = t.vertical.toLowerCase(), -1 === b.indexOf(t.vertical)) throw new TypeError("widgetPositioning() expects vertical parameter to be one of (" + b.join(", ") + ")"); n.widgetPositioning.vertical = t.vertical } return Z(), l }, l.calendarWeeks = function (e) { if (0 === arguments.length) return n.calendarWeeks; if ("boolean" != typeof e) throw new TypeError("calendarWeeks() expects parameter to be a boolean value"); return n.calendarWeeks = e, Z(), l }, l.showTodayButton = function (e) { if (0 === arguments.length) return n.showTodayButton; if ("boolean" != typeof e) throw new TypeError("showTodayButton() expects a boolean parameter"); return n.showTodayButton = e, m && (_(), ne()), l }, l.showClear = function (e) { if (0 === arguments.length) return n.showClear; if ("boolean" != typeof e) throw new TypeError("showClear() expects a boolean parameter"); return n.showClear = e, m && (_(), ne()), l }, l.widgetParent = function (t) { if (0 === arguments.length) return n.widgetParent; if ("string" == typeof t && (t = e(t)), null !== t && "string" != typeof t && !(t instanceof e)) throw new TypeError("widgetParent() expects a string or a jQuery object parameter"); return n.widgetParent = t, m && (_(), ne()), l }, l.keepOpen = function (e) { if (0 === arguments.length) return n.keepOpen; if ("boolean" != typeof e) throw new TypeError("keepOpen() expects a boolean parameter"); return n.keepOpen = e, l }, l.focusOnShow = function (e) { if (0 === arguments.length) return n.focusOnShow; if ("boolean" != typeof e) throw new TypeError("focusOnShow() expects a boolean parameter"); return n.focusOnShow = e, l }, l.inline = function (e) { if (0 === arguments.length) return n.inline; if ("boolean" != typeof e) throw new TypeError("inline() expects a boolean parameter"); return n.inline = e, l }, l.clear = function () { return ee(), l }, l.keyBinds = function (e) { return n.keyBinds = e, l }, l.debug = function (e) { if ("boolean" != typeof e) throw new TypeError("debug() expects a boolean parameter"); return n.debug = e, l }, l.allowInputToggle = function (e) { if (0 === arguments.length) return n.allowInputToggle; if ("boolean" != typeof e) throw new TypeError("allowInputToggle() expects a boolean parameter"); return n.allowInputToggle = e, l }, l.showClose = function (e) { if (0 === arguments.length) return n.showClose; if ("boolean" != typeof e) throw new TypeError("showClose() expects a boolean parameter"); return n.showClose = e, l }, l.keepInvalid = function (e) { if (0 === arguments.length) return n.keepInvalid; if ("boolean" != typeof e) throw new TypeError("keepInvalid() expects a boolean parameter"); return n.keepInvalid = e, l }, l.datepickerInput = function (e) { if (0 === arguments.length) return n.datepickerInput; if ("string" != typeof e) throw new TypeError("datepickerInput() expects a string parameter"); return n.datepickerInput = e, l }, l.parseInputDate = function (e) { if (0 === arguments.length) return n.parseInputDate; if ("function" != typeof e) throw new TypeError("parseInputDate() sholud be as function"); return n.parseInputDate = e, l }, l.disabledTimeIntervals = function (t) { if (0 === arguments.length) return n.disabledTimeIntervals ? e.extend({}, n.disabledTimeIntervals) : n.disabledTimeIntervals; if (!t) return n.disabledTimeIntervals = !1, Z(), l; if (!(t instanceof Array)) throw new TypeError("disabledTimeIntervals() expects an array parameter"); return n.disabledTimeIntervals = t, Z(), l }, l.disabledHours = function (t) {
        if (0 === arguments.length) return n.disabledHours ? e.extend({}, n.disabledHours) : n.disabledHours; if (!t) return n.disabledHours = !1, Z(), l; if (!(t instanceof Array)) throw new TypeError("disabledHours() expects an array parameter");
        if (n.disabledHours = ue(t), n.enabledHours = !1, n.useCurrent && !n.keepInvalid) { for (var a = 0; !z(p, "h") ;) { if (p.add(1, "h"), 24 === a) throw "Tried 24 times to find a valid date"; a++ } $(p) } return Z(), l
        }, l.enabledHours = function (t) { if (0 === arguments.length) return n.enabledHours ? e.extend({}, n.enabledHours) : n.enabledHours; if (!t) return n.enabledHours = !1, Z(), l; if (!(t instanceof Array)) throw new TypeError("enabledHours() expects an array parameter"); if (n.enabledHours = ue(t), n.disabledHours = !1, n.useCurrent && !n.keepInvalid) { for (var a = 0; !z(p, "h") ;) { if (p.add(1, "h"), 24 === a) throw "Tried 24 times to find a valid date"; a++ } $(p) } return Z(), l }, l.viewDate = function (e) { if (0 === arguments.length) return c.clone(); if (!e) return c = p.clone(), l; if (!("string" == typeof e || t.isMoment(e) || e instanceof Date)) throw new TypeError("viewDate() parameter must be one of [string, moment or Date]"); return c = ie(e), q(), l }, a.is("input")) r = a; else if (r = a.find(n.datepickerInput), 0 === r.size()) r = a.find("input"); else if (!r.is("input")) throw new Error('CSS class "' + n.datepickerInput + '" cannot be applied to non input element'); if (a.hasClass("input-group") && (f = 0 === a.find(".datepickerbutton").size() ? a.find(".input-group-addon") : a.find(".datepickerbutton")), !n.inline && !r.is("input")) throw new Error("Could not initialize DateTimePicker without an input element"); return e.extend(!0, n, I()), l.options(n), fe(), le(), r.prop("disabled") && l.disable(), r.is("input") && 0 !== r.val().trim().length ? $(ie(r.val().trim())) : n.defaultDate && void 0 === r.attr("placeholder") && $(n.defaultDate), n.inline && ne(), l
    }; e.fn.datetimepicker = function (t) { return this.each(function () { var n = e(this); n.data("DateTimePicker") || (t = e.extend(!0, {}, e.fn.datetimepicker.defaults, t), n.data("DateTimePicker", a(n, t))) }) }, e.fn.datetimepicker.defaults = { format: !1, dayViewHeaderFormat: "MMMM YYYY", extraFormats: !1, stepping: 1, minDate: !1, maxDate: !1, useCurrent: !0, collapse: !0, locale: t.locale(), defaultDate: !1, disabledDates: !1, enabledDates: !1, icons: { time: "glyphicon glyphicon-time", date: "glyphicon glyphicon-calendar", up: "glyphicon glyphicon-chevron-up", down: "glyphicon glyphicon-chevron-down", previous: "glyphicon glyphicon-chevron-left", next: "glyphicon glyphicon-chevron-right", today: "glyphicon glyphicon-screenshot", clear: "glyphicon glyphicon-trash", close: "glyphicon glyphicon-remove" }, tooltips: { today: "Go to today", clear: "Clear selection", close: "Close the picker", selectMonth: "Select Month", prevMonth: "Previous Month", nextMonth: "Next Month", selectYear: "Select Year", prevYear: "Previous Year", nextYear: "Next Year", selectDecade: "Select Decade", prevDecade: "Previous Decade", nextDecade: "Next Decade", prevCentury: "Previous Century", nextCentury: "Next Century" }, useStrict: !1, sideBySide: !1, daysOfWeekDisabled: !1, calendarWeeks: !1, viewMode: "days", toolbarPlacement: "default", showTodayButton: !1, showClear: !1, showClose: !1, widgetPositioning: { horizontal: "auto", vertical: "auto" }, widgetParent: null, ignoreReadonly: !1, keepOpen: !1, focusOnShow: !0, inline: !1, keepInvalid: !1, datepickerInput: ".datepickerinput", keyBinds: { up: function (e) { if (e) { var a = this.date() || t(); e.find(".datepicker").is(":visible") ? this.date(a.clone().subtract(7, "d")) : this.date(a.clone().add(this.stepping(), "m")) } }, down: function (e) { if (!e) return void this.show(); var a = this.date() || t(); e.find(".datepicker").is(":visible") ? this.date(a.clone().add(7, "d")) : this.date(a.clone().subtract(this.stepping(), "m")) }, "control up": function (e) { if (e) { var a = this.date() || t(); e.find(".datepicker").is(":visible") ? this.date(a.clone().subtract(1, "y")) : this.date(a.clone().add(1, "h")) } }, "control down": function (e) { if (e) { var a = this.date() || t(); e.find(".datepicker").is(":visible") ? this.date(a.clone().add(1, "y")) : this.date(a.clone().subtract(1, "h")) } }, left: function (e) { if (e) { var a = this.date() || t(); e.find(".datepicker").is(":visible") && this.date(a.clone().subtract(1, "d")) } }, right: function (e) { if (e) { var a = this.date() || t(); e.find(".datepicker").is(":visible") && this.date(a.clone().add(1, "d")) } }, pageUp: function (e) { if (e) { var a = this.date() || t(); e.find(".datepicker").is(":visible") && this.date(a.clone().subtract(1, "M")) } }, pageDown: function (e) { if (e) { var a = this.date() || t(); e.find(".datepicker").is(":visible") && this.date(a.clone().add(1, "M")) } }, enter: function () { this.hide() }, escape: function () { this.hide() }, "control space": function (e) { e.find(".timepicker").is(":visible") && e.find('.btn[data-action="togglePeriod"]').click() }, t: function () { this.date(t()) }, "delete": function () { this.clear() } }, debug: !1, allowInputToggle: !1, disabledTimeIntervals: !1, disabledHours: !1, enabledHours: !1, viewDate: !1 }
});;
var SiteSettings = {
	imagesLoaded: false,
	initialize: function() {
		SiteSettings.imagesLoaded = false;
		$('.background-image button').on('click', function() {
			// Load images
			if (!SiteSettings.imagesLoaded) {
				$.ajax({
					url: '/api/site/' + $('#SiteId').val() + '/image',
					type: 'GET',
					success: function(data, textStatus, xhr) {
						SiteSettings.imagesLoaded = true;
						if (xhr.status === 202) {
							for (i = 0; i < data.length; i++)
								$('#divImageGalleryThumbArea').append('<a class="background-thumb thumbnail col-sm-2"><img src="' + data[i].src + '" alt="' + data[i].alt + '" /></a>');

						}
					}
				});
			}
			$('#divImageGalleryThumbArea').show();
			return false;
		});

		$(document).on('click', '.background-thumb', function() {
			var selectedImageUrl = $('img', this).attr('src');
			$('#divSiteSettingsBackgroundExample').css('background-color', '');
			$('#divSiteSettingsBackgroundExample').css('background-image', 'url(' + selectedImageUrl + ')');
			$('#divImageGalleryThumbArea').hide();
		});

		$(document).on('click', '.background-color', function() {
			var backgroundColor = $(this).data('key');
			$('#divSiteSettingsBackgroundExample').css('background-image', '');
			$('#divSiteSettingsBackgroundExample').css('background-color', '#' + backgroundColor);
			$('#divImageGalleryThumbArea').hide();
		});

		$('#btnSiteSettingsSave').on('click', function() {
			SiteSettings.save();
		});
	},
	save: function() {

	}
};;
var Theme = {
	initialize: function() {
		// Set up the hue slider for color select
		$("#hue-slider").slider({
			min: 0,
			max: 360,
			slide: function(e, ui) {
				Theme.setHue(ui.value);
			},
			stop: function(e, ui) {
				$('#divColorSchemeList').html('<label>Select Color Scheme</label>');

				$('#divColorSchemeList').append(Theme.runSchemeGenerator(ui.value));
			}
		});
	},
	predefinedSchemes: [
		['mono', 'soft'],
		['mono', 'pastel'],
		['mono', 'light'],
		['mono', 'pale'],
		['contrast', 'pastel'],
		['contrast', 'soft'],
		['triade', 'pastel'],
		['triade', 'soft']
	],
	setHue: function (hue)
	{
		var scheme = new ColorScheme();
		scheme.from_hue(hue);
		var bg = scheme.colors()[0];
		$('#hue-box').css('background-color', '#' + bg);
		$('#hiddenHue').val(hue + ":" + bg);
	},

	// post-submit callback 
	runSchemeGenerator: function(hue) {
		var scheme = new ColorScheme();
		var colors;
		var htmlBuilder = '';

		// Loop through all the schemes we want to generate
		for (var index = 0; index < Theme.predefinedSchemes.length; index++) {
			// Do the business
			scheme.from_hue(hue)
				.scheme(Theme.predefinedSchemes[index][0])
				.variation(Theme.predefinedSchemes[index][1]);
			colors = scheme.colors();


			htmlBuilder += '<div class="input-group"><span class="input-group-addon wide"><input type="radio" name="colorSchemeRadio" value="' + colors.join() + '"></span>';

			// Loop through each color in the current theme and add a colorblock for it to the DOM
			for (var colorIndex = 0; colorIndex < colors.length; colorIndex++) {
				htmlBuilder += '<div class="input-group-addon col-sm-2 color-box" style="background-color:#' + colors[colorIndex] + ';" ></div>';
			}
			htmlBuilder += '</label></div>';
		}
		//$('#divColorSchemeList').append(htmlBuilder);

		return htmlBuilder;
	}

};;
$(function () {
    
    $("#txtExpiryMonth").on('keyup', function () {
        var expiryMonth = $(this).val();
        if (expiryMonth.length == 2) {
            $("#txtExpiryYear").focus();
        }
    });

});;
function JSdict() {
	this.Keys = [];
	this.Values = [];
}

// Check if dictionary extensions aren't implemented yet.
// Returns value of a key
if (!JSdict.prototype.getVal) {
	JSdict.prototype.getVal = function (key) {
		if (key == null) {
			return "Key cannot be null";
		}
		for (var i = 0; i < this.Keys.length; i++) {
			if (this.Keys[i] == key) {
				return this.Values[i];
			}
		}
		return "Key not found!";
	}
}


// Check if dictionary extensions aren't implemented yet.
// Updates value of a key
if (!JSdict.prototype.update) {
	JSdict.prototype.update = function (key, val) {
		if (key == null || val == null) {
			return "Key or Value cannot be null";
		}
		// Verify dict integrity before each operation
		if (keysLength != valsLength) {
			return "Dictionary inconsistent. Keys length don't match values!";
		}
		var keysLength = this.Keys.length;
		var valsLength = this.Values.length;
		var flag = false;
		for (var i = 0; i < keysLength; i++) {
			if (this.Keys[i] == key) {
				this.Values[i] = val;
				flag = true;
				break;
			}
		}
		if (!flag) {
			return "Key does not exist";
		}
	}
}



// Check if dictionary extensions aren't implemented yet.
// Adds a unique key value pair
if (!JSdict.prototype.add) {
	JSdict.prototype.add = function (key, val) {
		// Allow only strings or numbers as keys
		if (typeof (key) == "number" || typeof (key) == "string") {
			if (key == null || val == null) {
				return "Key or Value cannot be null";
			}
			if (keysLength != valsLength) {
				return "Dictionary inconsistent. Keys length don't match values!";
			}
			var keysLength = this.Keys.length;
			var valsLength = this.Values.length;
			for (var i = 0; i < keysLength; i++) {
				if (this.Keys[i] == key) {
					return "Duplicate keys not allowed!";
				}
			}
			this.Keys.push(key);
			this.Values.push(val);
		}
		else {
			return "Only number or string can be key!";
		}
	}
}

// Check if dictionary extensions aren't implemented yet.
// Removes a key value pair
if (!JSdict.prototype.remove) {
	JSdict.prototype.remove = function (key) {
		if (key == null) {
			return "Key cannot be null";
		}
		if (keysLength != valsLength) {
			return "Dictionary inconsistent. Keys length don't match values!";
		}
		var keysLength = this.Keys.length;
		var valsLength = this.Values.length;
		var flag = false;
		for (var i = 0; i < keysLength; i++) {
			if (this.Keys[i] == key) {
				this.Keys.shift(key);
				this.Values.shift(this.Values[i]);
				flag = true;
				break;
			}
		}
		if (!flag) {
			return "Key does not exist";
		}
	}
};
// a convenience function for parsing string namespaces and
// automatically generating nested namespaces
function extend(ns, ns_string) {
	var parts = ns_string.split('.'),
			parent = ns,
			pl, i;
	if (parts[0] == "sportsground") {
		parts = parts.slice(1);
	}
	pl = parts.length;
	for (i = 0; i < pl; i++) {
		//create a property if it doesnt exist
		if (typeof parent[parts[i]] == 'undefined') {
			parent[parts[i]] = {};
		}
		parent = parent[parts[i]];
	}
	return parent;
};
// Sportsground polyfill scripts are for javascript prototypes not supported in specific browsers

// String.prototype.includes not supported in IE, rewrite includes to indexOf
if (!String.prototype.includes) {
    String.prototype.includes = function(search, start) {
        if (typeof start !== 'number') {
            start = 0;
        }

        if (start + search.length > this.length) {
            return false;
        } else {
            return this.indexOf(search, start) !== -1;
        }
    };
}

// Array.prototype.includes not supported in IE, rewrite includes to test each item in array
if (!Array.prototype.includes) {
    Object.defineProperty(Array.prototype, 'includes', {
        value: function(searchElement, fromIndex) {

            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            // 1. Let O be ? ToObject(this value).
            var o = Object(this);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            // 3. If len is 0, return false.
            if (len === 0) {
                return false;
            }

            // 4. Let n be ? ToInteger(fromIndex).
            //    (If fromIndex is undefined, this step produces the value 0.)
            var n = fromIndex | 0;

            // 5. If n ≥ 0, then
            //  a. Let k be n.
            // 6. Else n < 0,
            //  a. Let k be len + n.
            //  b. If k < 0, let k be 0.
            var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

            function sameValueZero(x, y) {
                return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
            }

            // 7. Repeat, while k < len
            while (k < len) {
                // a. Let elementK be the result of ? Get(O, ! ToString(k)).
                // b. If SameValueZero(searchElement, elementK) is true, return true.
                if (sameValueZero(o[k], searchElement)) {
                    return true;
                }
                // c. Increase k by 1. 
                k++;
            }

            // 8. Return false
            return false;
        }
    });
};
$(function() {
    $(document)
        .on('click', 'form button[type="submit"].apply-spinner', function() {
            if ($('form').valid()) {
                $(this, '.apply-spinner').prop("disabled", true);
                var currentStyle = $(this, '.apply-spinner').attr('style');
                $(this, '.apply-spinner').attr('style', 'padding-right:24px;'
                    + ($(this, '.apply-spinner').hasClass('btn-block') ? 'display:inline;' : '')
                    + (currentStyle == undefined ? '' : currentStyle));
                $(this, '.apply-spinner').after('<i id="applySpinnerImage" class="fa fa-spin fa-spinner" style="margin-left:-18px;color:white;"></i>');
                $(this, '.apply-spinner').closest('form').submit();
            }
        })
        .on('click', 'a.apply-spinner', function () {
            if ($(this).attr('disabled') === 'disabled')
                return false;

            $(this).attr("disabled", "disabled");
            var buttonText = $(this).html();
            $(this, '.apply-spinner').html(buttonText + '&nbsp' + '<i id="applySpinnerImage" class="fa fa-spinner"></i>');
        })
        .on('click', '.apply-spinner:not(form button[type="submit"].apply-spinner, a.apply-spinner)', function() {
            $(this, '.apply-spinner').prop("disabled", true);
            var currentStyle = $(this, '.apply-spinner').attr('style');
            $(this, '.apply-spinner').attr('style', 'padding-right:24px;'
                + ($(this, '.apply-spinner').hasClass('btn-block') ? 'display:inline;' : '')
                + (currentStyle == undefined ? '' : currentStyle));
            $(this, '.apply-spinner').after('<i id="applySpinnerImage" class="fa fa-spin fa-spinner" style="margin-left:-18px;color:white;"></i>');
            $(this, '.apply-spinner').closest('form').submit();
        })
        .ajaxStop(function() {
            $('.apply-spinner').removeAttr('disabled');
            var currentStyle = $('.apply-spinner').attr('style');
            if (currentStyle != undefined) {
                currentStyle = currentStyle.replace('padding-right:24px;', '');
                if ($('.apply-spinner').hasClass('btn-block')) {
                    currentStyle = currentStyle.replace('display:inline;', '');
                }
                $('.apply-spinner').attr('style', currentStyle);
            }
            $('#applySpinnerImage').remove();
        });
});;
$(function () {
    $('#btnAddSport').on('click', function () {

        var id = $('#ddAddSport').val();

        if (sportsground.utils.isNullOrWhitespace(id) || id == 0) {
            $('#btnAddSport').closest('.form-group').addClass('has-error');
            e.stopImmediatePropagation();
            return false;
        }
        else {
            $('#btnAddSport').closest('.form-group').removeClass('has-error');
        }

        var sport = {
            id: id
        };

        $.ajax({
            url: '/api/sport',
            type: 'POST',
            data: sport,
            cache: false
        }).done(function (data) {

            $('#ulCurrentSports').append('<li data-id="' + data.id + '" class="list-group-item">' + data.name + '<a style="margin-top:-5px;" class="btn btn-danger btn-sm pull-right btn-delete-sport"><i class="glyphicon glyphicon-trash"></i></a></li>');
            var name = $('#ddAddSport option:selected').text();
            $('#ddAddSport option').filter(function () { return $(this).html() === name; }).remove();

        }).fail(function (xhr, textStatus) {
            sportsground.ui.highlight("#errorAlert");
        });

        e.stopImmediatePropagation();
        return false;
       
    });

    $(document).one('click', '.btn-delete-sport', function () {
        var sportItem = $(this).closest('li');
        var sportId = sportItem.data('id');
        $.ajax({
            url: '/api/sports?sportId=' + sportId,
            type: 'DELETE',
            cache: false,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.success) {
                    sportItem.remove();
                } else {
                    $("#errorAlert p").html(data.message);
                    sportsground.ui.highlight("#errorAlert");
                }
            }
        });
        e.stopImmediatePropagation();
        return false;
    });
});;
var sgModule = extend(sportsground, 'sportsground');

sgModule.authentication = {
    init: function () {
        $('.change-org-link').on('mousedown', function (event) {
            event.preventDefault();
            return false;
        });

        $('.change-org-link').on('click', function (event) {
            var model = {
                organisationId: $(event.currentTarget).data('id')
            };
            $.ajax({
                url: '/dashboard/changeorganisation',
                type: 'POST',
                data: JSON.stringify(model),
                contentType: 'application/json; charset=utf-8',
                success: function() {
                    location.reload();
                }
            });
            return false;
        });
    }
};

sgModule.forgottenPasswordPage = {
    init: function() {
        $('#loginPanel').css('top', ($(window).height() - $('#loginPanel').outerHeight()) / 2);
        $(window).resize(function () {
            $('#loginPanel').css('top', ($(this).height() - $('#loginPanel').outerHeight()) / 2);
        });
        $('#loginPanel').css('top', ($(window).height() - $('#loginPanel').outerHeight()) / 2);
        $(window).resize(function () {
            $('#loginPanel').css('top', ($(this).height() - $('#loginPanel').outerHeight()) / 2);
        });

        $("#btnChangePassword").on('click', function() {
            if ($('#password').val() != $('#passwordconfirm').val())
                return false;

            return true;
        });

        $("#btnSendReminder").on('click', function () {
            if ($(this).parent('form').valid()){
                $(this).find('.fa').addClass('fa-spinner');
                $(this).attr('disabled', 'disabled');
                $(this).parent('form').submit();
            }
        });
    }
};

sgModule.loginPage = {
    init: function () {
        // if login page is display, remove the lastAccessedTime
        UserSettings.removeLastAccessedTime();

        $('#loginPanel').css('top', ($(window).height() - $('#loginPanel').outerHeight()) / 2);
        $(window).resize(function () {
            $('#loginPanel').css('top', ($(this).height() - $('#loginPanel').outerHeight()) / 2);
        });
        $('#showRegisterLink').on('click', function(event) {
            $('#dvRegister').effect('slide', { direction: 'left', mode: 'show' }, 500);
            $('#dvLogin button').attr('disabled', 'disabled');
        });
        $('#btnCancelRegister').on('click', function(event) {
            $('#dvRegister').effect('slide', { direction: 'left', mode: 'hide' }, 500);
            $('#dvLogin button').removeAttr('disabled');
            $("#formRegisterModal").find(".form-control").val("");
            $("#formRegisterModal").find(".form-group").removeClass("has-error").removeClass("has-success");
        });

        $('#Username').focus();

        // gets a suggestion for the username if the user leaves the email field, and the username field is empty
        $('#ProfileData_Email').on('blur', function() {
            if (!$('#ProfileData_UserName').val()) {
                $.ajax({
                    method: "POST",
                    url: "/Validation/GetUniqueUsername",
                    data: { emailaddress: $('#ProfileData_Email').val() }
                })
                .done(function (data) {
                    $('#ProfileData_UserName').val(data);
                })
            }
        });
    }
};

sgModule.clubs = {
    searchInit: function() {
        $('.label-region').on('mouseover', sgModule.clubs.regionMouseOver);
        $('.label-region').on('mouseleave', sgModule.clubs.resetMap);
        $('#btnSubmitSearch').on('click', sgModule.commonValidators.searchSubmit);
        $('#btnKeywordSubmitSearch').on('click', sgModule.commonValidators.keywordSearchSubmit);
        $("#sportSelect").on("click", sgModule.clubs.selectSport);
    },
    regionMouseOver: function(event) {
        var regionId = $(event.currentTarget).parent().data("id");
        if (regionId > 14) {
            $("#mapnorth").attr("src", "/Content/images/maps/map-north.gif");
            $("#mapsouth").attr("src", "/Content/images/maps/map-south-" + regionId + ".gif");
        } else {
            $("#mapsouth").attr("src", "/Content/images/maps/map-south.gif");
            $("#mapnorth").attr("src", "/Content/images/maps/map-north-" + regionId + ".gif");
        }
    },
    resetMap: function (event) {
        var regionId = $('#mapRegions input[type="radio"]:checked').parent().data("id");
        if (regionId) {
            if (regionId > 14) {
                $("#mapnorth").attr("src", "/Content/images/maps/map-north.gif");
                $("#mapsouth").attr("src", "/Content/images/maps/map-south-" + regionId + ".gif");
            } else {
                $("#mapsouth").attr("src", "/Content/images/maps/map-south.gif");
                $("#mapnorth").attr("src", "/Content/images/maps/map-north-" + regionId + ".gif");
            }
        } else {
            $("#mapnorth").attr("src", "/Content/images/maps/map-north.gif");
            $("#mapsouth").attr("src", "/Content/images/maps/map-south.gif");
        }
    },
    
    selectSport: function() {
        $("#rbClub").prop("checked", true);
    },
    searchResultsInit: function () {

        $('.club-search-orglogo img').error(function () {
            $(this).attr('src', '/Content/images/default-organisation-logo.png');
        });
        $(".btn-email-organisation").on('click', function() {
            var result = $(this).closest("div.club-search-result");
            var organisationId = result.data("organisationId");
            var organisationName = result.data("organisationName");
            var url = "/clubs/ContactOrganisationModal?organisationId=" + organisationId + "&organisationName=" + encodeURIComponent(organisationName);

            $("#myModal").load(url, function() {
                // Boom, here comes the goodies
                $("#myModal").modal("show");
                // Attach some unobtrusive validation to this modal form		
                $.validator.unobtrusive.parse($("#formContactOrganisation"));
                // Form is loaded dynamically so these defaults are not set for it on page load
                overrideUnobtrusiveDefaults();
                // Handler for submitting form
                $("#btnContactOrganisation").on("click", function () {
                    if (!$("#formContactOrganisation").valid())
                        return false;

                    var model = {
                        OrganisationId: $("#hdnOrganisationId").val(),
                        SenderName: $("#inpSenderName").val(),
                        SenderEmail: $("#inpSenderEmail").val(),
                        Subject: $("#inpSubject").val(),
                        Message: $("#inpMessage").val(),
                        HoneyPot: $("#inpHp").val()
                    };

                    $.ajax({
                        url: "/clubs/ContactOrganisation",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(model),
                        success: function(data, textStatus, xhr) {
                            if (data === "True") {
                                $("#alertSuccess").show();
                                $("#btnContactOrganisation").hide();
                                $("#dismissButton").addClass("btn-primary").attr("value", "Done");
                            }
                        }
                    });
                });
            });
        });

        $(".btn-phone-organisation").on("click", function () {
            var button = $(this);
            var phoneNumber = button.data("phonenumber");
            if (phoneNumber !== "") {
                button.hide("fast");
                button.html(phoneNumber);
                button.show("fast");
            }
        });
    }
};

sgModule.clubsau = {
    searchInit: function () {
        $(document.body).on('mouseover', '.label-region', sgModule.clubsau.regionMouseOver);
        $(document.body).on('mouseleave', '.label-region', sgModule.clubsau.resetMap);
        $('#btnSubmitSearch').on('click', sgModule.commonValidators.searchSubmit);
        $('#btnKeywordSubmitSearch').on('click', sgModule.commonValidators.keywordSearchSubmit);
        $("#sportSelect").on("click", sgModule.clubsau.selectSport);
    },
    regionMouseOver: function (event) {
        var regionId = $(event.currentTarget).parent().data("id");
        if (regionId > 0) {
            $("#map").attr("src", "/Content/images/mapsau/region-" + regionId + ".png");
        } else {
            $("#map").attr("src", "/Content/images/mapsau/aus.png");
        }
    },
    resetMap: function (event) {
        var regionId = $('#mapRegions input[type="radio"]:checked').parent().data("id");
        if (regionId) {
            $("#map").attr("src", "/Content/images/mapsau/region-" + regionId + ".png");
        } else {
            $("#map").attr("src", "/Content/images/mapsau/aus.png");
        }
    },
    selectSport: function () {
        $("#rbClub").prop("checked", true);
    },
    searchResultsInit: function () {

        $('.club-search-orglogo img').error(function () {
            $(this).attr('src', '/Content/images/default-organisation-logo.png');
        });
        $(".btn-email-organisation").on('click', function () {
            var result = $(this).closest("div.club-search-result");
            var organisationId = result.data("organisationId");
            var organisationName = result.data("organisationName");
            var url = "/clubs/ContactOrganisationModal?organisationId=" + organisationId + "&organisationName=" + encodeURIComponent(organisationName);

            $("#myModal").load(url, function () {
                // Boom, here comes the goodies
                $("#myModal").modal("show");
                // Attach some unobtrusive validation to this modal form		
                $.validator.unobtrusive.parse($("#formContactOrganisation"));
                // Form is loaded dynamically so these defaults are not set for it on page load
                overrideUnobtrusiveDefaults();
                // Handler for submitting form
                $("#btnContactOrganisation").on("click", function () {
                    if (!$("#formContactOrganisation").valid())
                        return false;

                    var model = {
                        OrganisationId: $("#hdnOrganisationId").val(),
                        SenderName: $("#inpSenderName").val(),
                        SenderEmail: $("#inpSenderEmail").val(),
                        Subject: $("#inpSubject").val(),
                        Message: $("#inpMessage").val(),
                        HoneyPot: $("#inpHp").val()
                    };

                    $.ajax({
                        url: "/clubs/ContactOrganisation",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify(model),
                        success: function (data, textStatus, xhr) {
                            if (data === "True") {
                                $("#alertSuccess").show();
                                $("#btnContactOrganisation").hide();
                                $("#dismissButton").addClass("btn-primary").attr("value", "Done");
                            }
                        }
                    });
                });
            });
        });

        $(".btn-phone-organisation").on("click", function () {
            var button = $(this);
            var phoneNumber = button.data("phonenumber");
            if (phoneNumber !== "") {
                button.hide("fast");
                button.html(phoneNumber);
                button.show("fast");
            }
        });
    }
};

sgModule.commonValidators = {
    keywordSearchSubmit: function (event) {
        if (!sgModule.commonValidators.keywordSearchValidate())
            return false;

        return true;
    },
    searchSubmit: function (event) {
        if (!sgModule.commonValidators.searchValidate())
            return false;

        return true;
    },
    searchValidate: function () {
        var errors = [];
        if ($('#mapRegions input[type="radio"]:checked').length === 0)
            errors.push('Please select a region');
        if ($('input[type="radio"][name="clubSchool"]:checked').length === 0)
            errors.push('Choose whether you are looking for a club or a school');
        if ($('#rbClub').is(':checked') && $('#sportSelect option:checked').length === 0)
            errors.push('Please select a sport');

        if (errors.length === 0)
            return true;

        var errorHtml = '<div class="alert alert-danger" role="alert">' + errors.join('</div><div class="alert alert-danger" role="alert">') + '</div>';
        $('#errorsDiv').html(errorHtml);
        $('#errorsDiv').show();
        return false;
    },
    keywordSearchValidate: function () {
        var errors = [];
        if (($("#tbClubSearch").val() == '' || $("#tbClubSearch").val() == undefined) &&
            ($("#RegionId").val() == '' || $("#RegionId").val() == undefined) &&
            ($("#SportsId").val() == '' || $("#SportsId").val() == undefined)
        ) {
            errors.push('Please enter a search keyword or select a filter');
        }

        if (errors.length === 0) {
            $('#errorsDiv').html('');
            $('#errorsDiv').hide();
            return true;
        }

        var errorHtml = '<div class="alert alert-danger" role="alert">' + errors.join('</div><div class="alert alert-danger" role="alert">') + '</div>';
        $('#errorsDiv').html(errorHtml);
        $('#errorsDiv').show();
        return false;
    }
};

$("#removeSportsGroundBanner").click(function (e) {
    bootbox.confirm("<h1>Are you sure?</h3><p>You are about to permanently remove this warning from your website.</p>", function (value) {
        if (value) {
            $.ajax({
                url: '/admin/RemoveV1TransferBanner',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                async: false,
                success: function (data) {
                    if (data.success)
                    {
                        $("#v1SportsgroundBanner").remove();
                    }
                }
            });
        }
    });
    e.preventDefault();
});;
var sgUiModule = extend(sportsground, 'sportsground.ui');

sgUiModule.attachHandlerPrependHttpOnWwwLinks = function(self) {
    if ($(this).is('input')) {
        self = this;
    }
    var url = $(self).val();
    if (url.match('^www'))
        url = 'http://' + url;
    $(self).val(url);
}

sgUiModule.highlight = function (target) {
	$(target).hide().show('highlight', { color: '#FF42EC' }, 1000);
	setTimeout(function () {
		$(target).slideUp(500);
	}, 5500);
}

sgUiModule.loadingContainer = function (con, hide, content) {

	var loadingDiv = $("#loadingDiv");

	if (!content)
		content = "<div class='sporty-spinner'></div>";

	if (loadingDiv.length === 0) {
		var loadingDivHtml = '<div id="loadingDiv"><div class="sg-backdrop"></div><div class="center-page">' + content + '</div></div>';
		$(loadingDivHtml).appendTo(con);
		loadingDiv = $("#loadingDiv");
	}

	if (hide) {
		loadingDiv.remove();
	}
}

sgUiModule.loadingFullScreen = function (hide) {
	sgUiModule.loadingContainer(document.body, hide);
}

sgUiModule.loadingNrdFullScreen = function (hide) {
	sgUiModule.loadingContainer(document.body, hide, '<div class="well" style="width: 250px; text-align: center;"> <em>Awaiting NZ Rugby, please wait ...</em> <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"> <span class="sr-only">Awaiting NZ Rugby, please wait ...</span> </div> </div> </div> ');
}

sgUiModule.loadingCometFullScreen = function (hide) {
    sgUiModule.loadingContainer(document.body, hide, '<div class="well" style="width: 250px; text-align: center;"> <em>Awaiting NZ Football, please wait ...</em> <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"> <span class="sr-only">Awaiting NZ Football, please wait ...</span> </div> </div> </div> ');
}

sgUiModule.generateIFrameHtmlForVideo = function(src, width, height) {
    if (!width) {
        width = 200;
    }
    if (!height) {
        height = 200;
    }
    return '<iframe src="' + src + '"'
            + ' frameborder="0"'
            + ' width = "' + width + '"'
            + ' height = "' + height + '"'
            + ' allowfullscreen = "allowfullscreen"'
            + ' mozallowfullscreen = "mozallowfullscreen"'
            + ' msallowfullscreen = "msallowfullscreen"'
            + ' oallowfullscreen = "oallowfullscreen"'
            + ' webkitallowfullscreen = "webkitallowfullscreen"'
            + ' class="pull-right">'
        + '</iframe >';
};

sgUiModule.isMobile = function() {
    // the .navbar-toggle is the 3 bar menu (or hamburger menu), this script will try to detect if it is visible to determine if mobile device
    return $('.navbar .navbar-toggle').is(':visible');
};;
var UserSettings = {
    initialize: function () {
        var now = new Date();

        var userLastAccessedTime = $.localStorage.getItem('userLastAccessedTime');
        if (userLastAccessedTime == null) {
            // if userLastAccessedTime does not exist, update the LastAccessedTime and create the userLastAccessedTime.
            $.post('/Account/UpdateUserLastAccessedTime', function (data) {
                if (data.success) {
                    $.localStorage.setItem('userLastAccessedTime', now.getTime());
                }
            });
        }
        else {
            var twentyFourHours = 24 * 60 * 60 * 1000;
            var yesterday = now.getTime() - twentyFourHours;
            // if the user's LastAccessedTime is older than 24hrs; update the userLastAccessedTime.
            if (userLastAccessedTime < yesterday) {
                $.post('/Account/UpdateUserLastAccessedTime', function (data) {
                    if (data.success) {
                        $.localStorage.setItem('userLastAccessedTime', now.getTime());
                    }
                });
            }
        }
    },
    removeLastAccessedTime: function () {
        $.localStorage.removeItem('userLastAccessedTime');
    }
};
var module = extend(sportsground, 'sportsground.utils');

// Pads a number with 0's. e.g pad(2,3) => '002'
module.pad = function (a, b) {
	return (1e15 + a + '').slice(-b);
};

module.getQueryStringParameterByName = function (name) {
	name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
	var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
		results = regex.exec(location.search);
	return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

module.updateQueryStringParameter = function (uri, key, value) {
	if (uri.indexOf('#') !== -1)
		uri = uri.split('#')[0];

	var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
	var separator = uri.indexOf('?') !== -1 ? '&' : '?';
	if (uri.match(re)) {
		return uri.replace(re, '$1' + key + '=' + value + '$2');
	} else {
		return uri + separator + key + '=' + value;
	}
};

module.loadHandlebarsHelpers = function () {
	Handlebars.registerHelper('tolower', function (value) {
		if (value)
			return value.toLowerCase();
		return '';
	});

	Handlebars.registerHelper('summarize', function (value, options) {
        var length = 40;
		if (options && options.hash.length)
			length = options.hash.length;

		if (value.length > length)
			return value.substr(0, length - 3) + '...';

		return value;
	});
};

module.ckEditorBootstrapModalFix = function (modal, $) {
	modal.one('shown.bs.modal', function () {
		var that = $(this).data('modal');
		$(document)
			.off('focusin.modal')
			.on('focusin.modal', function (e) {
				// Add this line
				if (e.target.className && e.target.className.indexOf('cke_') === 0) return;

				// Original
				if (that && that.$element[0] !== e.target && !that.$element.has(e.target).length) {
					that.$element.focus();
				}
			});
	});
};

module.convertImageSrc = function (src, outputType, imageWidth, withUnderscore) {
	// strip all and any suffix's
    src = src.replace('_wo', '').replace('_t', '').replace('_ht', '').replace('_####', '').replace('####', '').replace('_539', '').replace('_sq', '');

	// strip the query
	var pos = src.lastIndexOf('?');
	if (pos > -1) {
		src = src.substring(0, pos);
	}

	// get the extension
	var lastIndexOfDot = src.lastIndexOf('.');
	var extension = src.substring(lastIndexOfDot + 1);

	var suffix = '';
	if (outputType === 'THUMB') {
		suffix = '_t';
    }
    else if (outputType === 'SQUARE') {
        suffix = '_sq';
    }
	else if (outputType === 'WEBOPTIMIZED') {
		if (imageWidth > 0) {

		    if (withUnderscore) {
		        suffix = "_" + imageWidth;
		    }
		    else {
		        suffix = imageWidth;
		    }
		}
		else {
			suffix = '_wo';
		}
	}
	else if (outputType === 'HEADERTHUMB') {
		suffix = '_ht';
	}

	return src.substring(0, lastIndexOfDot) + suffix + '.' + extension;
};

module.getImageIdFromSrc = function (src) {
    src = src.replace('_wo', '');

    var lastIndexOfSlash = src.lastIndexOf('/');
    var lastIndexOfDot = src.lastIndexOf('.');

    var imageId = src.substring(lastIndexOfSlash + 1, lastIndexOfDot);

    if (imageId.indexOf('_') == -1) {
        return imageId;
    }
    else {
        return imageId.split("_")[0];
    }
};

module.prependHttpForWwwLinks = function (link) {
	if (!/^https?:\/\//i.test(link) && link != "") {
		if (link.substring(0, 2) === "//") {
			link = 'http:' + link;
		} else {
			link = 'http://' + link;
		}
	}

	return link;
};

module.dateCompare = function ( dateFrom, dateTo, compareDateOnly ) {
    /// <summary>Compares dateFrom to dateTo using UTC format, returns -1 if dateFrom < dateTo, 0 if equal, and 1 if dateFrom > dateTo.</summary>  
    var a = new Date( dateFrom );
    var b = new Date( dateTo );

    var dateFromUtc = 0;
    var dateToUtc = 0;
    if ( compareDateOnly ) {
        dateFromUtc = Date.UTC( a.getFullYear(), a.getMonth(), a.getDate() );
        dateToUtc = Date.UTC( b.getFullYear(), b.getMonth(), b.getDate() );
    }
    else {
        dateFromUtc = Date.UTC( a.getFullYear(), a.getMonth(), a.getDate(), a.getHours(), a.getMinutes(), a.getSeconds() );
        dateToUtc = Date.UTC( b.getFullYear(), b.getMonth(), b.getDate(), b.getHours(), b.getMinutes(), b.getSeconds() );
    }

    if ( parseFloat( dateFromUtc ) < parseFloat( dateToUtc ) )
        return -1;
    else if ( parseFloat( dateFromUtc ) == parseFloat( dateToUtc ) )
        return 0;
    else if ( parseFloat( dateFromUtc ) > parseFloat( dateToUtc ) )
        return 1;
    else
        return null;
}

module.isNullOrWhitespace = function (input) {
	if (typeof input === 'undefined' || input === null) return true;
	return input.replace(/\s/g, '').length < 1;
};


module.validateEmailAddress = function (emailAddress) { //please update regex in ValidateEmail Attribute and question email if you are updating this
    var pattern = new RegExp(/^([a-zA-Z0-9._%+-])[^@]+(@[a-zA-Z0-9_-]+)\.([a-zA-Z]{2,63})(\.([a-zA-Z]{2,63})){0,3}$/i);
    return pattern.test(emailAddress);
};

module.validateMultipleEmailAddress = function (emailAddresses) {
    var pattern = new RegExp(/^(\s?[^\s,]+@[^\s,]+\.[^\s,]+[,;])*(\s?[^\s,]+@[^\s,]+\.[^\s,]+)$/i);
    return pattern.test( emailAddresses );
};

module.is_valid_url = function (url) {
    regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
    if (regexp.test(url)) {
        return true;
    }
    else {
        return false;
    }
};

function shuffle(array) {
	var m = array.length, t, i;

	// While there remain elements to shuffle…
	while (m) {

		// Pick a remaining element…
		i = Math.floor(Math.random() * m--);

		// And swap it with the current element.
		t = array[m];
		array[m] = array[i];
		array[i] = t;
	}

	return array;
}

// A lightweight wrapper for console.log
window.log = function () {
	if (window.console) {
		window.console.log(Array.prototype.slice.call(arguments));
	}
};;
$(function() {
	overrideUnobtrusiveDefaults();
});

(function ($) {
	$.validator.unobtrusive.parseDynamicContent = function (selector) {
		//use the normal unobstrusive.parse method
		$.validator.unobtrusive.parse(selector);

		//get the relevant form
		var form = $(selector).first().closest('form');
		
		//get the collections of unobstrusive validators, and jquery validators
		//and compare the two
		var unobtrusiveValidation = form.data('unobtrusiveValidation');
		var validator = form.validate();

	    if (!unobtrusiveValidation)
	        return;
		
		$.each(unobtrusiveValidation.options.rules, function (elname, elrules) {
			if (validator.settings.rules[elname] == undefined) {
				var args = {};
				$.extend(args, elrules);
				args.messages = unobtrusiveValidation.options.messages[elname];
				//edit:use quoted strings for the name selector
				$("[name='" + elname + "']").rules("add", args);
			} else {
				$.each(elrules, function (rulename, data) {
					if (validator.settings.rules[elname][rulename] == undefined) {
						var args = {};
						args[rulename] = data;
						args.messages = unobtrusiveValidation.options.messages[elname][rulename];
						//edit:use quoted strings for the name selector
						$("[name='" + elname + "']").rules("add", args);
					}
				});
			}
		});
	};
})($);



$.validator.addMethod('dobdaterange', function (value, element) {
    if (this.optional(element)) {
        return true;
    }

    var maxSetDate = new Date();
    maxSetDate.setYear(maxSetDate.getFullYear() - 1);
    
    var startDate = moment('1900-01-01'),
        endDate = maxSetDate,
        enteredDate = moment(value, "DD/MM/YYYY").toDate();

    if (isNaN(enteredDate)) {
        return false;
    }

    return ((startDate <= enteredDate) && (enteredDate <= endDate));
});

$.validator.unobtrusive.adapters.add(
    'dobdaterange', function (options) {
        options.rules['dobdaterange'] = options.params;
        options.messages['dobdaterange'] = "Age must be of minimum 1 year and maximum 118 years";
    }
);

$.validator.addMethod("date", function (value, element) {
	return this.optional(element) || /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/.test(value);
});

$.validator.addMethod("multiplemail", function (value, element) {
    if (value == undefined || value === "")
        return true;

    return sportsground.utils.validateMultipleEmailAddress(value);
});

$.validator.unobtrusive.adapters.add(
    'multiplemail', function (options) {
        options.rules['multiplemail'] = options.params;
        options.messages['multiplemail'] = "Please enter a valid email, separate multiple email addresses with a ; or ,";
    }
);

$.validator.addMethod("validateemail", function (value, element) {
    if (value === undefined || value === "")
        return true;

    return sportsground.utils.validateEmailAddress(value);
});

$.validator.unobtrusive.adapters.add(
    'validateemail', function (options) {
        options.rules['validateemail'] = options.params;
        options.messages['validateemail'] = "Please enter a valid email";
    }
);

$.validator.unobtrusive.adapters.add(
	'atleastonerequired', ['properties'], function (options) {
		options.rules['atleastonerequired'] = options.params;
		options.messages['atleastonerequired'] = options.message;
	}
);

$.validator.addMethod('atleastonerequired', function (value, element, params) {
	var properties = params.properties.split(',');
	var values = $.map(properties, function (property, index) {
		var val = $('#' + property).val();
		return val != '' ? val : null;
	});
	return values.length > 0;
}, '');

function overrideUnobtrusiveDefaults() {
	// This taps the defaults for jquery validation onto the form after it is loaded as Unobtrusive script overrides them if we add them too soon.
	// These settings are to make the unobtrusive validation work "Bootstrap" style :P
	$('form').each(function(i, o) {
		var validator = $(o).data('validator');
		if (!validator)
			return;
		var settings = $(o).data('validator').settings;
		settings.onkeyup = false;
		settings.onfocusout = function(element) { $(element).valid(); };
		settings.ignore = ":hidden";

		settings.highlight = function(element, errorClass, validClass) {
			if (element.type === 'radio') {
				this.findByName(element.name).addClass(errorClass).removeClass(validClass);
			} else {
				//$(element).addClass(errorClass).removeClass(validClass);
				$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
			}
			$(element).closest('.form-group').find('.glyphicon-ok').remove();
		};

        settings.unhighlight = function (element, errorClass, validClass) {
            if( $(element).closest('.form-group').hasClass('has-error') ){
                $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
            }
			if ($(element).closest('.form-group').hasClass('has-feedback'))
				$(element).after('<span class="glyphicon glyphicon-ok form-control-feedback"></span>');
		};
		//settings.errorElement = 'span';
		//settings.errorClass = 'help-block';
		//settings.errorPlacement = function(error, element) {
		//    if (element.parent('.input-group').length) {
		//        error.insertAfter(element.parent());
		//    } else {
		//        error.insertAfter(element);
		//    }
		//};;

	});
};
var addPageModule = extend(sportsground, 'sportsground.cms.modals.addPage');

addPageModule.init = function (parentPageId, parentPageType, addingRootPage) {
    var url = '/cms/site/' + $("#SiteId").val() + '/addpage?cpid=' + $('#PageId').val() + '&addingRootPage=' + addingRootPage;
	if (parentPageId)
		url += '&ppid=' + parentPageId + '&ppt=' + parentPageType;

    $("#myModal").load(url, function () {
        // Boom, here comes the goodies
        $("#myModal").modal('show');

        $("#addPageFinishButton").attr('disabled', false);
        $("#addPageFinishButton i").removeClass('fa-spinner');

        // Attach some unobtrusive validation to this modal form		
        $.validator.unobtrusive.parse($("#addPageForm"));
        // Form is loaded dynamically so these defaults are not set for it on page load
        overrideUnobtrusiveDefaults();

        $("#uxParentTooltipButton").popover({
            trigger: 'hover',
            placement: 'right'
        });

        addPageModule.parentPage.init();

        $('#uxCreatePageTemplateSelectDiv a').on('click', function () {
            $('#uxCreatePageTemplateSelectDiv a.selected').removeClass('selected');
            $(this).addClass('selected');

            $('#uxSelectedLayoutType').val($(this).data('enum'));
            $('#uxSelectedLayoutValue').val($(this).data('id'));
        });

        $("#addPageFinishButton").on('click', function (e) {
            if ( $("#addPageForm").valid() ) {
                $("#addPageFinishButton i").addClass('fa-spinner');
                $("#addPageFinishButton").attr('disabled', 'disabled');
                $("#addPageForm").submit();
            }
            else {
                $("#addPageFinishButton").attr('disabled', false);
                $("#addPageFinishButton i").removeClass('fa-spinner');
            }
            e.stopImmediatePropagation();
        });
	});
	return false;
};

addPageModule.parentPage = {
	init: function () {
		var parentId = $('#uxParentPageId').val();
        var parentType = $('#uxParentPageType').val();
		var options = $('#uxParentPageSelect option[value="' + parentId + '"]');
		if (options.length > 1)
			options = options.filter(function () {
				return $(this).data('type') == parentType;
			});

		options.prop('selected', true);

		$('#uxParentPageSelect').on('change', function () {
			$('#uxParentPageId').val($(this).val());
			$('#uxParentPageType').val($('option:selected', this).data('type'));
		});
	},
	validate: function() {
		
	}
};;
var adminModule = extend(sportsground, 'sportsground.cms.admin');

adminModule.init = function () {
    $('.role').on('change', function () {
        if ($(this).is(':checked') && $(this).data("role") == "Coach")
            $('#dvSiteAssign').show();
        else
            $('#dvSiteAssign').hide();
    });

    $('#btnAddUser').on('click', function () {
        if (!$("#formAddUser").valid()) {
            return false;
        }

        var model = {
            firstName: $("#txtFirstName").val(),
            lastName: $("#txtLastName").val(),
            emailAddress: $('#txtUserInvite').val(),
            role: $('.dvRoleAssign .role:checked').val(),
            sites: $.map($('.dvRoleAssign .site:checked'), function (value) {
                return value.name.replace('site_', '');
            })
        };

        $.ajax({
            url: '/dashboard/admin/security/adduser',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data) {
                if (data) {
                    window.location = window.location;
                } else {

                }
            }
        });

        return false;
    });

    $(".btn-delete-invite").on('click', function () {
        var tableRow = $(this).closest(".claim-nomination");
        var claimKey = tableRow.data("claim-key");
        // display bootbox
        bootbox.confirm('Are you sure you want to remove this invite?', function (result) {
            if (result) {
                $.ajax({
                    url: '/dashboard/admin/deleteinvitation?claimKey=' + claimKey,
                    type: 'DELETE',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data, textStatus, xhr) {
                        if (data) {
                            tableRow.remove();
                        } else {
                            bootbox.alert("Sorry! You are not authorised to remove this invitation.");
                        }
                    }
                });
            }
        });
    } );

    adminModule.initDelete();

    $( '#btnViewSubsiteEditors' ).on( 'click', function () {
        $( '#btnViewSubsiteEditors' ).prop( "disabled", true );
        $( '#btnViewSubsiteEditors' ).html( $( '#btnViewSubsiteEditors' ).html() + '&nbsp;<i class="fa fa-spin fa-spinner"></i>' );
        $.ajax({
            url: '/dashboard/admin/security/subsites',
            type: 'GET',
            success: function (data) {
                var userContainer = $('#viewSubsiteEditors');
                if (data.Users != null && data.Users.length > 0) {
                    userContainer.attr('style', 'border-top:none;');
                    var userTemplate = Handlebars.compile($('#view-subsite-editors').html());
                    for (var userIndex = 0; userIndex < data.Users.length; userIndex++) {
                        var roles = '';
                        for (var userRoleIndex = 0; userRoleIndex < data.Users[userIndex].Roles.length; userRoleIndex++) {
                            roles = roles + '<tr><td>' + data.Users[userIndex].Roles[userRoleIndex] + '</td></tr>';
                        }
                        userContainer.append(userTemplate(data.Users[userIndex]));
                        userContainer.find('#' + data.Users[userIndex].UserId).html(roles);
                    }
                    userContainer.removeAttr( 'style' );
                    $( '#btnViewSubsiteEditors' ).attr( 'style', 'display:none;' );
                    adminModule.initDelete();
                }
            }
        });
    });

    return false;
};

adminModule.initDelete = function () {
    $( ".btn-delete-user" ).on( 'click', function () {
        var tableRow = $( this ).closest( ".user-details" );
        var userId = tableRow.data( "user-id" );
        // display bootbox
        bootbox.confirm( "Are you sure you want to remove this user's permissions?", function ( result ) {
            if ( result ) {
                $.ajax( {
                    url: '/dashboard/admin/removeuserfromorg?userId=' + userId,
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    success: function ( data ) {
                        if ( data ) {
                            tableRow.remove();
                        } else {
                            bootbox.alert( "Sorry! You are not authorised to remove this user." );
                        }
                    }
                } );
            }
        } );
    } );
};;
$('document').ready(function () {
	var desktopElement = document.getElementById("banner-ad-desktop");
	if (desktopElement != undefined) {
		if (window.getComputedStyle(desktopElement).display === 'none') {
			desktopElement.parentNode.removeChild(desktopElement);
		}
		googletag.cmd.push(function() { googletag.display('div-gpt-ad-1468803611332-0'); });
	}
});;
function UpdateHiddenFields( currentRolesCount, currentSitesCount, currentFormsCount, currentFormSportsCount, currentSuperFormGroupsCount) {
	// Update hidden csv field for roles and sites before form submission
	var roleIds = $.map($('.dvRoleAssign .role:checked'), function (elem) {
		return elem.value != "on" ? elem.value : null;
	});
	var siteIds = $.map($('#dvSiteAssign .site:checked'), function (elem) {
		return elem.value != "on" ? elem.value : null;
	});
	var formIds = $.map($('#dvFormAssign .form:checked'), function (elem) {
		return elem.value != "on" ? elem.value : null;
	});
	var formSportIds = $.map($('#dvFormAssign .form-sport:checked'), function (elem) {
		return elem.value != "on" ? elem.value : null;
	});
	var superFormGroupIds = $.map($('#dvFormAssign .superform:checked'), function (elem) {
		return elem.value != "on" ? elem.value : null;
	});

	$("#hdnRoleIds").val(roleIds);
	$("#hdnSiteIds").val(siteIds);
	$("#hdnFormIds").val(formIds);
	$("#hdnSportIds").val(formSportIds);
	$("#hdnSuperFormGroupIds").val(superFormGroupIds);

	var allPermsRemoved = (roleIds.length === 0 && siteIds.length === 0 && formIds.length === 0 && formSportIds.length === 0 && superFormGroupIds.length === 0);
	var permsModified = roleIds.length != currentRolesCount ||
        siteIds.length != currentSitesCount ||
        formIds.length != currentFormsCount ||
        formSportIds.length != currentFormSportsCount ||
        superFormGroupIds.length != currentSuperFormGroupsCount;

    return { allPermissionsRemoved: allPermsRemoved, permissionsModified: permsModified };
};

function EnableControlsBasedOnRoleSelection() {

    if ($(".role[data-role='Web Master']").is(':checked')) {

        if ($(".site").length > 0) {
            $(".role[data-role='Subsite Editor']").prop('checked', true);
        }
    }

};

function EnableOrDisableSave() {
    
    var dbRoleMixed = $(".role[data-role='Database Admin']").attr("aria-checked") == "mixed" ? true : false;
    
    if (!$(".role[data-role='SKED System Admin']").is(':checked') &&
        !$(".role[data-role='Referee Appointment Officer']").is(':checked') &&
        !$(".role[data-role='Web Master']").is(':checked') && 
        !$(".role[data-role='Subsite Editor']").is(':checked') && 
        !$(".role[data-role='Database Admin']").is(':checked') &&
        !$(".role[data-role='Weigh Master']").is(':checked') 
        && !dbRoleMixed) {
       
        $('.btnSaveDb, .btnSaveWs').prop("disabled", true);
        $("#btnAddUser").attr("disabled", true);
        $(".clsInviteUser").attr("disabled", true);
    }
    else {
        $('.btnSaveDb, .btnSaveWs').prop("disabled", false);
        $("#btnAddUser").attr("disabled", false);
        $(".clsInviteUser").attr("disabled", false);
    }
}

function CheckSubSiteEditorBasedOnWebMaster() {

    if ($(".role[data-role='Web Master']").is(':checked')) {
        $(".role[data-role='Subsite Editor']").prop('checked', true);
        $('.site').prop('checked', true);
        $('.site-sport').attr({
            'aria-checked': true,
            'checked': true
        }).prop({
            indeterminate: false,
            checked: true
        });

    } else {
        $(".role[data-role='Subsite Editor']").prop('checked', false);
        $('.site').prop('checked', false);
        $('.site-sport').attr({
            'aria-checked': false,
            'checked': false
        }).prop({
            indeterminate: false,
            checked: false
        });
    }
}

function UnCheckSubSites() {

    if ($(".role[data-role='Subsite Editor']").is(':checked')) {      
        $('.site').prop('checked', true);
        $('.site-sport').attr({
            'aria-checked': true,
            'checked': true
        }).prop({
            indeterminate: false,
            checked: true
        });

    }
    else {
        $('.site').prop('checked', false);
        $('.site-sport').attr({
            'aria-checked': false,
            'checked': false
        }).prop({
            indeterminate: false,
            checked: false
        });

    }

    EnableOrDisableSave();
}

function CheckSubSiteEditorBasedOnSiteSelection() {

    if ($(".site:checked").length < 1) {
        $(".role[data-role='Subsite Editor']").prop('checked', false);
    } else {
        $(".role[data-role='Subsite Editor']").prop('checked', true);
    }
};

function HideOrShowSubEditorOptions() {

    if ($(".site").length < 1) {
        $("#dvSiteAssign").hide();
        $("[id='container_Subsite Editor']").hide();
    }

};

function DisableChildDbCheckboxes() {
	var dbAdminCheckbox = $(".role[data-role='Database Admin']"); 
	DisableChildCheckboxesIfCheckedAndDisabled(dbAdminCheckbox);

	var sportAdminCheckboxes = $(".form-sport");
	sportAdminCheckboxes.each(function() {
		DisableChildCheckboxesIfCheckedAndDisabled($(this));
	});
};

function DisableChildCheckboxesIfCheckedAndDisabled(parentCheckbox) {
	if (parentCheckbox.prop("checked") && parentCheckbox.prop("disabled")) {
		parentCheckbox.parent().find(':checkbox, input[role="checkbox"]').each(function() {
			$(this).prop("disabled", true);
		});
	};
}

$(document).ready(function () {
	DisableChildDbCheckboxes();
    HideOrShowSubEditorOptions();
    EnableControlsBasedOnRoleSelection();
    CheckSubSiteEditorBasedOnSiteSelection();

    $('.role').on('change', function () {
        EnableControlsBasedOnRoleSelection();

        if (this.attributes['data-role'].nodeValue === 'Web Master') {
            CheckSubSiteEditorBasedOnWebMaster();
        }

        EnableOrDisableSave();
    });

    $('.site').on('change', function () {
        CheckSubSiteEditorBasedOnSiteSelection();
        EnableOrDisableSave();
    });

    // to enable nested checkboxes use the following javascript.
    $('#dvSiteAssign :checkbox, #dvSiteAssign input[role="checkbox"], #dvFormAssign :checkbox, #dvFormAssign input[role="checkbox"]')
      .each(function () {
          var $checkbox = $(this),
            checked = this.checked = $checkbox.is('[checked]'), // explicitly set "checked" property for elements with checked attribute
            $ariaCheckbox, attributes;

          // Add aria-checked and checked attribute
          $checkbox.attr({
              'role': 'checkbox',
              'aria-checked': $checkbox.attr('aria-checked') || checked,
              'checked': checked
          });


      });

    $('#dvSiteAssign :checkbox, #dvSiteAssign input[role="checkbox"], #dvFormAssign :checkbox, #dvFormAssign input[role="checkbox"]').change(function () {
        var checked = this.checked,
            container = $(this).parent(),
            siblings = container.siblings();
        container.find(':checkbox, input[role="checkbox"]').prop({
            indeterminate: false,
            checked: checked
        }).attr({
            'aria-checked': checked,
            'checked': checked
        });

        function checkSiblings(el) {
            var parent = el.parent().parent(),
                all = true;

            el.siblings().each(function () {
                return all = ($(this).children(':checkbox, input[role="checkbox"]').prop("checked") === checked);
            });

            if (all && checked) {
                parent.children(':checkbox, input[role="checkbox"]').prop({
                    indeterminate: false,
                    checked: checked
                }).attr({
                    'aria-checked': checked,
                    'checked': checked
                });
                checkSiblings(parent);
            } else if (all && !checked) {
                parent.children(':checkbox, input[role="checkbox"]').attr({
                    'aria-checked': checked,
                    'checked': checked
                }).prop({
                    indeterminate: (parent.find(':checkbox:checked, input[role="checkbox"]:checked').length > 0),
                    checked: checked
                });
                checkSiblings(parent);
            } else {
                el.parents("li").children(':checkbox, input[role="checkbox"]').prop({
                    indeterminate: true,
                    checked: false
                }).attr({
                    'aria-checked': 'mixed',
                    'checked': false
                });
            }
        }
        checkSiblings(container);
        CheckSubSiteEditorBasedOnSiteSelection();
        EnableOrDisableSave();

    });

    $('#dvFormAssign input:checked, #dvSiteAssign input:checked, .role[data-role="Web Master"]:checked')
    .each(function () {

        //apply parent styling by propagating up
        $(this).trigger('click');
        //add back
        $(this).trigger('click');

    });

    //trello 1804
    function untickWebMaster() {
        $('#dvSiteAssign :checkbox, #dvSiteAssign input[role="checkbox"]').change(function () {

            var $checkbox = $(this),
           checked = this.checked = $checkbox.is('[checked]');

            if (!checked && ($(this).hasClass('site') || $(this).hasClass('site-sport'))) {
                $(".role[data-role='Web Master']").prop('checked', false);
            }
            EnableOrDisableSave();
        });

    }

    untickWebMaster();
    EnableOrDisableSave();

    $('.role').on('change', function () {
        
        if (this.attributes['data-role'].nodeValue === 'Subsite Editor') {
            UnCheckSubSites();
        }

    });

});
function dbTreeFilter() {
    var selectedSeason = $("#Seasons option:selected").val();
    var selectedSport = $("#Sports option:selected").val();

    if (selectedSeason == 0 && selectedSport == 0) {
        $(".sport-season-root").show();
    }
    else if (selectedSeason == 0 && selectedSport != 0) {
        $(".season-root").show();
        $(".sport-root").hide();
        $("li[data-sport='" + selectedSport + "'].sport-season-root").show();
    }
    else if (selectedSeason != 0 && selectedSport == 0) {
        $(".season-root").hide();
        $(".sport-root").show();
        $("li[data-season='" + selectedSeason + "'].sport-season-root").show();
    }
    else {
        $(".season-root").hide();
        $(".sport-root").hide();
        $("li[data-season='" + selectedSeason + "'].sport-season-root").show();
        $("li[data-sport='" + selectedSport + "'].sport-season-root").show();
    }
}

$("#dvFormAssign #Seasons").change(function () {

    dbTreeFilter();

});

$("#dvFormAssign #Sports").change(function () {

    dbTreeFilter();

});

function wsTreeFilter() {
    var selectedSeason = $("#SeasonsWs option:selected").val();
    var selectedSport = $("#SportsWs option:selected").val();

    if (selectedSeason == 0 && selectedSport == 0) {
        $(".sport-season-root-ws").show();
    }
    else if (selectedSeason == 0 && selectedSport != 0) {
        $(".season-root-ws").show();
        $(".sport-root-ws").hide();
        $("li[data-sport='" + selectedSport + "'].sport-season-root-ws").show();
    }
    else if (selectedSeason != 0 && selectedSport == 0) {
        $(".season-root-ws").hide();
        $(".sport-root-ws").show();
        $("li[data-season='" + selectedSeason + "'].sport-season-root-ws").show();
    }
    else {
        $(".season-root-ws").hide();
        $(".sport-root-ws").hide();
        $("li[data-season='" + selectedSeason + "'].sport-season-root-ws").show();
        $("li[data-sport='" + selectedSport + "'].sport-season-root-ws").show();
    }
}

$(".dvRoleAssign #SeasonsWs").change(function () {

    wsTreeFilter();

});

$(".dvRoleAssign #SportsWs").change(function () {

    wsTreeFilter();

});


$('#dvFormAssign .glyphicon, #dvSiteAssign .glyphicon').on('click', function () {
    $(this).toggleClass('glyphicon-chevron-down glyphicon-chevron-right');
});

$(".btnCancelWs").click(function () {
    window.history.back();
});;
var cmsModule = extend(sportsground, 'sportsground.cms.common');

String.prototype.endsWith = function (suffix) {
	return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

cmsModule.loadNextSuperSplitter = function (index) {

    var superSplitter = $(".supersplitter")[index];

    if (!superSplitter) {
        return;
    }

    var isLoaded = sportsground.cms.utils.isTrue($(superSplitter).attr("loaded"));

    //if visible and not loaded
    var windowTop = $(window).scrollTop() + $(window).height();
    var elementTop = $(superSplitter).offset().top;

    if (!isLoaded && elementTop <= windowTop) {
        sportsground.cms.common.loadPageWidgets($($(".supersplitter")[index]).data("id"));
        setTimeout(function () { cmsModule.loadNextSuperSplitter(index + 1); }, 500);
    }
    if ($("#hdnIsHomePage").val() == "True" && $("#hdnIsHomePageLocked").val() == "True" && $("#hdnIsSubSite").val() == "False") {
        sportsground.cms.common.disablewidgetsAndSplitters();
    }
}

cmsModule.loadSplitters = function () {
    var notLoadedYet = $(".supersplitter:not([loaded='true'])");

    notLoadedYet.each(function () {

        var superSplitter = $(this);
        var isLoaded = sportsground.cms.utils.isTrue(superSplitter.attr("loaded"));

        //if visible and not loaded
        var windowTop = $(window).scrollTop() + $(window).height();
        var elementTop = superSplitter.offset().top;

        if (!isLoaded && elementTop <= windowTop) {
            sportsground.cms.common.loadPageWidgets(superSplitter.data("id"));
        }

        sportsground.cms.common.setStylesForFullWidthSections();
    });

    sportsground.cms.common.setStylesForFullWidthSections();
};

$(function () {

    cmsModule.setStylesForFullWidthSections();

    //load first 
    sportsground.cms.common.loadPageWidgets($($(".supersplitter")[0]).data("id"));

    setTimeout(function () { cmsModule.loadNextSuperSplitter(1); }, 500);
    
    //edge case for /v2 ads
    var v2Ad = $("#superSplitter_20304")[0];

    if (v2Ad){
        sportsground.cms.common.loadPageWidgets(20304);
    }
    
    $(window).resize(function () {
        sportsground.cms.common.loadSplitters();
    });

    $(window).scroll(function () {
        sportsground.cms.common.loadSplitters();
    });

    //for mobile
    $(window).on('touchmove', function () {
        sportsground.cms.common.loadSplitters();
    });
	
	sportsground.cms.navigation.initialize();
	sportsground.utils.loadHandlebarsHelpers();

	// Hides loading indicator once the modal has loaded
	$("#myModal").on('shown.bs.modal', function () {
		$('#loading-indicator').hide();
	});

	// Run init methods required only in edit mode
	if ($('body').hasClass('edit')) {
        UserSettings.initialize();

	    if (cmsModule.isSafari()) {
	        $('#siteSettingsPanel').css('left', '0');
	    }

	    if (cmsModule.isIE11OrBelow()) {
	        $('body.edit').css('height', 'auto');
	    }
      
		sportsground.cms.common.bindDomEvents();
		sportsground.cms.widgets.initializeWidgetsHandlers();
		sportsground.cms.widgets.richText.styleCkEditorSaveAndCancelButtons();
		sportsground.cms.superSplitter.initialize();
		sportsground.cms.sortable.superSplittersInit();
		sportsground.cms.sortable.widgetPlaceholdersInit(); 
        sportsground.cms.common.bindRemoveEditModeOnPaste();

        if ($("#hdnIsHomePage").val() == "True" && $("#hdnIsHomePageLocked").val() == "True" && $("#hdnIsSubSite").val() == "False") {
            sportsground.cms.common.disablewidgetsAndSplitters();
        }

		$.ajaxSetup({ cache: false });
	}
	// Add padding for menu bar 
	sportsground.cms.common.setBodyOffsetForEditorBar();
	// Bind members only handlers
	cmsModule.bindMembersOnlyHandlers();
	// Set margin offset of sticky footer
	cmsModule.setFooterMargin();
	//ckeditor and bootstrap fix
	$.fn.modal.Constructor.prototype.enforceFocus = function () {
		var $modalElement = this.$element;
		$(document).on('focusin.modal', function (e) {
			var $parent = $(e.target.parentNode);
			if ($modalElement[0] !== e.target
											&& !$modalElement.has(e.target).length
											&& $(e.target).parentsUntil('*[role="dialog"]').length === 0) {
				$modalElement.focus();
			}
		});
	};

	$(document).on('click', 'label img', function () {
		$("#" + $(this).parents("label").attr("for")).click();
	});

	// Handle Session Timeout on Ajax Requests
	$(document).ajaxError(function (xhr, props) {
		if (props.status == 302 || props.status == 401) {
			// Status 302: temporarily moved
			location.reload();
		}
	});

	$("#btnRequestEditorPermission").on('click', function () {
	    var htmlNotification = '<div class=""><h4>You are not currently an Administrator for this site.<br><small>Click below to become an administrator for this site</small></h4></div>';
	   
        bootbox.dialog({
            title: "Request Access",
			message: htmlNotification,
			buttons: {
				success: {
					label: "Cancel",
					className: "btn-info",
					callback: function () {
						bootbox.hideAll();
					}
				},
				danger: {
					label: "Apply",
					className: "btn-primary",
					callback: function () {
						$.ajax({
							async: false,
							url: '/clubs/' + $("#OrganisationId").val() + '/requestedit',
							type: 'POST',
							contentType: 'application/json; charset=utf-8',
							data: JSON.stringify({
								organisationId: $("#OrganisationId").val(),
								SiteId: $("#SiteId").val(),
								RbRequestFrom: 'RequestAdminFromOrgAdmin'
							}),
							success: function (r) {
							    $("#myModal").modal('hide');

							    var notification = '<div class=""><h4 style="display:inline-block;margin-left:15px;">' + r.message + '</h4></div>';

							    bootbox.alert(notification);
							}
						});
					}
				}
			}
		});
    });
});

cmsModule.replaceLinkWithClickHere = function (text) {
    var replacedText, replacePattern;

    //URLs starting with http://, https://, file:// or ftp://
    replacePattern = /(^|[^\/"'=])(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = text.replace(replacePattern, ' <a href="$2" target="_blank" style="cursor:pointer;">Click here</a> ');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern = /(^|[^\/"'=])(www\.[^\s\t<]+)/gim;
    replacedText = replacedText.replace(replacePattern, '$1 <a href="http://$2" target="_blank" style="cursor:pointer;">Click here</a> ');

    //Change email addresses to mailto:: links.
    replacePattern = /((<p>)|[\s\n\r])(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
    replacedText = replacedText.replace(replacePattern, ' <a href="mailto:$3" style="cursor:pointer;">$3</a> ');

    return replacedText;
};

cmsModule.removeEditModeLinkParam = function (text) {
    var replacedText;

    //just replace url params ? or &
    replacedText = text.replace("?em=1", "?em=0");
    replacedText = replacedText.replace("&em=1", "&em=0");

    if ( ( text.indexOf( location.host ) < 0 ) ) {
        if ( $( '#urlNewTabCheckbox' ).length > 0 ) {
            $( '#urlNewTabCheckbox' ).prop( 'checked', true );
        }
        if ( $( '#cbLinkUrlNewTab' ).length > 0 ) {
            $( '#cbLinkUrlNewTab' ).prop( 'checked', true );
        }
    }

    return replacedText;
};

cmsModule.setAnchorToHaveChildColor = function (editorElem, html) {
    var updateWithNewHtml = false;
    $.each(editorElem.find('a'), function () {
        var anchor = $(this);
        $.each($(this).find('span'), function () {
            var textColor = $(this).css('color');
            if (textColor !== '' && textColor !== undefined) {
                $(anchor).css('color', textColor);
                updateWithNewHtml = true;
            }
        });
    });

    if (updateWithNewHtml) {
        html = editorElem.html();
        editorElem.unwrap();
    }

    return html;
};

cmsModule.bindRemoveEditModeOnPaste = function () {
    
    $("#tbLinkUrlLocation, #urlText").unbind("paste");
    $("#tbLinkUrlLocation, #urlText").bind("paste", function (e) {
        
        var pastedData = cmsModule.removeEditModeLinkParam(e.originalEvent.clipboardData.getData('text'));

        e.stopPropagation();
        e.preventDefault();
      
        $(this).val(pastedData);

        return pastedData;

    });

};

cmsModule.setBodyOffsetForEditorBar = function () {
	if ($(".cms-editor-bar").length > 0) {
		$('body').css('padding-top', '42px');
	}
};

cmsModule.setFooterMargin = function () {
	var footerHeight = $("#sticky-footer").height();
	var wrapperMargin = "auto 0 -" + footerHeight + "px";
	$("#sticky-push").css("height", footerHeight);
	$("#sticky-wrapper").css("margin", wrapperMargin);

};

cmsModule.loadPageWidgets = function (superSplitterId) {
	var canAddRemoveWidgets = $('#CanAddRemoveWidgets').val() == 'True';
	var columnsToUpdate;
    if (superSplitterId) {
        columnsToUpdate = $('#superSplitter_' + superSplitterId + ' .splitter-column-sortable');
        $('#superSplitter_' + superSplitterId).attr('loaded', true);
    }
	else
		columnsToUpdate = $('.splitter-column-sortable');	

	columnsToUpdate.each(function() {
       
		var container = $(this);

        var widgetHtml = $(this).data('widgetsettings');
        $(this).removeAttr("data-widgetsettings");
        sportsground.cms.widgets.load(container, widgetHtml, !canAddRemoveWidgets);

    });
    if ($("#hdnIsHomePage").val() == "True" && $("#hdnIsHomePageLocked").val() == "True" && $("#hdnIsSubSite").val() == "False") {
        sportsground.cms.common.disablewidgetsAndSplitters();
    }

    sportsground.cms.widgets.fluid.applyFluidStyle(superSplitterId);

};


cmsModule.bindMembersOnlyHandlers = function() {
	$("#btnMembersLogin").on('click', function () {
		$('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/memberslogin?returnUrl=" + window.location.href, function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			$.validator.unobtrusive.parseDynamicContent('#membersLoginForm');
			overrideUnobtrusiveDefaults();
		});
		return false;
	});

	$("#btnMembersLogout").on('click', function () {
		$.ajax({
			url: '/cms/site/members/logout?siteId=' + $("#SiteId").val(),
			type: 'POST',
			contentType: 'application/json; charset=utf-8',
			success: function (data, textStatus, xhr) {
				// reload this page
				location.reload();
			}
		});
	});

};

cmsModule.forbiddenToAddContent = function (splitterColumnId) {
	var plan = $("#hdnSubscriptionPlan").val();
	//Unlimited widgets on silver and gold
	if (plan !== "Bronze" && plan !== "Free") {
		return false;
	}
	// Unlimited widgets on bronze home page
	var isHomePage = $("#hdnIsHomePage").val();
	if (isHomePage === "True" && plan === "Bronze") {
		return false;
	}
	// All other pages on bronze and all pages on free, only one widget
	return ($("#" + splitterColumnId).find(".widget").length >= 1);
}

cmsModule.isSafari = function () {
    var userAgent = navigator.userAgent.toLowerCase();
    return (userAgent.indexOf('safari') != -1 && userAgent.indexOf('chrome') == -1);
}

cmsModule.isIE11OrBelow = function () {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    var trident = ua.indexOf('Trident/');

    return (msie > 0 || trident > 0);
}

cmsModule.bindDomEvents = function () {

    // initialize event handlers for the Widget Toolbox Modal
    sportsground.cms.settings.widgettoolbox.initEventHandlers();

	// Clicking the "Add Content" Button
	$(document).on('click', '.add-content-btn', function () {
		// Set context on Modal, placeholder, supersplitter/splitter
	    // If we have a parent widget, we are in a splitter not super splitter	 
		if ($(this).closest('.widget').length > 0) {
			$('#widgetToolboxModal').data('splittertype', 'Child');
		} else {
			$('#widgetToolboxModal').data('splittertype', 'Super');
		}

		// Set data on modal so it knows where the widget should be added
		var splitterColumnId = $(this).prev('.splitter-column-sortable-parent').attr('id');

		
		if (cmsModule.forbiddenToAddContent(splitterColumnId)) {
			$("#myModal").load("/cms/subscriptionadvert", function() {
				$("#myModal").modal('show');
			});
			return false;
		}

		$('#widgetToolboxModal').data('domId', splitterColumnId);
		$('#widgetToolboxModal').data('splitterId', $(this).closest('.splitter').data('id'));
		$('#widgetToolboxModal').data('splitterPlaceholder', $(this).prev('.splitter-column-sortable-parent').data('key'));
		$('#widgetToolboxModal').modal('show');

		return false;
	});

	$('#btnChangeStackerContent').on('click', function () {
		$('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changestackercontent", function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			sportsground.cms.settings.stacker.init();
		});
		return false;
	});

	$('#btnChangeBackground').on('click', function () {
		$('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changewallpaper?pid=" + $('#PageId').val(), function (response, status, xhr) {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			sportsground.cms.settings.wallpaper.init();	
		});
		return false;
	});

	$('#btnChangeMenu').on('click', function (response, status, xhr) {
	 $('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changemenu", function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			sportsground.cms.settings.menu.init();
		});
		return false;
	});

	$('#btnChangeHeader').on('click', function () {
		$('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changeheader?pid=" + $('#PageId').val(), function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			sportsground.cms.settings.header.init();
		});
		return false;
	});

	$('#btnChangeFooter').on('click', function () {
		sportsground.utils.ckEditorBootstrapModalFix($('#myModal'), $);
		$('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changefooter?pid=" + $('#PageId').val(), function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			sportsground.cms.settings.footer.init();
		});
		return false;
	});	

	$('#btnChangeText').on('click', function () {
		$('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changetext?pid=" + $('#PageId').val(), function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			sportsground.cms.settings.text.init();
		});
		return false;
	});

	$('#btnChangeSpinner').on('click', function () {
	    $('#loading-indicator').show();
	    $("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changespinner?pid=" + $('#PageId').val(), function () {
	        $("#myModal").modal({
	            backdrop: 'static',
	            keyboard: false  // to prevent closing with Esc button (if you want this too)
	        }).modal('show');
	        sportsground.cms.settings.text.init();
	    });
	    return false;
    });


    $('#btnChangeSectionPadding').on('click', function () {
        $('#loading-indicator').show();
        $("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changesectionpadding?pid=" + $('#PageId').val(), function () {
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false  // to prevent closing with Esc button (if you want this too)
            }).modal('show');
        });
        return false;
    });

    $('#btnSectionWidgetBehavior').on('click', function () {
        $('#loading-indicator').show();
        $("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changesectionwidgetbehaviour?pid=" + $('#PageId').val(), function () {
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false  // to prevent closing with Esc button (if you want this too)
            }).modal('show');

            $.validator.unobtrusive.parseDynamicContent('#changeSectionWidgetBehaviourForm');
        });
        return false;
    });    

    $('#btnChangeButton').on('click', function () {
        $('#loading-indicator').show();
        $("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changeSiteButton", function () {
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false  // to prevent closing with Esc button (if you want this too)
            }).modal('show');

            sportsground.cms.settings.sitebutton.init();
        });
        return false;
    });

	$(document).on('click', '.add-news-button', function () {
		sportsground.utils.ckEditorBootstrapModalFix($('#myModal'), $);
		$('#loading-indicator').show();
		$("#myModal").load("/organisation/" + $('#OrganisationId').val() + "/articles", function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false // to prevent closing with Esc button (if you want this too)
			}).modal('show');

			sportsground.cms.news.manageArticles.init();
			sportsground.cms.news.manageArticles.addClickHandler();
		});
		return false;
	});
    
	$('#btnManageNewsArticles').on('click', function () {
		sportsground.utils.ckEditorBootstrapModalFix($('#myModal'), $);
		$('#loading-indicator').show();
		$("#myModal").load("/organisation/" + $('#OrganisationId').val() + "/articles", function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false // to prevent closing with Esc button (if you want this too)
			}).modal('show');

			sportsground.cms.news.manageArticles.init();
		});
		return false;
	});

	$('#btnSponsorsManager').on('click', function() {
		$('#loading-indicator').show();
		$("#myModal").load("/organisation/" + $('#OrganisationId').val() + "/sponsors", function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			sportsground.cms.sponsorModule.init();
		});
		return false;
	});

	$("#btnMembersPassword").on('click', function () {
		// Open modal prompting for password
		$('#loading-indicator').show();

		var siteId = $("#SiteId").val();

		$("#myModal").load('/Dashboard/ChangeMembersPassword/site/' + siteId, function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			// do any members stuff you need to
			$.validator.unobtrusive.parse($('#changeSiteMembersPassword'));
			// Form is loaded dynamically so these defaults are not set for it on page load
			overrideUnobtrusiveDefaults();
			$("#btnMembersLoginSubmit").on("click", function () {
				if (!$("#changeSiteMembersPassword").valid())
                    return false;
                $("#btnMembersLoginSubmit i").addClass('fa-spinner');
                $("#btnMembersLoginSubmit").attr('disabled','disabled');
				$.ajax({
					url: '/Dashboard/ChangeMembersPassword/',
					type: 'POST',
					contentType: 'application/json; charset=utf-8',
					data: JSON.stringify({
						SiteId: siteId,
						Password: $("#txtMembersPassword").val()
					}),
					success: function (data, textStatus, xhr) {
						//close modal
                        $("#btnMembersLoginSubmit").removeClass('fa-spinner');
                        $("#btnMembersLoginSubmit").attr('disabled', false);
						$("#myModal").modal('hide');
					}
				});
			});
		});
		return false;
	});

	$('#btnSiteSettings').on('click', function () {
		$('#loading-indicator').show();
		$("#myModal").load("/Site/SiteSettings?siteId=" + $("#SiteId").val(), function() {
			$("#myModal").modal('show');
			SiteSettings.initialize();
		});
		return false;
	});

	$('#btnChangeTheme').on('click', function() {
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changetheme", function () {
			$("#myModal").modal('show');
			sportsground.cms.settings.theme.init();
		});
		return false;
	});

	$(document).on('click', '.selectable', function() {
		$('.selected').removeClass('selected');
		$(this).toggleClass('selected');
	});

	$('.btn-preview-page').on('click', function () {
		var url = sportsground.utils.updateQueryStringParameter(window.location.href, 'em', '0');
		url += '&ts=' + Math.random();
		window.previewTab = window.open(url, "sportsgroundpreview");
		return false;
	});

	$('#siteSettingsPanel a').on('click', function() {
		$('#siteSettingsDropdown').removeClass('open');
	});

    $("#linkBrowserSettings").on('click', function () {
		$('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/browsersettings?pid=" + $('#PageId').val(), function () {
            $.validator.unobtrusive.parseDynamicContent('#browserSettingsForm');
			overrideUnobtrusiveDefaults();

			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			$('#myModal').on('shown.bs.modal', function() {
				$("#txtMetaTitle").trigger('focus');
                cmsModule.initializeFavIcon();
                cmsModule.initializeAdFile();

                $("#txtMetaDescription").on('keyup', function () {
                    var metaDesc = $(this).val();
                    var count = metaDesc.length;
                    var allowed = $(this).attr("maxlength");
                    var available = allowed - count;
                    $('#metaDescCount').text(available);
                });
			});
		});
    });
};

cmsModule.initializeFavIcon = function () {
    $( '#btnUploadFavIcon' ).click( function () {
        $( '#inputUploadFavIcon' ).trigger( 'click' );
    } );

    $( '#inputUploadFavIcon' ).fileupload( {
        add: function ( e, data ) {
            var uploadErrors = [];
            var acceptFileTypes = /^image\/(png)$/i;
            if ( data.originalFiles[0]['type'].length && !acceptFileTypes.test( data.originalFiles[0]['type'] ) ) {
                uploadErrors.push( 'Not an accepted file type' );
            }
            if ( data.originalFiles[0]['size'] > 20000000 ) {
                uploadErrors.push( 'Filesize is too big' );
            }
            if ( uploadErrors.length > 0 ) {
                // TODO: Change this from alert??
                alert( uploadErrors.join( "\n" ) );
            } else {
                data.submit();
            }
        },
        dataType: 'json',
        url: '/cms/site/' + $( "#SiteId" ).val() + '/uploadfavicon',
        maxFileSize: 20000000,
        done: function ( e, data ) {
            var imageUrl = data.result;
            // set the image to the temp file
            $( "#imgEditFavIcon" ).removeClass( "sporty-spinner" );
            if ( imageUrl && imageUrl != '' ) {
                $( "#imgEditFavIcon img" ).attr( "src", imageUrl + "?qs=" + $.now() );
            }
            $( "#imgEditFavIcon img" ).show( "fast" );
            // Flag image has changed so we can move the blob
            $( "#HasUpdatedFavIcon" ).val( true );
            // display delete favicon option
            $( "#btnRemoveFavIcon" ).show();
        }
    } );

    $( '#btnRemoveFavIcon' ).click( function () {
        $.ajax( {
            url: '/cms/site/' + $( "#SiteId" ).val() + '/deletefavicon',
            type: 'DELETE',
            contentType: 'application/json; charset=utf-8',
            success: function () {
                $( '#imgEditFavIcon img' ).hide();
                $( '#btnRemoveFavIcon' ).hide();
            }
        } );
    } );
};


cmsModule.initializeAdFile = function () {
    $('#btnUploadAdFile').click(function () {
        $('#inputUploadAdFile').trigger('click');
    });

    $('#inputUploadAdFile').fileupload({
        add: function (e, data) {
            var uploadErrors = [];
            var acceptFileTypes = /^text\/(plain)$/i;
            if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                uploadErrors.push('Not an accepted file type');
            }
            if (data.originalFiles[0]['size'] > 20000000) {
                uploadErrors.push('Filesize is too big');
            }
            if (uploadErrors.length > 0) {
                // TODO: Change this from alert??
                alert(uploadErrors.join("\n"));
            } else {
                data.submit();
            }
        },
        dataType: 'json',
        url: '/cms/site/' + $("#SiteId").val() + '/uploadadfile',
        maxFileSize: 20000000,
        done: function (e, data) {
            // set the image to the temp file
            $("#imgEditAdFile").removeClass("sporty-spinner");

            $("#imgEditAdFile").html("ads.txt");

            $("#imgEditAdFile img").show("fast");
            // Flag image has changed so we can move the blob
            $("#HasUpdatedAdFile").val(true);
            // display delete favicon option
            $("#btnRemoveAdFile").show();
        }
    });

    $('#btnRemoveAdFile').click(function () {
        $.ajax({
            url: '/cms/site/' + $("#SiteId").val() + '/deleteadfile',
            type: 'DELETE',
            contentType: 'application/json; charset=utf-8',
            success: function () {
                $('#imgEditAdFile').html("");
                $('#btnRemoveAdFile').hide();
            }
        });
    });
};

cmsModule.changeThumbnailsForIE = function (className) {
    if ('objectFit' in document.documentElement.style === false) {
        var container = document.getElementsByClassName(className);

        for (var i = 0; i < container.length; i++) {
            if (container[i].querySelector('img').className.indexOf('imgThumbnail') >= 0) {

                var divElement = document.createElement('div'); // is a node
                container[i].appendChild(divElement);

                var childcontainer = container[i].getElementsByTagName("*");

                var imageSource = container[i].querySelector('img').src;



                container[i].querySelector('img').style.display = 'none';

                childcontainer[1].style.backgroundSize = 'cover';
                childcontainer[1].style.backgroundImage = 'url(' + imageSource + ')';
                childcontainer[1].style.backgroundPosition = 'center center';
                childcontainer[1].style.width = '100px';
                childcontainer[1].style.height = '100px';
            }
        }
    }
};

cmsModule.disablewidgetsAndSplitters = function () {
    $("#textForLockedHomepage").removeClass('hidden');

    $(".add-content-btn").addClass('homepageDisabled');

    $("#addSuperSplitterBtn").addClass('homepageDisabled');

    $(".widget-drag").addClass('homepageDisabled');
    $(".widget-settings-delete").addClass('homepageDisabled');

    $(".supersplitter-drag").addClass('homepageDisabled');
    $(".supersplitter-settings-edit").addClass('homepageDisabled');
    $(".supersplitter-settings-delete").addClass('homepageDisabled');
}

cmsModule.setStylesForFullWidthSections = function () {
    var bodyWidth = $('body').innerWidth();
    $(".full-screen-width").css('width', bodyWidth + "px");

    var marginLeft = "calc(-" + bodyWidth / 2 + "px + 50%)";
    $(".full-screen-width").css('margin-left', marginLeft);
};;
var CreateSiteWizard = extend(sportsground, "sportsground.cms.createSiteWizard");

var currentStep;
var steps = {
	"1": {
		number: 1,
		previousStep: null,
		nextStep: "2",
		customFunction: null
	},
	"2": {
		number: 2,
		previousStep: "1",
		nextStep: "2b",
		customFunction: function () {
			$.ajax({
				type: "POST",
				url: "/Site/InitialCreate",
				accepts: "application/json",
				data: { siteName: $("#SiteName").val(), siteTitle: $("#SiteTitle").val() }
			}).done(function (json) {
				// TODO : What if back button is pressed and this is then re-submitted? Or form cancelled out of
				// TODO : what if create site post hasn't finished and hidden input not set to siteid in time
				$(".siteId").val(json.siteId);
			});

			$('#wizardBackButton').one('click.wizard.override', function(e) {
				$('#wizardNextButton').off('click.wizard.override');
				CreateSiteWizard.setDefaultNextHandler();
			});

			// Remove current Handler from Next
			$('#wizardNextButton').off('click.wizard');

			// Add custom Handler to upload Image + logic to set button back to original event handler (when next is clicked)
			$('#wizardNextButton').on('click.wizard.override', function(e) {
				// still want to perform validation boss
				if (!CreateSiteWizard.isCurrentFormValid())
					return;

				// Fire the image upload button, this is inside the image form which is the only way could get JQuery Forms to work.
				// JQuery Forms leveraged to AJAX submit the file upload.
				$('#imageuploadbutton').click();

				// Success, off to next step, revert handlers on next button to normal
				$('#wizardBackButton').off('click.wizard.override');
				$('#wizardNextButton').off('click.wizard.override');
				CreateSiteWizard.setDefaultNextHandler();
			});

			// Add Cancel Site Wizard helper
			CreateSiteWizard.setCancelHandler();
		}
	},
	"2b": {
		number: 2,
		previousStep: null,
		nextStep: null,
		customFunction: function() {
			$('#schemeList').empty();
			$('#displayImageDiv').empty();
		}
	},
	"3": {
		number: 3,
		previousStep: "2",
		nextStep: null,
		customFunction: function() {
			$('#selectColorForm input[name=colorSchemeRadio]').on('click', function () {
				$('#SiteColors').val($(this).val());
			});
		}
	}
};

// These are the schemes we generate for the user
var predefinedSchemes = [
	['mono', 'soft'],
	['mono', 'pastel'],
	['mono', 'light'],
	['mono', 'pale'],
	['contrast', 'pastel'],
	['contrast', 'soft'],
	['triade', 'pastel'],
	['triade', 'soft']
];

/* Set Click Handler for 'Create Site' button */
$(function () {
	$("#beginWizardLink").click(function () {
		$("#myModal").load("/site/Create", function () {
			// Boom, here comes the goodies
			$("#myModal").modal('show');

			CreateSiteWizard.setDefaultBackHandler();
			CreateSiteWizard.setDefaultNextHandler();
			CreateSiteWizard.setStep('1');

			CreateSiteWizard.BindAjaxForm();

			// Set up the hue slider for color select
			$("#hue-slider").slider({
				min: 0,
				max: 360,
				slide: function (e, ui) {
					CreateSiteWizard.setHue(ui.value);
				}
			});

			$(".progress").progressbar({
				value: 0
			});

			$('#wizardFinishButton').on('click', function () {
				$('#myModal').off('hidden.bs.modal.removeSite');
				$('#uxHiddenFinishButton').click();
			});

			// Any fields we want to validate need to be manually parsed since they have been loaded dynamically
			// alternatively can call $jQval.unobtrusive.parse(document) but parsing individual elements better performance
			$.validator.unobtrusive.parseElement($('#SiteName').get(0));
			$.validator.unobtrusive.parseElement($('#imagefile').get(0));
			// TODO: Hiden elements not getting fired still
			$.validator.unobtrusive.parseElement($('#hiddenHue').get(0));

			$("#imagefile").change(function () {
				$(this).valid();
			});

			// Form is loaded dynamically so these defaults are not set for it on page load
			overrideUnobtrusiveDefaults();
		});
	});
});

CreateSiteWizard.isCurrentFormValid = function () {
	return $('.wizard-step:visible').find('form').valid();
}

CreateSiteWizard.setDefaultBackHandler = function() {
	$('#wizardBackButton').on('click.wizard', function() {
		CreateSiteWizard.setStep(steps[currentStep].previousStep);
	});
}

CreateSiteWizard.setDefaultNextHandler = function () {
	$('#wizardNextButton').on('click.wizard', function() {
		// trigger validation on the current form
		if (!CreateSiteWizard.isCurrentFormValid())
			return;
		CreateSiteWizard.setStep(steps[currentStep].nextStep);
	});
}

CreateSiteWizard.setCancelHandler = function () {
	$('#myModal').one('hidden.bs.modal.removeSite', function () {
		$.ajax({
			url: "/Site/Remove?siteId=" + $(".siteId").val()
		});
	});
}

CreateSiteWizard.setStep = function (step) {
	// You're doing it wrong!
	if (step == null)
		return;

	// update the current step and get the settings
	currentStep = step;
	var stepSettings = steps[step];

	// Set state of previous/next buttons
	$('#wizardBackButton').toggle(stepSettings.previousStep != null && stepSettings.number != "2");
	$('#wizardNextButton').toggle(stepSettings.nextStep != null);
	$('#wizardFinishButton').toggle(stepSettings.nextStep == null);

	if (stepSettings.customFunction != null)
		stepSettings.customFunction();

	// Set title of modal
	$('.modal-title').text('Create Site - Step ' + stepSettings.number + ' of 3');

	// Hide all wizard steps, then show the one we are currently on
	$('.wizard-step').hide('fast');
	$('#wizardStep' + currentStep + 'Container').show('fast');
}

CreateSiteWizard.setHue = function (hue) {
	var scheme = new ColorScheme();
	scheme.from_hue(hue);
	var bg = scheme.colors()[0];
	$('#hue-box').css('background-color', '#' + bg);
	$('#hiddenHue').val(hue + ":" + bg);
}

// prepare the form when the DOM is ready 
CreateSiteWizard.BindAjaxForm = function () {
	var options = {
		success: CreateSiteWizard.showResponse, // post-submit callback 
		uploadProgress: function(event, position, total, percentComplete) {
			$(".progress").progressbar({
				value: percentComplete
			});
		},
		beforeSubmit: function(arr) {
			CreateSiteWizard.setStep('2b');
		},
		timeout: 10000
	};

	// bind form using 'ajaxForm' 
	$('#imageform').ajaxForm(options);
}

// post-submit callback 
CreateSiteWizard.showResponse = function(responseText, statusText, xhr, $form) {
	if (responseText.ImageLocation)
		$('#displayImageDiv').append('<img class="image-block" src="' + responseText.ImageLocation + '" />');
	$('#displayImageDiv').append('<div style="background-color:' + responseText.AverageColorHex + ';" class="color-block" />');

	$('#divColorSchemeList').html("<label>Select Color Scheme</label>" + Theme.runSchemeGenerator(responseText.AverageColorHue));

	// FInally we're done here, display step 3
	CreateSiteWizard.setStep('3');
};
$.each($('[data-datepicker-id]'), function (index, datepicker) {
	$('input', datepicker).datepicker({
		dateFormat: 'dd/mm/yy',
		showOtherMonths: true,
		selectOtherMonths: true,
		changeMonth: true,
		changeYear: true,
		yearRange: "-100:+50",
		onSelect: function (dateString) {
			$(datepicker).closest('form').validate().element(this);
		},
		minDate: $(datepicker).data('datepicker-mindate'),
		maxDate: $(datepicker).data('datepicker-maxdate')
	});

	$('button', datepicker).click(function () {
		$('input', datepicker).datepicker('show');
	});
});
;
var docManagerModule = extend(sportsground, 'sportsground.cms.documentManager');
var xhrSearchAssets;

docManagerModule.init = function (settings) {
   
	Handlebars.registerHelper("pdfbutton", function (value) {
		if (value == "file-excel" || value == "file-word")
            return new Handlebars.SafeString('<button title="Convert to PDF" class="btn btn-xs btn-convert item-action btn-default" data-id="' + this.Id + '"><i class="glyphicon glyphicon-file"></i></button>');
		return '';
	});

	Handlebars.registerHelper("docclass", function (value) {
		if (value === 1) {
			docManagerModule.periodicallyCheckPendingStatus(this.Id);
			return '';
		}
		return 'document';
	});

	docManagerModule.settings = settings || {
		allowEditing: false,
        loadThumbsCallback: null,
        knowledgeLibrary: false
	};

    $("#btnCloseDocumentModal").on('click', function () {
        location.reload();
    });

	$('#btnGallerySearch').on('click', docManagerModule.search);
	$('#btnGallerySearchCancel').on('click', function () {
		$('#imageGallerySearch').val('');
		$('.document').show();
	});

	var libraryManagerSettings = {
		allowEditing: docManagerModule.settings.allowEditing,
		type: 'Document',
        useHeaderThumbs: false,
        knowledgeLibrary: docManagerModule.settings.knowledgeLibrary,
        container: docManagerModule.settings.container,
        isMedia: docManagerModule.settings.isMedia
	};

	if (docManagerModule.settings.allowEditing) {
        if (docManagerModule.settings.loadThumbsCallback) {
            libraryManagerSettings.folderSelectedCallback = function () {

                if (docManagerModule.settings.isMedia) {
                    docManagerModule.bindVideoHandlers();
                }
                else {
                    docManagerModule.bindDocumentHandlers();
                }

                docManagerModule.settings.loadThumbsCallback();
                docManagerModule.doDraggable();
            };
        }
        else {
            libraryManagerSettings.folderSelectedCallback = function () {

                if (docManagerModule.settings.isMedia) {
                    docManagerModule.bindVideoHandlers();
                }
                else {
                    docManagerModule.bindDocumentHandlers();
                }

                docManagerModule.doDraggable();
            };
        }
           
    }    
	else if (docManagerModule.settings.loadThumbsCallback)
		libraryManagerSettings.folderSelectedCallback = docManagerModule.settings.loadThumbsCallback;

	sportsground.cms.libraryManager.folders.init(libraryManagerSettings);

	docManagerModule.initFileUpload();

	$.ajax({
		url: '/api/getautopdfsetting',
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
		success: function(data, textStatus, xhr) {
			if (data.success) {
				$('#autoConvert').prop('checked', data.result);
				$('#autoConvert').on('change', function() {
					var model = {
						autoConvert: $(this).is(':checked')
					}
					$.ajax({
						url: '/api/setautopdfsetting',
						type: 'POST',
						contentType: 'application/json; charset=utf-8',
						data: JSON.stringify(model),
						success: function(data) {
						}
					});
				});
			}
		}
	});

    docManagerModule.loadCategories();
    docManagerModule.addTag();

    $(".close-document-settings").click(function () {

        $("#document-settings-modal").modal("hide");

    });

    $(".close-link-modal").click(function () {

        $("#add-link-modal").modal("hide");

    });

    $('#btnAddLink').click(function () {

        $("#addLinkName").val('');
        $("#addLinkName").parent('div').removeClass('has-error');

        $("#addLinkURL").val('');
        $("#addLinkURL").parent('div').removeClass('has-error');

        $("#add-link-modal").modal("show");       

    });

    docManagerModule.saveDocSettingsHandler();
    docManagerModule.saveLinkHandler();
    docManagerModule.searchFiles();
    docManagerModule.setupKnowledgeLibrary();
};

docManagerModule.setupKnowledgeLibrary = function () {

    if (!docManagerModule.settings.knowledgeLibrary) {
        return;
    }

    $(".gallery-action-buttons").hide();

    $("#divDocumentManagerModal .modal-title").html("Knowledge Library Templates");
}

docManagerModule.searchFiles = function () {

    $("#doc-search-box").keyup(function () {

        var val = $("#doc-search-box").val();


        if (val.length == 0)
        {
            var folderid = $('#uxGalleryCategoriesList .active').closest('li').attr("data-id");
            libraryManager.folders.folderSelected(folderid);
            docManagerModule.doDraggable();
            return;
        }
        else if (val.length < 3) {
            return;
        }

        var organisationId = parseInt($('#OrganisationId').val());

        if (docManagerModule.settings.knowledgeLibrary == undefined) {
            docManagerModule.settings.knowledgeLibrary = false;
        }

        var url = '/asset/SearchAssets?organisationId=' + organisationId + '&searchString=' + val + "&isKnowledgeLibrary=" + docManagerModule.settings.knowledgeLibrary;
        $('#cntGallery .cnt-images').html('');

        var sportySpinner = setTimeout(function () { $('#cntGallery .cnt-images').html("<tr><td colspan='5' style='width: 100vw;'><div class='sporty-spinner'></div></td></tr>"); }, 1000);

        if (xhrSearchAssets)
            xhrSearchAssets.abort();

        xhrSearchAssets = $.ajax({
            url: url,
            type: 'GET',
            success: function (data) {
                xhrAssets = null;
                clearTimeout(sportySpinner);
                var container = $('#cntGallery .cnt-images');
                container.html('');
                var rawHtml = $('#hbtThumbnail').html();
                if (libraryManager.folders.settings.isMedia) {
                    rawHtml = $('#hbtThumbnailMedia').html();
                }
                var template = Handlebars.compile(rawHtml);
                for (var index = 0; index < data.length; index++) {
                    if (libraryManager.folders.settings.useHeaderThumbs)
                        data[index].Src = data[index].Src.replace('_t', '_ht');
                    container.append(template(data[index]));
                }
                if (libraryManager.folders.settings.folderSelectedCallback) {
                    libraryManager.folders.settings.folderSelectedCallback();
                }


            }
        });
        return true;

    });

};

docManagerModule.doDraggable = function () {

    if (docManagerModule.settings.knowledgeLibrary){
        return;
    }

    $("#uxGalleryCategoriesList .ui-draggable").draggable({
        appendTo: 'body',
        revert: true,
        zIndex: 20000,
        refreshPositions: true,
        helper: function () {
            var divElem = $('<div />')

            var html = '<div style="width:200px;background-color:#aaa;"><ul><li>';
            html += $(this).html();
            html += '</li></ul></div>';
            var helper = divElem.append(html);
            helper.find('.editFolderGlyph').addClass('hidden');

            return helper;
        },
        stop: function () {
            docManagerModule.clearIntervals();
        }
    });

    $("#cntGallery .cnt-documents .ui-draggable").draggable({
        appendTo: 'body',
        revert: true,
        zIndex: 20000,
        refreshPositions: true,
        helper: function () {
            var helper = $('<div />').append($(this).html());
            $(helper).addClass('thumbnail');
            $(helper).data($(this).data('id'));
            return helper;
        },
        stop: function () {
            docManagerModule.clearIntervals();
        }
    });

    $("#dvDocumentsFolderHeader > .ui-droppable").droppable({
        greedy: true,
        activeClass: 'activeDroppable',
        hoverClass: 'hoverDroppable',
        tolerance: 'pointer',
        drop: function (event, ui) {
            ui.helper.fadeOut();

            var draggedFolderId = ui.draggable.data('id');
            var draggedFolderIsRootFolder = ui.draggable.data('isroot');

            if (draggedFolderIsRootFolder) {
                $(ui.draggable).draggable({ revert: true });
                return false;
            }
            else {
                var draggedFolder = ui.draggable.data('name');
                bootbox.dialog({
                    message: 'Are you sure you want to move the ' + draggedFolder + ' folder?',
                    buttons: {
                        danger: {
                            label: 'Cancel',
                            className: 'btn-info',
                            callback: function (result) {
                                if (result) {
                                    $(ui.draggable).draggable({ revert: true });
                                }
                            }
                        },
                        success: {
                            label: 'Proceed',
                            className: 'btn-primary',
                            callback: function (result) {
                                if (result) {
                                    docManagerModule.moveFolder(event, ui, true);
                                }
                            }
                        }
                    }
                });
            }
        },        
        over: function (e, ui) {
            docManagerModule.over(e, ui, this);
        }
    });

    $("#uxGalleryCategoriesList > .ui-droppable").filter(function () { return !$(this).children().is('.add'); }).droppable({
        activeClass: 'activeDroppable',
        hoverClass: 'hoverDroppable',
        tolerance: 'pointer',
        drop: function (event, ui) {
            ui.helper.fadeOut();

            if (ui.draggable[0].id.indexOf('folder') < 0) {
                docManagerModule.moveDocument(event, ui);
            }
            else {
                var draggedFolderId = ui.draggable.data('id');
                var draggedFolderIsRootFolder = ui.draggable.data('isroot');

                //should not be able to move rootfolder with subfolder to a subfolder
                if (draggedFolderIsRootFolder && $("#subfolders_" + draggedFolderId).find('li').length > 0) {
                    bootbox.alert('Unable to move a folder that would result in the creation of a folder under a sub-folder');
                    $(ui.draggable).draggable({ revert: true });
                    return false;
                }

                var draggedFolder = ui.draggable.data('name');
                var droppedFolder = $(event.target).data('name');

                if (droppedFolder != undefined && droppedFolder != "") {
                    bootbox.dialog({
                        message: 'Are you sure you want to move the ' + draggedFolder + ' folder inside the ' + droppedFolder + ' folder?',
                        buttons: {
                            danger: {
                                label: 'Cancel',
                                className: 'btn-info',
                                callback: function (result) {
                                    if (result) {
                                        $(ui.draggable).draggable({ revert: true });
                                    }
                                }
                            },
                            success: {
                                label: 'Proceed',
                                className: 'btn-primary',
                                callback: function (result) {
                                    if (result) {
                                        docManagerModule.moveFolder(event, ui, false);
                                    }
                                }
                            }
                        }
                    });
                }
            }
        },
        over: function (e, ui) {
            docManagerModule.over(e, ui, this);
        }
        
    });

    $("#uxGalleryCategoriesList .subfolders > .ui-droppable").filter(function () { return !$(this).children().is('.add'); }).droppable({
        greedy: true,
        activeClass: 'activeDroppable',
        hoverClass: 'hoverDroppable',
        tolerance: 'pointer',
        drop: function (event, ui) {
            ui.helper.fadeOut();

        if (ui.draggable[0].id.indexOf('folder') >= 0 || ui.draggable.hasClass('folder')) {
            bootbox.alert('Unable to move a folder that would result in the creation of a folder under a sub-folder');
            $(ui.draggable).draggable({ revert: true });
            return false;
        }

        docManagerModule.moveDocument(event, ui);
    }
});
};

docManagerModule.moveDocument = function (event, ui) {
            var model = {
                modalOrganisationId: $('#OrganisationId').val(),
                modalContainerId: $(event.target).data('id'),
                id: ui.draggable.data('id')
            };
            $.ajax({
                url: '/asset/MoveDocument',
                type: 'POST',
                data: JSON.stringify(model),
                contentType: 'application/json; charset=utf-8',
                beforeSend: function () {
                    $('#image-loader').modal('show');
                },
                complete: function () {
                    $('.item_' + ui.draggable.data('id')).remove();
                    $('#image-loader').modal('hide');
                }
            });        
};

docManagerModule.moveFolder = function (event, ui, creatingRoot) {

    var containerId = 0;
    if (!creatingRoot) {
        containerId = $(event.target).data('id');
    }

    var model = {
        organisationId: $('#OrganisationId').val(),
        containerId: containerId,
        folderId: ui.draggable.data('id')
    };
    $.ajax({
        url: '/asset/MoveFolder',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            libraryManager.folders.attachEditIconVisibilityHandlers();
            libraryManager.folders.getAvailableYears();
        }
    });
};

docManagerModule.saveLinkHandler = function () {

    $("#save-link-btn").click(function () {

        var model = {
            organisationId: parseInt($('#OrganisationId').val()),
            containerId: parseInt(sportsground.cms.libraryManager.folders.getSelectedFolder()),
            name: $("#addLinkName").val(),
            url: $("#addLinkURL").val()
        };

        var hasError = false;
        if ( model.name === "" ) {
            hasError = true;
            $("#addLinkName").parent('div').addClass('has-error');
        }
        else
            $("#addLinkName").parent('div').removeClass('has-error');

        if ( model.url === "" ) {
            hasError = true;
            $("#addLinkURL").parent('div').addClass('has-error');
        }
        else
            $("#addLinkURL").parent('div').removeClass('has-error');

        if ( hasError )
            return false;

        $.ajax({
            url: '/cms/documents/addlink',
            type: 'POST',
            data: JSON.stringify(model),
            contentType: 'application/json; charset=utf-8',
            success: function (data, textStatus, xhr) {
                if (data == true) {

                    var folderid = $('#uxGalleryCategoriesList .active').closest('li').attr("data-id");
                    libraryManager.folders.folderSelected(folderid);
                }

                $("#add-link-modal").modal("hide");
               
            }
        });

    });

};

docManagerModule.initFileUpload = function () {
	$(document).bind('drop dragover', function (e) {
		e.preventDefault();
	});

	$("#btnUploadImages").click(function () {
	    $("#inputUploadImages").trigger("click");
	    return false;
    });

    $("#btnUploadReplace").click(function () {
        $("#inputUploadReplace").trigger("click");
        return false;
    });

	var supportsXhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader);
	if (!supportsXhrFileUpload)
        $('#dropHintImg').hide();
    
    $('#inputUploadReplace').fileupload({
            
            add: function (e, data) {
                var uploadErrors = [];
                var acceptFileTypes = /^(.*\.(?!(pdf|xml|xsl|xls|xlsx|csv|doc|docx|ppt|pptx|odf|odt|ods|odp|mp3|m4a|css|mp4)$))?[^.]*$/i;
                if (data.originalFiles[0]['name'].length && acceptFileTypes.test(data.originalFiles[0]['name'])) {
                    uploadErrors.push('Not an accepted file type');
                }
                if (data.originalFiles[0]['size'] != null && data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 20000000) {
                    uploadErrors.push('Filesize is too big');
                }
                if (uploadErrors.length > 0) {
                    // TODO: Change this from alert??
                    alert(uploadErrors.join("\n"));
                } else {
                    data.formData = {
                        modalOrganisationId: parseInt($('#OrganisationId').val()),
                        modalContainerId: parseInt(sportsground.cms.libraryManager.folders.getSelectedFolder()),
                        assetID: $("#editingDocId").val(),
                        fileName: $("#previousFileName").val()
                    }
                    data.submit();
                }
            },
            dataType: 'json',
            url: '/Asset/ReplaceDoc',
            maxFileSize: 20000000,
            done: function (e, data) {

                var folderid = $('#uxGalleryCategoriesList .active').closest('li').attr("data-id");
                libraryManager.folders.folderSelected(folderid);
                $("#document-settings-modal").modal("hide");

                bootbox.alert({
                    title: '<i class="glyphicon glyphicon-ok"></i>&nbsp;Replacement Completed',
                    message: $("#previousFileName").val() + ' has been replaced by ' + data.result.GalleryThumbs[0].OriginalFileName
                });

            }
        });


	$('#inputUploadImages').fileupload({ 
		dropZone: $('#cntGallery'),
		//forceIframeTransport: true,
		add: function (e, data) {
			var selectedFolder = sportsground.cms.libraryManager.folders.getSelectedFolder();

			if (selectedFolder == null) {
                bootbox.alert('You have no folder selected. Please choose a year in which you have created document folders, or create a folder in your document manager.');
                return false;
			}

			var uploadErrors = [];
			var acceptFileTypes = /^(.*\.(?!(pdf|xml|xsl|xls|xlsx|csv|doc|docx|ppt|pptx|odf|odt|ods|odp|mp3|m4a|css|mp4)$))?[^.]*$/i;
            if (data.originalFiles[0]['name'].length && acceptFileTypes.test(data.originalFiles[0]['name'])) {          
				uploadErrors.push('Not an accepted file type');
			}
			if (data.originalFiles[0]['size'] != null && data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 20000000) {
				uploadErrors.push('Filesize is too big');
			}
			if (uploadErrors.length > 0) {
				// TODO: Change this from alert??
				alert(uploadErrors.join("\n"));
			} else {
				data.formData = {
					modalOrganisationId: parseInt($('#OrganisationId').val()),
                    modalContainerId: parseInt(sportsground.cms.libraryManager.folders.getSelectedFolder())
				}
				data.submit();
			}
		},
		dataType: 'json',
		url: '/Asset/UploadDocs',
		maxFileSize: 20000000,
		start: function (e) {
			$('.progress-bar').css('width', '0%');
		},
		progressall: function (e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			var percentValue = progress + '%';
			var progressBar = $('.progress-bar');
			progressBar.css('width', percentValue);
			progressBar.html(percentValue);
		},
		done: function (e, data) {
			var rawHtml = $('#hbtThumbnail').html();
			var template = Handlebars.compile(rawHtml);
			var autoConvert = $('#autoConvert').is(':checked');
			$.each(data.result.GalleryThumbs, function (index, thumbModel) {
				$('#cntGallery .cnt-images').prepend(template(thumbModel));

				var newDoc = $('#item_' + thumbModel.Id);
				newDoc.find('.btn-rename').on('click', function () {
					docManagerModule.renameItem($(this).data('id'));
					return false;
				});
				newDoc.find('.btn-convert').on('click', function () {
					docManagerModule.createPdf($(this).data('id'));
					return false;
				});
				newDoc.find('.btn-copy').on('click', function () {
                    docManagerModule.copyLink($(this).data('id'), $(this).data('type'), $(this).data('url'));
				    return false;
				});
				newDoc.find('.btn-delete').on('click', function () {
					docManagerModule.deleteItem($(this).data('id'));
					return false;
				});

				if (autoConvert) {
				    newDoc.find('.btn-convert').click();

				    //delete original doc if not pdf
				    if ($(this)[index].DocumentTypeDisplay == "Microsoft Word" || $(this)[index].DocumentTypeDisplay == "Microsoft Excel") {
				        docManagerModule.deleteOriginalItem(thumbModel.Id);
				    }
				}
			});
			$.each(data.result.Errors, function (index, error) {
				alert(error);
            });

            docManagerModule.doDraggable();

            if ( $('#videoContent').length > 0 ) {
                $(".document").removeClass('selected');
                $('#videoContent .cnt-images tr:first').addClass('selected');
                
                sportsground.cms.superSplitter.videoId = $('#videoContent .cnt-images tr:first').data('id');
            }
		}
	});
};

docManagerModule.bindDocumentHandlers = function() {
    $('.document .btn-rename').on('click', function () {
        docManagerModule.renameItem($(this).data('id'));
        return false;
    });
    $('.document .btn-convert').on('click', function () {
        docManagerModule.createPdf($(this).data('id'));
        return false;
    });
    $('.document .btn-copy').on('click', function () {
        docManagerModule.copyLink($(this).data('id'), $(this).data('type'), $(this).data('url'));
        return false;
    });
    $('.cnt-images').unbind("click");
    $('.cnt-images').on('click.download-document', '.document', docManagerModule.downloadDocument);
    $('.document .btn-delete').on('click', function () {
        docManagerModule.deleteItem($(this).data('id'));
        return false;
    });
};

docManagerModule.bindVideoHandlers = function () {
    
    //$('.cnt-images').unbind("click");
    //$('.cnt-images').on('click.download-document', '.document', function () {

    //    sportsground.cms.superSplitter.videoId = $(this).data("id");
    //    sportsground.cms.superSplitter.hideVideoModal();

    //});
   
};

docManagerModule.addTag = function () {

    $('#btnAddTag').on('click', function () {
        if (!$('#addTagForm').valid())
            return;
        var nameTextbox = $('#txtTag');
        $.ajax({
            url: '/cms/documents/tag',
            type: 'POST',
            data: '{organisationId:' + $('#OrganisationId').val() + ',name:"' + nameTextbox.val() + '"}',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                var template = Handlebars.compile($('#hbtCategory').html());
                data.DocumentCount = 0;
                var html = template(data);
                $('#fileDocumentTags').append(html);
                nameTextbox.val("");

                // Append Category to dropdownlist in the add/edit article menu
                $("#chkListTags").append("<option value='" + data.Id + "'>" + data.Name + "</option>");
                $("#chkListTags").multiselect('rebuild');
            }
        });
    });

};

docManagerModule.saveDocSettingsHandler = function () {

    $("#save-document-settings").click(function () {
                	
	        	var model = {
                    assetId: $("#editingDocId").val(),
                    name: $("#editingDocName").val(),
                    tagIds: $("#chkListTags").val() != null ? $("#chkListTags").val() : [""]
	        	};
	        	$.ajax({
	        		url: '/asset/rename',
	        		type: 'POST',
	        		data: JSON.stringify(model),
                    contentType: 'application/json; charset=utf-8',
	        		success: function (data, textStatus, xhr) {
	        			if (data == true) {
                            var folderid = $('#uxGalleryCategoriesList .active').closest('li').attr("data-id");
                            libraryManager.folders.folderSelected(folderid);
                        }

                        docManagerModule.loadCategories();

                        $("#document-settings-modal").modal("hide");
                        $('#chkListTags').multiselect('deselectall', false);
	        		}
                });
	        	

    });
}

docManagerModule.loadCategories = function () {

    var orgId = $('#OrganisationId').val();
    if (!$.isNumeric(orgId)) {
        return false;
    }

    $.ajax({
        url: '/cms/documents/tagswithcount?oid=' + orgId,
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

            $("#chkListTags option").remove();

            $('#fileDocumentTags').html("");
            var template = Handlebars.compile($('#hbtCategory').html());
            for (var i = 0; i < data.length; i++) {
                var html = template(data[i]);
                $('#fileDocumentTags').append(html);
                $("#chkListTags").append("<option value='" + data[i].Id + "'>" + data[i].Name + "</option>");
            }
            docManagerModule.attachItemClickHandlers();

            // Attach categories to multi-select box
            $('#chkListTags').multiselect({
                buttonTitle: function () {
                    return "Document Tags";
                },
                includeSelectAllOption: true,
                numberDisplayed: 1

            });

            $('#fileDocumentTags').sortable({
                cancel: 'input',
                cursor: 'move',
                handle: '.drag',
                update: function () {
                    var categoryIds = $('#fileDocumentTags').sortable('toArray');
                    var sortedcategoryIds = [];
                    for (var si = 0; si < categoryIds.length; si++) {
                        for (var ui = 0; ui < data.length; ui++) {
                            if (categoryIds[si].replace("ni_", "") == data[ui].Id) {
                                sortedcategoryIds[si] = data[ui].Id;
                                break;
                            }
                        }
                    }
                    $.ajax({
                        url: '/cms/documents/categories/reorder',
                        type: 'POST',
                        cache: false,
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify(sortedcategoryIds)
                    });
                }
            });
        }
    });
};

docManagerModule.attachItemClickHandlers = function () {
    $('#fileDocumentTags')
        .on('click', '.delete-category-button', docManagerModule.deleteClickHandler)
        .on('click', '.rename-category-button', docManagerModule.renameClickHandler)
        .on('click', '.save-name-button', docManagerModule.saveClickHandler)
        .on('click', '.cancel-name-button', docManagerModule.cancelClickHandler);
};

docManagerModule.detachItemClickHandlers = function () {
    $('#fileDocumentTags')
        .off('click', '.delete-category-button')
        .off('click', '.rename-category-button')
        .off('click', '.save-name-button')
        .off('click', '.cancel-name-button');
};

docManagerModule.setDisplayMode = function (categoryDomObject) {
    $('.category-edit', categoryDomObject).hide();
    $('.category-display', categoryDomObject).show();

    // enable add cat button and show/hide edit buttons
    $('#btnAddCategory').removeAttr('disabled');
    $('.category-edit-button').removeAttr('disabled');
    $('#btnCloseModal').removeAttr('disabled');
};

docManagerModule.deleteTag = function (id) {
    $.ajax({
        url: '/cms/documents/tag',
        type: 'DELETE',
        data: '{tagId:' + id + '}',
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, xhr) {
            if (data.success == true) {
                $('#ni_' + data.id).remove();
            }
            
            $("#chkListTags option[value='" + data.id + "']").remove();
            $("#chkListTags").multiselect('rebuild');
        }
    });
};


/* *********************************
 * 
 *    Click Handlers
 * 
 * *********************************/
docManagerModule.deleteClickHandler = function (event) {
    var categoryDomObject = $(event.currentTarget).closest('.list-group-item');
    var tagId = categoryDomObject.data('id');
    var numArticles = $('.badge', categoryDomObject).html();
    if (numArticles != '0' && numArticles != '') {
        bootbox.alert("<h3>Unable to delete</h3><p>This Document Tag has " + numArticles + " Documents using it.</p>");//, function (result) {
        //    if (result) {
        //        docManagerModule.deleteTag(tagId);
        //    }
        //});
    }
    else {
        docManagerModule.deleteTag(tagId);
    }
    return false;
};

docManagerModule.renameClickHandler = function (event) {
    // Hide the label and show the input area
    var categoryDomObject = $(event.currentTarget).closest('.list-group-item');
    $('.category-display', categoryDomObject).hide();
    $('.category-edit', categoryDomObject).show();

    // disable add cat button and show/hide edit buttons
    $('#btnAddCategory').attr('disabled', 'disabled');
    $('.category-edit-button').attr('disabled', 'disabled');
    $('#btnCloseModal').attr('disabled', 'disabled');
    return false;
};

docManagerModule.saveClickHandler = function (event) {
    var categoryDomObject = $(event.currentTarget).closest('.list-group-item');
    var input = $('.category-edit-input', categoryDomObject);
    if (input.val().length == 0) {
        input.parent().addClass('has-error');
        return false;
    }
    input.removeClass('has-error');

    // Save Changes
    var data = {
        tagId: categoryDomObject.data('id'),
        name: input.val()
    }
    $.ajax({
        url: '/cms/documents/tag/rename',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(data),
        success: function () {
            $('.category-name', categoryDomObject).html(data.name);
            docManagerModule.setDisplayMode(categoryDomObject);

            $("#chkListTags option[value='" + data.tagId + "']").html(data.name);
            $("#chkListTags").multiselect('rebuild');
        }
    });

    return false;
};

docManagerModule.cancelClickHandler = function (event) {
    var categoryDomObject = $(event.currentTarget).closest('.list-group-item');
    docManagerModule.setDisplayMode(categoryDomObject);
};


docManagerModule.renameItem = function (id) {
  
    $("#document-settings-modal").modal('show');

    var item = $('#item_' + id);
	var input = item.find('.doc-rename');
    var label = item.find('.name-label');
    var tags = item.find('.doc-tags');
    
    $("#editingDocId").val(id);
    $("#editingDocName").val(input.val());
    $("#previousFileName").val(item.data('filename'));

    if (tags.val() == "") {
        $('#chkListTags').multiselect('deselectall', false);
        $("#chkListTags").multiselect('rebuild');
    }
    else {
        $('#chkListTags').multiselect('select', tags.val().split(','));
    }
    
};

docManagerModule.copyLink = function(id, fileType, link) {
    if (fileType == 'css') {
        // get the whole path of the source when the fileType is css
        $.ajax({
            url: '/asset/GetAssetPath?id=' + id,
            type: 'GET',
            success: function(data) {
                var copyElement = "<h3>Copy Document URL</h3><br/><label>Copy URL</label><input  class='copyDocUrl' type='text' value='" + data + "' />";

                bootbox.dialog({
                    message: copyElement,
                    buttons: {
                        ok: {
                            label: "Copy",
                            callback: function() {
                                $(".copyDocUrl").focus();
                                $(".copyDocUrl").select();
                                document.execCommand("copy")
                            }
                        }
                    }
                });
            }
        });
    }
    else {

        // window.location.host only works on Chrome, Edge, and FF. **IE fix for original host URL
        var hostUrl = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
        var copyUrl = hostUrl + "/asset/downloadasset?id=" + id;

        if (fileType == 'Link') {
            copyUrl = link;
        }       

        var copyElement = "<h3>Copy Document URL</h3><br/><label>Copy URL</label><input  class='copyDocUrl' type='text' value='" + copyUrl + "' />"

        bootbox.dialog({
            message: copyElement,
            buttons: {
                ok: {
                    label: "Copy",
                    callback: function() {
                        $(".copyDocUrl").focus();
                        $(".copyDocUrl").select();
                        document.execCommand("copy")
                    }
                }
            }
        });
    }
};

docManagerModule.createPdf = function(documentId) {
	$.ajax({
		url: '/asset/CreatePdf?documentId=' + documentId,
		type: 'GET',
		success: function (data) {
			if (data) {
                var tableBody = $('#cntGallery .cnt-images tr#item_' + documentId);
				var rawHtml = $('#hbtThumbnail').html();
				var template = Handlebars.compile(rawHtml);
                var html = template(data);
                tableBody.after(html);
			}
		}
	});
};

docManagerModule.retryPdfConversion = function(failedDocumentId, retryDocumentId) {
    //first we must delete the failed conversion
    var model = { itemId: failedDocumentId };
    $.ajax({
        url: '/asset/delete',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, xhr) {
            $('#item_' + failedDocumentId).remove();
        }
    });

    //now retry the conversion for the original document
    docManagerModule.createPdf(retryDocumentId);

    return false;
}

docManagerModule.periodicallyCheckPendingStatus = function (documentId) {
    setTimeout(function () {
        $.ajax({
            url: '/asset/GetDocumentConversionStatus?assetId=' + documentId,
            type: 'GET',
            cache: false,
            success: function (data) {
                if (data === 2 || data === 3) {
                    var newDoc = $('#item_' + documentId);
                    newDoc.find('.btn-delete').show();
                    newDoc.find('.pending-conversion').remove();
                    newDoc.addClass('document');

                    if (data === 3) {
                        newDoc.find('.conversion-error').show();
                    } else {
                        newDoc.find('.btn-rename').show();
                    }
          
                    newDoc.find('.btn-rename').on('click', function () {
                        docManagerModule.renameItem($(this).data('id'));
                        return false;
                    });
                    newDoc.find('.btn-copy').on('click', function () {		
                        docManagerModule.copyLink($(this).data('id'), $(this).data('type'), $(this).data('url'));
                        return false;
                    });
                    newDoc.find('.btn-convert').on('click', function () {
                        docManagerModule.createPdf($(this).data('id'));
                        return false;
                    });
                    newDoc.on('click', docManagerModule.downloadDocument);
                    newDoc.find('.btn-delete').on('click', function () {
                        docManagerModule.deleteItem($(this).data('id'));
                        return false;
                    });
                }
                else {
                    docManagerModule.periodicallyCheckPendingStatus(documentId);
                }
            }
        });
	}, 3000);
}

docManagerModule.deleteItem = function (itemId) {
	var model = { itemId: itemId };
	bootbox.confirm("<h3>Are you sure?</h3><p>Are you sure you want to delete this document?</p>", function (result) {
		if (result) {
			$.ajax({
				url: '/asset/delete',
				type: 'POST',
				data: JSON.stringify(model),
				contentType: 'application/json; charset=utf-8',
				success: function (data, textStatus, xhr) {
					$('.item_' + itemId).remove();
				}
			});
		}
	});
  return false;
};


docManagerModule.deleteOriginalItem = function (itemId) {
  
    var model = { itemId: itemId, organisationId: parseInt($('#OrganisationId').val()) };
    $.ajax({
        url: '/asset/softdelete',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, xhr) {
            if (data) {
                $('#item_' + itemId).remove();
            }
        }
    });
    return false;
};

docManagerModule.downloadDocument = function () {  
    
    var type = $(this).data('type');
    var url;
    if (type == "Link") {
        if ($(this).data('url').indexOf("http") == -1){
            url = "http://" + $(this).data('url');
        }
        else {
            url = $(this).data('url');
        }
       
    }
    else {
        url = '/asset/downloadasset?id=' + $(this).data('id');
    }

    if (docManagerModule.settings.knowledgeLibrary) {
        //log access if in knowledge library
        $.ajax({
            url: '/asset/LogKnowledgeLibraryAccess?assetId=' + $(this).data('id'),
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            success: function (data, textStatus, xhr) {
                //do nothing

            }
        });
    }

    window.open(url, "_blank");

    return false;
};


docManagerModule.over = function (e, ui, element) {

    var dropScrollContainer = $('.cnt-folder');
    var offset = dropScrollContainer.offset();
    var offsetWidth = offset.left + dropScrollContainer.width();
    var offsetHeight = offset.top + dropScrollContainer.height();

    var distance = 70;
    var timer = 100;
    var step = 10;

    var isMoving = false;
    //Left
    if ((e.pageX - offset.left) <= distance) {
        isMoving = true;
        docManagerModule.clearIntervals();
        docManagerModule.intLeftHandler = setInterval(function () {
            dropScrollContainer.scrollLeft(dropScrollContainer.scrollLeft() - step)
        }, timer);
        console.log('left');
    }

    //Right
    if (e.pageX >= (offsetWidth - distance)) {
        isMoving = true;
        docManagerModule.clearIntervals();
        docManagerModule.intRightHandler = setInterval(function () {
            dropScrollContainer.scrollLeft(dropScrollContainer.scrollLeft() + step)
        }, timer);
        console.log('right')
    }

    //Top
    if ((e.pageY - offset.top) <= distance) {
        isMoving = true;
        docManagerModule.clearIntervals();
        docManagerModule.intTopHandler = setInterval(function () {
            dropScrollContainer.scrollTop(dropScrollContainer.scrollTop() - step)
        }, timer);
        console.log('top')
    }

    //Bottom
    if (e.pageY >= (offsetHeight - distance)) {
        isMoving = true;
        docManagerModule.clearIntervals();
        docManagerModule.intBottomHandler = setInterval(function () {
            dropScrollContainer.scrollTop(dropScrollContainer.scrollTop() + step)
        }, timer);
        console.log('bottom');
    }

    //No events
    if (!isMoving)
        docManagerModule.clearIntervals();
};

docManagerModule.intRightHandler = null;
docManagerModule.intLeftHandler = null;
docManagerModule.intTopHandler = null;
docManagerModule.intBottomHandler = null;

docManagerModule.clearIntervals = function () {
    clearInterval(docManagerModule.intRightHandler);
    clearInterval(docManagerModule.intLeftHandler);
    clearInterval(docManagerModule.intTopHandler);
    clearInterval(docManagerModule.intBottomHandler);
};;
var galleryPage = extend(sportsground, 'sportsground.cms.galleryPage');

galleryPage.init = function () {
    Handlebars.registerPartial("galleryPageFolder", $('#hbtFolder-gallerypage').html());
    galleryPage.folderToggle();

    // load folders
    $('#galleryPageYear').on('change', function () {
        sportsground.cms.galleryPage.getFolders($(this).val(), "Image");
    } );
    galleryPage.GetAvailableYears();

    sportsground.cms.galleryPage.attachEditIconHandlers();

    $("#btnTriggerImageGallery").on('click', function () {
        $('#loading-indicator').show();
        $("#myModal").load("/Asset/ImageGallery?organisationid=" + $("#OrganisationId").val(), function () {
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false  // to prevent closing with Esc button (if you want this too)
            }).modal('show');
            sportsground.cms.imageGallery.init({
                allowEditing: true,
                loadThumbsCallback: sportsground.cms.galleryPage.thumbsCallBack
            });
            sportsground.cms.imageGallery.fileupload.init();
        });
        return false;
    });

    $('#contextActionHide').on('click', function () {
        // Cancel the one time context cancel event handler
        $('body:not(#galleryFolderContextMenu)').off('click.cancelcontextmenu');
        var folderId = $('#galleryFolderContextMenu').data('contextitem-id');
        var folderNode = $('#gallerypage_folder_' + folderId);

        var isVisible = folderNode.data("visible");
        var model = {
            siteId: $("#SiteId").val(),
            containerId: folderNode.data('id'),
            isVisible: !isVisible
        };
        $.ajax({
            url: '/cms/site/UpdateContainerGalleryPageVisiblity',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data, textStatus, xhr) {
                folderNode.data('visible', model.isVisible);
                if (model.isVisible) {
                    folderNode.removeClass("public-hidden");
                } else {
                    folderNode.addClass("public-hidden");
                }
                galleryPage.attachEditIconHandlers();
            }
        });
        folderNode.find(".editFolderGlyph").hide();
        $('#galleryFolderContextMenu').hide();
        return false;
    });

    $("#galleryContent").on('click.editFolderGlyph', '.editFolderGlyph', sportsground.cms.galleryPage.triggerContextMenu);

    $(".fancybox").fancybox({
        openEffect: 'none',
        closeEffect: 'none',
        titleShow: true
    });

    $(window).resize(function () {
        galleryPage.SetHeightForGalleryContainer();
    });

    galleryPage.SetHeightForGalleryContainer();
};

galleryPage.GetAvailableYears = function() {
    $('#loading-indicator').show();
    $.ajax({
        url: '/asset/GetGalleryYearsOfOrganisation',
        type: 'GET',
        data: {
            siteId: $('#SiteId').val(),
            organisationId: $('#OrganisationId').val(),
            type: 'Image'
        },
        success: function(data) {
            $('#galleryPageYear > option').remove();
            $.each(data.GalleryYear.AvailableYears, function(index, value) {
                if (data.GalleryYear.LatestYearWithImage > 0) {
                    $('#galleryPageYear').append('<option value="' + value + '"' + (value == data.GalleryYear.LatestYearWithImage ? ' selected' : '') + '>' + value + '</option>');
                }
                else {
                    $('#galleryPageYear').append('<option value="' + value + '"' + (index == 0 ? ' selected' : '') + '>' + value + '</option>');
                }
            });

            $('#loading-indicator').hide();
            sportsground.cms.galleryPage.getFolders(data.GalleryYear.LatestYearWithImage, "Image");
        }
    });
};

galleryPage.getFolders = function(year, type) {
    $('#loading-indicator').show();
    var container = $('.uxGalleryPageCategoriesList');
    var subsiteContainer = $('#uxPageSubsites');
    container.html('');
    subsiteContainer.html('');
    $('#cntGalleryPage .cnt-gallerypage-images').html('');
    $('#cntGalleryPage .cnt-mobile-gallerypage-images').html('');

    $.ajax({
        url: '/asset/GetGalleryPageContainers',
        type: 'GET',
        data: {
            organisationId: $('#OrganisationId').val(),
            siteId: $("#SiteId").val(),
            type: type,
            year: year
        },
        success: function(data) {

            $(".uxNoPhotosAlert").hide();
            container.html('');
            var rawHtml = $('#hbtFolder-gallerypage').html();
            var template = Handlebars.compile(rawHtml);

            for (var index = 0; index < data.GalleryThumbnail.length; index++) {
                container.append(template(data.GalleryThumbnail[index]));
            }

            $('.gallery-folder').on('click', sportsground.cms.galleryPageResponsive.folderSelect);

            if (data.GalleryThumbnail.length > 0) {
                // if gallery thumbnail exist, select the first instance of the folder that is visible
                $('.cnt-gallerypage-folder > .uxGalleryPageCategoriesList li[data-visible="true"] a:first').click();
                $(".uxNoPhotosAlert").hide();
            }
            else {
                $(".uxNoPhotosAlert").show();
            }
                        
            xhrSubsites = $.ajax({
                url: '/asset/GetSubsiteGalleryPageContainers',
                type: 'GET',
                data: {
                    organisationId: $('#OrganisationId').val(),
                    siteId: $("#SiteId").val(),
                    type: type,
                    year: year
                },
                success: function(data) {
                    xhrSubsites = null;
                    // if it has subsites, do below
                    if (data != null && data.length > 0) {
                        var subsiteTemplate = Handlebars.compile($('#hbtSubsite-gallerypage').html());
                        // iterate subsites
                        for (var subsiteIndex = 0; subsiteIndex < data.length; subsiteIndex++) {
                            subsiteContainer.append(subsiteTemplate(data[subsiteIndex]));
                        }
                    }

                    $('#uxPageSubsites .gallery-folder').on('click', sportsground.cms.galleryPageResponsive.folderSelect);

                    // if no main folders visible, select the first instance of the subsite folder that is visible
                    if (!$('.cnt-gallerypage-folder > .uxGalleryPageCategoriesList li[data-visible="true"]').length) {
                        if ($('#uxPageSubsites li').length > 0) {
                            if ($('#uxPageSubsites li[data-visible="true"]').length) {
                                $('#uxPageSubsites li[data-visible="true"] a:first').click();
                            }
                            else {
                                $('#uxPageSubsites li[data-visible="false"] a:first').click();
                            }
                            $(".uxNoPhotosAlert").hide();
                        }
                        else {
                            // if there are no subsites and there is an existing folder which is visible, select that folder as default
                            if ($('.cnt-gallerypage-folder > .uxGalleryPageCategoriesList li[data-visible="false"]').length) {
                                $('.cnt-gallerypage-folder > .uxGalleryPageCategoriesList li[data-visible="false"] a:first').click();
                                $(".uxNoPhotosAlert").hide();
                            }
                            else {
                                $(".uxNoPhotosAlert").show();
                            }
                        }
                    }
                    $('#loading-indicator').hide();

                    

                }
            });

            if (!$('body').hasClass('edit')) {
                var folders = $(".uxGalleryPageCategoriesList li");
                folders.each(function (idx, li) {
                    var hasassets = $(this).data('hasassets');
                    var id = $(this).data('id');
                    if (hasassets) {
                        $('#uxFolderEmptyAlert').html('')
                        $('.uxGalleryPageCategoriesList .active').removeClass('active');
                        $('#gallerypage_folder_' + id).addClass('active');
                        sportsground.cms.galleryPageResponsive.folderSelected($(this));
                        return false;
                    }
                    else if ($(this).data('isroot') == true) {
                        if ($(".uxGalleryPageCategoriesList li[data-hasassets=true]").length > 0) {
                            $('#gallerypage_folder_' + id + ' a').click();
                        }
                    }
                });
            }
        }
    });
};

galleryPage.triggerContextMenu = function () {
    var editIcon = $(this);
    galleryPage.detachEditIconHandlers();
    var contextMenu = $("#galleryFolderContextMenu");
    var folderDomElement = editIcon.closest('li');

    if (folderDomElement.data('visible'))
        $('#contextActionHide').html('Hide');
    else
        $('#contextActionHide').html('Show');

    // set the image id or folder id as the data-contextitem-id attribute on the context menu root
    contextMenu.data('contextitem-id', folderDomElement.data('id'));

    sportsground.cms.galleryPageResponsive.setPositionOfMenu(editIcon, contextMenu);

    // set the handler to hide the menu if clicked outside of the both context menu and edit icon
    $('body:not(#galleryFolderContextMenu)').one('click.cancelcontextmenu', function() {
        if (event.target.className != "icon-img_pencil") {
            galleryPage.attachEditIconHandlers();
            contextMenu.hide();
            editIcon.hide();
        }
    });
    return false;
};

galleryPage.attachEditIconHandlers = function () {
    $(document).on('mouseenter.galleryfolderedit', '.uxGalleryPageCategoriesList li', function () {
        $(this).find('.editFolderGlyph').first().show();
    });
    $(document).on('mouseleave.galleryfolderedit', '.uxGalleryPageCategoriesList li', function () {
        $(this).find('.editFolderGlyph').first().hide();
    });

};

galleryPage.detachEditIconHandlers = function () {
    $(document).off('mouseenter.galleryfolderedit');
    $(document).off('mouseleave.galleryfolderedit');
};

galleryPage.thumbsCallBack = function () {
    sportsground.cms.imageGallery.attachEditIconVisibilityHandlers();

    $("#btnCloseImageGallery").one('click', function () {
        sportsground.cms.galleryPage.getFolders($('#galleryPageYear').val(), "Image");
    });
}

galleryPage.folderToggle = function () {
    $(document).on('click', '.main-folder .folder-toggle', function () {
        if ($(this).parent().find('.nav-subsite-folders').attr('style') == 'display: none;') {
            $(this).children().find('.folder-caret').attr('class', 'folder-caret fa fa-caret-down');
        } else {
            $(this).children().find('.folder-caret').attr('class', 'folder-caret fa fa-caret-up');
        }
        $(this).parent().find('.nav-subsite-folders').slideToggle('slow');
    });
}

galleryPage.SetHeightForGalleryContainer = function () {

    var bodyHeight = $('body').height();
    var galleryHeader = $(".no-stretch-container-parent").height();
    var galleryFooter = $("#sticky-push").height();

    var containerHeight = parseInt(bodyHeight) - (parseInt(galleryHeader) + parseInt(galleryFooter));

    var managePhotosDiv = $(".divManagePhotos").height();// button div is hidden in public mode
    var extraPadding = 10;
    if ($('body').hasClass('edit')) {
        containerHeight = (containerHeight - (managePhotosDiv * 2)) + parseInt(extraPadding); 
    }
    else {
        containerHeight = (containerHeight - managePhotosDiv) - parseInt(extraPadding); 
    }

    $('.gallery-image-container').css('height', containerHeight + 'px');
};
/*
This script handles the computing of the position from another element's CSS for responsiveness of the gallery page.
*/
var galleryPageResponsive = extend(sportsground, 'sportsground.cms.galleryPageResponsive');

galleryPageResponsive.setPositionOfMenu = function(editIcon, contextMenu) {
    // show the menu at the right of edit icon when desktop, and left when mobile
    var leftPos = editIcon.offset().left;
    if (sportsground.ui.isMobile()) {
        leftPos = editIcon.offset().left - contextMenu.width() + editIcon.outerWidth();
    }

    var topPos = editIcon.offset().top + editIcon.outerHeight();

    // reverse the visibility of the context menu
    contextMenu.css({
        display: contextMenu.is(':visible') ? "none" : "block",
        left: leftPos,
        top: topPos
    });
}

galleryPageResponsive.setActiveFolder = function(folder) {
    // remove all active
    $('.uxGalleryPageCategoriesList .active').removeClass('active');
    // set active folder
    folder.addClass('active');
}

galleryPageResponsive.folderSelect = function(event) {
    var activeFolder = $(this).parent();
    galleryPageResponsive.setActiveFolder(activeFolder);

    galleryPageResponsive.folderSelected(activeFolder);
   
    event.preventDefault();
};

galleryPageResponsive.folderSelected = function(folder) {
    var folderId = folder.data('id');
    $.ajax({
        url: '/asset/GetContainerAssets?containerId=' + folderId,
        type: 'GET',
        success: function(data) {
            var container = galleryPageResponsive.selectContainerToAddImages(folder);
            container.html('');

            if (data.length < 1) {
                container.html($('#uxFolderEmptyAlert').html());
            }
            else {
                var rawHtml = $('#hbtThumbnail-gallerypage').html();
                var template = Handlebars.compile(rawHtml);
                for (var index = 0; index < data.length; index++) {
                    container.append(template(data[index]));
                }
            }
            sportsground.cms.common.changeThumbnailsForIE('thumbnail');
        }
    });
};

galleryPageResponsive.selectContainerToAddImages = function(folder) {
    // create a div container and append below the folder when on mobile
    if (sportsground.ui.isMobile()) {
        // remove the div first, before creating a new container
        $('.cnt-mobile-gallerypage-images').remove();

        var generatedContainer = document.createElement("div");
        generatedContainer.className = 'cnt-mobile-gallerypage-images';
        folder.closest('li').append(generatedContainer);
        return $(generatedContainer);
    }
    else {
        // on desktop, use the existing container on the right side of the folder menu
        return $('#cntGalleryPage .cnt-gallerypage-images');
    }
};
function initialize(propertyName) {
   
    var latId = "#" + propertyName + "_Lat";
    var longId = "#" + propertyName + "_Long"
    var lat = $(latId).val() != null ? $(latId).val() : -41.288578;
    var long = $(longId).val() != null ? $(longId).val() : 174.777704;
	var mapOptions = {
	    center: new google.maps.LatLng(lat, long),
		zoom: 14, //appropriate zoom to see where an org is located
		streetViewControl: false,
		scaleControl: false,
		mapTypeControl: false,
		zoomControl: false,
		draggable: false,
		scrollwheel: false
	};
	var map = new google.maps.Map(document.getElementById(propertyName + '_map_canvas'),
		mapOptions);

	var marker = new google.maps.Marker({
		map: map
    });

    $("#" + propertyName + "_pac_input").locationAutoComplete({       
        suburbField: '#' + propertyName + '_Suburb',
        cityField: '#' + propertyName + '_City',
        countryField: '#' + propertyName + '_Country',
        postCodeField: '#' + propertyName + '_PostCode',
        map: map,
        marker: marker,
        latField: latId,
        lngField: longId
    });

}

function select2Dropdown(hiddenID, valueID, ph, listAction, getAction, isMultiple) {
	var sid = '#' + hiddenID;
	$(sid).select2({
		placeholder: ph,
		minimumInputLength: 2,
		allowClear: true,
		multiple: isMultiple,
		ajax: {
			url: "/api/" + listAction,
			dataType: 'json',
			data: function (term, page) {
				return {
					id: term // search term
				};
			},
			results: function (data) {
				return { results: data };
			}
		},
		initSelection: function (element, callback) {
			// the input tag has a value attribute preloaded that points to a preselected make's id
			// this function resolves that id attribute to an object that select2 can render
			// using its formatResult renderer - that way the make text is shown preselected
			var id = $('#' + valueID).val();
			if (id !== null && id.length > 0) {
				$.ajax("/api/" + getAction + "/" + id, {
					dataType: "json"
				}).done(function (data) { callback(data); });
			}
		},
		formatResult: s2FormatResult,
		formatSelection: s2FormatSelection
	});

	$(document.body).on("change", sid, function (ev) {
		var choice;
		var values = ev.val;
		// This is assuming the value will be an array of strings.
		// Convert to a comma-delimited string to set the value.
		if (values !== null && values.length > 0) {
			for (var i = 0; i < values.length; i++) {
				if (typeof choice !== 'undefined') {
					choice += ",";
					choice += values[i];
				}
				else {
					choice = values[i];
				}
			}
		}

		// Set the value so that MVC will load the form values in the postback.
		$('#' + valueID).val(choice);
	});
}

function s2FormatResult(item) {
	return item.text;
}

function s2FormatSelection(item) {
	return item.text;
}

if ($('#address_PropertyNameTypePrefix').length) {
	google.maps.event.addDomListener(window, 'load', initialize($('#address_PropertyNameTypePrefix').val()));
}
;
var gallery = extend(sportsground, 'sportsground.cms.imageGallery');

gallery.init = function(settings) {
	gallery.settings = settings || {
		allowEditing: false,
		useHeaderThumbs: false,
        loadThumbsCallback: null,
        container: null,
        isSuperSplitterBG: false
    };

    if (gallery.settings.container == null) {
        gallery.settings.container = $('#divImageGalleryModal');
    }

	$('#btnGallerySearch').on('click', gallery.search);
	$('#btnGallerySearchCancel').on('click', function() {
		$('#imageGallerySearch').val('');
		$('.gallery-thumb').show();
	});

	var libraryManagerSettings = {
		allowEditing: gallery.settings.allowEditing,
		type: 'Image',
		useHeaderThumbs: gallery.settings.useHeaderThumbs,
		preselectedFolderId: gallery.settings.preselectedFolderId,
        year: gallery.settings.year,
        container: gallery.settings.container,
        isSuperSplitterBG: gallery.settings.isSuperSplitterBG
	};

	if (gallery.settings.allowEditing) {
		libraryManagerSettings.folderSelectedCallback = function() {
			gallery.attachEditIconVisibilityHandlers();
			if (gallery.settings.loadThumbsCallback)
				gallery.settings.loadThumbsCallback();
		};
	}
	if (gallery.settings.loadThumbsCallback)
		libraryManagerSettings.folderSelectedCallback = gallery.settings.loadThumbsCallback;
	sportsground.cms.libraryManager.folders.init(libraryManagerSettings);

    $('#cntGallery').on('click.editAsset', '.asset-settings', function() {
		$('#imageContextMenu').data('contextitem-id', $(this).closest('.gallery-thumb').data('id'));
		gallery.editImageSettings();
	});
    $('#cntGallery').on('click.deleteAsset', '.asset-delete', function() {
		var deleteButton = $(this);
		bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you want to delete this image?</p>', function(result) {
			if (result) {
				$('#imageContextMenu').data('contextitem-id', deleteButton.closest('.gallery-thumb').data('id'));
				gallery.deleteItem();
			}
		});
    });   
};

gallery.deleteItem = function() {
	// Cancel the one time context cancel event handler
	$('.modal-content:not(#imageContextMenu)').off('click.cancelcontextmenu');
	var contextMenu = $('#imageContextMenu');
	var itemId = $('#imageContextMenu').data('contextitem-id');
	var model = { itemId: itemId };

	$.ajax({
		url: '/asset/delete',
		type: 'POST',
		data: JSON.stringify(model),
		contentType: 'application/json; charset=utf-8',
		success: function(data, textStatus, xhr) {
			$('#item_' + itemId).remove();
			contextMenu.hide();
			gallery.attachEditIconVisibilityHandlers();
		}
	});
	return false;
};

gallery.editImageSettings = function() {
	$('#imageContextMenu').hide();
	// slide out gallery and slide in edit image interface
    $('#cntGallery').effect('slide', { direction: 'left', mode: 'hide' }, 500, function() {
        $('#cntEditImage').effect('slide', { direction: 'right', mode: 'show' }, 500);
	});

	// populate the text inputs for name/link to those of the asset we're editting
	var galleryThumb = $('#item_' + $('#imageContextMenu').data('contextitem-id'));
	var imgThumb = galleryThumb.find('.thumbnail img');
	$('#txtImageLink').val(galleryThumb.attr('data-link'));
	$('#txtImageName').val(galleryThumb.attr('data-title'));
	$('#imgPreview').attr('src', imgThumb.attr('src'));

	// hide the footer upload and save buttons
	$('.gallery-action-buttons').hide();
	$('#btnCloseImageGallery').hide();
	$('#btnImageSettingsSave').show();
	$('.btn-group-rotate').show();
	$('#btnImageSettingsBack').show();
	$('.progress').hide();
	// keypress should trigger settings save
	$('#cntEditImage').keypress(function(e) {
		if (e.which === 13) {
			$('#btnImageSettingsSave').trigger('click');
			return false;
		}
	});
	// bind handler for cancelling out of edit mode
	$('#btnImageSettingsBack').on('click.cancelEdit', function() {
		gallery.saveImageSettings();
	});

	// bind handler for rotating image left
	$('#btnImageSettingRotateLeft').on('click.rotate', function() {
		rotate(this, -90);
	});

	// bind handler for rotating image right
	$('#btnImageSettingRotateRight').on('click.rotate', function() {
		rotate(this, 90);
	});

    $('#myModal').on('hidden.bs.modal', function () {
        // this only executes when rotate was done on images
        if ($('#btnCloseImageGallery').hasClass('refresh-images')) {
            $('img').each(function () {
                // dismiss button doesn't get the latest modified date, so we need to perform update to image src
                var imgSrc = $(this).attr('src').split('?');
                $(this).attr('src', imgSrc[0] + '?t=' + new Date().getTime());
            });
        }
    });

	function rotate(element, rotate) {
		var $this = $(element);

		if ($this.parent().data('rotating')) {
			return;
		}

		var $profileImage = $('#imgPreview');
		var galleryThumbId = $('#item_' + $('#imageContextMenu').data('contextitem-id')).data('id');
		var model = {
			assetId: galleryThumbId,
			rotate: rotate
		};

		$this.parent().data('rotating', true).attr('disabled', true);
		$this.removeClass('btn-primary');
		$profileImage.parent().prepend('<div id="spinner" style="position:absolute;top:50%;left:50%;margin-top:-50px;margin-left:-25px;color:#319A31;"><i class="fa fa-refresh fa-spin fa-4x"></i></div>');

		$.ajax({
			url: '/asset/rotate',
			type: 'POST',
			data: JSON.stringify(model),
			contentType: 'application/json; charset=utf-8',
			success: function(data, textStatus, jqXHR) {
				if (data) {
					var date = new Date();
					var thumbnail = $('img', '[data-id=' + galleryThumbId + ']');
					var preview = $('#imgPreview');
					thumbnail.attr('src', thumbnail.attr('src') + '?v=' + date.getTime());
                    preview.attr('src', preview.attr('src') + '?v=' + date.getTime());

                    // add refresh image class on close button
                    $('#btnCloseImageGallery').addClass('refresh-images');
				}
			},
			error: function(jqXHR, textStatus, errorThrown) {

			},
			complete: function(data, textStatus, jqXHR) {
				$this.parent().data('rotating', false).attr('disabled', false);
				$this.addClass('btn-primary');
				$('#spinner').remove();
			}});
	}

	// bind handler for saving/updating the name and link
	$('#btnImageSettingsSave').on('click.save', function() {
		gallery.saveImageSettings();
		galleryThumb = $('#item_' + $('#imageContextMenu').data('contextitem-id'));
		var link = sportsground.utils.prependHttpForWwwLinks($('#txtImageLink').val());
		var model = {
			assetId: galleryThumb.data('id'),
			name: $('#txtImageName').val(),
			link: link
		};
		$.ajax({
			url: '/asset/rename',
			type: 'POST',
			data: JSON.stringify(model),
			contentType: 'application/json; charset=utf-8',
			success: function(data, textStatus, xhr) {
				if (data === true) {
					var captionInput = $('#txtImageName');

					galleryThumb.attr('data-title', captionInput.val());
					galleryThumb.attr('data-link', link);
					galleryThumb.find('.thumbnail img').attr('alt', captionInput.val());
				}

			}
		});
	});
};

gallery.saveImageSettings = function() {
	$('#cntEditImage').effect('slide', { direction: 'left', mode: 'hide' }, 500, function() {
		$('#cntGallery').effect('slide', { direction: 'right', mode: 'show' }, 500);
	});
	$('.gallery-action-buttons').show();
	$('#btnCloseImageGallery').show();
	$('#btnImageSettingsSave').hide();
	$('.btn-group-rotate').hide();
	$('#btnImageSettingsBack').hide();
	$('.progress').show();
	$('#btnImageSettingsSave').off('click.save');
	$('#btnImageSettingRotateLeft').off('click.rotate');
	$('#btnImageSettingRotateRight').off('click.rotate');
	$('#btnImageSettingsBack').off('click.cancelEdit');
};

gallery.hideRenameControls = function(caption, captionInput, editBtn, saveBtn, cancelBtn) {
	caption.show();
	captionInput.hide();
	editBtn.show(0);
	saveBtn.hide(0);
	cancelBtn.hide(0);
	gallery.attachEditIconVisibilityHandlers();
};

gallery.triggerContextMenu = function(e) {
	var editIcon = $(this);
	gallery.detachEditIconVisibilityHandlers();
	var contextMenu = $('#imageContextMenu');

	// set the image id or folder id as the data-contextitem-id attribute on the context menu root
	contextMenu.data('contextitem-id', editIcon.closest('.gallery-thumb').data('id'));
	contextMenu.css({
		display: 'block',
		left: editIcon.offset().left - $(window).scrollLeft(),
		top: editIcon.offset().top - $(window).scrollTop() + 28,
		'z-index': 1
	});

	// set the handler to hide the menu if clicked outside
	$('.modal-content:not(#imageContextMenu)').one('click.cancelcontextmenu', function() {
		gallery.attachEditIconVisibilityHandlers();
		contextMenu.hide();
		editIcon.hide();
	});
	return false;
};

gallery.attachEditIconVisibilityHandlers = function() {
	$('.cnt-images').on('mouseenter.editablethumbmouseover', '.gallery-thumb', function() {
		$(this).addClass('active');
		$(this).find('.btn-toolbar').show();
	});
	$('.cnt-images').on('mouseleave.editablethumbmouseover', '.gallery-thumb', function() {
		$(this).removeClass('active');
		$(this).find('.btn-toolbar').hide();
	});
	$('.cnt-images').on('click.igcontextmenu', '.editImageGlyph', gallery.triggerContextMenu);

};

gallery.detachEditIconVisibilityHandlers = function() {
	$('.cnt-images').off('mouseenter.editablethumbmouseover');
	$('.cnt-images').off('mouseleave.editablethumbmouseover');
	$('.cnt-images').off('click.igcontextmenu');
};

gallery.fileupload = {
    init: function(fileUploadCompletedCallback) {
		$(document).bind('drop dragover', function(e) {
			e.preventDefault();
        });

        var btnUploadImages = "#btnUploadImages";

        if (gallery.settings != undefined && gallery.settings.container == "#ckeditorModal") {
            btnUploadImages = "#ckeditorModal #btnUploadImages";
        }

        $(btnUploadImages).click(function () {
            if ($('#rbWallpaperLibrary').is(':checked')) {
                if ($('#uxLibraryCategoriesList li.active').hasClass('isWallpaperFolder')) {
                    gallery.fileupload.triggerLibraryUpload();
                }
                else {
                    bootbox.alert('Please select My Wallpapers folder to upload an image.');
                }
                return false;
            }
            else {
                if ($('#rbGallery').length > 0) {
                    $.ajaxSetup({ async: false });

                    if ($('#tabContainer li.active .mobile-header-tab-item').length > 0) {
                        $('#tabContainer a[href="#tabMobile"]').click();
                    } else {
                        $('#tabContainer a[href="#tabBackground"]').click();
                    }

                    $('#rbGallery').trigger('click');
                    $.ajaxSetup({ async: true });
                }

                if ($('.gallery-folder').length === 0) {
                    bootbox.alert('<h3>No Folder Selected:</h3><p>You have no folder selected.</p><p>Please choose a year which you have created gallery folders, or create a folder in your gallery.</p>');
                    return false;
                }

                gallery.fileupload.triggerUpload();
                return false;
            }
		});

        var progressBarSettings = {
            TotalFiles: 0,
            TotalUploadPercentage: 0,
            TotalDownloadPercentage: 0,
            TotalFilesDownloaded: 0,
            ProgressInterval: '',
            initInterval: true
        };
		$('#inputUploadImages').fileupload({
            dropZone: $('#cntGallery .cnt-images'),
            sequentialUploads: true,
			add: function(e, data) {
				if ($('.gallery-folder').length === 0) {
					bootbox.alert('You have no folder selected. Please choose a year which you have created gallery folders, or create a folder in your gallery.');
					return false;
				}

				var uploadErrors = [];
                var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
                if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
					uploadErrors.push('Not an accepted file type');
				}
				if (data.originalFiles[0]['size'] > 20000000) {
					uploadErrors.push('Filesize is too big');
				}
				if (uploadErrors.length > 0) {
					// TODO: Change this from alert??
					alert(uploadErrors.join('\n'));
                } else {
                    progressBarSettings.TotalFiles = data.originalFiles.length;
					data.formData = {
						modalOrganisationId: $('#OrganisationId').val(),
                        modalContainerId: sportsground.cms.libraryManager.folders.getSelectedFolder()
					};
					data.submit();
				}
			},
			dataType: 'json',
			url: '/Asset/UploadImages',
			maxFileSize: 20000000,
            start: function(e) {
                progressBarSettings.TotalFilesDownloaded = 0;
                // set-up how many percentage will be given to upload and download
                if (progressBarSettings.TotalFiles > 4) {
                    progressBarSettings.TotalDownloadPercentage = 50;
                    progressBarSettings.TotalUploadPercentage = 50;
                }
                else {
                    progressBarSettings.TotalDownloadPercentage = progressBarSettings.TotalFiles * 10;
                    progressBarSettings.TotalUploadPercentage = 100 - progressBarSettings.TotalDownloadPercentage;
                }
                $('.progress-bar').css('width', '0%');
            },
            progressall: function(e, data) {
                // progress all only indicate when upload is finish, so only fill-up percentage upto TotalUploadPercentage
                var progress = parseInt(data.loaded / data.total * progressBarSettings.TotalUploadPercentage, 10);
                if (progressBarSettings.TotalFiles > 1) {
                    gallery.fileupload.updateProgressBar(progress);
                }
                else {

                    if (progressBarSettings.initInterval) {

                        progressBarSettings.initInterval = false;

                        //for single image upload, images that are heavy takes some time to process
                        //we want the progress bar to still update, so we will update it after each 5 seconds by 15%
                        //when the upload is done, it will get update to 100% on done part
                        var processNumber = 1;
                        progress = 25;
                        gallery.fileupload.updateProgressBar(progress);

                        progressBarSettings.ProgressInterval = window.setInterval(function () {

                            progress = progress + 15;
                            gallery.fileupload.updateProgressBar(progress);
                            processNumber = processNumber + 1;

                            if (progress >= 85 || processNumber >= 5) {//dont want to exceed 100%
                                progressBarSettings.initInterval = false;
                                clearInterval(progressBarSettings.ProgressInterval);
                            }

                        }, 5000);
                    }
                }
			},
            done: function(e, data) {
                var rawHtml = $('#hbtThumbnail').html();

                if (gallery.settings.isSuperSplitterBG) {
                    rawHtml = $('#hbtThumbnailSS').html();
                }

                var template = Handlebars.compile(rawHtml);

                progressBarSettings.initInterval = true;
                clearInterval(progressBarSettings.ProgressInterval);//clear it after done.

                $.each(data.result.GalleryThumbs, function (index, thumbModel) {
                    if (thumbModel.Id != null) {
                        if (gallery.settings.useHeaderThumbs)
                            thumbModel.Src = sportsground.utils.convertImageSrc(thumbModel.Src, 'HEADERTHUMB');
                        //thumbModel.Src = sportsground.utils.convertImageSrc(thumbModel.Src, 'SQUARE');

                        $('#cntGallery .cnt-images').prepend(template(thumbModel));

                        if (gallery.settings.loadThumbsCallback)
                            gallery.settings.loadThumbsCallback();
                    }
                    else {
                        data.result.Errors.push('Not an accepted file type');
                    }
                });

                // for each completed upload, done is executed, increase the TotalFilesDownloaded
                var progressBar = $('.progress-bar');
                progressBarSettings.TotalFilesDownloaded = progressBarSettings.TotalFilesDownloaded + 1;
                if (progressBarSettings.TotalFiles == progressBarSettings.TotalFilesDownloaded) {
                    // when TotalFiles reached, just indicate 100%
                    progressBar.css('width', '100%');
                    progressBar.html('100%');
                }
                else {
                    // get the allocated TotalDownloadPercentage and divide it by files downloaded and total files left
                    var downloadPercentCompleted = parseFloat(progressBarSettings.TotalFilesDownloaded / progressBarSettings.TotalFiles).toFixed(2) * progressBarSettings.TotalDownloadPercentage;
                    var percentValue = progressBarSettings.TotalUploadPercentage + downloadPercentCompleted + '%';
                    progressBar.css('width', percentValue);
                    progressBar.html(percentValue);
                }

                if (fileUploadCompletedCallback)
                    fileUploadCompletedCallback();

                sportsground.cms.common.changeThumbnailsForIE('thumbnail');

				$.each(data.result.Errors, function(index, error) {
					alert(error);
				});
			}
        });

        $('#inputUploadLibraryImages').fileupload({
            dropZone: $('#cntLibrary .cnt-images'),
            add: function (e, data) {
                var uploadErrors = [];
                var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
                if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                    uploadErrors.push('Not an accepted file type');
                }
                if (data.originalFiles[0]['size'] > 20000000) {
                    uploadErrors.push('Filesize is too big');
                }
                if (uploadErrors.length > 0) {
                    // TODO: Change this from alert??
                    alert(uploadErrors.join('\n'));
                } else {
                    progressBarSettings.TotalFiles = data.originalFiles.length;
                    data.formData = {
                        siteId: $("#SiteId").val(),
                        type: "My Wallpapers"
                    };
                    data.submit();
                }
            },
            dataType: 'json',
            url: '/Asset/UploadLibraryAssets',
            maxFileSize: 20000000,
            start: function (e) {
                progressBarSettings.TotalFilesDownloaded = 0;
                // set-up how many percentage will be given to upload and download
                if (progressBarSettings.TotalFiles > 4) {
                    progressBarSettings.TotalDownloadPercentage = 50;
                    progressBarSettings.TotalUploadPercentage = 50;
                }
                else {
                    progressBarSettings.TotalDownloadPercentage = progressBarSettings.TotalFiles * 10;
                    progressBarSettings.TotalUploadPercentage = 100 - progressBarSettings.TotalDownloadPercentage;
                }
                $('.progress-bar').css('width', '0%');
            },
            progressall: function (e, data) {
                // progress all only indicate when upload is finish, so only fill-up percentage upto TotalUploadPercentage
                var progress = parseInt(data.loaded / data.total * progressBarSettings.TotalUploadPercentage, 10);
                var percentValue = progress + '%';
                var progressBar = $('.progress-bar');
                progressBar.css('width', percentValue);
                progressBar.html(percentValue);
            },
            done: function (e, data) {
                var rawHtml = $('#hbtWallpaperThumbnail').html();
                var template = Handlebars.compile(rawHtml);

                $.each(data.result.GalleryThumbs, function (index, thumbModel) {
                    $('#cntLibrary .cnt-images').prepend(template(thumbModel));
                });

                // for each completed upload, done is executed, increase the TotalFilesDownloaded
                var progressBar = $('.progress-bar');
                progressBarSettings.TotalFilesDownloaded = progressBarSettings.TotalFilesDownloaded + 1;
                if (progressBarSettings.TotalFiles == progressBarSettings.TotalFilesDownloaded) {
                    // when TotalFiles reached, just indicate 100%
                    progressBar.css('width', '100%');
                    progressBar.html('100%');
                }
                else {
                    // get the allocated TotalDownloadPercentage and divide it by files downloaded and total files left
                    var downloadPercentCompleted = parseFloat(progressBarSettings.TotalFilesDownloaded / progressBarSettings.TotalFiles).toFixed(2) * progressBarSettings.TotalDownloadPercentage;
                    var percentValue = progressBarSettings.TotalUploadPercentage + downloadPercentCompleted + '%';
                    progressBar.css('width', percentValue);
                    progressBar.html(percentValue);
                }

                if (fileUploadCompletedCallback)
                    fileUploadCompletedCallback();

                sportsground.cms.common.changeThumbnailsForIE('thumbnail');

                $.each(data.result.Errors, function (index, error) {
                    alert(error);
                });
            }
        });

        $(document).ready(function () {
            gallery.fileupload.doDraggable();            
        });
        $(document).ajaxComplete(function () {
            gallery.fileupload.doDraggable();
        });
    },
    updateProgressBar: function (progress) {
        var percentValue = progress + '%';
        var progressBar = $('.progress-bar');
        progressBar.css('width', percentValue);
        progressBar.html(percentValue);
    },
	triggerUpload: function() {
		$('#inputUploadImages').trigger('click');
    },
    triggerLibraryUpload: function () {
        $('#inputUploadLibraryImages').trigger('click');
    },
    doDraggable: function () {
        $("#cntGallery #uxGalleryCategoriesList .ui-draggable").draggable({
            appendTo: 'body',
            revert: true,
            zIndex: 20000,
            refreshPositions: true,
            helper: function () {

                var divElem = $('<div />');
                var html = '<div style="width:200px;background-color:#aaaa;"><ul>';
                html += $(this)[0].outerHTML;
                html += '</ul></div>';
                var helper = divElem.append(html);
                helper.find('.editFolderGlyph').addClass('hidden');

                return helper;
            },
            stop: function () {
                gallery.clearIntervals();
            }

        });

        $("#cntGallery .cnt-images .ui-draggable").draggable({
            appendTo: 'body',
            revert: true,
            zIndex: 20000,
            refreshPositions: true,
            helper: function () {
                var helper = $('<div />').append($(this).html());
                $(helper).addClass('thumbnail');
                $(helper).data($(this).data('id'));
                return helper;
            },
            stop: function () {
                gallery.clearIntervals();
            }
        });

        $("#dvImagesFolderHeader > .ui-droppable").droppable({
            greedy: true,
            activeClass: 'activeDroppable',
            hoverClass: 'hoverDroppable',
            tolerance: 'pointer',
            drop: function (event, ui) {
                ui.helper.fadeOut();

                var draggedFolderId = ui.draggable.data('id');
                var draggedFolderIsRootFolder = ui.draggable.data('isroot');

                if (draggedFolderIsRootFolder) {
                    $(ui.draggable).draggable({ revert: true });
                    return false;
                }
                else {
                    var draggedFolder = ui.draggable.data('name');
                    bootbox.dialog({
                        message: 'Are you sure you want to move the ' + draggedFolder + ' folder?',
                        buttons: {
                            danger: {
                                label: 'Cancel',
                                className: 'btn-info',
                                callback: function (result) {
                                    if (result) {
                                        $(ui.draggable).draggable({ revert: true });
                                    }
                                }
                            },
                            success: {
                                label: 'Proceed',
                                className: 'btn-primary',
                                callback: function (result) {
                                    if (result) {
                                        gallery.fileupload.moveFolder(event, ui, true);
                                    }
                                }
                            }
                        }
                    });
                }
            },
            over: function (e, ui) {
                gallery.fileupload.over(e, ui, this);
            }
        });

        $("#uxGalleryCategoriesList > .ui-droppable").filter(function () { return !$(this).children().is('.add'); }).droppable({
            activeClass: 'activeDroppable',
            hoverClass: 'hoverDroppable',
            tolerance: 'pointer',
            drop: function (event, ui) {
                ui.helper.fadeOut();

                if (ui.draggable[0].id.indexOf('folder') < 0) {
                    gallery.fileupload.moveImage(event, ui);
                }
                else {
                    var draggedFolderId = ui.draggable.data('id');
                    var draggedFolderIsRootFolder = ui.draggable.data('isroot');

                    //should not be able to move rootfolder with subfolder to a subfolder
                    if (draggedFolderIsRootFolder && $("#subfolders_" + draggedFolderId).find('li').length > 0) {
                        bootbox.alert('Unable to move a folder that would result in the creation of a folder under a sub-folder');
                        $(ui.draggable).draggable({ revert: true });
                        return false;
                    }

                    var draggedFolder = ui.draggable.data('name');
                    var droppedFolder = $(event.target).data('name');

                    if (droppedFolder != undefined && droppedFolder != "") {
                        bootbox.dialog({
                            message: 'Are you sure you want to move the ' + draggedFolder + ' folder inside the ' + droppedFolder + ' folder?',
                            buttons: {
                                danger: {
                                    label: 'Cancel',
                                    className: 'btn-info',
                                    callback: function (result) {
                                        if (result) {
                                            $(ui.draggable).draggable({ revert: true });
                                        }
                                    }
                                },
                                success: {
                                    label: 'Proceed',
                                    className: 'btn-primary',
                                    callback: function (result) {
                                        if (result) {
                                            gallery.fileupload.moveFolder(event, ui, false);
                                        }
                                    }
                                }
                            }
                        });
                    }
                }
            },
            over: function (e, ui) {
                gallery.fileupload.over(e, ui, this);
            }
        });

        $("#uxGalleryCategoriesList .subfolders > .ui-droppable").filter(function () { return !$(this).children().is('.add'); }).droppable({
            greedy: true,  
            activeClass: 'activeDroppable',
            hoverClass: 'hoverDroppable',
            tolerance: 'pointer',
            drop: function (event, ui) {
                ui.helper.fadeOut();

                if (ui.draggable[0].id.indexOf('folder') >= 0 || ui.draggable.hasClass('folder')) {
                    bootbox.alert('Unable to move a folder that would result in the creation of a folder under a sub-folder');
                    $(ui.draggable).draggable({ revert: true });
                    return false;
                }

                moveImage(event, ui);
            },
            over: function (e, ui) {
                gallery.fileupload.over(e, ui, this);
            }
        });
    },
    moveImage: function (event, ui) {
        var model = {
            modalOrganisationId: $('#OrganisationId').val(),
            modalContainerId: $(event.target).data('id'),
            imageId: ui.draggable.data('id')
        };
        $.ajax({
            url: '/asset/UploadDroppedImages',
            type: 'POST',
            data: JSON.stringify(model),
            contentType: 'application/json; charset=utf-8',
            beforeSend: function () {
                $('#image-loader').modal('show');
            },
            complete: function () {
                $('#item_' + ui.draggable.data('id')).remove();
                $('#image-loader').modal('hide');
            }
        });

        gallery.clearIntervals();
    },
    moveFolder: function (event, ui, creatingRoot) {

        var containerId = 0;
        if (!creatingRoot) {
            containerId = $(event.target).data('id');
        }

        var model = {
            organisationId: $('#OrganisationId').val(),
            containerId: containerId,
            folderId: ui.draggable.data('id')
        };
        $.ajax({
            url: '/asset/MoveFolder',
            type: 'POST',
            data: JSON.stringify(model),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                libraryManager.folders.attachEditIconVisibilityHandlers();
                libraryManager.folders.getAvailableYears();
            }
        });

        gallery.clearIntervals();
    },
    over: function (e, ui, element) {
        
        var dropScrollContainer = $('.cnt-folder');
        var offset = dropScrollContainer.offset();
        var offsetWidth = offset.left + dropScrollContainer.width();
        var offsetHeight = offset.top + dropScrollContainer.height();
       
        var distance = 70;
        var timer = 100;
        var step = 10;

        var isMoving = false;
        //Left
        if ((e.pageX - offset.left) <= distance) {
            isMoving = true;
            gallery.clearIntervals();
            gallery.intLeftHandler = setInterval(function () {
                dropScrollContainer.scrollLeft(dropScrollContainer.scrollLeft() - step)
            }, timer);
            console.log('left');
        }

        //Right
        if (e.pageX >= (offsetWidth - distance)) {
            isMoving = true;
            gallery.clearIntervals();
            gallery.intRightHandler = setInterval(function () {
                dropScrollContainer.scrollLeft(dropScrollContainer.scrollLeft() + step)
            }, timer);
            console.log('right');
        }

        //Top
        if ((e.pageY - offset.top) <= distance) {
            isMoving = true;
            gallery.clearIntervals();
            gallery.intTopHandler = setInterval(function () {
                dropScrollContainer.scrollTop(dropScrollContainer.scrollTop() - step)
            }, timer);
            console.log('top');
        }

        //Bottom
        if (e.pageY >= (offsetHeight - distance)) {
            isMoving = true;
            gallery.clearIntervals();
            gallery.intBottomHandler = setInterval(function () {
                dropScrollContainer.scrollTop(dropScrollContainer.scrollTop() + step)
            }, timer);
            console.log('bottom');
        }

        //No events
        if (!isMoving)
            gallery.clearIntervals();  
    }
   
};

gallery.intRightHandler = null;
gallery.intLeftHandler = null;
gallery.intTopHandler = null;
gallery.intBottomHandler = null;

gallery.clearIntervals = function () {
    clearInterval(gallery.intRightHandler);
    clearInterval(gallery.intLeftHandler);
    clearInterval(gallery.intTopHandler);
    clearInterval(gallery.intBottomHandler);
};;
var libraryModule = extend(sportsground, 'sportsground.cms.library');

libraryModule.init = function (options) {
    libraryModule.options = options;

	$.ajax({
		url: '/asset/getpredefinedlibrarycategories?type=' + options.type,
		type: 'GET',
		success: function(data, textStatus, xhr) {
			$('#uxLibraryCategoriesList').html('');
			for (var index = 0; index < data.length; index++) {
                var mylibrary = index == 0;
                if (data[index].Id == 2) {
                    $('#uxLibraryCategoriesList').append('<li class="isWallpaperFolder"><a  id="folder_' + data[index].Id + '" data-mylibrary="' + mylibrary + '" class="library-folder" href="#"><i class="fa fa-folder"></i>&nbsp;&nbsp;' + data[index].Name + '</a></li>');
                }
                else {
                    $('#uxLibraryCategoriesList').append('<li><a  id="folder_' + data[index].Id + '" data-mylibrary="' + mylibrary + '" class="library-folder" href="#"><i class="fa fa-folder"></i>&nbsp;&nbsp;' + data[index].Name + '</a></li>');
                }
             }
			$('.library-folder').on('click', sportsground.cms.library.changeCategory);
			$('#uxLibraryCategoriesList li a:first').click();

		}
	});
};

libraryModule.changeCategory = function() {
	var anchor = $(this);
	$('#uxLibraryCategoriesList .active').removeClass('active');
	anchor.parent().addClass('active');

	var categoryId = anchor.attr('id').substring(7);
	if (anchor.data('mylibrary'))
		sportsground.cms.library.loadThumbs(categoryId, $('#SiteId').val());
	else
		sportsground.cms.library.loadThumbs(categoryId);
	//return false;
};

libraryModule.loadThumbs = function(categoryId, siteId) {
	var url = '/asset/getpredefinedlibraryassets?categoryId=' + categoryId;
	if (siteId)
		url += '&siteId=' + siteId;

	$.ajax({
		url: url,
		type: 'GET',
		cache: false,
		success: function(data) {
			var container = $('#cntLibrary .cnt-images');
			container.html('');
			if (container.hasClass('wallpaper')) {
				var rawHtml = $('#hbtWallpaperThumbnail').html();
			}
			else {
				var rawHtml = $('#hbtThumbnail').html();
			}
			var template = Handlebars.compile(rawHtml);
			for (var index = 0; index < data.length; index++) {
				container.append(template(data[index]));
			}
			$('.' + libraryModule.options.selector).on('click.thumbnail-click', libraryModule.options.click);

			// check the selected thumbnails if there are more than one
            if(libraryModule.options.selected)
            {
			var imageIds = libraryModule.options.selected.split(',');
			if (imageIds.length >= 1) {
				$.each(imageIds, function (index, id) {
					log($('[data-id="' + id + '"] input'));
					$('[data-id="' + id + '"] input').prop('checked', true);
				});
			}
            }
            sportsground.cms.common.changeThumbnailsForIE('thumbnail');
		}
	});
}

libraryModule.attachEditIconVisibilityHandlers = function () {
	$('#cntLibrary').on('mouseenter.editablethumbmouseover', '.' + libraryModule.options.selector, function () {
		$(this).addClass('active');
		$(this).find('.btn-toolbar').show();

	});
	$('#cntLibrary').on('mouseleave.editablethumbmouseover', '.' + libraryModule.options.selector, function () {
		$(this).removeClass('active');
		$(this).find('.btn-toolbar').hide();

	});
	$('#cntLibrary').on('mouseenter.editablethumbmouseover', ".library-asset-delete", function () {
		$('.' + libraryModule.options.selector).off('click.thumbnail-click');
	});
	$('#cntLibrary').on('mouseleave.editablethumbmouseover', '.library-asset-delete', function () {
		$('.' + libraryModule.options.selector).on('click.thumbnail-click', libraryModule.options.click);
	});
	$('#cntLibrary').on('click.deleteheader', ".library-asset-delete", function (event) {
		var thumb = $(this).closest(".gallery-thumb");
		var itemId = thumb.data('id');

        var isHeaderAsset = $("#hdnData").val() != undefined;

        var assetInUse = false;
        if (isHeaderAsset) {
            if ($("#hdnData").val().indexOf(itemId) >= 0) {
                bootbox.alert("<h3>Sorry!</h3><p>This header is currently in use, please select another " + libraryModule.options.type.toLowerCase() + " before deleting this.</p>");
                return false;
            }
        }
        else {
            if ($("#hdnWallpaperData").val().indexOf(itemId) >= 0) {
                assetInUse = true;
            }
        }

        var model = { assetId: itemId };
		$.ajax({
			url: '/asset/deletelibraryasset',
			type: 'DELETE',
			contentType: 'application/json; charset=utf-8',
			data: JSON.stringify(model),
			success: function (data, textStatus, xhr) {
                thumb.remove();

                //delete wallpaper from existings wallpaper variables so they wont create problem on save.
                if (!isHeaderAsset && assetInUse) {

                    var wallpaperData = changeWallpaperModule.settings.selected.data;
                    if (wallpaperData != null && wallpaperData != "") {
                        libraryModule.getUpdatedWallpapers(wallpaperData, false, itemId)
                    }

                    var wallpaperimageIds = changeWallpaperModule.settings.selected.imageId;
                    if (wallpaperimageIds != null && wallpaperimageIds != "") {
                        libraryModule.getUpdatedWallpapers(wallpaperData, true, itemId)
                    }

                }
			}
		});
		event.stopImmediatePropagation();
		return false;
	});
};

libraryModule.getUpdatedWallpapers = function (data, updateImageIds, itemId) {
    var wallpaperData = data.split(',');

    var updatedWallpaperData = [];
    for (var i = 0; i < wallpaperData.length; i++) {
        if (wallpaperData[i].indexOf(itemId) < 0) {
            updatedWallpaperData.push(wallpaperData[i]);
        }
    }

    if (updateImageIds) {
        changeWallpaperModule.settings.selected.imageId = updatedWallpaperimageIds.join();
    }
    else {
        changeWallpaperModule.settings.selected.data = updatedWallpaperData.join();
    }
}

libraryModule.detachEditIconVisibilityHandlers = function () {
	$('#cntLibrary').off('mouseenter.editablethumbmouseover');
	$('#cntLibrary').off('mouseleave.editablethumbmouseover');
	$('#cntLibrary').off('click.deleteheader');
};;
var libraryManager = extend(sportsground, 'sportsground.cms.libraryManager');
var xhrFolders;
var xhrSubsites;
var xhrAssets;
libraryManager.folders = {
	init: function (settings) {
		Handlebars.registerPartial("folder", $('#hbtFolder').html());

		libraryManager.folders.settings = settings || {
			allowEditing: false,
            useHeaderThumbs: false,
            folderSortType: 'Desc',
            assetSortType: 'Desc',
            sortColumn: 'Created',
            container: null
        };

        if (!libraryManager.folders.settings.container) {
            libraryManager.folders.settings.container = $('#divDocumentManagerModal');
        }

        var year = new Date().getFullYear();
        if (libraryManager.folders.settings.year)
        {
            year = libraryManager.folders.settings.year;
        }
		
        libraryManager.folders.getAvailableYears(year);

		if (libraryManager.folders.settings.allowEditing) {
			libraryManager.folders.attachEditIconVisibilityHandlers();

			$(document).on('click.editFolderGlyph', '.editFolderGlyph', libraryManager.folders.triggerContextMenu);
			$('#myModal').one('hidden.bs.modal', function () {
				$(document).off('click.editFolderGlyph');
			});

			$("#contextActionMoveYear").on('click', function () {
				$('.modal-content:not(#folderContextMenu)').off('click.cancelcontextmenu');
				$('#folderContextMenu').hide();
                var folderId = $('#folderContextMenu').data('contextitem-id');
			    var folder = $('#folderContextMenu').data('contextitem-el');
				
				var ddlMoveYear = $("<select id='ddlMoveYear' class='form-control'></select>");
                $.each($('#galleryYear option'), function (index, option) {
                    ddlMoveYear.append('<option value="' + option.value + '" >' + option.value + '</option>');
				});
				bootbox.confirm("<h4>Select Folder:</h4>" + ddlMoveYear[0].outerHTML, function (result) {
                    var model = { containerId: folderId, mainFolder: $("#ddlMoveYear").val() };
					if (result) {
					    $.ajax({
                            url: '/asset/ChangeContainerMainFolder',
							type: 'POST',
							data: JSON.stringify(model),
							contentType: 'application/json; charset=utf-8',
                            success: function () {
                                
                                libraryManager.folders.getAvailableYears();
							}
						});
					} 
					
					libraryManager.folders.attachEditIconVisibilityHandlers();
					folder.find('.editFolderGlyph').hide();
				});
            });
		    $('#contextActionCreateSubFolder').on('click', function () {
                $('.modal-content:not(#folderContextMenu)').off('click.cancelcontextmenu');
		        var folder = $('#folderContextMenu').data('contextitem-el');
                libraryManager.folders.addFolder(folder);
		        $('#folderContextMenu').hide();
		        return false;
		    });
			$('#contextActionRename').on('click', function () {
				$('.modal-content:not(#folderContextMenu)').off('click.cancelcontextmenu');
				
                var folderNode = $($('#folderContextMenu').data('contextitem-el'));
                var folderId = $('#folderContextMenu').data('contextitem-id');
                
				var model = {
                    Id: folderId,
					Name: folderNode.data('name')
				};
				var rawHtml = $('#hbtFolderEdit').html();
				var template = Handlebars.compile(rawHtml);
				var html = template(model);
				folderNode.after(html);
				folderNode.remove();

				$('#folderContextMenu').hide();

				var folderEditNode = $('#folderEdit_' + folderId);
				folderEditNode.find('input').focus();
				folderEditNode.find('.btn-edit-folder-save').on('click', libraryManager.folders.renameSave);
				folderEditNode.find('.btn-edit-folder-cancel').on('click', libraryManager.folders.renameCancel);
				return false;
			});
			$('#contextActionDelete').on('click', function () {
				$('.modal-content:not(#folderContextMenu)').off('click.cancelcontextmenu');
                var folderId = $('#folderContextMenu').data('contextitem-id');
                var folder = $('#folderContextMenu').data('contextitem-el');
               
                var assetId = folderId;
                var model = { itemId: assetId };

                var assetText = "";
                if ( $("#dvImagesFolderHeader").length > 0 )
                    assetText = "images";
                else
                    assetText = "documents";
			   
                bootbox.confirm("<h3>Are you sure?</h3><p>This will delete the folder, all subfolders and all " + assetText + " contained in these folders.</p>", function (result) {
                    if (result) {

                        $.ajax({
                            url: '/asset/HasItemsInSubFolder',
                            type: 'POST',
                            data: JSON.stringify(model),
                            contentType: 'application/json; charset=utf-8',
                            success: function (data) {
                                if (data == true) {
                                    bootbox.dialog({
                                        message: '<div class="alert alert-warning">Please type "DELETE" below to confirm you wish to continue.</div><div class="form-group"><input class="form-control" id="folderSecondWarningDeleteText" type="text" autofocus/></div>',
                                        title: "Confirm Delete",
                                        buttons: {
                                            cancel: {
                                                label: "Cancel",
                                                callback: function () {
                                                    $('#folderContextMenu').hide();
                                                    folder.find('.editFolderGlyph').hide();
                                                    libraryManager.folders.attachEditIconVisibilityHandlers();
                                                }
                                            },
                                            delete: {
                                                label: "Delete",
                                                className: "btn-danger",
                                                callback: function () {
                                                    var check = $("#folderSecondWarningDeleteText").val();
                                                    if (check.toLowerCase() === "delete") {
                                                        confirmdelete(model, folder);
                                                    }
                                                    else {
                                                        bootbox.dialog({
                                                            message: "Please type DELETE.",
                                                            title: "Warning",
                                                            buttons: {
                                                                main: {
                                                                    label: "Ok",
                                                                    className: "btn-info"
                                                                }
                                                            }
                                                        });
                                                        return false;
                                                    }
                                                }
                                            }
                                        }
                                    }).on("shown.bs.modal", function () {
                                        $(this).find('[autofocus]').focus();
                                    });
                                }
                                else {
                                    confirmdelete(model, folder);
                                }
                            }
                        });
					} else {
						$('#folderContextMenu').hide();
						folder.find('.editFolderGlyph').hide();
						libraryManager.folders.attachEditIconVisibilityHandlers();
					}
				});

				return false;
            });
            var confirmdelete = function (model, folder) {
                $.ajax({
                    url: '/asset/delete',
                    type: 'POST',
                    data: JSON.stringify(model),
                    contentType: 'application/json; charset=utf-8',
                    success: function () {
                        folder.remove();
                        $('#folderContextMenu').hide();
                        if ($('#uxGalleryCategoriesList li.active').length == 0) {
                            if ($('#uxGalleryCategoriesList li a:first').length > 0)
                                $('#uxGalleryCategoriesList li a:first').click();
                            else
                                $('#cntGallery .cnt-images').html('');
                        }
                        libraryManager.folders.attachEditIconVisibilityHandlers();
                        libraryManager.folders.getAvailableYears();
                    }
                });
            };
			$('#contextActionPrivacy').on('click', function () {
				var folderId = $('#folderContextMenu').data('contextitem-id');
                var folderDomElement = $('#folderContextMenu').data('contextitem-el');
				var isPrivate = !folderDomElement.data('isprivate');
				var model = {
					itemId: folderId,
					isPrivate: isPrivate
				};
				$.ajax({
					url: '/asset/changeprivacy',
					type: 'POST',
					data: JSON.stringify(model),
					contentType: 'application/json; charset=utf-8',
					success: function () {
						folderDomElement.data('isprivate', isPrivate);
						if (isPrivate)
							folderDomElement.find('.privacy-icon').show();
						else
							folderDomElement.find('.privacy-icon').hide();
						$('#folderContextMenu').hide();
						libraryManager.folders.attachEditIconVisibilityHandlers();
					}
				});
				return false;
			});
		    $('#btnAddGalleryFolder').on('click', function() {
		            libraryManager.folders.addFolder(null);
		    });
		
          
        }

        $(".clsFolderSortType").click(function () {
            if ($(".clsFolderSortType i").hasClass('fa-caret-down')) {
                $(".clsFolderSortType i").removeClass('fa-caret-down');
                $(".clsFolderSortType i").addClass('fa-caret-up');
                libraryManager.folders.settings.folderSortType = 'Asc';
            }
            else {
                $(".clsFolderSortType i").removeClass('fa-caret-up');
                $(".clsFolderSortType i").addClass('fa-caret-down');
                libraryManager.folders.settings.folderSortType = 'Desc';
            }
            libraryManager.folders.changeFoldersSortType();
            return false;
        });

        $(".documentSort").click(function () {
            if ($(".documentSort i").hasClass('fa-caret-down')) {
                libraryManager.folders.settings.assetSortType = 'Asc';
            }
            else {
                libraryManager.folders.settings.assetSortType = 'Desc';
            }
            if ($(this).data('column') == "FileName") {
                libraryManager.folders.settings.sortColumn = "FileName";
                if ($(".documentSort[data-column='Created'] i").hasClass('fa-caret-down') || $(".documentSort[data-column='Created'] i").hasClass('fa-caret-up')) {
                    libraryManager.folders.settings.assetSortType = 'Asc';
                }
            }
            else {
                if ($(".documentSort[data-column='FileName'] i").hasClass('fa-caret-down') || $(".documentSort[data-column='FileName'] i").hasClass('fa-caret-up')) {
                    libraryManager.folders.settings.assetSortType = 'Desc';
                }
                libraryManager.folders.settings.sortColumn = "Created";
            }
            
            libraryManager.folders.changeDocumentsSortType();
            return false;
        });
	},
	renameCancel: function () {
		var li = $(this).closest('li');
		var model = {
			Id: li.data('id'),
			Name: li.data('name')
		};
		var rawHtml = $('#hbtFolder').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(model);
		li.after(html);
		li.remove();
		libraryManager.folders.attachEditIconVisibilityHandlers();
		$('#folder_' + model.Id).find('.gallery-folder').on('click', libraryManager.folders.folderSelect);
		return false;
	},
	renameSave: function () {
        var li = $(this).closest('li');
		var input = li.find('input').val();
		// Quick validation to check the length of the folder
		var formGroup = li.find('.input-group').removeClass('has-error');
		if (input.length > 100) {
			li.find('.input-group').addClass('has-error');
			return false;
		}
		// Okay proceed with the saving! :)
		var model = {
			assetId: li.data('id'),
			name: li.find('input').val()
		};
		$.ajax({
			url: '/asset/rename',
			type: 'POST',
			data: JSON.stringify(model),
			contentType: 'application/json; charset=utf-8',
			success: function (data) {
				if (data == true) {
                    libraryManager.folders.attachEditIconVisibilityHandlers();
				    libraryManager.folders.getAvailableYears();
				}
            },
            error: function (r) {
                bootbox.alert(r.responseJSON);
			        libraryManager.folders.attachEditIconVisibilityHandlers();
			        libraryManager.folders.getAvailableYears();
			}
		});
		return false;
    },
    getAvailableYears: function (name) {
        $.ajax({
            url: '/asset/GetGalleryYearsOfOrganisation',
            type: 'GET',
            data: {
                organisationId: $('#OrganisationId').val(),
                type: libraryManager.folders.settings.type
            },
            success: function(data) {
                $('#galleryYear > option').remove();
                $.each(data.GalleryYear.AvailableYears, function(index, value) {
                    $('#galleryYear').append('<option value="' + value + '"' + (value == name ? ' selected' : '') + '>' + value + '</option>');
                });

                libraryManager.folders.getFolders(name, libraryManager.folders.settings.type, libraryManager.folders.settings.knowledgeLibrary);
            }
        });
    },
    getFolders: function (year, type, isKnowledgeLibrary) {

        var parentContainer = $("#myModal");
        if (libraryManager.folders.settings.container != undefined && libraryManager.folders.settings.container != null) {
            parentContainer = $(libraryManager.folders.settings.container);
        }

        var container = parentContainer.find('#uxGalleryCategoriesList');

		// get site id, pass to ajax call
		container.html("");

		var sportySpinner = setTimeout(function () { container.html("<div class='sporty-spinner'></div>"); }, 1000);

		parentContainer.find('#uxSubsites').html(""); //clear subsite folders too
        parentContainer.find('#cntGallery .cnt-images').html(''); //clear files shown too
        var url = '/asset/GetAssetContainers?organisationId=' + $('#OrganisationId').val() + '&siteId=' + $("#SiteId").val() + '&type=' + type + '&year=' + year;
		// if no siteId available (e.g. Dashboard), get all containers this user is authenticated to edit
		if ($("#SiteId").val() == undefined) {
            url = '/asset/GetOrganisationAssetContainers?organisationId=' + $('#OrganisationId').val() + '&type=' + type + '&isKnowledgeLibrary=' + isKnowledgeLibrary ;
		}

		if (xhrFolders)
		    xhrFolders.abort();

		xhrFolders = $.ajax({
			url: url,
			type: 'GET',
            success: function (data) {

                if (data.RootSiteFolders[0].SortType == '0') {//Desc
                    $("#folderHeader i").addClass('fa-caret-down');
                }
                else {
                    $("#folderHeader i").addClass('fa-caret-up');
                }

			    xhrFolders = null;
			    clearTimeout(sportySpinner);

                container.html( '' );
				var rawHtml = $('#hbtFolder').html();
				var template = Handlebars.compile(rawHtml);

				for (var index = 0; index < data.RootSiteFolders.length; index++) {
					container.append(template(data.RootSiteFolders[index]));
                }

                parentContainer.find('.gallery-folder').on('click', libraryManager.folders.folderSelect);
                if (libraryManager.folders.settings.preselectedFolderId) {
					$('#folder_' + libraryManager.folders.settings.preselectedFolderId + ' a:first').click();
				}
                else {
                    if (parentContainer.find('#uxGalleryCategoriesList li a:first').length > 0)
                        parentContainer.find('#uxGalleryCategoriesList li a:first').click();
                    else if (parentContainer.find('#uxSubsites li a:first').length > 0)
                        parentContainer.find('#uxSubsites li a:first').click();
					else
                        parentContainer.find('#cntGallery .cnt-images').html('');
				}
				container.trigger('foldersloaded');

				var urlSubsites = '/asset/GetSubsiteAssetContainers?organisationId=' + $('#OrganisationId').val() + '&siteId=' + $("#SiteId").val() + '&type=' + type + '&year=' + year;
			    // if no siteId available (e.g. Dashboard), get all containers this user is authenticated to edit
			    if ($("#SiteId").val() == undefined) {
			        urlSubsites = '/asset/GetOrganisationSubsiteAssetContainers?organisationId=' + $('#OrganisationId').val() + '&type=' + type + '&year=' + year;
			    }

				if (xhrSubsites)
				    xhrSubsites.abort();

				xhrSubsites = $.ajax({
				    url: urlSubsites,
				    type: 'GET',
				    success: function (data) {
				        xhrSubsites = null;
				        // if it has subsites, do below
                        parentContainer.find('#uxSubsites').html("");
				        if (data.Subsites != null && data.Subsites.length > 0) {
                            var subsiteTemplate = Handlebars.compile($('#hbtSubsite').html());
                            var subsiteContainer = parentContainer.find('#uxSubsites');
				            // iterate subsites
				            for (var subsiteIndex = 0; subsiteIndex < data.Subsites.length; subsiteIndex++) {
				                subsiteContainer.append(subsiteTemplate(data.Subsites[subsiteIndex]));
				            }
				        }

                        parentContainer.find('#uxSubsites .gallery-folder').unbind("click");
                        parentContainer.find('#uxSubsites .gallery-folder').on('click', libraryManager.folders.folderSelect);

				    }
				});

			}
		});
	
	},
	folderSelect: function () {
		var anchor = $(this);
		$('#uxGalleryCategoriesList .active').removeClass('active');
		var li = anchor.parent();
		li.addClass('active');
	
        var folderId = li.attr('id').substring(7);
    
        libraryManager.folders.folderSelected(folderId);
		return true;
	},
    folderSelected: function (folderId) {

        var isVideo = false;
        if (docManagerModule.settings) {
            isVideo = docManagerModule.settings.isMedia;
        }
        var url = '/asset/GetContainerAssets?containerId=' + folderId + "&videoOnly=" + isVideo;

        var assetsContainer = $('#cntGallery .cnt-images');
        if (isVideo)
            assetsContainer = $('#cntGallery .cnt-documents .cnt-images');

        $(assetsContainer).html('');

        var sportySpinner = setTimeout(function () { $(assetsContainer).html("<tr><td colspan='5' style='width: 100vw;'><div class='sporty-spinner'></div></td></tr>"); }, 1000);
        
	    if (xhrAssets)
	        xhrAssets.abort();

	    xhrAssets = $.ajax({
			url: url,
			type: 'GET',
            success: function (data) {

                if (data.length > 0) {
                    if (data[0].AssetType == '2' || data[0].AssetType == '3') {//Document or Link
                        if (data[0].SortColumn == 'FileName') {
                            $(".documentSort[data-column='Created'] i").removeClass('fa-caret-down');
                            $(".documentSort[data-column='Created'] i").removeClass('fa-caret-up');
                            if (data[0].SortType == '0') {//Desc
                                $(".documentSort[data-column='FileName'] i").removeClass('fa-caret-up');
                                $(".documentSort[data-column='FileName'] i").addClass('fa-caret-down');
                            }
                            else {
                                $(".documentSort[data-column='FileName'] i").removeClass('fa-caret-down');
                                $(".documentSort[data-column='FileName'] i").addClass('fa-caret-up');
                            }
                        }
                        else {
                            $(".documentSort[data-column='FileName'] i").removeClass('fa-caret-down');
                            $(".documentSort[data-column='FileName'] i").removeClass('fa-caret-up');
                            if (data[0].SortType == '0') {//Desc
                                $(".documentSort[data-column='Created'] i").removeClass('fa-caret-up');
                                $(".documentSort[data-column='Created'] i").addClass('fa-caret-down');
                            }
                            else {
                                $(".documentSort[data-column='Created'] i").removeClass('fa-caret-down');
                                $(".documentSort[data-column='Created'] i").addClass('fa-caret-up');
                            }
                        }
                    }
                }

			    xhrAssets = null;
			    clearTimeout(sportySpinner);
                var container = $(assetsContainer);
				container.html('');
                var rawHtml = $('#hbtThumbnail').html();
                if (gallery.settings && gallery.settings.isSuperSplitterBG) {
                    rawHtml = $('#hbtThumbnailSS').html();
                }
                if (docManagerModule.settings && docManagerModule.settings.isMedia) {
                    rawHtml = $('#hbtThumbnailMedia').html();
                }

                if (!rawHtml) {
                    rawHtml = $('#hbtThumbnail').html();
                }

				var template = Handlebars.compile(rawHtml);
				for (var index = 0; index < data.length; index++) {
					if (libraryManager.folders.settings.useHeaderThumbs)
						data[index].Src = data[index].Src.replace('_t', '_ht');
					container.append(template(data[index]));
				}
				if (libraryManager.folders.settings.folderSelectedCallback) {
					libraryManager.folders.settings.folderSelectedCallback();
                }
                sportsground.cms.common.changeThumbnailsForIE('thumbnail');
			}
		});
		return true;
	},
	getSelectedFolder: function () {
		if ($('#uxGalleryCategoriesList .active').length > 0)
			return $('#uxGalleryCategoriesList .active').attr('id').substring(7);

		return null;
    },
    getSelectedFolderActiveMainFolder: function () {
        var el = $('#uxGalleryCategoriesList .active');
        if (el.length > 0 && el.data("isroot")) {
            return el.data("name");
        }

	    return "";
    },
	getSelectedFolderEl: function () {
	    if ($('#uxGalleryCategoriesList .active').length > 0)
	        return $('#uxGalleryCategoriesList .active');

	    return null;
	},
	attachEditIconVisibilityHandlers: function () {
        $(document).on('mouseenter.folderedit', '#uxGalleryCategoriesList li', function () {
			$(this).find('>.editFolderGlyph').show();
		});
		$(document).on('mouseleave.folderedit', '#uxGalleryCategoriesList li', function () {
			$(this).find('>.editFolderGlyph').hide();
		});
	},
	detachEditIconVisibilityHandlers: function () {
		$(document).off('mouseenter.folderedit');
		$(document).off('mouseleave.folderedit');
	},
	triggerContextMenu: function () {
		var editIcon = $(this);

		// bugfix, not sure why this is broken but force shown state of edit icon:
		editIcon.show();

		libraryManager.folders.detachEditIconVisibilityHandlers();
		var contextMenu = $("#folderContextMenu");
		var folderDomElement = editIcon.closest('li');
        var isRoot = folderDomElement.data("isroot");

        if (isRoot) {
            $("#contextActionCreateSubFolder").show();
            $("#contextActionMoveYear").hide();
        } else {
            $("#contextActionCreateSubFolder").hide();
            if ($('#dvImagesFolderHeader').length == 0) { //not show move folder option in Images modal
                $("#contextActionMoveYear").show();
            }
            else {
                $("#contextActionMoveYear").hide();
            }
        }

		if (folderDomElement.data('isprivate'))
			$('#contextActionPrivacy').html('Set Public');
		else
			$('#contextActionPrivacy').html('Set Private');
        
		// set the image id or folder id as the data-contextitem-id attribute on the context menu root
        contextMenu.data('contextitem-id', folderDomElement.data('id'));
	    contextMenu.data('contextitem-el', folderDomElement);

        // reverse the visibility of the context menu
		contextMenu.css({
            display: contextMenu.is(':visible') ? "none" : "block",
			left: editIcon.offset().left,
			top: editIcon.offset().top + 28
		});

		// set the handler to hide the menu if clicked outside of the both context menu and edit icon
        $('.modal-content:not(#folderContextMenu)').one('click.cancelcontextmenu', function(event) {
            if (event.target.className != "icon-img_pencil") {
                libraryManager.folders.attachEditIconVisibilityHandlers();
                contextMenu.hide();
                editIcon.hide();
            }
		});
		return false;
	},
    addFolder: function (folder) {
       
	    var container = {};
       
	    // no folder selected
        if (folder == null) {
            container = $("#uxGalleryCategoriesList");
        } else {
            container = folder
        }
		
		if (container.length < 1)
			container = $("#uxGalleryCategoriesList");
		
		libraryManager.folders.addFolderItem(container);
		
	},
    addFolderItem: function (container) {
        
		libraryManager.folders.detachEditIconVisibilityHandlers();
		$('#btnAddGalleryFolder').attr('disabled', 'disabled');
		var model = {
			Id: '',
			Name: ''
		}
		var rawHtml = $('#hbtFolderEdit').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(model);
		container.append(html);

	    if (container.hasClass('collapse'))
	        container.collapse('show');

		var folderEditNode = $('#folderEdit_');
		folderEditNode.find('input').focus();
		folderEditNode.find('.btn-edit-folder-save').on('click', libraryManager.folders.createSave);
		folderEditNode.find('.btn-edit-folder-cancel').on('click', libraryManager.folders.createCancel);
		return false;
	},
	createSave: function () {
		var li = $('#folderEdit_');
		var container = li.closest("#uxGalleryCategoriesList");

		var siteId = $("#SiteId").val();
		if (siteId == null)
			siteId = container.data("site-id");

        var mainFolder = "";
	    var folderId;
        if (li.parents("li").data("isroot")) {
            mainFolder = li.parents("li").data("name");
            folderId = li.parents("li").data("id");
        }
        
		var model = {
			organisationId: $('#OrganisationId').val(),
			siteId: siteId,
			type: libraryManager.folders.settings.type,
            name: li.find('input').val(),
            mainFolder: mainFolder
		};
		$.ajax({
			url: '/asset/adddirectory',
			type: 'POST',
			data: JSON.stringify(model),
			contentType: 'application/json; charset=utf-8',
			success: function (data) {
				
				libraryManager.folders.attachEditIconVisibilityHandlers();
                libraryManager.folders.settings.preselectedFolderId = folderId || data.Id;
			    libraryManager.folders.getAvailableYears(mainFolder);
			    
			}
		});
	},
	createCancel: function () {
		$('#folderEdit_').remove();
		libraryManager.folders.attachEditIconVisibilityHandlers();
		$('#btnAddGalleryFolder').removeAttr('disabled');
    },
    changeFoldersSortType: function () {
        var model = {
            organisationId: $('#OrganisationId').val(),
            assetType: libraryManager.folders.settings.type,
            sortType: libraryManager.folders.settings.folderSortType 
        };
        $.ajax({
            url: '/asset/ChangeOrgFoldersSortType/',
            type: 'PUT',
            data: JSON.stringify(model),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.success) {
                    var list = $('#uxGalleryCategoriesList');
                    var listItems = list.children('li');
                    list.append(listItems.get().reverse());
                    var folderid = listItems.last().attr("data-id");
                    listItems.removeClass('active');
                    $("#folder_" + folderid).addClass('active');
                    libraryManager.folders.folderSelected(folderid);
                } else {
                    bootbox.alert('<h3>Sorry</h3><p>An error occurred, please try again.</p>');
                }
            }
        });
    },
    changeDocumentsSortType: function () {
        var model = {
            containerId: $('#uxGalleryCategoriesList .active').closest('li').attr("data-id"),
            sortType: libraryManager.folders.settings.assetSortType,
            sortColumn: libraryManager.folders.settings.sortColumn
        };
        $.ajax({
            url: '/asset/ChangeDocumentsSortType/',
            type: 'PUT',
            data: JSON.stringify(model),
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.success) {
                    libraryManager.folders.folderSelected(model.containerId);
                } else {
                    bootbox.alert('<h3>Sorry</h3><p>An error occurred, please try again.</p>');
                }
            }
        });
    }
};;
var linkModule = extend(sportsground, 'sportsground.cms.link');

linkModule.init = function ( widget, settings ) {
	linkModule.settings = settings || {
		defaultUrl: ''
	};

    if (widget){
        linkModule.update(
            widget.data('link-type'),
            widget.data('link-data'),
            widget.data('link-target')
        );
    }
	
};

// function to allow for explicit updates
linkModule.update = function (linkType, linkData, linkTarget) {
	linkModule.type = linkType;
	linkModule.data = linkData;
	linkModule.target = linkTarget;
};

linkModule.initEdit = function (widget, editSettings) {

	linkModule.editSettings = editSettings || {
		allowNone: false,
		modalLoadingBox: null,
		modalLoadedBox: null
	};

    if (widget) {
        linkModule.update(
            widget.data('link-type'),
            widget.data('link-data'),
            widget.data('link-target')
        );
    }

	if ( linkModule.editSettings.allowNone ) {
		$('#noneLinkTypeRadio').show();
		$('#noneLinkTypeLabel').show();
	}
	else {
		$('#noneLinkTypeRadio').hide();
		$('#noneLinkTypeLabel').hide();
	}

	$.when(
		// populate pages drop down
		$.ajax({
            url: '/cms/site/' + $('#SiteId').val() + '/getsitepages?showHiddenPages=false',
			type: 'GET',
			contentType: 'application/json; charset=utf-8',
            success: function (data) {
                var html = '';
                for (var mainPage = 0; mainPage < data.length; mainPage++) {
                    var mainPageItem = data[mainPage];

                    if (mainPageItem.Type == 'section') {
                       
                        html += '<option disabled style="font-weight:bold;">' + mainPageItem.Title + '</option>';
                        var subPages = mainPageItem.Children;
                        
                        for (var subPage = 0; subPage < subPages.length; subPage++) {
                            var subPageItem = subPages[subPage];

                            if (subPageItem.Type == 'section') {
                                html += '<option disabled >&nbsp;&nbsp;&nbsp;&nbsp;' + subPageItem.Title + '</option>';
                                var subsubPages = subPageItem.Children;
                                for (var subsubPage = 0; subsubPage < subsubPages.length; subsubPage++) {
                                    var subsubPageItem = subsubPages[subsubPage];
                                    html += '<span>-</span><option class="subsubpage" value="' + subsubPageItem.Id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- ' + subsubPageItem.Title + '</option>';
                                }
                            }
                            else {
                                html += '<option value="' + subPageItem.Id + '">&nbsp;&nbsp;&nbsp;&nbsp;' + subPageItem.Title + '</option>';
                            }

                        }
                        html += '</optgroup>';
                    }
                    else {
                        html += '<option value="' + mainPageItem.Id + '" style="font-weight:bold;">' + mainPageItem.Title + '</option>';
                    }
                }
                $('#pageDropDownList').append(html);
			}
		}),
		//populate documents drop down
		$.ajax({
			url: '/cms/site/' + $('#SiteId').val() + '/documents',
			type: 'GET',
			contentType: 'application/json; charset=utf-8',
			success: function (data) {
				for (var folderIndex = 0; folderIndex < data.length; folderIndex++) {
					var folder = data[folderIndex];
					var assets = folder.Assets;

                    $('#documentDropDownList').append('<option disabled value="parent" class="mainfolder">' + folder.FolderName + '</option>');
					for (var docIndex = 0; docIndex < assets.length; docIndex++) {
						$('#documentDropDownList').append('<option value="' + assets[docIndex].Value + '">&nbsp;&nbsp;' + assets[docIndex].Key + '</option>');
                    }

                    for (var i = 0; i < folder.SubFolders.length; i++) {
                        var subfolder = folder.SubFolders[i];
                        var subfolderAssets = subfolder.Assets;
                        $('#documentDropDownList').append('<option disabled value="parent" class="subfolder">&nbsp;&nbsp;&nbsp;&nbsp;' + subfolder.FolderName + '</option>');
                        for (var j = 0; j < subfolderAssets.length; j++) {
                            $('#documentDropDownList').append('<option value="' + subfolderAssets[j].Value + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + subfolderAssets[j].Key + '</option>');
                        }
                    }
				}
			}
		}),
        //populate forms drop down
		$.ajax({
		    url: '/Site/getorganisationforms?orgid=' + $('#OrganisationId').val(),
		    type: 'GET',
		    contentType: 'application/json; charset=utf-8',
		    success: function (data) {
		        for (var index = 0; index < data.length; index++) {

		            $('#formDropDownList').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
		        }

		    }
		})
	).done( function () {
		$('input[type="radio"][value="' + linkModule.type + '"]').prop('checked', true);
        
		$('#urlNewTabCheckbox').prop('checked', (linkModule.target === '_blank'));
		if ( linkModule.isUrl() ) {
			$('#urlText').val( linkModule.data );
            $( '#linkSettings_all' ).show();
		}
		else if ( linkModule.isPage() ) {
			$('#pageDropDownList').val( linkModule.data );
            $( '#linkSettings_all' ).show();
		}
		else if ( linkModule.isDocument() ) {
			$('#documentDropDownList').val( linkModule.data );
            $( '#linkSettings_all' ).show();
		}
		else if ( linkModule.isOnlineForm() ) {
			$('#formDropDownList').val( linkModule.data );
            $( '#linkSettings_all' ).show();
		}
		else if ( linkModule.isEmail() ) {
			$('#emailText').val( linkModule.data );
            $( '#linkSettings_all' ).show();
        }
        else {
		    $('#urlNewTabCheckbox').prop('checked', true);
        }

		if ( linkModule.editSettings.modalLoadingBox ) {
			linkModule.editSettings.modalLoadingBox.hide();
		}

		if ( linkModule.editSettings.modalLoadedBox ) {
			linkModule.editSettings.modalLoadedBox.show();
		}

		$('#linkSettings_' + linkModule.type).show();
	} );

	$('input[type="radio"][name="linkTypeRadio"]').on('change', function() {
		$('.link-settings').hide();
		$('#linkSettings_' + $(this).val()).show();
		$('#linkSettings_all').show();
	});

    $('#urlText').on('blur', sportsground.ui.attachHandlerPrependHttpOnWwwLinks);

	sportsground.cms.common.bindRemoveEditModeOnPaste();

};

linkModule.refresh = function () {
	var linkType = $('input[name=linkTypeRadio]:checked').val();
	var linkData = '', linkTarget = '';
    
	if ( $('#urlNewTabCheckbox') ) {
		linkTarget = $('#urlNewTabCheckbox').is(':checked') ? '_blank' : '';
	}
	switch (linkType) {
		case 'url':
			linkData = $('#urlText').val();
			break;
		case 'page':
			linkData = $('#pageDropDownList').val();
			break;
		case 'document':
			linkData = $('#documentDropDownList').val();
			break;
		case 'onlineForm':
		    linkData = $('#formDropDownList').val();
			break;
		case 'email':
			linkData = $('#emailText').val();
			break;
		default:
			linkData = '';
	}

	linkModule.update( linkType, linkData, linkTarget );
};

//note: sometimes the widget and link will be the same e.g. button widget
linkModule.updateWidget = function (widget, link, isCheckboxVisible) {

	var urlNewTabCheckbox = $('#urlNewTabCheckbox');
	if ( urlNewTabCheckbox && urlNewTabCheckbox.is(':checked') ) {
		linkModule.target = '_blank';
    }

	if ( linkModule.isUrl() ) {
		linkModule.url = linkModule.data;

		setLinkData(widget, link);
	}
	else if (linkModule.isPage()) {
		$.ajax({
			async: false,
			type: 'GET',
			url: '/cms/page/' + linkModule.data + '/geturl',
			success: function (url) {
				if (!url.substr(0,4) === 'http') {
					url = window.location.origin + url;
				}
                linkModule.url = url;
                if (!isCheckboxVisible)
                    linkModule.target = '';

				setLinkData(widget, link);
			}
		});
	}
	else if ( linkModule.isDocument() ) {
		linkModule.url = '/asset/downloadasset?id=' + linkModule.data;
		setLinkData(widget, link);
	}
	else if ( linkModule.isEmail() ) {
		linkModule.url = 'mailto:' + linkModule.data;
		setLinkData(widget, link);
	}
	else if (linkModule.isOnlineForm()) {
	    var url = $('#baseUrl').val();

	    linkModule.url = 'http:' + url + '/viewform/' + linkModule.data;
	    setLinkData(widget, link);
	}
	else {
		linkModule.url = '';
		linkModule.target = '';
		setLinkData(widget, link);
	}
};

function setLinkData(widget, link) {

	widget.data('link-type', linkModule.type);
	widget.data('link-data', linkModule.data);
	widget.data('link-target', linkModule.target);

	if (link) {
		link.attr('href', linkModule.url);
		link.attr('target', linkModule.target);
	}
}

linkModule.setDefaultUrl = function( defaultUrl ) {
	if ( linkModule.isNotSet() ) {
		if ( defaultUrl.length > 0 ) {
			var linkType = 'url';
			var linkData = defaultUrl;

			$('input[type="radio"][value="' + linkType + '"]').prop('checked', true);
			$('#urlText').val( linkData );
			$('#urlNewTabCheckbox').prop('checked', true);
			$('#linkSettings_' + linkType).show();
		    $('#linkSettings_all').show();
		}
		else {
			$('.link-settings').hide();
			$('input[name="linkTypeRadio"]').prop('checked', false);
			$('#urlText').val( '' );
			$('#urlNewTabCheckbox').prop('checked', false);
		}
	}
};

linkModule.isNotSet = function () {
    return linkModule.type === '' ? true : false;
};

linkModule.isNone = function () {
	return linkModule.type === 'none' ? true : false;
};

linkModule.hasValue = function () {
	return ((!linkModule.isNotSet()) && (!linkModule.isNone()));
};

linkModule.isUrl = function () {
	return linkModule.type === 'url' ? true : false;
};

linkModule.isPage = function () {
	return linkModule.type === 'page' ? true : false;
};

linkModule.isDocument = function () {
	return linkModule.type === 'document' ? true : false;
};

linkModule.isOnlineForm = function () {
	return linkModule.type === 'onlineForm' ? true : false;
};

linkModule.isEmail = function () {
	return linkModule.type === 'email' ? true : false;
};;
var navigation = extend(sportsground, 'sportsground.cms.navigation');

navigation.actionContexts = {
	rootSort: 'rs',
	rename: 'r',
	edit: 'e'
};

navigation.initialize = function () {
	$('#btnMenuStyle').on('click', function () {
		$('#loading-indicator').show();
		$("#myModal").load("/cms/site/" + $("#SiteId").val() + "/changemenu", function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			sportsground.cms.settings.menu.init();
		});
		return false;
	});

	$('.navItemEdit').on('click', function(event) {
		navigation.actions.edit($(this), event);

		return false;
	});
	navigation.editIcons.attachHoverVisibilityHandlers();
    navigation.rootSort.attachHandlers();
    $('#btnReorderParentNavigation').on('click', navigation.rootSort.init);

	$('#btnEnCancel').on('click', function () {
		var context = navigation.getActionContext();
		if (context == navigation.actionContexts.rootSort)
			navigation.rootSort.cancel();
		if (context == navigation.actionContexts.rename)
			navigation.actions.rename.cancel();
		if (context == navigation.actionContexts.edit)
			navigation.editIcons.cancelTouchMode();
	});
	$('#btnEnSave').on('click', function () {
		var context = navigation.getActionContext();
		if (context == navigation.actionContexts.rootSort)
			navigation.rootSort.save();
		if (context == navigation.actionContexts.rename)
			navigation.actions.rename.save();
	});

	// Nav context menu handlers
	navigation.contextMenu.initHandlers();

	// Free/Bronze organisations and Sub-sites cannot use the "add-page" option so disable this option
	if (($("#hdnSubscriptionPlan").val() == "Silver" || $("#hdnSubscriptionPlan").val() == "Gold") && $("#hdnIsSubSite").val() == "False") {
        $('#btnAddPageParentNavigation').on('click', function () {
            sportsground.cms.modals.addPage.init("", "", true);
			return false;
		});
	} else {
		$('#btnAddPageParentNavigation').remove();
		$('#navContextActionAddSubPage').remove();
		$('#navContextActionDelete').remove();		
	}
	
	$('#btnEditPagesTouchMode').on('click', navigation.editIcons.startTouchMode);
    $('#btnSavePageLink').on('click', navigation.actions.saveOrEditLink);
    $('#btnUpdatePageLink').on('click', navigation.actions.saveOrEditLink);
    $('#btnDeletePageLink').on('click', navigation.actions.deleteLink);
    $('#tbPageLinkUrl').on('blur', sportsground.ui.attachHandlerPrependHttpOnWwwLinks);

    navigation.setSubMenuActions();

    sportsground.cms.settings.menu.setupLogoImage();

    navigation.megaMenuSetup();
};

navigation.megaMenuSetup = function () {

    $('.cms-nav-link-root').hover(function (e) {
        var offset = ($(this).offset().left - $(".navbar.menu-bg").offset().left) * -1;
        $($(this).find('.megamenu-content')[0]).css('margin-left', offset + 'px');
    });

    $('.cms-nav-link-root').hover(function (e) {
        $($(this).find('.megamenu-content')[0]).css('display', 'block');
    });

    $('#cmsContent, .supersplitter, .no-stretch-header').click(function (e) {
        var targetClass = e.target.className;
        if (targetClass === "upload-menu-image" || targetClass === "uploaded-menu-edit-image" || targetClass === "icon-trash" || targetClass === "fa fa-cog")
            return; // we dont want to hide mega-menu if user is editing menu photo

        $('.megamenu-content').css('display', 'none');
    });

    $('body #cmsContent, body .supersplitter, body .header-image, body .menu-logo').hover(function (e) {
        if ( !$('body').hasClass('editinginmegamenu') )
            $('.megamenu-content').css('display', 'none');
    });

    // edit add image
    $(document).on('click', '.edit-mega-menu-image, .uploaded-menu-edit-image, .menu-image-settings-edit, .upload-menu-image', function () {
        var id = $(this).data('id');
        navigation.editMegaMenuImage(id); 
    });

    // delete added image
    $(document).on('click', '.menu-image-settings-delete', function () {
        var id = $(this).data('id');
        navigation.deleteMegaMenuImage(id);
    });

    //link images
    $(".uploaded-menu-image").each(function (index) {

        var image = $(this);
        sportsground.cms.link.init(image);
        var imageAnchor = $('a', image);
        if (sportsground.cms.link.hasValue()) {
            if (imageAnchor.length == 0) {
                image.wrap('<a href=""></a>');
                imageAnchor = image.parent();
            }
        } else if (imageAnchor.length > 0) {
            image.unwrap();
        }

        sportsground.cms.link.updateWidget(image, imageAnchor);
    });
    
};

navigation.editMegaMenuImage = function (id) {
   
    $('#myModal').load('/cms/editmegamenuimage?id=' + id, function () {
      
        $('#myModal').modal('show');
        navigation.initializeImageGallerySettings();

        var modal = $('#mega-menu-modal');
        // init link editing
        sportsground.cms.link.initEdit(modal, {
            allowNone: true,
            modalLoadingBox: $('#modalLoadingBox'),
            modalLoadedBox: $('#modalLoadedBox')
        });

        $('#saveMegaMenuImage').click(function () {
            navigation.saveMegaMenuImage(id);
        });

    });
};

navigation.deleteMegaMenuImage = function (id) {

    var model = {
        Id: id
    };

    $.ajax({
        type: 'POST',
        url: '/cms/megamenu/deleteimage?em=1',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model)
    })
    .done(function (result) {
        var imageIconHtml = '<a href="javascript:void(0); " data-id="' + id + '" class="upload-menu-image">+ Add Image</a>';
        $("#section" + model.Id + " .megamenu-content .column:first").html(imageIconHtml);
    });  

};

navigation.saveMegaMenuImage = function (id) {

    var image = $('#rbImageContent .cnt-images .library-image.selected img').attr('src');
    if (image === undefined || image === '') {
        bootbox.alert('Please select an image.');
        return false;
    }

    $("body").addClass('editinginmegamenu'); //adding a class, so mega menu doesn't hide on body hover after user clicks on save
    setTimeout(function () {
        $("body").removeClass('editinginmegamenu'); // will add the hover state again after 15 seconds
    }, 15000);

    //get link
    sportsground.cms.link.refresh();
    
    var model = {
        Id: id,
        ImageUrl: image,
        LinkType: sportsground.cms.link.type,
        LinkData: sportsground.cms.link.data,
        LinkTarget: sportsground.cms.link.target
    };

    $.ajax({
        type: 'POST',
        url: '/cms/megamenu/updateimage?em=1', 
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model)
    }).done(function (result) {

        imageContainer = $("#section" + model.Id + " .megamenu-content .column:first");
        if ( $(imageContainer).find('.uploaded-menu-edit-image').length > 0 ) {
            $('.uploaded-menu-edit-image').attr('src', model.ImageUrl + "?v=" + Math.random());
        }
        else {
            var imagehtml = '<img href="javascript:void(0);" title="Upload new image" class="uploaded-menu-edit-image" src="' + model.ImageUrl + '" data-id="' + model.Id + '">';
            imagehtml += '<div class="btn-toolbar" role="toolbar"><div class="btn-group">';
            imagehtml += '<button type="button" class="btn btn-primary menu-image-settings-edit btn-xs" title="Edit Image" data-id="' + model.Id + '"><span class="fa fa-cog"></span></button>';
            imagehtml += '<button type="button" class="btn btn-primary menu-image-settings-delete btn-xs" title="Remove Image" data-id="' + model.Id + '"><span class="icon-trash"></span></button>';
            imagehtml += '</div></div>';
            $(imageContainer).html(imagehtml);
        }
        $('#myModal').modal('hide');
    });   

};

navigation.initializeImageGallerySettings = function () {

    var imageGallerySettings = {
        allowEditing: false,
        container: $("#mega-menu-modal")
    };

    sportsground.cms.imageGallery.init(imageGallerySettings);

    // initialize the file uploader
    sportsground.cms.imageGallery.fileupload.init();

    // event to set image to selected
    $(document).off('click', '#rbImageContent .cnt-images .library-image')
        .on('click', '#rbImageContent .cnt-images .library-image', function () {
            $('#rbImageContent .cnt-images .library-image').removeClass('selected');
            $(this).addClass('selected');
        });
};


navigation.openSubMenu = function (menuItem, e) {

    if (!sportsground.ui.isMobile()) {
        if (navigation.doNotTriggerHover()) { return; }

        // if you hover into sub-menu, hide all sub-sub-menu, show sub-menu and stop propagation/prevent default will stop hover-out and click event of menu
        var subMenu = $(menuItem).siblings('.dropdown-menu');
        $('.dropdown-submenu .dropdown-menu').not(subMenu).hide();
        // show the edit pencil
        $(menuItem).siblings('.navItemEdit').show();

        if (subMenu.length > 0) {
            subMenu.show();
            var totalMenuLength = $('#cmsNavigationContainer').offset().left + $('#cmsNavigationContainer').width();
            var menuLength = $(menuItem).offset().left + $(menuItem).width();
            if ((menuLength + subMenu.width()) > totalMenuLength) {
                // calculate left position by getting the actual width of submenu subtracted by the min-width of menu (160px)
                // need to move 5px more to the left to prevent overlap (resulted into subtraction of 157)
                var calculatedLeftPosition = subMenu.width() - ($(menuItem).width() + 36);

                subMenu.css({ left: "calc(-100% - " + calculatedLeftPosition + "px)" });
            }
            else {
                subMenu.css({ left: "100%" });
            }

            var rootElem = $(menuItem).parent('li');
            if ($('.navbar.full-width').length > 0 && $(rootElem).data('type') === 'section') {
                navigation.checkIfMenuIsCutOffAtRight($(rootElem), -15);
            }

            e.stopPropagation();
            e.preventDefault();
        }
    }
};

navigation.setSubMenuActions = function() {
    // click of sub-menu
    $('.dropdown-submenu .cms-nav-link-2').on("click", function(e) {
        if (!sportsground.ui.isMobile()) {
            // if the sub-menu was clicked, hide the context menu
            navigation.contextMenu.hide();
        }
        var subMenu = $(this).siblings('.dropdown-menu');
        $('.dropdown-submenu .dropdown-menu').not(subMenu).hide();

        // if a sub-sub-menu exist, trigger show/hide of sub-sub-menu and stop propagation/prevent default will stop click event of menu
        if (subMenu.length > 0) {
            subMenu.toggle();
            e.stopPropagation();
            e.preventDefault();
        }
    });

    $('.dropdown-submenu .dropdown-menu').hover(
        // hover-in sub-sub-menu
        function(e) {
            if (!sportsground.ui.isMobile()) {
                if (navigation.doNotTriggerHover()) { return; }

                // if you hover into sub-sub-menu, show sub-sub-menu and stop propagation/prevent default will stop hover-out and click event of menu
                $(this).show();
                // show the edit pencil
                $(this).find('.navItemEdit:first').show();
                e.stopPropagation();
                e.preventDefault();
            }
        },
        // hover-out sub-sub-menu, trigger hover-out menu
        function(e) {
            if (!sportsground.ui.isMobile()) {
                if (navigation.doNotTriggerHover()) { return; }

                $(this).parent('cms-nav-link-root').fadeOut();
            }
        }
    );

    $('.dropdown-submenu .cms-nav-link-2').click(function (e) {

        navigation.openSubMenu(this, e);

    });

    $('.dropdown-submenu .cms-nav-link-2').hover(
        // hover-in sub-menu
        function(e) {

            navigation.openSubMenu(this, e);

        },
        // hover-out sub-menu, trigger hover-out menu
        function(e) {
            if (!sportsground.ui.isMobile()) {
                if (navigation.doNotTriggerHover()) { return; }
                
            }
        }
    );
    

        $('.cms-nav-link-root').hover(
            // hover-in menu
            function (e) {
                      
                if (!$(".navbar-toggle").is(":visible")) {
                    if (navigation.doNotTriggerHover()) { return; }

                    // hide all input and show all dropdown links on hover of root navigation
                    navigation.actions.rename.cancelAll();

                    $(this).click();
                    
                }
               
            },
            // hover-out menu
            function(e) {
            
            }
        );

        $('.cms-nav-link-root').click(
            // hover-in menu
            function (e) {

                if (!$(".navbar-toggle").is(":visible")) {
                    if (navigation.doNotTriggerHover()) { return; }
                    // hide all input and show all dropdown links on hover of root navigation
                    navigation.actions.rename.cancelAll();
                    $(".cms-nav-link-root").removeClass('open');
                    
                    $(this).toggleClass('open');
                    if ( $('.navbar.full-width').length > 0 && $(this).data('type') === 'section' ) {
                        navigation.checkIfMenuIsCutOffAtRight( $(this), 52 );
                    }
                }
                else {
                    $(this).toggleClass('open');
                }
            }
           
        );

        $(document).click(function (evt) {
           
            if ($(evt.target).parents('.navbar-nav').length > 0) {
                return;
            }

            $(".cms-nav-link-root").removeClass('open');
            $(".navItemEdit").hide();
        });

        $(".no-stretch-container-parent, #cms-content, #cmsHeader, .container").not(".edit .no-stretch-container-parent, .edit #cms-content, .edit #cmsHeader, .edit .container").hover(function (evt) {

            if ($(evt.target).parents('.navbar-nav').length > 0)
                return;
            
            $(".cms-nav-link-root").removeClass('open');
        });

        $(".edit .no-stretch-container-parent, .edit #cms-content, .edit #cmsHeader, .edit .container").hover(function (evt) {
            if (navigation.doNotTriggerHover()) { return; }

            if ($(evt.target).parents('.navbar-nav').length > 0)
                return;
            
            $(".cms-nav-link-root").removeClass('open');
        });

};

navigation.checkIfMenuIsCutOffAtRight = function (rootElem, additionalOffset) {
    var bounding = $(rootElem).find('ul')[0].getBoundingClientRect();
    if (bounding.right > (window.innerWidth || document.documentElement.clientWidth)) {
        var rootElemWidth = parseInt(additionalOffset) + $(rootElem).width();
        $(rootElem).find('ul:first').css('left', -(rootElemWidth) + 'px');
    }
};

navigation.doNotTriggerHover = function () {
    // do not trigger hover when the context menu is visible or the save and cancel button is visible
    return navigation.contextMenu.isVisible() || $('.en-save-cancel').is(':visible');
};

navigation.setActionContext = function(context) {
	$('#enActionList').data('context', context);
};

navigation.getActionContext = function() {
	return $('#enActionList').data('context');
};

navigation.contextMenu = {
	initHandlers: function () {
        $('#navContextActionManageUrl').on('click', navigation.actions.manageUrl);
		$('#navContextActionAddSubPage').on('click', navigation.actions.addSubPage);
		$('#navContextActionRename').on('click', navigation.actions.rename.init);
        $('#navContextActionMove').on('click', navigation.actions.moveRootPage);
		$('#navContextActionHide').on('click', navigation.actions.hide);
		$('#navContextActionUnHide').on('click', navigation.actions.unhide);
		$('#navContextActionMembers').on('click', navigation.actions.setMembers);
		$('#navContextActionUnsetMembers').on('click', navigation.actions.unsetMembers);
		$('#navContextActionDelete').on('click', navigation.actions.smoke);
        $('#navContextActionMoveSubPage').on('click', navigation.actions.moveSubPage);
		$('#navContextActionLink').on('click', navigation.actions.link);
        $('#navContextActionUnLink').on('click', navigation.actions.unLink);
        $('#navContextActionConceal').on('click', navigation.actions.conceal);
        $('#navContextActionDisplay').on('click', navigation.actions.unconceal);

		$("#navContextMenu").on('click', function (event) {
			event.stopPropagation();
		});
	},
	isVisible: function() {
		return $('#navContextMenu').is(':visible');
	},
    hide: function () {
		$("#navContextMenu").hide();
		$('html').off('click.cancelcontextmenu');
	},
	trigger: function (item, id, type, isSub, isHidden, isMembersOnly, isHomePage, isGalleryPage, isConcealed) {
		var contextMenu = $("#navContextMenu");
		
		// HIde all items, then show either sub-nav or root-nav items
		$('li', contextMenu).hide();
		var li = item.closest('li');
		if (isSub) {
			$('.sub', contextMenu).show();
		}
		else
			$('.root', contextMenu).show();

		// If its a page, show the link item
		if (type == 'page' && !isHomePage) {
			if (li.find('.cms-nav-link').first().attr('href').indexOf('http') != -1)
				$('#navContextActionUnLink').closest('li').show();
			else
				$('#navContextActionLink').closest('li').show();
		}

		var rootPages = $("li.cms-nav-link:not(.cms-nav-link-child)").children("a.cms-nav-link");
		var isLastPage = rootPages.not("a.nav-hidden").not("a.nav-members-only").length == 1;
		
		// If this is the Homepage you cannot hide/make-members/delete
		if (isHomePage || isGalleryPage) {
			$("#navContextActionDelete").hide();
		} else {
			$("#navContextActionDelete").show();
		}
		
		if (isGalleryPage) {
			$("#navContextActionAddSubPage").hide();
		} else {
			$("#navContextActionAddSubPage").show();
		}
		// Toggle Hide/Unhide depending on state
		if (isHidden && !isLastPage) {
			$('#navContextActionUnHide').show();
			$('#navContextActionHide').hide();
		}
		else if (isHidden && isLastPage) {
			$('#navContextActionHide').hide();
			$('#navContextActionUnHide').show();
		}
		else if (!isHidden && isLastPage) {
			$('#navContextActionHide').hide();
			$('#navContextActionUnHide').hide();
		} else {
			$('#navContextActionHide').show();
			$('#navContextActionUnHide').hide();
		}

		// Toggle MembersOnly/Public depending on state
		if (isMembersOnly && !isLastPage) {
			$('#navContextActionUnsetMembers').show();
			$('#navContextActionMembers').hide();
		} 
		else if (isMembersOnly && isLastPage) {
			$('#navContextActionMembers').hide();
			$('#navContextActionUnsetMembers').show();
		}
		else if (!isMembersOnly && isLastPage) {
			$('#navContextActionMembers').hide();
			$('#navContextActionUnsetMembers').hide();
		} else {
			$('#navContextActionMembers').show();
			$('#navContextActionUnsetMembers').hide();
        }

        if (type == 'section') {
            $('#navContextActionConceal').hide();
            $('#navContextActionDisplay').hide();
        }
        else if (isConcealed) {
            $('#navContextActionConceal').hide();
            $('#navContextActionDisplay').show();
        }
        else {
            $('#navContextActionDisplay').hide();
            $('#navContextActionConceal').show();
        }
		
		navigation.contextMenu.setContext(contextMenu, id, type);
		contextMenu.css({
			display: "block",
			left: item.offset().left,
			top: item.offset().top + 18,
			"z-index": 1100
		});
		// set the handler to hide the menu if clicked outside
		$('html').one('click.cancelcontextmenu', function () {
            navigation.editIcons.attachHoverVisibilityHandlers();
			contextMenu.hide();
			item.hide();
		});
	},
	setContext: function(contextMenu, id, type) {
		contextMenu.data('id', id);
		contextMenu.data('type', type);
	},
	getContext: function (contextMenu) {
		contextMenu = contextMenu || $("#navContextMenu");
		return { id: contextMenu.data('id'), type: contextMenu.data('type') };
	}
};

navigation.actions = {
	unLink: function() {
		navigation.contextMenu.hide();
        $('.navItemEdit').hide();

        var context = navigation.contextMenu.getContext();
        $.ajax({
            url: '/cms/page/getpage?pageId=' + context.id,
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data != false) {

                    $("#modalLinkPage").modal({
                        backdrop: 'static',
                        keyboard: false  // to prevent closing with Esc button (if you want this too)
                    }).modal('show');

                    $('#modalLinkPage').on('hidden.bs.modal', function () {
                        navigation.editIcons.attachHoverVisibilityHandlers();
                    });

                    $('#modalLinkPage').on('shown.bs.modal', function () {
                        $("#tbPageLinkUrl").removeClass('haserror');

                        $("#tbPageLinkUrl").focus();

                        $("#tbPageLinkUrl").val(data.linkUrl);
                        if (data.linkTarget == "_blank") {
                            $("#tbPageNewTabCheckbox").prop("checked", "checked");
                        }

                        $("#btnCancelPageLink").addClass('hidden');
                        $("#btnSavePageLink").addClass('hidden');

                        $("#btnUpdatePageLink").removeClass('hidden');
                        $("#btnDeletePageLink").removeClass('hidden');
                    });

                }
            }
        });
    },
    deleteLink: function () {
        bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the link from this page?</p>', function (ret) {
            if (ret) {
                var context = navigation.contextMenu.getContext();
                $.ajax({
                    url: '/cms/page/unlink?pageId=' + context.id,
                    type: 'GET',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        if (data.success) {
                            location.reload();
                        }
                    }
                });
            }
            navigation.editIcons.attachHoverVisibilityHandlers();
        });
    },
	link: function () {
		navigation.contextMenu.hide();
		$('.navItemEdit').hide();
		$("#modalLinkPage").modal({
			backdrop: 'static',
			keyboard: false  // to prevent closing with Esc button (if you want this too)
		}).modal('show');
		$('#modalLinkPage').on('hidden.bs.modal', function() {
			navigation.editIcons.attachHoverVisibilityHandlers();
        });

        $('#modalLinkPage').on('shown.bs.modal', function () {
            $("#tbPageLinkUrl").removeClass('haserror');
            $("#tbPageLinkUrl").focus();

            $("#btnCancelPageLink").removeClass('hidden');
            $("#btnSavePageLink").removeClass('hidden');

            $("#btnUpdatePageLink").addClass('hidden');
            $("#btnDeletePageLink").addClass('hidden');
        });
	},
    saveOrEditLink: function() {
        var context = navigation.contextMenu.getContext();
        var model = {
            url: $('#tbPageLinkUrl').val(),
            target: $('#tbPageNewTabCheckbox').is(':checked') ? '_blank' : ''
        };

        if ( model.url.length > 255 ) {
            $('#tbPageLinkUrl').parent().addClass('has-error');
            $("#spnLinkUrlError").removeClass('hidden');
            $("#spnLinkUrlError").html('URL too long. Please enter a URL with less than 255 characters');
            return false;
        }
        else {
            $("#spnLinkUrlError").addClass('hidden');
        }

        if ( !isUrl(model.url) ) {
            $('#tbPageLinkUrl').parent().addClass('has-error');
            return false;
        }

        $('#tbPageLinkUrl').parent().removeClass('has-error');

        $.ajax({
            url: '/cms/page/link/' + context.id,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function(data) {
                location.reload();
            }
        });
	},
	edit: function (item, event) {
	  
		if (navigation.contextMenu.isVisible()) {
			navigation.contextMenu.hide();
			navigation.editIcons.attachHoverVisibilityHandlers();
		}
		else {
			navigation.editIcons.detachHoverVisibilityHandlers();
			var navLink = item.closest('li');
			var anchor = $('a.cms-nav-link:first', navLink);
			var isSub = navLink.hasClass('cms-nav-link-child');
            navigation.contextMenu.trigger(item, navLink.data('id'), navLink.data('type'), isSub, anchor.hasClass('nav-hidden'), anchor.hasClass('nav-members-only'),
                navLink.data("home-page") == "True", navLink.data("gallery-page") == "True", anchor.hasClass('nav-concealed'));

			if (navLink.data("type") == "section") {
				$("#navContextActionMembers").hide();
				$("#navContextActionUnsetMembers").hide();
            }

            if (navLink.data("gallery-page") == "True") {
                $("#navContextActionMove").parent('li').addClass('hidden');
            }
            else {
                $("#navContextActionMove").parent('li').removeClass('hidden');
            }

            var isSub2 = navLink.hasClass('cms-nav-link-child-2');

            if (isSub2){
                $("#navContextActionAddSubPage").hide();
            }

            var bounding = $('#navContextMenu')[0].getBoundingClientRect();
            if ( bounding.right + 2 > (window.innerWidth || document.documentElement.clientWidth) ) {
                var editModalPosition = $("#navContextMenu").position().left - 135;
                $("#navContextMenu").css('left', editModalPosition + 'px');
            }
		}
	},
    manageUrl: function () {
        navigation.contextMenu.hide();
        navigation.editIcons.hideAll();
        navigation.editIcons.attachHoverVisibilityHandlers();
        var context = navigation.contextMenu.getContext();
        sportsground.cms.modals.manageUrl.init(context.id, context.type);
        return false;
    },
	addSubPage: function () {
		navigation.contextMenu.hide();
		navigation.editIcons.hideAll();
		navigation.editIcons.attachHoverVisibilityHandlers();
        var context = navigation.contextMenu.getContext();
        sportsground.cms.modals.addPage.init(context.id, context.type, false);
		return false;
	},
	rename: {
		init: function () {
			navigation.setActionContext(navigation.actionContexts.rename);
			$('.en-main').hide();
			$('.en-save-cancel').show();
			var navItemContext = navigation.contextMenu.getContext();
			var item = $('#' + navItemContext.type + navItemContext.id);

			var input = $('> input', item);
			var anchor = $('> a.cms-nav-link', item);

			input.width(anchor.outerWidth() - 10);
			anchor.fadeOut(function () {
				input.fadeIn(function () {
					input.focus();
				});
			});

			$(input).keypress(function (e) {
				if (e.which == 13) {
					e.preventDefault();
					$("#btnEnSave").trigger("click");
				}
			});

			navigation.editIcons.detachHoverVisibilityHandlers();
			navigation.contextMenu.hide();
			navigation.editIcons.hideAll();

			input.on('click.prevent-nav-close', function(e) {
				e.stopPropagation();
			});

			return false;
		},
		save: function () {
			var context = navigation.contextMenu.getContext();
			var contextItem = navigation.getContextItem(context);
			var input = $('.cms-nav-link-edit:first', contextItem);
			var anchor = $('a.cms-nav-link:first', contextItem);

			var model = {
				name: input.val()
			};
			$.ajax({
				url: '/cms/site/' + $('#SiteId').val() + '/' + context.type + '/' + context.id + '/rename?em=1',
				type: 'PUT',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(model),
				success: function (data, textStatus, xhr) {
					//$(window).location = data;
					if (window.location.href != "")
						window.location = data;
					else
						window.location.href = data;
				},
				error: function() {
					$("#loading-indicator").hide();
				}
			});
			// Display loading indicator while we wait for page to reload to new url
			$("#loading-indicator").show();
		},
		cancel: function () {
			$('.en-save-cancel').hide();
			$('.en-main').show();

			var input = $('.cms-nav-link-edit').not(':hidden');
			var anchor = $('a.cms-nav-link').filter(':hidden');
			input.fadeOut(function () { anchor.fadeIn(); });

			navigation.editIcons.attachHoverVisibilityHandlers();
			var pageNameSpan = $('span', anchor);
			input.val(pageNameSpan.html());
        },
        cancelAll: function() {
            var input = $('.cms-nav-link-edit');
            var anchor = $('a.cms-nav-link');
            $.each(input, function(index, element) {
                $(element).hide();
            });
            $.each(anchor, function(index, element) {
                $(element).show();
            });
        }
	},
	hide: function() {
		var context = navigation.contextMenu.getContext();
		var contextItem = navigation.getContextItem(context);
		var anchor = $('.cms-nav-link:first', contextItem);
		var isSection = context.type == 'section';
		navigation.togglePageVisibility(context.id, isSection, true, function () {		   
			anchor.addClass('nav-hidden');
			navigation.contextMenu.hide();
			navigation.editIcons.hideAll();
			navigation.editIcons.attachHoverVisibilityHandlers();
			var context = navigation.contextMenu.getContext();
			var contextItem = navigation.getContextItem(context);

			if (isSection){
			    //hide all children	
			    $(contextItem).children().find('.cms-nav-link').addClass('nav-hidden');
			}
			else {
			    //hide parent if no more visible children
			    var subPages = $(contextItem).parent().children().length;
			    var hiddenSubPages = $(contextItem).parent().find(".nav-hidden").length;
			    if (subPages == hiddenSubPages) {
			        var parentSection = contextItem.parent('ul').siblings('.cms-nav-link');
			        $(parentSection).addClass('nav-hidden');
			    }
			}
		});
		return false;
	},
	unhide: function() {
		var context = navigation.contextMenu.getContext();
		var contextItem = navigation.getContextItem(context);
		var anchor = $('.cms-nav-link:first', contextItem);
		var isSection = context.type == 'section';
		navigation.togglePageVisibility(context.id, isSection, false, function() {
			anchor.removeClass('nav-hidden');
			navigation.contextMenu.hide();
			navigation.editIcons.hideAll();
			navigation.editIcons.attachHoverVisibilityHandlers();
			var context = navigation.contextMenu.getContext();
			var contextItem = navigation.getContextItem(context);
			if (isSection) {
			    //unhide all children	
			    $(contextItem).children().find('.cms-nav-link').first().find('.cms-nav-link').removeClass('nav-hidden');
			}
			else
			{
			    //unhide parent if no more visible children
			    var parentSection = contextItem.parent('ul').siblings('.cms-nav-link');
			    $(parentSection).removeClass('nav-hidden');
			}
		});
		return false;
	},
	setMembers: function () {
		var context = navigation.contextMenu.getContext();
		var contextItem = navigation.getContextItem(context);
		var anchor = $('a.cms-nav-link:first', contextItem);

		if (context.type == 'section')
			return false;

		navigation.toggleMembersOnlyStatus(context.id, true, function () {
			// append members lock icon
			anchor.removeClass('nav-non-members').addClass('nav-members-only');
			navigation.contextMenu.hide();
			navigation.editIcons.hideAll();
			navigation.editIcons.attachHoverVisibilityHandlers();
		});

		return false;
	},
	unsetMembers: function () {
		var context = navigation.contextMenu.getContext();
		var contextItem = navigation.getContextItem(context);
		var anchor = $('.cms-nav-link:first', contextItem);

		if (context.type == 'section')
			return false;

		navigation.toggleMembersOnlyStatus(context.id, false, function () {
			// append members lock icon
			anchor.removeClass('nav-members-only').addClass('nav-non-members');

			navigation.contextMenu.hide();
			navigation.editIcons.hideAll();
			navigation.editIcons.attachHoverVisibilityHandlers();
		});

		return false;
	},
	smoke: function () {
		navigation.editIcons.hideAll();
		navigation.contextMenu.hide();
		if ($('a.cms-nav-link:not(.dropdown-toggle)').length == 1) {
			bootbox.alert('You cannot delete the last page on your site.');
			return false;
		}

		bootbox.confirm("<h3>Are you sure?</h3><p>Are you sure you would like to delete the page?", function(result) {
			if (!result) {
				navigation.editIcons.attachHoverVisibilityHandlers();
				return true;
            }
            if (result) {
                var context = navigation.contextMenu.getContext();
                var isSection = context.type == 'section';
                var model = { isSection: isSection };
                if (isSection == true) {
                    bootbox.dialog({
                        message: '<div class="alert alert-warning">Please type "DELETE" below to confirm you wish to continue.</div><div class="form-group"><input class="form-control" id="sectionWarningDeleteText" type="text" autofocus/></div>',
                        title: "Confirm Delete",
                        buttons: {
                            cancel: {
                                label: "Cancel",
                                callback: function () {
                                    navigation.editIcons.attachHoverVisibilityHandlers();
                                    return true;
                                }
                            },
                            delete: {
                                label: "Delete",
                                className: "btn-danger",
                                callback: function () {
                                    var check = $("#sectionWarningDeleteText").val();
                                    if (check.toLowerCase() === "delete") {
                                        navigation.confirmPageDeletion(context.id, model);
                                    }
                                    else {
                                        bootbox.dialog({
                                            message: "Please type DELETE.",
                                            title: "Warning",
                                            buttons: {
                                                main: {
                                                    label: "Ok",
                                                    className: "btn-info"
                                                }
                                            }
                                        });
                                        return false;
                                    }
                                }
                            }
                        }
                    }).on("shown.bs.modal", function () {
                        $(this).find('[autofocus]').focus();
                    });

                }
                else {
                    navigation.confirmPageDeletion(context.id, model);
                }

            }
		});
		return false;
    },
   
	moveUp: function () {
        var context = navigation.contextMenu.getContext();        
		var contextItem = navigation.getContextItem(context);
        $.ajax({
            url: '/cms/page/' + context.id + '/decrementsortorder?isSection=' + (context.type == 'section'),
			type: 'POST',
			contentType: 'application/json; charset=utf-8',
			success: function (data, textStatus, xhr) {
				contextItem.prev().before(contextItem);
				navigation.contextMenu.hide();
				navigation.editIcons.attachHoverVisibilityHandlers();
			}
		});
		return false;
	},
	moveDown: function () {
		var context = navigation.contextMenu.getContext();
		var contextItem = navigation.getContextItem(context);
		$.ajax({
            url: '/cms/page/' + context.id + '/incrementsortorder?isSection=' + (context.type == 'section'),
			type: 'POST',
			contentType: 'application/json; charset=utf-8',
			success: function (data, textStatus, xhr) {
				contextItem.next().after(contextItem);
				navigation.contextMenu.hide();
				navigation.editIcons.attachHoverVisibilityHandlers();
			}
		});
		return false;
    },
    moveSubPage: function () {
        var context = navigation.contextMenu.getContext();
        var siteId = $("#SiteId").val();
        var isSection = context.type == 'section';
        var id = context.id;
        var currentPosition = "1";

        if (isSection) {
            currentPosition = $("#section" + id).index() + 1;
        }
        else {
            currentPosition = $("#page" + id).index() + 1;
        }

        $("#myModal").load('/cms/page/' + siteId + '/getmovepagemodal?selectedPageId=' + id + '&isSection=' + isSection + '&isRootPage=false', function () {
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false
            }).modal('show');

            $("#ddlPageListForMovePageModal").closest('.modal-body').click(); 
            $("#ddlPositions").val(currentPosition);
            $("#spnSelectedPosition").text(currentPosition);
            navigation.bindDropDownOfPageForMovePageModal($("#SelectedParentId").val());

            $("#ddlPageListForMovePageModal").on('change', function () {
                var pageId = $(this).val();
                var type = $(this).find('option[value="' + pageId + '"]').data('type');
                navigation.bindDropDownOfPositions(pageId, type == 'section', pageId != $("#SelectedParentId").val());
                return false;
            });

            $("#btnMoveSubPage").on('click', function () {
                var pageIdToMove = context.id;
                var pageIsSection = context.type == 'section';

                var parentId = $("#ddlPageListForMovePageModal").val();
                var parentType = $("#ddlPageListForMovePageModal").find('option[value="' + parentId + '"]').data('type');
                var parentIsSection = parentType == 'section';

                var poistion = $("#ddlPositions").val();

                if (pageIsSection && parentIsSection && $("#section" + parentId).hasClass('cms-nav-link-child')) {
                    bootbox.alert("Unable to move this page. Please remove the sub-page to proceed with changing this page position");
                    return false;
                }

                if (pageIsSection && !parentIsSection && $("#page" + parentId).hasClass('cms-nav-link-child')) {
                    bootbox.alert("Unable to move this page. Please remove the sub-page to proceed with changing this page position");
                    return false;
                }

                if (!pageIsSection && !parentIsSection && ($("#hdnSubscriptionPlan").val() == "Free" || $("#hdnSubscriptionPlan").val() == "Bronze")) {
                    bootbox.alert("Unable to move this page. Please <a target='_blank' href='https://www.sporty.co.nz/viewform/52969?returnUrl=www.sporty.co.nz'>upgrade</a> to a Silver or Gold site to create menu subpages");
                    return false;
                }

                var model = {
                    pageIdToMove: pageIdToMove,
                    pageIsSection: pageIsSection,
                    parentId: parentId,
                    parentIsSection: parentIsSection,
                    position: poistion
                };

                $.ajax({
                    url: '/cms/page/movesubpage',
                    type: 'POST',
                    data: JSON.stringify(model),
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        $('.header-link').attr('href', $('.header-link').attr('href') + '?em=1');
                        $('.header-link')[0].click();
                    }
                });
                return false;
            });

        });
        return false;
    },
    moveRootPage: function () {
        var context = navigation.contextMenu.getContext();
        var siteId = $("#SiteId").val();
        var isSection = context.type == 'section';
        var id = context.id;

        var currentPosition = 1;
        if (isSection) {
            currentPosition = $("#section" + id).index() + 1;
        }
        else {
            currentPosition = $("#page" + id).index() + 1;
        }

        $("#myModal").load('/cms/page/' + siteId + '/getmovepagemodal?selectedPageId=' + id + '&isSection=' + isSection + '&isRootPage=true', function () {
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false
            }).modal('show');

            $("#ddlPositions").val(currentPosition);
            $("#ddlPageListForMovePageModal").closest('.modal-body').click(); // just to hide the menu drop down
            navigation.bindDropDownOfPageForMovePageModal(0);

            $("#ddlPageListForMovePageModal").on('change', function () {
                var pageId = $(this).val();
                var type = $(this).find('option[value="' + pageId + '"]').data('type');
                navigation.bindDropDownOfPositions(pageId, type == 'section', pageId != $("#SelectedParentId").val());
                return false;
            });
            
            $("#btnMoveRootPage").on('click', function () {
                var rootId = context.id;
                var position = $("#ddlPositions").val();
                var rootIsSection = context.type == 'section';
               
                var parentId = $("#ddlPageListForMovePageModal").val();
                var parentType = "";
                var parentIsSection = false;
                var convertingToSubPage = false;

                if (parentId != undefined && parentId != 0) {
                    parentType = $("#ddlPageListForMovePageModal").find('option[value="' + parentId + '"]').data('type');
                    parentIsSection = parentType == 'section';
                    convertingToSubPage = true;

                    var showError = false;
                    if (rootIsSection && parentIsSection && $("#section" + parentId).hasClass('cms-nav-link-child')) {
                        showError = true;
                    }
                    if (rootIsSection && !parentIsSection && $("#page" + parentId).hasClass('cms-nav-link-child')) {
                        showError = true;
                    }
                    if (showError) {
                        bootbox.alert("Unable to move this page. Please remove the sub-page to proceed with changing this page position");
                        return false;
                    }

                    if (!parentIsSection && ($("#hdnSubscriptionPlan").val() == "Free" || $("#hdnSubscriptionPlan").val() == "Bronze")) {
                        bootbox.alert("Unable to move this page. Please <a target='_blank' href='https://www.sporty.co.nz/viewform/52969?returnUrl=www.sporty.co.nz'>upgrade</a> to a Silver or Gold site to create menu subpages");
                        return false;
                    }

                }

                var model = {};

                if (convertingToSubPage) {
                    if (parentId == undefined) {
                        parentId = 0;
                    }

                    var model = {
                        rootId: rootId,
                        position: position,
                        rootIsSection: rootIsSection,
                        parentId: parentId,
                        parentIsSection: parentIsSection
                    };

                    navigation.ConvertRootToSubPage(model);

                }
                else {
                    var model = {
                        siteId: $("#SiteId").val(),
                        rootId: rootId,
                        position: position,
                        rootIsSection: rootIsSection
                    };

                    navigation.UpdateSortOrderOfRootMenu(model);
                }

                return false;
            });

        });
        return false;
    },
    conceal: function () {
        var context = navigation.contextMenu.getContext();
		var contextItem = navigation.getContextItem(context);
		var anchor = $('.cms-nav-link:first', contextItem);

        if (context.type == 'section')
            return false;

        navigation.toggleConcealedStatus(context.id, true, function () {
            anchor.removeClass('nav-non-concealed').addClass('nav-concealed');

			navigation.contextMenu.hide();
			navigation.editIcons.hideAll();
			navigation.editIcons.attachHoverVisibilityHandlers();
		});
    },
    unconceal: function () {
        var context = navigation.contextMenu.getContext();
        var contextItem = navigation.getContextItem(context);
        var anchor = $('.cms-nav-link:first', contextItem);

        if (context.type == 'section')
            return false;

        navigation.toggleConcealedStatus(context.id, false, function () {
            anchor.removeClass('nav-concealed').addClass('nav-non-concealed');

            navigation.contextMenu.hide();
            navigation.editIcons.hideAll();
            navigation.editIcons.attachHoverVisibilityHandlers();
        });
    }
};

navigation.UpdateSortOrderOfRootMenu = function (model) {
    $.ajax({
        url: '/cms/page/moverootpage',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
                $('.header-link').attr('href', $('.header-link').attr('href') + '?em=1');
                $('.header-link')[0].click();
        }
    });
};

navigation.ConvertRootToSubPage = function (model) {
    $.ajax({
        url: '/cms/page/convertroottosubpage',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data.success) {
                $('.header-link').attr('href', $('.header-link').attr('href') + '?em=1');
                $('.header-link')[0].click();
            }
            else {
                bootbox.alert(data.message);
                return false;
            }
        }
    });
};

navigation.confirmPageDeletion = function (id, model) {
    $.ajax({
        url: '/cms/page/' + id,
        type: 'DELETE',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (successUrl) {
            // When deleting a page, add em=1 before redirect
            $('.header-link').attr('href', $('.header-link').attr('href') + '?em=1');
            $('.header-link')[0].click();
        }
    });
};

navigation.togglePageVisibility = function(id, isSection, isHidden, callback) {
	var model = { isSection: isSection, isHidden: isHidden };
	$.ajax({
		url: '/cms/page/' + id + '/togglehidden',
		type: 'POST',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model),
		success: function (data, textStatus, xhr) {
			callback();
		}
	});
};

navigation.toggleMembersOnlyStatus = function (id, isMembersOnly, callback) {
	var model = { isMembersOnly: isMembersOnly };
	$.ajax({
		url: '/cms/page/' + id + '/togglemembersonlystatus',
		type: 'POST',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model),
		success: function (data, textStatus, xhr) {
			callback();
		}
	});
};

navigation.toggleConcealedStatus = function (id, isConcealed, callback) {
    var model = { isConcealed: isConcealed };
    $.ajax({
        url: '/cms/page/' + id + '/toggleconcealedstatus',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (result) {
            if (result)
                callback();
        }
    });
};

navigation.getContextItem = function(context) {
	return $('#' + context.type + context.id);
};

navigation.editIcons = {
	hideAll: function() {
		$('.navItemEdit').hide();
	},
	startTouchMode: function() {
		navigation.editIcons.detachHoverVisibilityHandlers();
		$('.navItemEdit').show();
		navigation.setActionContext(navigation.actionContexts.edit);
		$('.en-main').hide();
		$('.en-save-cancel').show();
		$('#btnEnSave').parent().hide();
		return false;
	},
	cancelTouchMode: function() {
		navigation.editIcons.attachHoverVisibilityHandlers();
		navigation.editIcons.hideAll();
		$('.en-main').show();
		$('#btnEnSave').parent().show();
		$('.en-save-cancel').hide();
	},
	attachHoverVisibilityHandlers: function() {
		$(document).on('mouseenter.navitem', '.nav li', function() {
			$(this).find('.navItemEdit:first').show();
		});
		$(document).on('mouseleave.navitem', '.nav li', function() {
			$(this).find('.navItemEdit:first').hide();
		});
	},
	detachHoverVisibilityHandlers: function() {
		$(document).off('mouseleave.navitem');
		$(document).off('mouseenter.navitem');
	}
};

navigation.rootSort = {
	attachHandlers: function() {
		$(document).on('click', '.root-nav-left', function () {
			sportsground.cms.navigation.rootSort.moveLeft($(this).parent());
		});
		$(document).on('click', '.root-nav-right', function () {
			sportsground.cms.navigation.rootSort.moveRight($(this).parent());
		});
	},
	init: function () {
		$('.cms-nav-link-root.active').removeClass('active').addClass('active-disable');
		navigation.contextMenu.hide();
		navigation.editIcons.hideAll();
		navigation.setActionContext(navigation.actionContexts.rootSort);
		$('.en-main').hide();
		$('.en-save-cancel').show();
		navigation.editIcons.detachHoverVisibilityHandlers();
		$('.root-nav-sort').show();
		$('.root-nav-left:first').hide();
		$('.root-nav-right:last').hide();
		$('.root-nav-sort').each(function () {
			$(this).width($(this).parent().width() / 2);
		});
		return false;
	},
	save: function () {
		$('.cms-nav-link-root.active-disable').removeClass('active-disable').addClass('active');
		var pages = [];
		$('#uxCmsSiteNavigation').children().each(function () {
			pages.push({ Id: $(this).data('id'), Type: $(this).data('type') });
		});
		$.ajax({
			url: '/cms/site/' + $('#SiteId').val() + '/pages/updateorder',
			type: 'POST',
			contentType: 'application/json; charset=utf-8',
			data: JSON.stringify(pages),
			success: function() {
				$('.en-save-cancel').hide();
				$('.en-main').show();
				$('.root-nav-sort ').hide();
				navigation.editIcons.attachHoverVisibilityHandlers();
			}
		});
	},
	cancel: function () {
		// Bug fix, cancelling after reorder doesn't reset the order, need to reload page
		window.location.reload();

		//$('.en-save-cancel').hide();
		//$('.en-main').show();
		//$('.root-nav-sort ').hide();
		//navigation.editIcons.attachHoverVisibilityHandlers();
	},
	moveLeft: function (element) {
		element.prev().before(element);
		$('.root-nav-sort').show();
		$('.root-nav-left:first').hide();
		$('.root-nav-right:last').hide();
	},
	moveRight: function (element) {
		element.next().after(element);
		$('.root-nav-sort').show();
		$('.root-nav-left:first').hide();
		$('.root-nav-right:last').hide();
	}
};

navigation.showMenuStyleModal = function(){
	
};

navigation.bindDropDownOfPageForMovePageModal = function (pageId) {
    $.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/getsitepages?showHiddenPages=true',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var html = '';
            if (pageId == 0) {
                html = '<option style="font-weight:bold;" value="0" data-type="page">Main Menu</option>'
            }
            for (var mainPage = 0; mainPage < data.length; mainPage++) {
                var mainPageItem = data[mainPage];

                if (mainPageItem.Type == 'section') {

                    html += '<option style="font-weight:bold;" value="' + mainPageItem.Id + '" data-type="' + mainPageItem.Type + '">' + mainPageItem.Title + '</option>';
                    var subPages = mainPageItem.Children;

                    for (var subPage = 0; subPage < subPages.length; subPage++) {
                        var subPageItem = subPages[subPage];

                        if (subPageItem.Type == 'section') {
                            html += '<option value="' + subPageItem.Id + '" data-type="' + subPageItem.Type + '">&nbsp;&nbsp;&nbsp;&nbsp;' + subPageItem.Title + '</option>';
                        }
                        else {
                            html += '<option value="' + subPageItem.Id + '" data-type="' + subPageItem.Type + '">&nbsp;&nbsp;&nbsp;&nbsp;' + subPageItem.Title + '</option>';
                        }

                    }
                    html += '</optgroup>';
                }
                else {
                    html += '<option value="' + mainPageItem.Id + '" style="font-weight:bold;" data-type="' + mainPageItem.Type + '">' + mainPageItem.Title + '</option>';
                }
            }
            $('#ddlPageListForMovePageModal').append(html);
            $("#ddlPageListForMovePageModal").val(pageId);
            
        }
    });
};

navigation.bindDropDownOfPositions = function (pageId, isSection, isDifferentParent) {
    $.ajax({
        url: '/cms/page/' + $('#SiteId').val() + '/getSubPagesCount?pageId=' + pageId + '&isSection=' + isSection + '&isDifferentParent=' + isDifferentParent,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var html = '';
            for (var i = 1; i <= data; i++) {
                html += '<option value="' + i + '">'+ i +'</option>';
            }
            $("#ddlPositions").html(html);
            $("#ddlPositions").val(data);//selecting last position
        }
    });
};

function isUrl(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
};
var naModule = extend(sportsground, 'sportsground.cms.news.manageArticles');
var pageNumber = 0;
var take = 200;
naModule.init = function () {
    naModule.loadArticles(true);
    $("#YouTubeUrl").on('blur', sportsground.ui.attachHandlerPrependHttpOnWwwLinks);

    naModule.imageGalleryInitialised = false;
    naModule.images = [];

    $('#load-more-articles').click(function () { naModule.loadArticles(false); });

};

naModule.loadArticles = function (isInitialLoad) {
    var model = {
        take: take,
        pageNumber: pageNumber, // Paginated results not required here
        categories: ""
    };


	$.ajax({
		url: '/cms/site/' + $('#OrganisationId').val() + '/news/list',
		type: 'POST',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model),
		success: function (data, textStatus, xhr) {
            if (xhr.status === 200) {
                if (isInitialLoad) {
                    $("#lgNewsArticles").html('');
                }
				var template = Handlebars.compile($("#hbtDisplayArticle").html());
				if (data.length > 0) {
					for (var i = 0; i < data.length; i++) {
						var html = template(data[i]);
						$("#lgNewsArticles").append(html);
					}
				} else {
					var message = "<h4 id='btn-add-articles-none-exist' style='margin-left:47%;cursor:pointer;' class='btnAddArticle'><a style='text-decoration:none;'><i class='glyphicon glyphicon-plus'></i>&nbsp;&nbsp;Add news article</a></h4>";
					$("#lgNewsArticles").append(message);
                }

                if (data.length < take) {
                    $("#load-more-articles").hide();
                }
                naModule.attachItemClickHandlers();

				$('#lgNewsArticles').sortable({
					cancel: 'input',
					cursor: 'move',
					handle: '.article-drag',
					update: function () {
						//TODO: Create a sortOrder column for articles
						var sortData = {
							oid: $("#OrganisationId").val(),
							articleIds: $('#lgNewsArticles').sortable('toArray')
						};

						// Send the order of articles to the server
						$.ajax({
							url: '/cms/news/article/sort',
							type: 'POST',
							contentType: 'application/json; charset=utf-8',
							data: JSON.stringify(sortData),
							success: function(data, textStatus, xhr) {
								//
							}
						});
					}
				});
			}
		}
    });

    pageNumber++;

};

naModule.attachItemClickHandlers = function () {

    
    $('#lgNewsArticles').off('click', '.hide-article-button', naModule.hideClickHandler);
    $('#lgNewsArticles').unbind('click', '.hide-article-button', naModule.hideClickHandler);
    $('#lgNewsArticles').on('click', '.hide-article-button', naModule.hideClickHandler);

    $('#lgNewsArticles').off('click', '.delete-article-button', naModule.deleteClickHandler);
    $('#lgNewsArticles').unbind('click', '.delete-article-button', naModule.deleteClickHandler);
    $('#lgNewsArticles').on('click', '.delete-article-button', naModule.deleteClickHandler);

    $('#lgNewsArticles').off('click', '.edit-article-button', naModule.editClickHandler);
    $('#lgNewsArticles').unbind('click', '.edit-article-button', naModule.editClickHandler);
    $('#lgNewsArticles').on('click', '.edit-article-button', naModule.editClickHandler);

    $(".btnAddArticle").off('click', naModule.addClickHandler);
    $(".btnAddArticle").unbind('click', naModule.addClickHandler);
    $(".btnAddArticle").on('click', naModule.addClickHandler);

    $("#btnCloseModal").unbind('click');
    $("#btnCloseModal").on('click', function() {
		location.reload();
    });
   
    $("#newsTabContainer").off('click', '.tabCategories:not(.active)', naModule.initTabCategories);
    $("#newsTabContainer").unbind('click', '.tabCategories:not(.active)', naModule.initTabCategories);
    $("#newsTabContainer").on('click', '.tabCategories:not(.active)', naModule.initTabCategories);

    $("#newsTabContainer").off('click', '.tabArticles:not(.active)', naModule.initTabArticles);
    $("#newsTabContainer").unbind('click', '.tabArticles:not(.active)', naModule.initTabArticles);
    $("#newsTabContainer").on('click', '.tabArticles:not(.active)', naModule.initTabArticles);

    $("#btnAddOrUpdateArticle").off('click.done-editting-article', naModule.saveChangesClickHandler);
    $("#btnAddOrUpdateArticle").unbind('click.done-editting-article', naModule.saveChangesClickHandler);
    $("#btnAddOrUpdateArticle").on('click.done-editting-article', naModule.saveChangesClickHandler);

    $("#btnCancelAddOrUpdateArticle").off('click.cancel-editting-article', naModule.cancelChangesClickHandler);
    $("#btnCancelAddOrUpdateArticle").unbind('click.cancel-editting-article', naModule.cancelChangesClickHandler);
    $("#btnCancelAddOrUpdateArticle").on('click.cancel-editting-article', naModule.cancelChangesClickHandler);

};

naModule.updateImage = function () {
    var imgSrc = $("#imgArticleEditThumb img").attr("src");
    if ( imgSrc && imgSrc !== '' ) {
        $("#imgArticleEditThumb img").attr("src", imgSrc + "?qs=" + $.now());
    }
}

naModule.addClickHandler = function (event) {
	$('#newsTabContainer a:first').tab('show');
    $.ajax("/cms/news/categories?oid=" + $("#OrganisationId").val(), {
        cache: false
    }).done(function(categories) {
        // Clear old markup
		$("#edit-article-container").html("");
		// Hide management area and display edit interface
        var template = Handlebars.compile($("#hbtEditArticle").html());

        var currentDate = new Date();

		var data = {
			Id: "-1",
			Title: "",
			Categories: categories,
            VisibleInMobileApp: true,
            Content: "<br/><br/><i>Article added: " + moment(currentDate).format('dddd DD MMMM YYYY') + "</i>",
            HasScaledThumbnail: true
		};	
        var html = template(data);
        $("#edit-article-container").append(html);
        naModule.updateImage();
		// Slide out display interface and slide in edit area
		$("#article-display-container").effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$("#edit-article-container").effect('slide', { direction: 'right', mode: 'show' }, 500, function() {
                // Attach handlers for edit article interface
                naModule.initEditSettings();
                $('.tabImage a').click();


                setTimeout(function () { naModule.loadIframelyEmbedJs() }, 1000);
			});
		});
		$(".btnAddArticle").toggle(false, "fast");
        });
};

naModule.loadIframelyEmbedJs = function () {

    try {
        $('.cke_wysiwyg_frame').attr('id', 'cke_wysiwyg_frame');

        var ifs = document.getElementById("cke_wysiwyg_frame").contentDocument.createElement('script'); ifs.type = 'text/javascript'; ifs.async = true;
        ifs.src = ('https:' == document.location.protocol ? 'https:' : 'http:') + '//cdn.iframe.ly/embed.js';
        var s = document.getElementById("cke_wysiwyg_frame").contentDocument.getElementsByTagName('script')[0];
        $(".cke_wysiwyg_frame").contents()[0].body.append(ifs);
    }
    catch (e) {
        //iframely doesnt exist on page
    }


    setTimeout(function () {

        try {

            var frameWindow = document.getElementById("cke_wysiwyg_frame").contentWindow;
            var iframely = frameWindow.iframely = frameWindow.iframely || {};
            var widgets = iframely.widgets = iframely.widgets || {};

            widgets.load();

        }
        catch (e) {
            //iframely doesnt exist on page
        }

    }, 3000);
     
}


naModule.editClickHandler = function (event) {
  
	var articleDomObject = $(event.currentTarget).closest('.list-group-item');
	var articleId = articleDomObject.data("articleId");
	
	// Clear old markup
	$("#edit-article-container").html("");

	// Load information into edit 
	$.ajax({
		url: '/cms/news/article/' + articleId + '?includeCategories=True',
		type: 'GET',
        cache : false,
		contentType: 'application/json; charset=utf-8',
		success: function (data, textStatus, xhr) {
			if (xhr.status === 200) {
                data.HasContent = data.HasThumbnailImage || data.HasVideoUrl;
				// Hide management area and display edit interface
				var template = Handlebars.compile($("#hbtEditArticle").html());
                var html = template(data);
                $("#edit-article-container").append(html);
                naModule.updateImage();
				// Slide out display interface and slide in edit area
				$("#article-display-container").effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
					$("#edit-article-container").effect('slide', { direction: 'right', mode: 'show' }, 500, function() {
						// Attach handlers for edit article interface
						// NOTE: CKEditor must be initialised after slide animation
                        naModule.initEditSettings();
                        if (data.HasVideoUrl) {
                            $('.tabVideo a').click();
                        }
                        else {
                            $('.tabImage a').click();
                        }
                       
                        setTimeout(function () { naModule.loadIframelyEmbedJs() }, 1000);
					});
				});
				$(".btnAddArticle").toggle(false, "fast");
				// If optional htumbnail present then display "delete" button
				if (data.HasThumbnailUrl != undefined)
					$("#btnRemoveArticleThumb").show("fast");
			}
		}
	});
};

naModule.initEditSettings = function () {
	// Attach categories to multi-select box
	$('#chkListCategories').multiselect({
		buttonTitle: function() {
			return "News Article Categories";
		},
		numberDisplayed: 1,
		templates: {
			button: '<button type="button" class="btn-primary multiselect dropdown-toggle" data-toggle="dropdown"></button>',
			li: '<li><a href="javascript:void(0);"><label class="old"></label></a></li>'
		}
	});
    var cachebuster = Math.round(new Date().getTime() / 1000);
	// Init CKEditor for Content
	 var editor = CKEDITOR.replace('newsCkEditor', {
         customConfig: '/Content/ckeditor/noncms_config.js?cb=' + cachebuster
	});

	

	// Attach unobtrusive validation
     $.validator.unobtrusive.parseDynamicContent($("#editArticleForm"));
     $.validator.unobtrusive.parse($('#youtubeForm'));
	overrideUnobtrusiveDefaults();
	// Replace "Save Button" Handler so it returns to article-list area
	naModule.toggleFooterButtons(true);
    
    $("#btnUploadArticleThumb").on('click', naModule.uploadThumbnailClickHandler);
    $("#btnRemoveArticleThumb").on('click', naModule.deleteThumbnailClickHandler);

    $('.btn-save-youtube').on('click', naModule.saveYoutubeThumbnailClickHandler);
    $('.btn-dismiss-youtube').on('click', function() {
        $('#youTubeModal').modal('hide');
    });

    $('input[name=rbthumnailType]').on('click', function () {
        if ($("#rbSquareThumbail").is(':checked')) {
            $("#imgArticleEditThumb").find('img').addClass('articleSquareImgPreview');
        }
        else {
            $("#imgArticleEditThumb").find('img').removeClass('articleSquareImgPreview');
        }
    })
};

naModule.deleteClickHandler = function (event) {
	var articleDomObject = $(event.currentTarget).closest('.list-group-item');
	var articleId = articleDomObject.data("articleId");

	bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you want to delete the article?</p>', function(result) {
		if (!result) return true;
		
		$.ajax({
			url: '/cms/news/article/delete/' + articleId,
			type: 'DELETE',
			contentType: 'application/json; charset=utf-8',
			success: function (data, textStatus, xhr) {
				// Remove the article from the dom
				articleDomObject.hide("fast");
				articleDomObject.remove();
			}
		});
	});
};

naModule.uploadThumbnailClickHandler = function() {
    if ($('#tabImage').hasClass('active')) {
        // Destroy CKEditor instance
        CKEDITOR.instances["newsCkEditor"].destroy();

        $('#btnCancelAddOrUpdateArticle').hide();
        $('#btnAddOrUpdateArticle').hide();
        $('#btnDoneSelectingImage').show();
        $('#btnCancelSelectingImage').show();
        
        $('#btnUploadImages').show();
        $('.tabCategories').addClass('disabled');
        $('.tabCategories').append('<a href="#" class="disabledCategory">Categories</a>');
        $('.tabCategories a').hide();
        $('#edit-article-container').effect('slide', { direction: 'left', mode: 'hide' }, 500, function() {
            $('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
        });

        $('#btnDoneSelectingImage, #btnCancelSelectingImage').off('click');
        $('#btnDoneSelectingImage').on('click', naModule.doneSelectingImageHandler);
        $('#btnCancelSelectingImage').on('click', naModule.hideImageModal);
        
        var imageGallerySettings = {
            allowEditing: false,
            container: $('#tabImages_gallerySelect'),
            loadThumbsCallback: function() {
                $('.cbImageSelect').parent().hide();
                $('.cbImageSelect').off('change.imageslideshowthumbhandler');
                $('.cbImageSelect').on('change.imageslideshowthumbhandler', function() {
                    var id = $(this).closest('.gallery-thumb-image').data('id');
                    naModule.images = [];
                    $('.gallery-thumb-image').removeClass('selected');
                    if (this.checked) {
                        naModule.images.push({ id: id, caption: '', linkType: 'none' });
                        $(this).closest('.gallery-thumb-image').addClass('selected');
                    }
                });
                $('.gallery-thumb-image').off('click.imageslideshowthumbimghandler');
                $('.gallery-thumb-image').on('click.imageslideshowthumbimghandler', function() {
                    $(this).closest('.gallery-thumb-image').find('.cbImageSelect').trigger('click');
                });
            }
        };
        sportsground.cms.imageGallery.init(imageGallerySettings);
        if (!naModule.imageGalleryInitialised) {
            sportsground.cms.imageGallery.fileupload.init(naModule.fileUploadCompletedCallback);
            naModule.imageGalleryInitialised = true;
        }
    }
    if ($('#tabVideo').hasClass('active')) {
        $('#youTubeModal').modal('show');
        $('#YouTubeUrl').val($("#videoArticleEditThumb").find('iframe').attr('src'));
    }
};

naModule.hideImageModal = function () {
    // on clicking save or cancel, hide the done and upload buttons
    $('#btnDoneSelectingImage').hide();
    $('#btnCancelSelectingImage').hide();
    $('#btnUploadImages').hide();

    $('#tabImages_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#edit-article-container').effect('slide', { direction: 'right', mode: 'show' }, 500, function () {
            // NOTE: CKEditor must be initialised after slide animation
            CKEDITOR.replace('newsCkEditor', { customConfig: '/Content/ckeditor/noncms_config.js' });
            setTimeout(function () { naModule.loadIframelyEmbedJs() }, 1000);

            // save/cancel buttons should show after CKEditor has been initialised (to prevent trigger of getData of CKEditor before it is loaded)
            $('#btnCancelAddOrUpdateArticle').show();
            $('#btnAddOrUpdateArticle').show();
            $('.tabCategories').removeClass('disabled');
            $('.tabCategories a').show();
            $('.disabledCategory').remove();
        });
    });
};

naModule.doneSelectingImageHandler = function() {

    naModule.hideImageModal();

    // update the hidden fields and src when a new image has been selected
    if ($('.gallery-thumb-image.selected').length > 0) {
        var srcWebOpt = $('.gallery-thumb-image.selected').find(".thumbnail img").data("src-web-opt");
        $("#imgArticleEditThumb img").attr("src", srcWebOpt);
        naModule.updateImage();
        $("#imgArticleEditThumb img").show("fast");
        $("#hdnHasThumbnailImage").val(true);
        $("#hdnUpdatedImage").val(true);
        if (srcWebOpt.lastIndexOf("?t=") < 0) {
            $("#hdnThumbFileExtension").val(srcWebOpt.substring(srcWebOpt.lastIndexOf(".") + 1, srcWebOpt.length));
        }
        else {
            $("#hdnThumbFileExtension").val(srcWebOpt.substring(srcWebOpt.lastIndexOf(".") + 1, srcWebOpt.lastIndexOf("?t=")));
        }
        $("#btnRemoveArticleThumb").show("fast");

        // if there is no caption saved in the article yet, allow getting caption from the image in gallery
        if ($('#hdnCaptionInArticle').val() === '') {
            var caption = $('.gallery-thumb-image.selected').find(".thumbnail img").data("caption");
            if (caption != '') {
                $('#edit-photo-caption').val(caption);
                $('#articleHasPhotoCaption').prop('checked', true);
            }
        }
    }
};

naModule.deleteThumbnailClickHandler = function() {
    if ($('#tabImage').hasClass('active')) {
        var imageData = {
            ArticleId: $("#hdnArticleId").val(),
            OrganisationId: $("#OrganisationId").val(),
            FileExtension: $("#hdnThumbFileExtension").val()
        }
        $.ajax({
            url: '/cms/news/article/deletearticleimage',
            type: 'DELETE',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(imageData),
            success: function(data, textStatus, xhr) {
                // Remove image from dom
                $("#imgArticleEditThumb img").hide("fast");
                $("#btnRemoveArticleThumb").hide("fast");
                // Image removed so reset image-changed flags
                $("#hdnHasThumbnailImage").val(false);
                $("#hdnUpdatedImage").val(false);
                $("#hdnThumbFileExtension").val("");
            }
        });
    }
    if ($('#tabVideo').hasClass('active')) {
        $('#videoArticleEditThumb iframe').attr('src', '');
        $('#hdnHasVideoUrl').val(false);
    }
};

naModule.saveChangesClickHandler = function () {
	if (CKEDITOR.instances['newsCkEditor'].getData() == "") {
		$("#newsCkEditor").closest(".form-group").addClass("has-error");
		$("#cke_newsCkEditor").css("border-color", "red");

		return false;
    } 

    var html = CKEDITOR.instances['newsCkEditor'].getData();
    var editorElem = $('<p>').append(html);
    if ( editorElem.length === 1 && editorElem.find('a').length > 0 ) { //set the anchors to inherit child element color
        html = sportsground.cms.common.setAnchorToHaveChildColor(editorElem, html);
    }
		
	// Validate form
	if (!$("#editArticleForm").valid())
        return false;

    // switch from image or video
    if ($('#tabImage').hasClass('active')) {
        $("#hdnHasVideoUrl").val(false);
    }
    if ($('#tabVideo').hasClass('active')) {
        $("#hdnHasThumbnailImage").val(false);
    }

    $("#btnAddOrUpdateArticle i").addClass('fa-spinner');
    $("#btnAddOrUpdateArticle").attr("disabled", true);

	// Save article
	var model = {
		Id: $("#hdnArticleId").val(),
		Title: $("#edit-article-title").val(),
		OrganisationId: $("#OrganisationId").val(),
		SelectedCategories: $("#chkListCategories").val(),
        Content: html,
		HasThumbnailImage: $("#hdnHasThumbnailImage").val(),
        HasUpdatedImage: $("#hdnUpdatedImage").val(),
        SrcWebOpt: $("#imgArticleEditThumb img").attr("src"),
		FileExtension: $("#hdnThumbFileExtension").val(),
        VisibleInMobileApp: $("#articleVisibleInMobileApp")[0].checked,
        VideoUrl: $("#videoArticleEditThumb iframe").attr('src'),
        HasVideoUrl: $("#hdnHasVideoUrl").val(),
        HasPhotoCaption: $("#articleHasPhotoCaption")[0].checked,
        PhotoCaption: $("#edit-photo-caption").val(),
        HasScaledThumbnail: $("#rbScaledThumbail").is(':checked')
	};
	$.ajax({
		url: '/cms/news/article/update',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model),
		success: function (data, textStatus, xhr) {
			if (data.HasThumbnailImage == true && data.ThumbnailPath != undefined && data.ThumbnailPath != '')
				data.ThumbnailPath = data.ThumbnailPath + "?qs=" + $.now();
			// Remove existing display and re-Compile article display template.	
			data.Content = $.trim(data.Content);

			var template = Handlebars.compile($("#hbtDisplayArticle").html());
			var articleHtml = template(data);
			if ($("#article-" + data.Id).length > 0) {
				$("#article-" + data.Id).replaceWith(articleHtml);
			} else {
				$("#lgNewsArticles").prepend(articleHtml);
				// If "Add Article" prompt in modal center exists then hide it;
				$("#btn-add-articles-none-exist").remove();
			}
			// Slide out edit area and and slide in display
			$("#edit-article-container").effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
				$("#article-display-container").effect('slide', { direction: 'right', mode: 'show' }, 500);
            });

            $("#btnAddOrUpdateArticle i").removeClass('fa-spinner');
            $("#btnAddOrUpdateArticle").attr("disabled", false);

			// Replace "Save Button" Handler so it returns to article-list area
			naModule.toggleFooterButtons(false);
			$(".btnAddArticle").toggle(true, "fast");
			// Destroy CKEditor instance
			if(CKEDITOR.instances["newsCkEditor"].length > 0)
				CKEDITOR.instances["newsCkEditor"].destroy();
		}
	});
};

naModule.cancelChangesClickHandler = function () {
		// Slide out edit area and and slide in display
		$("#edit-article-container").effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$("#article-display-container").effect('slide', { direction: 'right', mode: 'show' }, 500);
		});
		// Replace "Save Button" Handler so it returns to article-list area
		naModule.toggleFooterButtons(false);
		$(".btnAddArticle").toggle(true, "fast");
		// Destroy CKEditor instance
		if (CKEDITOR.instances["newsCkEditor"].length > 0)
			CKEDITOR.instances["newsCkEditor"].destroy();
};

naModule.hideClickHandler = function(event) {
	var articleDomObject = $(event.currentTarget).closest('.list-group-item');
	var articleId = articleDomObject.data("articleId");

	// Check if article is already hidden
	var hideArticle = "true";
	if ($("#hdnIsHidden-" + articleId).val() == "true") {
		hideArticle = "false";
	}
	
	$.ajax({
		url: '/cms/news/article/hide/' + articleId + '?hideArticle=' + hideArticle,
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		success: function (data, textStatus, xhr) {
			var hideButton = articleDomObject.find(".hide-article-button");

			if (hideArticle == "true") {
				// Set background color to indicate article is hidden
                articleDomObject.addClass("hidden-true");

                //hideButton.find(".icon-hide").removeClass("icon-hide").addClass("icon-show");
			} else {
                articleDomObject.removeClass("hidden-true");

                //hideButton.find(".icon-show").removeClass("icon-show").addClass("icon-hide");
			}
			$("#hdnIsHidden-" + articleId).val(hideArticle);
		}
	});
};

naModule.fileUploadCompletedCallback = function () {
    $('#cntGallery .cnt-images').find('.gallery-thumb').removeClass('selected');
    $('#cntGallery .cnt-images').find('.gallery-thumb:first').addClass('selected');
};

naModule.toggleFooterButtons = function (isEditArticleState) {
    $("#btnCloseModal").toggle(!isEditArticleState, "fast");
    //$(".btnAddArticle").toggle(!isEditArticleState, "fast");
	$("#btnAddOrUpdateArticle").toggle(isEditArticleState, "fast");
	$("#btnCancelAddOrUpdateArticle").toggle(isEditArticleState, "fast");
};

naModule.initTabCategories = function() {
    $(".btnAddArticle").toggle(false, "fast");
    sportsground.cms.news.manageCategories.init();
};

naModule.initTabArticles = function() {
    // If we're still in edit mode then set the footer buttons to "save/cancel" not "done"
    if ($("#edit-article-container").css('display') != 'none') {
        naModule.toggleFooterButtons(true);
        $(".btnAddArticle").toggle(false, "fast");
    } else {
        $(".btnAddArticle").toggle(true, "fast");
    }
};

naModule.saveYoutubeThumbnailClickHandler = function() {
    var youtubeUrl = $('#YouTubeUrl').val();

    var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
    if (!youtubeUrl.match(p)) {
        return;
    }

    // Set the src to the new URL
    var newUrl = "https://www.youtube.com/embed/" + youtubeUrl.match(p)[1] + "?h1=en&autoplay=0&showsearch=0&showinfo=0&rel=0";
    $('#videoArticleEditThumb iframe').attr('src', newUrl);
    $('#hdnHasVideoUrl').val(true);
    $('#youTubeModal').modal('hide');
    $("#btnRemoveArticleThumb").show("fast");
};;
var ncModule = extend(sportsground, 'sportsground.cms.news.manageCategories');

ncModule.initialized = false;
ncModule.init = function () {
	sportsground.cms.news.manageArticles.toggleFooterButtons(false);

	if (ncModule.initialized) {
		ncModule.detachItemClickHandlers();
		ncModule.loadCategories();
		return;
	}

	ncModule.loadCategories();

	$("#txtCategory").keypress(function (e) {
		if (e.which == 13) {
			e.preventDefault();
			$("#btnAddCategory").click();
		}
	});

	$('#btnAddCategory').on('click', function () {
		if (!$('#addCategoryForm').valid())
			return;
		var nameTextbox = $('#txtCategory');
		$.ajax({
			url: '/cms/news/category',
			type: 'POST',
			data: '{organisationId:' + $('#OrganisationId').val() + ',name:"' + nameTextbox.val() + '"}',
			contentType: 'application/json; charset=utf-8',
			success: function (data) {
				var template = Handlebars.compile($('#hbtCategory').html());
				data.ArticleCount = 0;
				var html = template(data);
				$('#lgNewsCategories').append(html);
				nameTextbox.val("");

				// Append Category to dropdownlist in the add/edit article menu
				$("#chkListCategories").append("<option value='" + data.Id + "'>" + data.Name + "</option>");
				$("#chkListCategories").multiselect('rebuild');
			}
		});
	});

	// Parse unobstrusive validation
	$.validator.unobtrusive.parseDynamicContent('form');
	overrideUnobtrusiveDefaults();

	ncModule.initialized = true;
};

ncModule.loadCategories = function() {
    $.ajax({
        url: '/cms/news/categorieswithcount?oid=' + $('#OrganisationId').val(),
        type: 'GET',
        cache: false,
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			$('#lgNewsCategories').html("");
			var template = Handlebars.compile($('#hbtCategory').html());
			for (var i = 0; i < data.length; i++) {				
				var html = template(data[i]);
				$('#lgNewsCategories').append(html);
            }
           
            $('#lgNewsCategories').sortable({
                cancel: 'input',
                cursor: 'move',
                handle: '.drag',
                update: function () {
                    var categoryIds = $('#lgNewsCategories').sortable('toArray');
                    var sortedcategoryIds = [];
                    for (var si = 0; si < categoryIds.length; si++) {
                        for (var ui = 0; ui < data.length; ui++) {
                            if (categoryIds[si].replace("ni_","") == data[ui].Id) {
                                sortedcategoryIds[si] = data[ui].Id;
                                break;
                            }
                        }
                    }
                    $.ajax({
                        url: '/cms/news/categories/reorder',
                        type: 'POST',
                        cache: false,
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify(sortedcategoryIds)
                    });
                }
            });

			ncModule.attachItemClickHandlers();
		}
	});
};

ncModule.attachItemClickHandlers = function () {
	$('#lgNewsCategories')
		.on('click', '.delete-category-button', ncModule.deleteClickHandler)
		.on('click', '.rename-category-button', ncModule.renameClickHandler)
		.on('click', '.save-name-button', ncModule.saveClickHandler)
		.on('click', '.cancel-name-button', ncModule.cancelClickHandler);
};

ncModule.detachItemClickHandlers = function () {
	$('#lgNewsCategories')
		.off('click', '.delete-category-button')
		.off('click', '.rename-category-button')
		.off('click', '.save-name-button')
		.off('click', '.cancel-name-button');
};

ncModule.setDisplayMode = function (categoryDomObject) {
	$('.category-edit', categoryDomObject).hide();
	$('.category-display', categoryDomObject).show();

	// enable add cat button and show/hide edit buttons
	$('#btnAddCategory').removeAttr('disabled');
	$('.category-edit-button').removeAttr('disabled');
	$('#btnCloseModal').removeAttr('disabled');
};

ncModule.deleteCategory = function (id) {
	$.ajax({
		url: '/cms/news/category',
		type: 'DELETE',
		data: '{categoryId:' + id + '}',
		contentType: 'application/json; charset=utf-8',
		success: function (data, textStatus, xhr) {
			if (data.success == true) {
				$('#ni_' + data.id).remove();
			}

			$("#chkCategory_" + data.id).remove();
			$("#chkListCategories").multiselect('rebuild');
		}
	});
};


/* *********************************
 * 
 *    Click Handlers
 * 
 * *********************************/
ncModule.deleteClickHandler = function(event) {
	var categoryDomObject = $(event.currentTarget).closest('.list-group-item');
	var categoryId = categoryDomObject.data('id');
	var numArticles = $('.badge', categoryDomObject).html();
	if (numArticles != '0') {
		bootbox.confirm("<h3>Are you sure?</h3><p>This News Category has " + numArticles + " News Articles using it.</p>", function (result) {
			if (result) {
				ncModule.deleteCategory(categoryId);
			}
		});
	}
	else {
		ncModule.deleteCategory(categoryId);
	}
	return false;
};

ncModule.renameClickHandler = function(event) {
	// Hide the label and show the input area
	var categoryDomObject = $(event.currentTarget).closest('.list-group-item');
	$('.category-display', categoryDomObject).hide();
	$('.category-edit', categoryDomObject).show();

	// disable add cat button and show/hide edit buttons
	$('#btnAddCategory').attr('disabled', 'disabled');
	$('.category-edit-button').attr('disabled', 'disabled');
	$('#btnCloseModal').attr('disabled', 'disabled');
	return false;
};

ncModule.saveClickHandler = function (event) {
	var categoryDomObject = $(event.currentTarget).closest('.list-group-item');
	var input = $('.category-edit-input', categoryDomObject);
	if (input.val().length == 0) {
		input.parent().addClass('has-error');
		return false;
	}
	input.removeClass('has-error');

	// Save Changes
	var data = {
		categoryId: categoryDomObject.data('id'),
		name: input.val()
	}
	$.ajax({
		url: '/cms/news/category/rename',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(data),
		success: function () {
			$('.category-name', categoryDomObject).html(data.name);
			ncModule.setDisplayMode(categoryDomObject);

			$("#chkCategory_" + data.categoryId).html(data.name);
			$("#chkListCategories").multiselect('rebuild');
		}
	});

	return false;
};

ncModule.cancelClickHandler = function(event) {
	var categoryDomObject = $(event.currentTarget).closest('.list-group-item');
	ncModule.setDisplayMode(categoryDomObject);
};
;
var responseModule = extend( sportsground, 'sportsground.cms.response' );

responseModule.initResponsePage = function () {
    $(".submit-button").click(function (e) {
        if (!formRendering.customValidationIsValid()) {
            if ($(".has-error").length) {
                sportsground.forms.rendering.scrollTo($(".has-error").first());
            }
            e.preventDefault();
            return false;
        }
    });
    $('#lnkSubmit').click(function (e) {
        if (!formRendering.customValidationIsValid()) {
            if ($(".has-error").length) {
                sportsground.forms.rendering.scrollTo($(".has-error").first());
            }
            e.preventDefault();
            return false;
        }
        $('[role="form"]').submit();
    });

    var organisationFormId = $('#OrganisationFormId').val();
    var formContainer = $('#dvFormContainer');
    var hashedPreviousRegistrationId = $('#HashedOrganisationFormResponseId').val();
    sportsground.forms.rendering.loadForm(organisationFormId, formContainer, function () {
        setTimeout(function () { sportsground.forms.admin.populateForm(formContainer, hashedPreviousRegistrationId) }, 400); 
    });

    $('#btnResendConfirmationEmail').on('click', function () {
        var model = { responseId: $('#OrganisationFormResponseId').val() }
        var button = $(this);
        button.button('loading');
        $.ajax({
            url: '/formservice/resendconfirmation',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data, textStatus, xhr) {
                if (data.success) {
                    button.replaceWith('<div class="alert alert-success"><h4>Confirmation Email Resent</h4></div>');
                }
            }
        });

        return false;
    });

    // bind handler for rotating image left
    $( "#btnImageSettingRotateLeft" ).on( 'click.rotate', function () {
        responseModule.rotate( this, -90 );
    } );

    // bind handler for rotating image right
    $( "#btnImageSettingRotateRight" ).on( 'click.rotate', function () {
        responseModule.rotate( this, 90 );
    } );

    responseModule.setPromptToSave();
};

responseModule.initApprovalsOnResponsePage = function ( playerName, nrdTransferToOrgName, nrdTransferToPUName, organisationFormResponseId ) {
    $( ".approveNrdTransfer" ).click( function () {
        sportsground.cms.response.confirm( "Click OK to approve the transfer of " + playerName + ". An email will be sent to "
            + nrdTransferToOrgName + " and " + nrdTransferToPUName + " to notify them that the transfer has been approved.",
            "OK", "Cancel", function ( result ) {
                if ( !result )
                    return;

                sportsground.ui.loadingFullScreen();

                $.ajax( "/dashboard/forms/ApproveNrdRegistrationTransfer/" + organisationFormResponseId )
                    .done( function ( r ) {

                        if ( r.success ) {
                            var location = window.location.href.split("?")[0];
                            window.location = location;
                        }
                        else
                            bootbox.alert( r.message );
                    } );
            } );
    } );

    $( ".declineNrdTransfer" ).click( function () {
        sportsground.cms.response.prompt( "To decline this transfer enter your reason below and click OK. An email will be sent to "
            + nrdTransferToOrgName + " and " + nrdTransferToPUName + " to notify them the transfer has been declined."
            + " If you require further information on the New Zealand Rugby transfer process, please contact your Provincial Union.",
            "OK", "Cancel", function ( result ) {

                if ( !result )
                    return;

                sportsground.ui.loadingFullScreen();

                $.ajax( "/dashboard/forms/DeclineNrdRegistrationTransfer/" + organisationFormResponseId + "?reason=" + result )
                    .done( function ( r ) {

                        if ( r.success ) {
                            var location = window.location.href.split("?")[0];
                            window.location = location;
                        }
                        else
                            bootbox.alert( r.message );
                    } );
            } );
    });

    $(".approveSportyTransfer").click(function () {
        sportsground.cms.response.confirm("Click OK to approve the transfer of " + playerName + ". An email will be sent to "
            + nrdTransferToOrgName + " to notify them that the transfer has been approved.",
            "OK", "Cancel", function (result) {
                if (!result)
                    return;

                sportsground.ui.loadingFullScreen();

                $.ajax("/dashboard/forms/ApproveSportyTransfer/?organisationFormResponseId=" + organisationFormResponseId)
                    .done(function (r) {

                        if (r.success) {
                            var location = window.location.href.split("?")[0];
                            window.location = location;
                        }
                        else
                            bootbox.alert(r.message);
                    });
            });
    });

    $(".declineSportyTransfer").click(function () {
        sportsground.cms.response.prompt("To decline this transfer enter your reason below and click OK. An email will be sent to "
            + nrdTransferToPUName + " to notify them the transfer has been declined.",
            "OK", "Cancel", function (result) {

                if (!result)
                    return;

                sportsground.ui.loadingFullScreen();

                $.ajax("/dashboard/forms/DeclineSportyTransfer/?organisationFormResponseId=" + organisationFormResponseId + "&reason=" + result)
                    .done(function (r) {

                        if (r.success) {
                            var location = window.location.href.split("?")[0];
                            window.location = location;
                        }
                        else
                            bootbox.alert(r.message);
                    });
            });
    });
};

responseModule.displayError = function ( error ) {
    if (error != null && error) {
        bootbox.alert(error);
    }
};

responseModule.confirm = function ( message, confirmText, cancelText, callBack ) {
    bootbox.confirm( {
        message: message,
        buttons: {
            confirm: {
                label: confirmText,
                className: 'btn-success'
            },
            cancel: {
                label: cancelText,
                className: 'btn-danger'
            }
        },
        callback: callBack
    } );
};

responseModule.prompt = function ( message, confirmText, cancelText, callBack ) {
    bootbox.prompt( {
        title: message,
        buttons: {
            confirm: {
                label: confirmText,
                className: 'btn-success'
            },
            cancel: {
                label: cancelText,
                className: 'btn-danger'
            }
        },
        callback: callBack
    } );
};


responseModule.rotate = function ( element, rotate ) {
    var $this = $(element);

    if ($this.parent().data('rotating')) {
        return;
    }

    $("#btnImageSettingRotateLeft").attr("disabled", true);
    $("#btnImageSettingRotateRight").attr("disabled", true);

    var $profileImage = $("#profile-image");
    var profileImageId = $profileImage.data('id');
    var src = $profileImage.attr('src');

    var model = {
        assetId: profileImageId,
        rotate: rotate,
        imageSource: src,
        responseId: $("#OrganisationFormResponseId").val()
    };

    $this.parent().data('rotating', true).attr('disabled', true);
    $this.removeClass('btn-primary');
    $profileImage.parent().prepend('<div id="spinner" style="position:absolute;top:50%;left:50%;margin-top:-50px;margin-left:-25px;color:#319A31;"><i class="fa fa-refresh fa-spin fa-4x"></i></div>');

    $.ajax({
        url: '/asset/rotate',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, jqXHR) {
            if (data) {

                $("#AddingRotatedImage").val(true);
                var date = new Date();

                var thumbnail = $("#profile-image");
                if (src.indexOf("data:") < 0) {
                    
                    thumbnail.attr('src', thumbnail.attr('src') + '?v=' + date.getTime());
                }
                else {
                    thumbnail.attr('src', data + '?v=' + date.getTime());
                }

                $("#btnImageSettingRotateLeft").attr("disabled", false);
                $("#btnImageSettingRotateRight").attr("disabled", false);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {

        },
        complete: function (data, textStatus, jqXHR) {
            $this.parent().data('rotating', false).attr('disabled', false);
            $this.addClass('btn-primary');
            $('#spinner').remove();
        }
    });
};

responseModule.setSerializedFormData = function () {
    if ( !$( '[role="form"]' ).data( 'serialize' ) ) {
        $( '[role="form"]' ).data( 'serialize', $( '[role="form"]' ).serialize() );
    }
};

responseModule.setPromptToSave = function () {

    var orgFormId = $('#OrganisationFormId').val();

    $.ajax({
        url: '/formservice/isRugbyRegistrationsDisabled?orgFormId=' + orgFormId,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (!data.isDisabled) {
                $('#lnkBack').on('click', function (e) {
                    responseModule.promptToSave(e);
                });
            }
        }
    });
    
    /*
     * this swallows backspace keys on any non-input element.
     * stops backspace -> back
     */
    var rx = /INPUT|SELECT|TEXTAREA/i;
    $( document ).bind( "keydown keypress", function ( e ) {
        if ( e.which == 8 ) { // 8 == backspace
            if ( !rx.test( e.target.tagName ) || e.target.disabled || e.target.readOnly ) {
                responseModule.promptToSave( e );
            }
        }
    } );
};

responseModule.promptToSave = function ( e ) {
    var message = 'This text is not saved. Press OK to save changes or press CANCEL to continue editing text.'
    // continue back when there is no initial form data
    if ( $( '[role="form"]' ).data( 'serialize' ) ) {
        // if current form data and initial form data are different
        if ($('[role="form"]').serialize() != $('[role="form"]').data('serialize')) {
            bootbox.confirm( '<div class="align-text-center"><p>' + message + '</p></div>', function ( value ) {
                if ( value ) {
                    $( '[role="form"]' ).submit();
                }
            } );
            e.preventDefault();
        }
    }
};;
var sortableModule = extend(sportsground, 'sportsground.cms.sortable');

sortableModule.superSplittersInit = function () {
	// Super Splitters, control on axis, don't allow nesting
	$('#superSplitterContainer').sortable({
		cancel: 'input',
		handle: '.supersplitter-drag',
        axis: 'y',
        placeholder: 'sortable-placeholder',
        containment: 'parent',
        tolerance: 'pointer',
        cursor: 'move',
		update: function() {
			$.ajax({
				url: '/cms/page/' + $('#PageId').val(),
				type: 'PUT',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify($(this).sortable('toArray', { attribute: "data-id" })),
				fail: function() {
					alert('Sorry an error has occurred. Please contact sportsground if this happens again.');
				}
			});
		}
	});	
};

sortableModule.widgetPlaceholdersInit = function () {
    // This class needs added before the sortable even initialises, would be great if sortable had a preInit event
    $(document).on('mousedown', '.splitter-column-sortable .widget-drag', function () {
        $('body').addClass('drag-mode');
    });

    $(".splitter-column-sortable-parent").sortable({
        cancel: 'input',
        revert: true,
        connectWith: ".splitter-column-sortable-parent",
        containment: '#cmsContent', // '#superSplitterContainer',
		handle: '.widget-drag',
        cursor: 'move',
        cursorAt: { cursor: "move", top: 25, left: 150 },
		start: function (e, ui) {
			ui.placeholder.height(20);
            $('body').addClass('drag-mode');
            $('body').addClass('dragging');
		},
		helper: function (event) {
            var name = $(event.target).closest('.widget').data('widgettype');
            var widgetId = $(event.target).closest('.widget').data('id');
            return $("<div class='widget-drag-placeholder btn btn-primary dragged'><span>" + name + "</span></div>");
		},
		opacity: 0.6,
		scrollSensitivity: 60,
		update: function () {
           
			var plan = $("#hdnSubscriptionPlan").val();
			var isHomePage = $("#hdnIsHomePage").val();
			var currentWidgets = $(this).find(".widget").length;
            
			if (!sportsground.cms.utils.canAddWidget(plan, isHomePage, currentWidgets)) {
				$("#myModal").load("/cms/subscriptionadvert", function () {
					$("#myModal").modal('show');
				});
                $(".splitter-column-sortable-parent").sortable("cancel");
				return false;
            }  
            
			var model = {
				Placeholder: $(this).data('key'),
				SplitterId: $(this).closest('.childsplitter').data('id'),
				SuperSplitterId: $(this).closest('.supersplitter').data('id'),
                WidgetInstanceIds: $(this).sortable('toArray', { attribute: "data-id" })
            };            

			$.ajax({
				url: '/cms/splitter/updatewidgetsortorder',
				type: 'PUT',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(model),
				fail: function() {
					alert('Sorry an error has occurred. Please contact sportsground if this happens again.');
				}
			});

			// HACK : let's call the create method on any slideshow widgets
			sortableModule.resizeSlideshowWidgets(this, ".wImageSlideshow");
			sortableModule.resizeSlideshowWidgets(this, ".wSponsorsSlideshow");
			sortableModule.resizeSlideshowWidgets(this, ".wThumbnailSlider");
            sortableModule.resizeSlideshowWidgets(this, ".wContactList");
		},
		stop: function () {
            $('body').removeClass('drag-mode');
            $('body').removeClass('dragging');
		},
		placeholder: 'widget-drag-droparea'
    });    
};

sortableModule.resizeSlideshowWidgets = function(splitter, className) {
	// HACK : let's call the create method on any of these widgets types
	var slideshowWidgets = $(splitter).find(className);
	$.each(slideshowWidgets, function () {
		if (className == ".wImageSlideshow")
			sportsground.cms.widgets.imageSlideshow.create($(this).data("id"));
		if (className == ".wSponsorsSlideshow")
			sportsground.cms.widgets.sponsorsSlideshow.create($(this).data("id"));
		if (className == ".wThumbnailSlider")
			sportsground.cms.widgets.thumbnailSlider.create($(this).data("id"));
		if (className == ".wContactList")
			sportsground.cms.widgets.contactList.create($(this).data("id"));
	});
};

;
var sponsorModule = extend(sportsground, 'sportsground.cms.sponsorModule');

sponsorModule.init = function () {
    // Load in Sponsors
    sponsorModule.loadSponsors();

    // Attach Handlers
    sponsorModule.attachEditIconVisibilityHandlers();

    // If no sponsors are present then big "Add a sponsor" button needs to trigger add sponsor click
    $("#modal-body").on('click.trigger-add-sponsor', '.btnTriggerAddSponsor', function () {
        $("#btnAddSponsor").show();
        $('.sponsors-list-group').html('');
        sponsorModule.addNewSponsor();
    });

    // Define Context Menu Handlers
    $('#contextActionEdit').on('click.sponsor-context-edit', function () {
        sponsorModule.editSponsor();

        $("#sponsorsContextMenu").hide();

        $('.modal-content:not(#sponsorsContextMenu)').off('click.cancelcontextmenu');
    });

    $('#contextActionDelete').on('click.sponsor-context-delete', function () {
        sponsorModule.deleteSponsor();

        $("#sponsorsContextMenu").hide();

        $('.modal-content:not(#sponsorsContextMenu)').off('click.cancelcontextmenu');
    });

    $('#sponsor-image-upload').fileupload({
        add: function (e, data) {
            var uploadErrors = [];
            var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
            if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                uploadErrors.push('Not an accepted file type');
            }
            if (data.originalFiles[0]['size'] > 20000000) {
                uploadErrors.push('Filesize is too big');
            }
            if (uploadErrors.length > 0) {
                // TODO: Change this from alert??
                alert(uploadErrors.join("\n"));
            } else {
                var imageElem = sponsorModule.getUploadSponsorImageElem();
                var originalSrc = imageElem.attr('src');
                data.originalSrc = originalSrc;

                imageElem.attr("src", "/Content/images/sg-loading-circular.gif");
                imageElem.css("margin-top", "20px");

                data.formData = {
                    SponsorId: $('#sponsor-image-upload').data("currentId")
                }
                data.submit();
            }
        },
        dataType: 'json',
        url: '/cms/site/' + $("#OrganisationId").val() + '/sponsors/addsponsorimage',
        maxFileSize: 20000000,
        done: function (e, data) {
            if (data.result.success) {
                var currentSponsorId = $('#sponsor-image-upload').data("currentId");
                var imageElem = sponsorModule.getUploadSponsorImageElem();
                imageElem.attr("src", data.result.src + "?qs=" + $.now());
                imageElem.css("margin-top", "0px");
                // Flag image has changed so we can move the blob
                $("#sponsor-image-updated-boolean-" + currentSponsorId).val("True");

                // Save file extension
                var fileExtension = data.result.src.substr((data.result.src.lastIndexOf('.') + 1));

                if (currentSponsorId != "") {
                    $("#sponsor-image-extension-" + currentSponsorId).val(fileExtension);
                } else {
                    $("#sponsor-image-new").val(fileExtension);
                    $("#hdnHasUploadedLogo").val("True");
                    $("#sponsor-image-new").removeClass("no-image-error");
                }
            }
            else {
                alert('Not an accepted file type');
                var sponsorImageElem = sponsorModule.getUploadSponsorImageElem();
                sponsorImageElem.attr("src", data.originalSrc);
                sponsorImageElem.css("margin-top", "0px");
            }
        }
    });
};

sponsorModule.getUploadSponsorImageElem = function() {
    var currentSponsorId = $('#sponsor-image-upload').data("currentId");
    // set the image to the temp file
    var imageElem;
    if (currentSponsorId != "") {
        // Existing sponsor with ID
        imageElem = $("#sponsor-image-" + currentSponsorId);
    } else {
        // This is a new sponsor with no ID
        imageElem = $(".sponsor-image-new");
    }
    return imageElem;
}

sponsorModule.attachEditIconVisibilityHandlers = function () {
    $("#modal-body").on('mouseenter.sponsor-list-item', '.sponsor-item', function () {
        $('.sponsor-item').removeClass('active');
        $(this).addClass('active');

        $(this).find('.btn-edit-sponsor').show();
    });

    $("#modal-body").on('mouseleave.sponsor-list-item', '.sponsor-item', function () {
        $('.sponsor-item').removeClass('active');
        $(this).find('.btn-edit-sponsor').hide();
    });

    $("#modal-body").on('click.btn-edit-sponsor', '.btn-edit-sponsor', sponsorModule.triggerContextMenu);

    $('#btnAddSponsor').on('click.add-sponsor', sponsorModule.addNewSponsor);
};

sponsorModule.detachEditIconVisibilityHandlers = function () {
    $("#modal-body").off('mouseenter.sponsor-list-item');
    $("#modal-body").off('mouseleave.sponsor-list-item');
    $("#modal-body").off('click.btn-edit-sponsor');
    $('#btnAddSponsor').off('click.add-sponsor');
};

sponsorModule.editSponsor = function () {
    // Swap label container for input
    var id = $("#sponsorsContextMenu").data('contextitem-id');
    // Hide Label
    var label = $("#sponsor-label-" + id);
    $(label).hide();
    // Populate and display inputs
    var input = $("#sponsor-input-" + id);
    var inputSponsor = input.find('.txtSponsorName');
    var inputLink = input.find('.txtSponsorLink');

    inputSponsor.val($("#sponsor-label-name-" + id).text());
    inputLink.val($("#sponsor-label-link-" + id).text());

    input.show();
    input.find('.txtSponsorName').focus();

    // Add Disabled attr to Add Sponsor button
    $('#btnAddSponsor').attr('disabled', 'disabled');

    // Add id to sponsorImage upload
    $('#sponsor-image-upload').data("currentId", id);
    $("#sponsor-image-" + id).attr("src", $("#sponsor-image-display-" + id).attr("src"));

    // Attach handler for item save/cancel buttons 
    input.on('click.btn-cancel', '.btn-cancel', function () {
        input.hide();
        label.show();

        $('#btnAddSponsor').removeAttr('disabled');
        sponsorModule.attachEditIconVisibilityHandlers();

        sponsorModule.removeEditSponsorHandlers(id);

        return false;
    });

    input.on('click.btn-save', '.btn-save', function () {
        if (!inputSponsor.valid() || !inputLink.valid())
            return false;

        input.find('.btn-save').attr('disabled', true);

        var link = sportsground.utils.prependHttpForWwwLinks(inputLink.val());
        var model = {
            Id: input.data('id'),
            Name: inputSponsor.val(),
            Link: link,
            FileExtension: $("#sponsor-image-extension-" + id).val(),
            UpdatedImage: $("#sponsor-image-updated-boolean-" + id).val(),
            OrganisationId: $("#OrganisationId").val()
        };

        $.ajax({
            url: '/cms/site/' + $("#OrganisationId").val() + '/sponsors/updatesponsor',
            type: 'POST',
            data: JSON.stringify(model),
            contentType: 'application/json; charset=utf-8',
            success: function (data, textStatus, xhr) {
                input.find('.btn-save').attr('disabled', false);

                sponsorModule.loadSponsors();

                $('#btnAddSponsor').removeAttr('disabled');

                data.Result.ImageUrl = data.Result.ImageUrl + "?ts=" + new Date().getTime();
                $("#sponsorSlideImg_" + model.Id).prop("src", data.Result.ImageUrl);

                // Compile new sponsor
                var template = Handlebars.compile($('#hbtSponsor').html());
                var html = template(data.Result);
                $('.sponsors-list-group').append(html);

                $("#sponsor-" + input.data('id')).remove();
                var options = {
                    attr: 'sort-n',
                    order: 'asc'
                };
                $('.sponsors-list-group').tsort(options);

                // Attach Handlers
                sponsorModule.attachEditIconVisibilityHandlers();

                sponsorModule.removeEditSponsorHandlers(id);

                sponsorModule.loadSponsorWidgets(data.widgetIds);
                
            }
        });

        return false;
    });

    input.on('click.sponsor-logo-upload', '.sponsor-logo-upload', function () {
        $("#sponsor-image-upload").trigger('click');

        return false;
    });

    input.on('click.sponsor-image-upload', '.sponsor-image', function () {
        $("#sponsor-image-upload").trigger('click');

        return false;
    });
};

sponsorModule.removeEditSponsorHandlers = function(id) {
    var input = $("#sponsor-input-" + id);

    input.off('click.btn-cancel');

    input.off('click.btn-save');

    input.off('click.sponsor-logo-upload');

    input.off('click.sponsor-image-upload');
};

sponsorModule.deleteSponsor = function () {
    var id = $("#sponsorsContextMenu").data('contextitem-id');
    $.ajax({
        url: "/cms/site/sponsors/removesponsor?sponsorId=" + id,
        type: 'GET',
        success: function (data, textStatus, xhr) {
            var id = $("#sponsorsContextMenu").data('contextitem-id');
            $("#sponsor-" + id).remove();

            sponsorModule.loadSponsorWidgets(data);
               
            sponsorModule.attachEditIconVisibilityHandlers();
        }
    });
};

sponsorModule.loadSponsors = function () {
    $.ajax({
        url: "/cms/site/" + $("#OrganisationId").val() + "/sponsors",
        type: 'GET',
        success: function (data, textStatus, xhr) {
            // load handlebar templates
            $('.sponsors-list-group').html('');

            if (data.length > 0) {
                //
                $("#btnAddSponsor").show();
                // We have sponsors to add. Dooo it
                var template = Handlebars.compile($('#hbtSponsor').html());
                for (var index = 0; index < data.length; index++) {
                    $('.sponsors-list-group').append(template(data[index]));
                }

                sponsorModule.addFormUnobtrusiveValidation();
            } else {
                // No sponsors. Add a message
                var message = "<li style='height:100%;'><h3 class='btnTriggerAddSponsor'><i class='glyphicon glyphicon-cloud-upload'></i>&nbsp;&nbsp;Add a sponsor</h3></li>";
                $('.sponsors-list-group').append(message);
            }
        }
    });
};

sponsorModule.loadSponsorWidgets = function (data) {
    for (var i = 0; i < data.length; i++) {
        (function (i) {
            var widgetInstanceId = data[i];
            $.ajax({
                url: '/cms/widgets/' + widgetInstanceId + '?em=1',
                type: 'GET',
                success: function (html, textStatus, xhr) {
                    var splitterContainer = $('#widget_' + widgetInstanceId);
                    splitterContainer.replaceWith(html);
                    sponsorsSlideshowModule.create(widgetInstanceId);
                }
            });
            
        })(i);
    }
}

sponsorModule.addNewSponsor = function () {
    // Add Empty Markup
    var newSponsorHtml = $('#hbtAddSponsor').html();
    $('.sponsors-list-group').append(newSponsorHtml);

    sponsorModule.addFormUnobtrusiveValidation();

    sponsorModule.detachEditIconVisibilityHandlers();

    // Focus on Name textbox
    $("#sponsor-input-new").find('.txtNewSponsorName').focus();

    // Reset sponsor Id so temp image added
    $('#sponsor-image-upload').data("currentId", "");

    // Attach Handlers for Save and Cancel new sponsor
    $("#sponsor-input-new").find('.btn-cancel').on('click', function () {
        $("#sponsor-input-new").remove();

        sponsorModule.attachEditIconVisibilityHandlers();
        return false;
    });

    $("#sponsor-input-new").find('.btn-save').on('click', function () {
        if (!$(".txtNewSponsorName").valid() || !$(".txtNewSponsorLink").valid())
            return false;

        // Check image has been uploaded
        $("#sponsor-image-new").removeClass("no-image-error");
        if ($("#hdnHasUploadedLogo").val() == "False") {
            $("#sponsor-image-new").addClass("no-image-error");

            return false;
        }

        $("#sponsor-input-new").find('.btn-save').attr("disabled", true);

        var link = sportsground.utils.prependHttpForWwwLinks($(".txtNewSponsorLink").val());
        var model = {
            Id: -1,
            Name: $("#sponsor-input-new").find('.txtNewSponsorName').val(),
            Link: link,
            FileExtension: $("#sponsor-image-new").val(),
            UpdatedImage: "True",
            OrganisationId: $("#OrganisationId").val()
        };

        $.ajax({
            url: "/cms/site/" + $("#OrganisationId").val() + "/sponsors/addsponsor",
            type: 'POST',
            data: JSON.stringify(model),
            contentType: 'application/json; charset=utf-8',
            success: function (data, textStatus, xhr) {
                if (data != null) {
                    $("#sponsor-input-new").find('.btn-save').attr("disabled", false);
                    // Compile new sponsor
                    var template = Handlebars.compile($('#hbtSponsor').html());
                    var html = template(data);
                    $('.sponsors-list-group').append(html);

                    $("#sponsor-input-new").remove();
                    var options = {
                        attr: 'sort-n',
                        order: 'asc'
                    };
                    $('.sponsor-item').tsort(options);
                }
            }
        });

        sponsorModule.attachEditIconVisibilityHandlers();
        return false;
    });

    $("#sponsor-input-new").find('.sponsor-logo-upload').on('click', function () {
        $("#sponsor-image-upload").trigger('click');
    });

    $("#sponsor-input-new").find('.sponsor-image-new').on('click', function () {
        $("#sponsor-image-upload").trigger('click');
    });
};

sponsorModule.triggerContextMenu = function () {
    var editIcon = $(this);
    sponsorModule.detachEditIconVisibilityHandlers();
    var contextMenu = $("#sponsorsContextMenu");

    $(window).scrollTop(0);
    // set the image id or folder id as the data-contextitem-id attribute on the context menu root
    contextMenu.data('contextitem-id', editIcon.data('id'));
    contextMenu.css({
        display: "block",
        left: editIcon.offset().left - 160,
        top: editIcon.offset().top + 17,
        "z-index": 1

    });

    // set the handler to hide the menu if clicked outside
    $('.modal-content:not(#sponsorsContextMenu)').one('click.cancelcontextmenu', function () {
        sponsorModule.attachEditIconVisibilityHandlers();
        contextMenu.hide();
        editIcon.hide();
    });
    return false;
};

sponsorModule.addFormUnobtrusiveValidation = function() {
    var form = $("#manageSponsorsForm");
    form.removeData('validator');
    form.removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parseDynamicContent(form);
    overrideUnobtrusiveDefaults();
};;
var strokeModule = extend(sportsground, 'sportsground.cms.stroke');

strokeModule.init = function (containerId, strokeClass) {
    var simpleColorSpan = $("#dvStrokeColor_" + containerId).find('.icon');
    simpleColorSpan.css('background-color', '#eeeeee');

    var strokeIndicator = "<span class='btn-stroke " + strokeClass + "'></span>";
    $(simpleColorSpan).html(strokeIndicator);

    var buttonStrokeColor = $("#ButtonStrokeColor_" + containerId).val();
    $(".btn-stroke").css('border-color', buttonStrokeColor);

    var buttonisSquare = $("#ButtonUsingSquareCorners_" + containerId).val() === "True";
    if (buttonisSquare) {
        $('.btn-stroke').css('border-radius', 0 + "px");
    }
    else {
        var buttonRadius = $("#ButtonRadius_" + containerId).val();
        $('.btn-stroke').css('border-radius', buttonRadius + "px");
    }

    $("#uxstrokeColor").on('change', function () {
        simpleColorSpan.css('background-color', '#eeeeee');
        var selectedStrokeColor = $("#dvStrokeColor_" + containerId).find('.picker span[data-selected]');
        $('.btn-stroke').css('border-color', selectedStrokeColor.data('color'));
        return false;
    });

    $("#rbSquareCorner").on('change', function () {
        $(".buttonRadius").addClass('hidden');
        $('.btn-stroke').css('border-radius', 0 + "px");
        return false;
    });

    $("#rbRoundCorner").on('change', function () {
        $(".buttonRadius").removeClass('hidden');
        $('.btn-stroke').css('border-radius', 4 + "px");
        return false;
    });
};;
var superSplitterModule = extend(sportsground, 'sportsground.cms.superSplitter');

superSplitterModule.initialize = function() {

	// Attach button click event to 'Add Section' button
	$('#addSuperSplitterBtn').on('click', function() {

		var plan = $('#hdnSubscriptionPlan').val();
		var isHomePage = $('#hdnIsHomePage').val();
		var currentSections = $('.supersplitter').length - 1;//page will always have a footer section and we do not want to count it as a normal section

		if (sportsground.cms.utils.canAddSection(plan, isHomePage, currentSections)) {
            $('#myModal').load('/cms/addsection?siteId=' + $("#SiteId").val(), function() {
				$('#myModal').modal('show');
                
                superSplitterModule.loadSuperSplitterSettings(null);

				$('#saveSuperSplitter').click(function() {
					superSplitterModule.createSuperSplitter();
					
					return false;
				});
			});
		} else {
			$('#myModal').load('/cms/subscriptionadvert', function() {
				$('#myModal').modal('show');
			});
		}
		return false;
	});

	// Delete button handler
	$(document).on('click', '.supersplitter-settings-delete', function() {
		var id = $(this).closest('.supersplitter').data('id');
		var widgets = $(this).closest('.supersplitter').find('.widget');

		if (!(widgets.length > 0)) {
			superSplitterModule.deleteSuperSplitter(id);
			return false;
		}

		var htmlNotification = '<div class="text-center"><h1><i class="glyphicon glyphicon-warning-sign" style="color:#cc002e;"></i></h1><h4 style="color:#cc002e;">Are you sure you want to permanently delete this content?</h4>';
		// This is a splitter, different message required
		htmlNotification += widgetModule.buildSplitterDeleteConfirmation(widgets);
		htmlNotification += '</div>';

		bootbox.dialog({
			message: htmlNotification,
			buttons: {
				success: {
					label: 'No, Keep',
					className: 'btn-info',
					callback: function() {
						bootbox.hideAll();
					}
				},
				danger: {
					label: 'Yes, Delete',
					className: 'btn-danger',
					callback: function(result) {
						if (result) {
							// Delete widget
							superSplitterModule.deleteSuperSplitter(id);
						}
					}
				}
			}
		});
	});

	// Edit button handler
	$(document).on('click', '.supersplitter-settings-edit', function() {
		superSplitterModule.editSuperSplitter(this);
    });

    // Edit button handler
    $(document).on('click', '.supersplitter-settings-hide', function () {
        superSplitterModule.toggleHideSuperSplitter(this);
    });
};

superSplitterModule.editSuperSplitter = function(sSplitter) {
	var superSplitter = $(sSplitter).closest('.supersplitter');
    var columnContainers = superSplitter.find('.splitter-column-sortable-parent');
	var id = superSplitter.data('id');

    $('#myModal').load('/cms/addsection?siteId=' + $("#SiteId").val(), function() {
		$('#saveSuperSplitter').show();
		$('#myModal').modal('show');
                
        superSplitterModule.loadSuperSplitterSettings(superSplitter);

		$('#saveSuperSplitter').click(function() {
            superSplitterModule.saveSuperSplitter(columnContainers, id);
		});

		// set is FullscreenWidth
		var fullscreenOption = superSplitter.data('fullscreen');
		if (fullscreenOption === true || fullscreenOption === 'True') {
			$('#FullScreenWidth').prop('checked', true);
		} else {
			$('#FullScreenWidth').prop('checked', false);
        }

        // set is fluid widgets
        var fluidWidgetsOption = superSplitter.data('fluidwidgets');
        if (fluidWidgetsOption === true || fluidWidgetsOption === 'True') {
            $('#FluidWidgets').prop('checked', true);
        } else {
            $('#FluidWidgets').prop('checked', false);
        }

		// set is bg fullscreenwidth
		var fullscreenBGOption = superSplitter.data('fullscreenbg');
		if (fullscreenBGOption === true || fullscreenBGOption === 'True') {
			$('#FullScreenWidthBG').prop('checked', true);
		} else {
			$('#FullScreenWidthBG').prop('checked', false);
        }

        var backgroundVideoImage = superSplitter.data('bgvideoimage');
        var bgImageId = sportsground.utils.getImageIdFromSrc(backgroundVideoImage);
        superSplitterModule.videoImageId = bgImageId;

        var backgroundVideo = superSplitter.data('bgvideo');
        var bgId = sportsground.utils.getImageIdFromSrc(backgroundVideo);
        superSplitterModule.videoId = bgId;

        superSplitterModule.loadSelectedMobileVideoImage();
        superSplitterModule.loadSelectedVideo();

	});
};


superSplitterModule.toggleHideSuperSplitter = function (sSplitter) {
    var superSplitter = $(sSplitter).closest('.supersplitter');
    var id = superSplitter.data('id');

    $.ajax({
        type: 'PUT',
        url: '/cms/supersplitter/togglevisibility/' + id,
        contentType: 'application/json; charset=utf-8'
    }).done(function (isHidden) {

        if (sportsground.cms.utils.isTrue(isHidden)) {
            superSplitter.find(".supersplitter-settings-hide .fa").addClass("fa-eye-slash");
            superSplitter.find(".supersplitter-settings-hide .fa").removeClass("fa-eye");
        }
        else {
            superSplitter.find(".supersplitter-settings-hide .fa").addClass("fa-eye");
            superSplitter.find(".supersplitter-settings-hide .fa").removeClass("fa-eye-slash");
        }
        
    });
};

superSplitterModule.createSuperSplitter = function () {

    $("#saveSuperSplitter .fa").addClass('fa-spinner');
    $("#saveSuperSplitter").attr('disabled', 'disabled');

    var backgroundVideo;
    if ($("#desktop-video a").attr('href')) {
        backgroundVideo = $("#desktop-video a").attr('href').replace('_539', '');
    }

    var backgroundVideoImage;
    if ($('#rbVideoContent #mobile-video-image img').attr('src')) {
        backgroundVideoImage = $('#rbVideoContent #mobile-video-image img').attr('src').replace('_539', '_wo');
    }

    if (backgroundVideo && !backgroundVideoImage) {
        bootbox.alert('Please select an image to display instead of the video when viewed on a mobile device.');
        $("#saveSuperSplitter").attr('disabled', false);
        $("#saveSuperSplitter .fa").removeClass('fa-spinner');
        return;
    }

    var columnOption = $( '.selectable-layout.selected' ).data( 'val' );
    var backgroundImage = $('#rbImageContent .cnt-images .library-image.selected img').attr('src');
    var model = {
        PageId: $( '#PageId' ).val(),
        SplitterColumnOption: columnOption === undefined ? 0 : columnOption,
        IsFullScreenWidth: $( '#FullScreenWidth' ).prop( 'checked' ),
        BackgroundColor: $( '#sectionBackgroundColor' ).val(),
        BackgroundTransparency: $('#sectionTransparencySliderInput').val(),
        IsBackgroundColorFullScreenWidth: $( '#FullScreenWidthBG' ).prop( 'checked' ),
        ShowBackgroundImage: $( '#rbImage' ).prop( 'checked' ),
        BackgroundImage: backgroundImage,
        MarginOnDesktop: $('#txtDesktopMargin').val(),
        MarginOnMobile: $('#txtMobileMargin').val(),
        WidgetsMargin: $('#txtWidgetsMargin').val(),
        IsFluidWidgets: $('#FluidWidgets').prop('checked'),
        BackgroundVideo: backgroundVideo,
        ShowBackgroundVideo: $('#rbVideo').prop('checked'),
        BackgroundVideoImage: backgroundVideoImage
	};
	$.ajax({
		type: 'POST',
		url: '/cms/supersplitter/create',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model)
	})
	.done(function(result) {
		$('#superSplitterContainer').append(result);
        sportsground.cms.sortable.widgetPlaceholdersInit();

        $("#saveSuperSplitter").attr('disabled', false);
        $("#saveSuperSplitter .fa").removeClass('fa-spinner');

        $('#myModal').modal('hide');
	});

};

superSplitterModule.deleteSuperSplitter = function(id) {
	$.ajax({
		type: 'DELETE',
		url: '/cms/supersplitter/' + id,
		contentType: 'application/json; charset=utf-8',
	}).done(function(result) {
		$('#superSplitter_' + id).remove();
	});
};

superSplitterModule.saveSuperSplitter = function (columnContainers, id) {
    $("#saveSuperSplitter .fa").addClass('fa-spinner');
    $("#saveSuperSplitter").attr('disabled', 'disabled');

    var numColumnsUsed = 0;
    $.each( columnContainers, function ( index, columnContainer ) {
        // super splitter and child splitter are included in this loop. Only count super splitter by checking if data-id == undefined.
        if ( $( columnContainer ).data( 'id' ) == undefined && $( columnContainer ).find( '.widget' ).length > 0 ) {
            numColumnsUsed++;
        }
    } );

    var selectedColumnOption = $( '.selectable-layout.selected' );
    // check if the number of columns used is greater than the data-count of the selected layout
    if ( numColumnsUsed > parseInt( selectedColumnOption.data( 'count' ) ) ) {
        bootbox.alert('Unable to fit your widgets in this section layout, please choose a different layout or remove some widgets.');
        $("#saveSuperSplitter").attr('disabled', false);
        $("#saveSuperSplitter .fa").removeClass('fa-spinner');
        return;
    }    

    var backgroundImage = $('#rbImageContent .cnt-images .library-image.selected img').attr('src');
    var backgroundVideo;
    if ($("#desktop-video a").attr('href')) {
        backgroundVideo = $("#desktop-video a").attr('href').replace('_539', '');
    }

    var backgroundVideoImage;
    if ($('#rbVideoContent #mobile-video-image img').attr('src')) {
        backgroundVideoImage = $('#rbVideoContent #mobile-video-image img').attr('src').replace('_539', '_wo');
    }

    if (backgroundVideo && !backgroundVideoImage) {
        bootbox.alert('Please select an image to display instead of the video when viewed on a mobile device.');
        $("#saveSuperSplitter").attr('disabled', false);
        $("#saveSuperSplitter .fa").removeClass('fa-spinner');
        return;
    }

    var model = {
        Id: id,
        SplitterColumnOption: selectedColumnOption.data( 'val' ),
        IsFullScreenWidth: $( '#FullScreenWidth' ).prop( 'checked' ),
        BackgroundColor: $( '#sectionBackgroundColor' ).val(),
        BackgroundTransparency: $( '#sectionTransparencySliderInput' ).val(),
        IsBackgroundColorFullScreenWidth: $( '#FullScreenWidthBG' ).prop( 'checked' ),
        ShowBackgroundImage: $( '#rbImage' ).prop( 'checked' ),
        BackgroundImage: backgroundImage,
        MarginOnDesktop: $('#txtDesktopMargin').val(),
        MarginOnMobile: $('#txtMobileMargin').val(),
        WidgetsMargin: $('#txtWidgetsMargin').val(),
        IsFluidWidgets: $('#FluidWidgets').prop('checked'),
        HideFooter: $('#HideFooter').prop('checked'),
        BackgroundVideo: backgroundVideo,
        ShowBackgroundVideo: $('#rbVideo').prop('checked'),
        BackgroundVideoImage: backgroundVideoImage
    };
    $.ajax( {
        type: 'POST',
        url: '/cms/supersplitter/update?em=1', //em parameter is used in SecurityHelper to show the toolbars in widgets after save super splitter
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify( model )
    } )
    .done(function(html) {
		$('#superSplitter_' + id).replaceWith(html);
		sportsground.cms.common.loadPageWidgets(id);
		sportsground.cms.sortable.superSplittersInit();
        sportsground.cms.sortable.widgetPlaceholdersInit();

        $("#saveSuperSplitter").attr('disabled', false);
        $("#saveSuperSplitter .fa").removeClass('fa-spinner');

        $('#myModal').modal('toggle');
        sportsground.cms.common.setStylesForFullWidthSections();
	});
};

superSplitterModule.loadSuperSplitterSettings = function (superSplitter) {

    // initialize radio buttons
    var show = false;
    var showVideo = false;
    if ( superSplitter ) {
        show = sportsground.cms.utils.isTrue(superSplitter.data('showbgimage').toLowerCase());
        showVideo = sportsground.cms.utils.isTrue(superSplitter.data('showbgvideo').toLowerCase());

        var isFooter = sportsground.cms.utils.isTrue(superSplitter.data('isfooter'));
        if (isFooter) {
            $(".footer-section-title").show();
            $(".standard-section-title").hide();
            $(".hide-footer-checkbox-wrapper").show();

            var isHidden = sportsground.cms.utils.isTrue(superSplitter.data('ishidden'));
            if (isHidden) {
                $('#HideFooter').prop('checked', true);
            } else {
                $('#HideFooter').prop('checked', false);
            }

        }
    }

    $( "input:radio[name=rbBackground]" ).click( function () {
        if ( $( this ).val() == 'colour' ) {
            $( '#rbColourContent' ).show();
            $( '#rbImageContent' ).hide();
            $('.gallery-action-buttons').hide();
            $('#rbVideoContent').hide();
            $('#videoContent').hide();
            $('#videoImageContent').hide();
        }
        else if ( $( this ).val() == 'image' ) {
            $( '#rbColourContent' ).hide();
            $( '#rbImageContent' ).show();
            $('.gallery-action-buttons').show();
            $('#rbVideoContent').hide();
            $('#videoContent').hide();
            $('#videoImageContent').hide();
            if (docManagerModule && docManagerModule.settings) {
                docManagerModule.settings.isMedia = false;
            }
        }
        else if ($(this).val() == 'video') {
            $('#rbVideoContent').show();
            $('#rbColourContent').hide();
            $('#rbImageContent').hide();
            $('.gallery-action-buttons').hide();
        }
        else {
            $( '#rbColourContent' ).hide();
            $( '#rbImageContent' ).hide();
            $('.gallery-action-buttons').hide();
            $('#rbVideoContent').hide();
            $('#videoContent').hide();
            $('#videoImageContent').hide();
        }
    } );

    if ( show ) {
        $( '#rbImage' ).click();
    }
    else if ( showVideo ) {
        $('#rbVideo').click();
    }
    else {
        $( '#rbColour' ).click();
    }

    $( '.gallery-action-buttons' ).hide();
    $( '.tabSelect' ).click( function () {
        $( '.gallery-action-buttons' ).hide();
        if ( show && $( this ).find( 'a' ).attr( 'href' ) == '#tabBackground' ) {
            $( '.gallery-action-buttons' ).show();
        }
    } );

    // initialize contents of each nav tab
    superSplitterModule.initializeLayoutSettings( superSplitter );
    superSplitterModule.initializeBackgroundColorSettings( superSplitter );
    superSplitterModule.initializeImageGallerySettings( superSplitter );
    superSplitterModule.initializeMarginSettings(superSplitter);

    //add bg video
    superSplitterModule.setAddVideoClickHandler();

    //add mobile video
    superSplitterModule.setAddMobileVideoImageClickHandler();

    //set video link
    if (superSplitter) {
        $("#splitterVideoUrl").val(superSplitter.data('bgvideo'));
    }
    
};

superSplitterModule.initializeLayoutSettings = function ( superSplitter ) {
    if ( superSplitter ) {
        var columnOption = superSplitter.data( 'key' );
        $( '.selectable-layout' ).each( function () {
            if ( $( this ).data( 'val' ) === columnOption )
                $( this ).addClass( 'selected' );
        } );
    }
    if ( $( '.selectable-layout.selected' ).length == 0 ) {
        $( '.selectable-layout.col1' ).addClass( 'selected' );
    }

    $( '.selectable-layout' ).click( function () {
        $( '.selectable-layout' ).removeClass( 'selected' );
        $( this ).addClass( 'selected' );
    } );
};

superSplitterModule.initializeBackgroundColorSettings = function ( superSplitter ) {
    var backgroundColor;
    var transparency;
    if ( superSplitter ) {
        backgroundColor = superSplitter.data( 'bgcolor' );
        transparency = superSplitter.data( 'transparency' );
    } else {
        //defaults
        backgroundColor = '';
        transparency = 0;
    }

    $( '#sectionBackgroundColor' ).val( backgroundColor );
    $('#sectionBackgroundColor').simplecolorpicker({ trigger: 'sectionBackgroundColorTrigger', selectedColor: backgroundColor });

    if (backgroundColor == null || backgroundColor == '') {
        $('span.simplecolorpicker.input-group-addon').text('No colour selected');
    }

    $('#sectionTransparencySlider').slider({
        isRTL: true,
        range: 'false',
        value: -transparency,
        min: -1,
        max: 0,
        step: 0.01,
        slide: function ( event, ui ) {
            $('#sectionTransparencySliderInput').val(Math.abs( Math.round( ui.value * 100) ) + '%' );
        }
    } );

    $('#sectionTransparencySliderInput').val(Math.abs( Math.round( transparency * 100 )) + '%' );

    $('.color').on('click', function () {
        $('span.simplecolorpicker.input-group-addon').text('');
    });
};

superSplitterModule.initializeImageGallerySettings = function ( superSplitter ) {
    var src = null;
    if ( superSplitter ) {
        src = superSplitter.data( 'bgimage' );
    }

    // initialize the image gallery, also find the selected background image and set to selected
    var imageGallerySettings = {
        allowEditing: false,
        container: $("#rbImageContent"),
        isSuperSplitterBG: true
    };
    if (src) {

        $("#saveSuperSplitter").attr('disabled','disabled');
        var imageId = sportsground.utils.getImageIdFromSrc(src);
        $.ajax({
            url: '/asset/getcontainerid?assetId=' + imageId,
            type: 'GET',
            async: false,
            success: function (data) {
                imageGallerySettings.year = data.Year;
                imageGallerySettings.preselectedFolderId = data.ContainerId;
                imageGallerySettings.loadThumbsCallback = function () {
                    $('#item_' + imageId).addClass('selected');
                };
                sportsground.cms.imageGallery.init(imageGallerySettings);
                $("#saveSuperSplitter").attr('disabled', false);

                $('.cbImageSelect').parent().hide();
            }
        });
    }
    else {
        sportsground.cms.imageGallery.init(imageGallerySettings);
    }

    // initialize the file uploader
    sportsground.cms.imageGallery.fileupload.init();

    // event to set image to selected
    $( document ).off( 'click', '#rbImageContent .cnt-images .library-image' )
        .on( 'click', '#rbImageContent .cnt-images .library-image', function () {
            $( '#rbImageContent .cnt-images .library-image' ).removeClass( 'selected' );
            $( this ).addClass( 'selected' );
        } );
};

superSplitterModule.initializeMarginSettings = function (superSplitter) {
    var marginOnDesktop = $("#hdnSiteSectionMargin").val();
    var marginOnMobile = '';
    var widgetsMargin = $("#hdnSiteWidgetMargin").val();

    if (superSplitter) {
        if ( !isNaN( parseInt( superSplitter.data('desktopmargin') ) ) )
            marginOnDesktop = superSplitter.data('desktopmargin');

        if ( !isNaN( parseInt( superSplitter.data('mobilemargin') ) ) )
            marginOnMobile = superSplitter.data('mobilemargin');

        if ( !isNaN( parseInt( superSplitter.data('widgetsmargin') ) ) )
            widgetsMargin = superSplitter.data('widgetsmargin');
    }

    $("#txtDesktopMargin").val(marginOnDesktop);
    $("#txtMobileMargin").val(marginOnMobile);
    $("#txtWidgetsMargin").val(widgetsMargin);
};

superSplitterModule.setAddVideoClickHandler = function () {

    $('.btnChooseVideo').unbind("click");
    $('.btnChooseVideo').click(function (e) {

        $('#rbVideoContent').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
            $('#videoContent').effect('slide', { direction: 'right', mode: 'show' }, 500);
            $(".layoutSaveAndCancel").hide();
            $("#btnCancelSelectingImages").hide();
            $("#btnDoneSelectingImages").hide();

            var videoGallerySettings = {
                allowEditing: true,
                container: $("#videoContent"),
                loadThumbsCallback: function () {
                    superSplitterModule.setVideoClickHandler();
                },
                isMedia: true
            };

            var videoId = superSplitterModule.videoId;
            if (videoId !== undefined && videoId !== '') {
                $.ajax({
                    url: '/asset/getcontainerid?assetId=' + videoId,
                    type: 'GET',
                    async: false,
                    success: function (data) {
                        videoGallerySettings.year = data.Year;
                        videoGallerySettings.preselectedFolderId = data.ContainerId;
                        videoGallerySettings.loadThumbsCallback = function () {
                            $('#item_' + videoId).addClass('selected');
                            superSplitterModule.setVideoClickHandler();
                        };
                    }
                });
            }

            $("#videoContent").load("/Asset/MediaManager?organisationId=" + $("#OrganisationId").val() + "&isKnowledgeLibrary=false", function () {
                sportsground.cms.documentManager.init( videoGallerySettings );

                $('#btnCloseDocumentModal').hide();
                $('#videoContent .gallery-action-buttons #btnAddLink').hide();
                $('#videoContent .gallery-action-buttons #btnAddGalleryFolder').hide();
                $('#videoContent .gallery-action-buttons label').hide();
               
                if ($('#btnDoneSelectingVideo').length === 0) {
                    $(".layoutSaveAndCancel").hide();
                    $('.layoutSaveAndCancel').after('<button id="btnCancelSelectingVideo" class="btn btn-info">Cancel</button><button id="btnDoneSelectingVideo" class="btn btn-primary">Save</button>');
                    $('#btnCancelSelectingVideo').on('click', function () {
                        superSplitterModule.hideVideoModal();
                    });
                    $('#btnDoneSelectingVideo').on('click', function () {
                        superSplitterModule.hideVideoModal();
                    });
                }
                else {
                    $('#btnDoneSelectingVideo').show();
                    $('#btnCancelSelectingVideo').show();
                }

            });
        });
       

    });
};

superSplitterModule.setAddMobileVideoImageClickHandler = function () {

    $('.btnChooseMobileVideoImages').unbind('click');
    $('.btnChooseMobileVideoImages').click(function (e) {

        superSplitterModule.isEditingMobileVideoImage = true;

        if (docManagerModule && docManagerModule.settings) {
            docManagerModule.settings.isMedia = false;
        }    

        $('#rbVideoContent').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
            $('#videoImageContent').effect('slide', { direction: 'right', mode: 'show' }, 500);
            $('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
            $(".layoutSaveAndCancel").hide();
            $('.gallery-action-buttons').show();
            $("#btnCancelSelectingVideo").hide();
            $("#btnDoneSelectingVideo").hide();

        });

        if ($('#btnDoneSelectingImages').length === 0) {
            $(".layoutSaveAndCancel").hide();
            $('.layoutSaveAndCancel').after('<button id="btnCancelSelectingImages" class="btn btn-info">Cancel</button><button id="btnDoneSelectingImages" class="btn btn-primary">Save</button>');
            $('#btnCancelSelectingImages').on('click', function () {
                superSplitterModule.hideImageModal();
            });
            $('#btnDoneSelectingImages').on('click', function () {
                superSplitterModule.hideImageModal();
            });
        }
        else {
            $('#btnDoneSelectingImages').show();
            $('#btnCancelSelectingImages').show();
        }

        $('.widget-settings-cancel-update').hide();
        $('.widget-settings-update').hide();

        var imageGallerySettings = {
            allowEditing: false,
            container: $('#videoImageContent'),
            loadThumbsCallback: function () {
                superSplitterModule.setImageClickHandler();
            },
            isSuperSplitterBG: true
        };

        var imageId = superSplitterModule.videoImageId;
        if (imageId !== undefined && imageId && imageId.length > 0) {
            $.ajax({
                url: '/asset/getcontainerid?assetId=' + imageId,
                type: 'GET',
                async: false,
                success: function (data) {
                    if (data.ContainerId > 0)
                        $('#modalContainerId').val(data.ContainerId);

                    imageGallerySettings.year = data.Year;
                    imageGallerySettings.preselectedFolderId = data.ContainerId;
                    imageGallerySettings.loadThumbsCallback = function () {
                        $('#item_' + imageId).addClass('selected');
                        superSplitterModule.setImageClickHandler();
                    };
                }
            });
        }

        sportsground.cms.imageGallery.init(imageGallerySettings);
        if (!superSplitterModule.imageGalleryInitialised) {
            sportsground.cms.imageGallery.fileupload.init(superSplitterModule.fileUploadCompletedCallback);
            superSplitterModule.imageGalleryInitialised = true;
        }

        e.stopImmediatePropagation();
        return false;
    });
};

superSplitterModule.setImageClickHandler = function () {

    $('.cbImageSelect').parent().hide();

    $('.gallery-thumb').off('click.imagewidget-select');
    $('.gallery-thumb').on('click.imagewidget-select', function () {
        $('.gallery-thumb').removeClass('selected');
        $(this).addClass('selected');

        var id = $(this).data('id');
        superSplitterModule.videoImageId = id;

    });
};

superSplitterModule.setVideoClickHandler = function () {
    $('.btn-copy').addClass('hidden');
    $('.btn-rename').addClass('hidden');
    $('.btn-delete').addClass('hidden');

    $('.cnt-images').unbind("click");
    $('.cnt-images').on('click.download-document', '.document', function () {
        $('.document').removeClass('selected');
        $(this).addClass('selected');
        sportsground.cms.superSplitter.videoId = $(this).data("id");
    });
};

superSplitterModule.hideVideoModal = function () {
    $('#videoContent').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#rbVideoContent').effect('slide', { direction: 'right', mode: 'show' }, 500);
        $('.gallery-action-buttons').hide();
    });
    $('#btnDoneSelectingVideo').hide();
    $('#btnCancelSelectingVideo').hide();
    $('.widget-settings-cancel-update').show();
    $('.widget-settings-update').show();
    superSplitterModule.loadSelectedVideo();
    superSplitterModule.loadSelectedMobileVideoImage();
    $('.gallery-action-buttons').hide();
    $(".layoutSaveAndCancel").show();
};

superSplitterModule.hideImageModal = function () {
    $('#videoImageContent').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#rbVideoContent').effect('slide', { direction: 'right', mode: 'show' }, 500);
        $('.gallery-action-buttons').hide();
    });
    $('#btnDoneSelectingImages').hide();
    $('#btnCancelSelectingImages').hide();
    $('.widget-settings-cancel-update').show();
    $('.widget-settings-update').show();
    superSplitterModule.loadSelectedMobileVideoImage();
    superSplitterModule.loadSelectedVideo();
    $('.gallery-action-buttons').hide();
    $(".layoutSaveAndCancel").show();
};


superSplitterModule.loadSelectedVideo = function () {
    if (superSplitterModule.videoId === undefined)
        return;

    var videoIds = [];
    videoIds.push(superSplitterModule.videoId);
    $.ajax({
        url: '/asset/GetImageAssetUrls',
        type: 'POST',
        data: JSON.stringify(videoIds),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var rawHtml = $('#hbtSelectedVideoThumb').html();
            var template = Handlebars.compile(rawHtml);
            if (data.length > 0) {
                data[0].BtnClass = "btnChooseMobileImages";
                $("#desktop-video-logo").addClass('hidden');
                $("#desktop-video").append(template(data[0]));
                $("#desktop-video").removeClass('hidden');
            }
            else {
                $("#desktop-video").html('');
                $("#desktop-video").addClass('hidden');
                $("#desktop-video-logo").removeClass('hidden');
            }

            $('#selectedVideoContainer .selected-image-delete').on('click', function () {
                bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected background video?</p>', function (result) {
                    if (!result)
                        return;

                    $('#desktop-video').html('');
                    $('#desktop-video').addClass('hidden');
                    $("#desktop-video-logo").removeClass('hidden');
                    superSplitterModule.videoId = [{}];
                });
                return false;
            });
        }
    });
};

superSplitterModule.loadSelectedMobileVideoImage = function () {
    if (superSplitterModule.videoImageId === undefined)
        return;

    $('.selected-image-thumb').remove();
    var imageIds = [];
    imageIds.push(superSplitterModule.videoImageId);
    $.ajax({
        url: '/asset/GetImageAssetUrls',
        type: 'POST',
        data: JSON.stringify(imageIds),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var rawHtml = $('#hbtSelectedThumb').html();
            var template = Handlebars.compile(rawHtml);
            if (data.length > 0) {
                data[0].BtnClass = "btnChooseMobileImages";
                $("#mobile-video-image-logo").addClass('hidden');
                $("#mobile-video-image").append(template(data[0]));
                $("#mobile-video-image").removeClass('hidden');
            }
            else {
                $("#mobile-video-image").html('');
                $("#mobile-video-image").addClass('hidden');
                $("#mobile-video-image-logo").removeClass('hidden');
            }            

            $('#selectedMobileVideoImageContainer .selected-image-delete').on('click', function () {
                bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected mobile background video image?</p>', function (result) {
                    if (!result)
                        return;

                    $('#mobile-video-image').html('');
                    $('#mobile-video-image').addClass('hidden');
                    $("#mobile-video-image-logo").removeClass('hidden');
                    superSplitterModule.videoImageId = [{}];
                });
                return false;
            });
        }
    });
};

//remove the bg video from mobile
$(document).ready(function () {
    if (window.outerWidth <= 768) {
        $("video").remove();
    }
});   ;
var module = extend(sportsground, 'sportsground.cms.utils');

module.canAddSection = function(plan, isHomePage, currentSections) {
	
	if (plan !== "Bronze" && plan !== "Free") {
		return true;
	}
	// Unlimited on bronze home page
	if (isHomePage === "True" && plan === "Bronze") {
		return true;
	}
	// 2 sections on free home page, otherwise only 1
	var allowedSections = 1;
	if (isHomePage === "True" && plan === "Free") {
		allowedSections = 2;
	}

	return currentSections < allowedSections;
};
	
module.canAddWidget = function (plan, isHomePage, currentWidgets) {
  
  if (plan !== "Bronze" && plan !== "Free") {
    return true;
  }
  // Unlimited on bronze home page
  if (isHomePage === "True" && plan === "Bronze") {
    return true;
  }
  
  var allowedWidgets = 1;  // 1 level deep for all free (& underlying bronze) pages

  return currentWidgets <= allowedWidgets;
};

if (!Date.prototype.toLocalISOString) {
    (function() {

        Date.prototype.toLocalISOString = function() {
            return this.getFullYear() +
                '-' + sportsground.cms.utils.pad(this.getMonth() + 1) +
                '-' + sportsground.cms.utils.pad(this.getDate()) +
                'T' + sportsground.cms.utils.pad(this.getHours()) +
                ':' + sportsground.cms.utils.pad(this.getMinutes()) +
                ':' + sportsground.cms.utils.pad(this.getSeconds()) +
                '.' + (this.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
                'Z';
        };

    }());
}

if (!Date.prototype.toDateOnlyLocalISOString) {
    (function() {

        Date.prototype.toDateOnlyLocalISOString = function() {
            return this.getFullYear() +
                '-' + sportsground.cms.utils.pad(this.getMonth() + 1) +
                '-' + sportsground.cms.utils.pad(this.getDate());
        };

    }());
}

if (!Date.prototype.toTimeFormatAMPM) {
    (function() {

        Date.prototype.toTimeFormatAMPM = function() {

            var hours = this.getHours();
            var minutes = this.getMinutes();
            var ampm = hours >= 12 ? 'pm' : 'am';
            hours = hours % 12;
            hours = hours ? hours : 12; // the hour '0' should be '12'
            var strTime = hours +
                ':' + sportsground.cms.utils.pad(minutes) +
                '' + ampm;
            return strTime;

        };

    }());
}

if (!String.prototype.toBool) {
    (function () {
        String.prototype.toBool = function () {
            return module.isTrue(this.toString());
        };
    }());
}

module.pad = function(number) {
    if (number < 10) {
        return '0' + number;
    }
    return number;
}

// Ensure that value will be checked for 'true', even if value is string or boolean
module.isTrue = function(value) {
    if (value == null) {
        return false;
    }
    if (typeof value == 'string') {
        return value.toLowerCase() == 'true';
    }
    else if (typeof value == 'boolean') {
        return value;
    }

    return false;
}

module.getSelectedValuesFromMultiSelectList = function(multiSelectList) {
    var items = [];
    multiSelectList.find('option:selected').each(function() {
        items.push($(this).val());
    });
    return items.join(",");
};
(function (sportsground) {
    var module = extend(sportsground, 'sportsground.cms.modals.manageUrl');

    var modal;
    var isAdding = false;
    var editTemplate;
    var itemTemplate;

    module.init = function (parentPageId, parentPageType) {

        var url = '/cms/site/' + $("#SiteId").val() + '/manageurl?pid=' + parentPageId + '&pt=' + parentPageType;
        modal = $('#myModal');
        isAdding = false;

        modal.on('hidden.bs.modal', function () {
            modal.off('click'); //Cleanup events
        });

        modal.load(url, function () {

            modal.modal('show');

            editTemplate = Handlebars.compile($('#editRedirectionTemplate').html());
            itemTemplate = Handlebars.compile($('#itemRedirectionTemplate').html());

            // Attach some unobtrusive validation to this modal form		
            $.validator.unobtrusive.parse(modal);

            // Form is loaded dynamically so these defaults are not set for it on page load
            overrideUnobtrusiveDefaults();

            modal.on('click', '.new-redirection', module.new);
            modal.on('click', '.update-redirection', module.update);
            modal.on('click', '.cancel-update-redirection', module.cancelUpdate);

            modal.on('click', '.redirections .edit', module.edit);
            modal.on('click', '.redirections .delete', module.delete);
            
            $('#VanityPath').on('blur', function() {

                var parent = $(this).closest('.form-group');
                parent.removeClass('has-success');

            });

            modal.find('form').submit(module.submit);
        });

        return false;
    };

    function objectifyForm(formArray) {//serialize data function

        var returnArray = {};
        for (var i = 0; i < formArray.length; i++){
            returnArray[formArray[i]['name']] = formArray[i]['value'];
        }
        return returnArray;
    }

    module.submit = function (e) {
        e.preventDefault();

        var saveBtn = $(this).find('.modal-footer .save');

        var marginLeft = $("#VanityPath").position().left + 'px';//setting the error right below the input box for vanity url
        $("#vanity-error-text").css('margin-left', marginLeft);

        
        
        var vanityUrl = $("#VanityPath").val();
        if (/^[a-zA-Z0-9- ]*$/.test(vanityUrl) == false) {
            $("#VanityPath").addClass('input-has-error');
            $("#vanity-error-text span").text("Value not valid. Please only enter text or numbers");
            $("#vanity-error-text").removeClass('hidden');
            return false;
        }
        else if ( vanityUrl.length > 250 ) {
            $("#VanityPath").addClass('input-has-error');
            $("#vanity-error-text span").text("Value too long. Please enter a text with less than 250 characters");
            $("#vanity-error-text").removeClass('hidden');
            return false;
        }
        else {
            $("#VanityPath").removeClass('input-has-error');
            $("#vanity-error-text").addClass('hidden');
        }

        $("#VanityPath").val($("#VanityPath").val().toLowerCase());

        saveBtn.button('loading');

        var post = objectifyForm( $(this).serializeArray() );
        var action = $(this).attr("action");

        var redirections = $.map($(this).find('.redirections tr'), function (val) {

            return {
                id: $(val).data('id'),
                redirection: $(val).data('redirection'),
                action: $(val).data('action')
            };
        });

        post.redirections = redirections;
        var data2send = JSON.stringify(post);

        $.ajax({
            url: action,
            type: 'POST',
            data: data2send,
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (r) {
            if (r.Error) {
                $("#vanity-error-text span").text(r.Error);
                $("#VanityPath").addClass('input-has-error');
                $("#vanity-error-text").removeClass('hidden');
                saveBtn.button('reset');
            } else {
                modal.modal('hide');
            }
        });
    };

    module.update = function () {

        var row = $(this).closest('tr');

        var val = row.find('input').val();

        if ($(".redirections tr[data-redirection='" + val + "']").length > 0) {
            bootbox.alert('This alias is already defined in your list.');
            return;
        }

        $(itemTemplate({
            id: row.data('id'),
            redirection: val,
            action: row.data('action')
        })).insertBefore(row);

        isAdding = false;

        row.remove();
    };

    module.cancelUpdate = function () {

        var row = $(this).closest('tr');

        if (row.data('action') == '1') {
            isAdding = false;
        }
        else if (row.data('action') == '2') {

            $(itemTemplate({
                id: row.data('id'),
                redirection: row.find('input').val(),
                action: row.data('action')
            })).insertBefore(row);

        }

        row.remove();

    };

    module.new = function () {

        if (isAdding)
            return;

        isAdding = true;

        modal.find(".redirections tbody").append(editTemplate({
            id: 0,
            redirection: '',
            action: 1
        }));
    };

    module.delete = function () {
        var row = $(this).closest('tr');
        row.data('action', 3);
        row.addClass("strikeout");
    };

    module.edit = function () {

        var row = $(this).closest('tr');

        var action = 2;

        if (row.data('id') === 0)
            action = 1;

        $(editTemplate({
            id: row.data('id'),
            redirection: row.data('redirection'),
            action: action
        })).insertBefore(row);

        row.remove();
    };

}(sportsground));

;
var footerModule = extend(sportsground, 'sportsground.cms.settings.footer');

footerModule.init = function () {
    $("#uxBackgroundTransparencySlider").slider({
        isRTL: true,
        range: 'false',
		value: -$("#uxBackgroundTransparencyInput").val(),
		min: -1,
		max: 0,
		step: 0.01,
        slide: function (event, ui) {
            $("#uxBackgroundTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
		}
    });
    $("#uxBackgroundTransparencyInput").val(Math.abs(Math.round($("#uxBackgroundTransparencyInput").val() * 100)) + '%');
	$("#uxBackgroundColor").simplecolorpicker({ trigger: 'uxBackgroundColorTrigger', selectedColor: $("#uxBackgroundColor").val() });

    var cachebuster = Math.round(new Date().getTime() / 1000);
	var ckInstance = CKEDITOR.replace('txtFooterText', {
        customConfig: '/Content/ckeditor/noncms_config.js?v=1.0&cb=' + cachebuster 
	});

	$("#uxBackgroundColor").change(function() {
		$("iframe.cke_wysiwyg_frame").css("background-color", $(this).val());
	});

	// Insert the "addCss" function call:
	//ckInstance.addCss('body { background-color: ' + 'red' + '; }');

    $('#btnSaveFooter').on('click', function () {

        $("#btnSaveFooter i").addClass('fa-spinner');
        $("#btnSaveFooter").attr('disabled', 'disabled');

        var sliderValue = Math.abs($("#uxBackgroundTransparencySlider").slider("option", "value"));
		$("#uxBackgroundTransparencyInput").val(sliderValue);
		$("#changeFooterForm").submit();
	});
};
;
var changeHeaderModule = extend(sportsground, 'sportsground.cms.settings.header');
var predefinedGalleryInitialised = false;

changeHeaderModule.settings = {
	selected: {},
	/* e.g
			{
				title: 'Andy is a god damn Animal!',
				hideTitle: true,
				font: 'Arial',
				fontColor: '#C3C3C3,
				type: 'color',		other options: gallery, library
				data: '#FFFFFF',	other options: {libraryImageUrl}
				height: 150,			other options: auto, 0, 231 (or custom)
				width: 'full' 		other options: default
			}
	*/
	backgroundTypeEnum: {
		library: 'Library',
		color: 'Color',
		gallery: 'Gallery'
	}
};

changeHeaderModule.init = function () {
    // set selected settings from hidden fields
    changeHeaderModule.settings.selected.hideTitle = $('#HideTitle').is(':checked');
    changeHeaderModule.settings.selected.font = $('#uxFontHidden').val();
    changeHeaderModule.settings.selected.fontColor = $("#uxHeaderFontColor").val();
    changeHeaderModule.settings.selected.type = $('#hdnType').val();
    changeHeaderModule.settings.selected.data = $('#hdnData').val();
    changeHeaderModule.settings.selected.headerColour = $('#hdnColourData').val();
    changeHeaderModule.settings.selected.height = $('#hdnHeight').val();
    changeHeaderModule.settings.selected.width = $('#hdnWidth').val();
    changeHeaderModule.settings.selected.mobileHeaderData = $('#hdnMobileHeaderData').val();
    changeHeaderModule.settings.selected.mobileView = false;
    changeHeaderModule.settings.selected.noMobileHeader = $('#NoMobileHeader').is(':checked');
    changeHeaderModule.settings.selected.noHeaderImage = $('#NoHeaderImage').is(':checked');

    changeHeaderModule.fontSelect.init();
    changeHeaderModule.colorSelect.init();
    changeHeaderModule.hideTitle.init();
    changeHeaderModule.background.init(); 
    changeHeaderModule.size.init();
    sportsground.cms.imageGallery.fileupload.init(changeHeaderModule.fileUploadCompletedCallback);
    changeHeaderModule.noMobileHeader.init();
    changeHeaderModule.noHeaderImage.init();

	$("#cntLibrary").on("click", ".library-folder", function () {
		if ($(this).data("mylibrary") == true) {
			sportsground.cms.library.attachEditIconVisibilityHandlers();
		} else {
			sportsground.cms.library.detachEditIconVisibilityHandlers();
		}
	});

	$('#btnSaveHeader').on('click', changeHeaderModule.save);
	changeHeaderModule.mobileTabSelect.init();

    // background tranparency
	$("#uxBackgroundTransparencySlider").slider({
	    isRTL: true,
        range: 'false',
        value: -$("#uxBackgroundTransparencyInput").val(),
	    min: -1,
	    max: 0,
	    step: 0.01,
        slide: function (event, ui) {
            $("#uxBackgroundTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
	    }
	});
    $("#uxBackgroundTransparencyInput").val(Math.abs(Math.round($("#uxBackgroundTransparencyInput").val() * 100)) + '%');

    $(".bg-header-colour-tab-item").on('click', function () {
        $('#headerBackgroundColor').simplecolorpicker('destroy');
        changeHeaderModule.background.color.init();
    });

    $(".header-title-tab").on('click', function () {
        $('#uxHeaderFontColor').simplecolorpicker('destroy');
        changeHeaderModule.colorSelect.init();
    });
};

changeHeaderModule.fontSelect = {
	init: function() {
		// init font select dropdown
		$('#fontSelect').fontSelector({
			'hide_fallbacks': true,
			'initial': changeHeaderModule.settings.selected.font + ',' + changeHeaderModule.settings.selected.font,
			'selected': function(style) {
				changeHeaderModule.fontSelect.fontChanged(style);
			}
		});
		$('#uxFontSelectTrigger').on('click', function() {
			$('#fontSelect').click();
			return false;
		});
	},
	fontChanged: function(style) {
		//$('#uxFontHidden').val(style);
		$('#headerPreviewHeading').css('font-family', style);
		changeHeaderModule.settings.selected.font = style;
	}
};

changeHeaderModule.mobileTabSelect = {
    init: function () {

        $('#tabContainer > li > a').click(function () {

            $("#uxHeaderPreviewWrapper").hide();
            $("#uxHeaderPreviewWrapperMobile").hide();

            if ($(this).hasClass("mobile-header-tab-item")) {

                var bgDiv = ($('#tabBackground .wrapper-header-image-picker')).detach();
                $("#tabMobile").append(bgDiv);

                $("#rbColor").hide();
                $("#rbColorLabel").hide();

                $("#uxHeaderPreviewWrapper").hide();
                $("#uxHeaderPreviewWrapperMobile").show();

                changeHeaderModule.settings.selected.mobileView = true;

                $("#rbLibrary").trigger('click');
            }
            else if ($(this).hasClass("bg-header-tab-item"))
            {
                if ($("#tabBackground").has(".wrapper-header-image-picker"))
                {
                    var mobileDiv = ($('#tabMobile .wrapper-header-image-picker')).detach();
                    $("#tabBackground").append(mobileDiv);
                }                 

                $("#uxHeaderPreviewWrapper").show();
                $("#uxHeaderPreviewWrapperMobile").hide();

                $("#rbColor").show();
                $("#rbColorLabel").show();

                changeHeaderModule.settings.selected.mobileView = false;
            }
            else {

                $("#uxHeaderPreviewWrapper").show();
                $("#uxHeaderPreviewWrapperMobile").hide();

                changeHeaderModule.settings.selected.mobileView = false;
            }
        });
    }
};

changeHeaderModule.colorSelect = {
    init: function () {
		var tbFontColor = $("#uxHeaderFontColor");
		tbFontColor.simplecolorpicker(
			{
				trigger: 'uxHeaderFontColorTrigger',
				selectedColor: $("#uxHeaderFontColor").val()
			});
        tbFontColor.on('change', function () {
            changeHeaderModule.colorSelect.colorChanged($(this).val());
		});
		$('#headerPreviewHeading').css('color', changeHeaderModule.settings.selected.fontColor);
	},
    colorChanged: function(color) {	 
		$('#headerPreviewHeading').css('color', color);
		changeHeaderModule.settings.selected.fontColor = color;
	}
};

changeHeaderModule.hideTitle = {
	init: function() {
		var hideTitleCheckbox = $('#HideTitle');
		if (hideTitleCheckbox.is(':checked'))
		    $('#headerPreviewHeading').hide();
		    $('#headerPreviewHeadingMobile').hide();
		hideTitleCheckbox.on('change', function() {
		    changeHeaderModule.hideTitle.hideTitleChanged($(this).is(':checked'));
		});
	},
	hideTitleChanged: function(value) {
		if (value)
			$('#headerPreviewHeading').hide();
		else
			$('#headerPreviewHeading').show();
		changeHeaderModule.settings.selected.hideTitle = value;
	}
};

changeHeaderModule.noMobileHeader = {
    init: function () {
        var noMobileHeaderCheckbox = $('#NoMobileHeader');
        noMobileHeaderCheckbox.on('change', function () {
            changeHeaderModule.noMobileHeader.noMobileHeaderChanged($(this).is(':checked'));
        });
    },
    noMobileHeaderChanged: function (value) {
        changeHeaderModule.settings.selected.noMobileHeader = value;
    }
};

changeHeaderModule.noHeaderImage = {
    init: function () {
        var noHeaderImageCheckbox = $('#NoHeaderImage');
        noHeaderImageCheckbox.on('change', function () {
            changeHeaderModule.noHeaderImage.noHeaderImageChanged($(this).is(':checked'));
        });
    },
    noHeaderImageChanged: function (value) {
        changeHeaderModule.settings.selected.noHeaderImage = value;

        var wrapperDiv = $('#uxHeaderPreviewWrapper');

        if (changeHeaderModule.settings.selected.noHeaderImage) {
            wrapperDiv.css('background-image', '');
            wrapperDiv.css('background-color', changeHeaderModule.settings.selected.headerColour);
        }
        else {
            var timeStamp = $("#hdnHeaderTimeStamp").val();
            wrapperDiv.css('background-image', "url('" + changeHeaderModule.settings.selected.data + "?v=" + timeStamp + "')");
        }
    }
};

changeHeaderModule.background = {
	init: function() {
		changeHeaderModule.background.galleryInitialized = false;
		sportsground.cms.library.init({
			type: 'Header',
			selector: 'library-image',
			click: changeHeaderModule.background.libraryThumbSelect
		});
		$("input:radio[name=rbHeaderSource]").click(function () {
			changeHeaderModule.background.changeTab($(this).val());
		});
		changeHeaderModule.background.color.init();
		// Set the state of the preview
		var timeStamp = $("#hdnHeaderTimeStamp").val();
		var wrapperDiv = $('#uxHeaderPreviewWrapper');
        var scaledHeight = changeHeaderModule.background.scale.getScaledPreviewHeight(changeHeaderModule.settings.selected.height);
        wrapperDiv.css('height', scaledHeight + 'px');
		
		if (changeHeaderModule.settings.selected.type == changeHeaderModule.settings.backgroundTypeEnum.color &&
            changeHeaderModule.settings.selected.noHeaderImage) {
			wrapperDiv.css('background-image', '');
			wrapperDiv.css('background-color', changeHeaderModule.settings.selected.data);
		}
		else if( changeHeaderModule.settings.selected.headerColour != null && changeHeaderModule.settings.selected.noHeaderImage){
		    wrapperDiv.css('background-image', '');
		    wrapperDiv.css('background-color', changeHeaderModule.settings.selected.headerColour);
		}
		else {
		    wrapperDiv.css('background-image', "url('" + changeHeaderModule.settings.selected.data + "?v=" + timeStamp + "')");
			wrapperDiv.css('background-size', wrapperDiv.outerWidth() + 'px ' + scaledHeight + 'px');
		}

		var scaledMobileHeight = changeHeaderModule.background.scale.getScaledMobilePreviewHeight(changeHeaderModule.settings.selected.height);
		var wrapperDivMobile = $('#uxHeaderPreviewWrapperMobile');
		wrapperDivMobile.css('height', scaledMobileHeight + 'px');
		wrapperDivMobile.css('background-image', "url('" + changeHeaderModule.settings.selected.mobileHeaderData + "?v=" + timeStamp + "')");
        wrapperDivMobile.css('background-size', wrapperDivMobile.outerWidth() + 'px ' + scaledMobileHeight + 'px');

        $('#uxHeaderPreviewWrapper').click(changeHeaderModule.background.headerImageEdit);
	},
	scale: {
		getScaledPreviewHeight: function(fullHeight) {
			var previewWidth = $('#uxHeaderPreviewWrapper').outerWidth();
			var scale = previewWidth / changeHeaderModule.size.actualHeaderSize;
			return Math.round(scale * fullHeight);
		},
		getScaledMobilePreviewHeight: function (fullHeight) {
		    var previewWidth = $('#uxHeaderPreviewWrapperMobile').outerWidth();
		    var scale = previewWidth / changeHeaderModule.size.actualMobileHeaderSize;
		    return Math.round(scale * fullHeight);
		},
		getFullSizeFromPreviewHeight: function(preveiwHeight) {
			var previewWidth = $('#uxHeaderPreviewWrapper').outerWidth();
			return Math.round(preveiwHeight / (previewWidth / changeHeaderModule.size.actualHeaderSize));
		}
	},
    libraryThumbSelect: function () {

        var url = $(this).find('img').attr('src').replace('_ht', '');
        $('#hdnHeaderImage').removeAttr('src');

	    if (changeHeaderModule.settings.selected.mobileView) {
	        var wrapperDiv = $('#uxHeaderPreviewWrapperMobile');
	        wrapperDiv.css('background-image', "url('" + url + "')");
	        $('#uxHeaderPreviewWrapper').hide();
            changeHeaderModule.settings.selected.mobileHeaderData = url;

            $("#NoMobileHeader").prop('checked', false);
            changeHeaderModule.settings.selected.noMobileHeader = false;
	    }
	    else {
	        var wrapperDiv = $('#uxHeaderPreviewWrapper');
	        wrapperDiv.css('background-image', "url('" + url + "')");
	        $('#uxHeaderPreviewWrapperMobile').hide();
            changeHeaderModule.settings.selected.data = url;

            $("#NoHeaderImage").prop('checked', false);
            changeHeaderModule.settings.selected.noHeaderImage = false;
        }

		// set size back to defaults for image, remove full width if set
		$("#rbHeightOriginal").prop("checked", true).trigger("change");

		changeHeaderModule.settings.selected.type = changeHeaderModule.settings.backgroundTypeEnum.library;

	},
    galleryThumbSelect: function (item) {

        var urlWebOpt = item.find('img').data('src-web-opt');
		var wrapperDiv = $('#uxHeaderPreviewWrapper');

        if (changeHeaderModule.settings.selected.mobileView) {
            wrapperDiv = $('#uxHeaderPreviewWrapperMobile');
            $("#NoMobileHeader").prop('checked', false);
            changeHeaderModule.settings.selected.noMobileHeader = false;
        }
        else {
            $("#NoHeaderImage").prop('checked', false);
            changeHeaderModule.settings.selected.noHeaderImage = false;
        }

		var selectedHeight = changeHeaderModule.size.assertStaticHeight();
		var previewWidth = wrapperDiv.outerWidth();
        wrapperDiv.after('<img id="headerImageEditMode" class="croppable" data-isMobileHeader="' + changeHeaderModule.settings.selected.mobileView + '" src="' + urlWebOpt + '" style="width:' + previewWidth + 'px;" data-height="' + selectedHeight + '"/>');
        wrapperDiv.hide();

		$(document).waitForImages(function() {
		    $('#headerImageEditMode').croppable(function (data) {

                if (data == 'cancel') {
                    return;
                }

		        if (!changeHeaderModule.settings.selected.mobileView)
		        {
                    changeHeaderModule.settings.selected.type = changeHeaderModule.settings.backgroundTypeEnum.gallery;
                    $('#hdnHeaderImage').attr('src', urlWebOpt);
		        }
		        else
		        {
                    changeHeaderModule.settings.selected.mobileHeaderData = data;
		        }

			});
		});
    },
    headerImageEdit: function() {
        if (changeHeaderModule.settings.selected.noHeaderImage) {
            // header image edit will not execute when no header image is set.
            return;
        }
        var scaledHeight = changeHeaderModule.background.scale.getScaledPreviewHeight(changeHeaderModule.settings.selected.height);
        if ($('#hdnHeaderImage').height() > scaledHeight) {
            var url = $('#hdnHeaderImage').attr('src');
            var wrapperDiv = $('#uxHeaderPreviewWrapper');
            var selectedHeight = changeHeaderModule.size.assertStaticHeight();
            var previewWidth = wrapperDiv.outerWidth();
            wrapperDiv.after('<img id="headerImageEditMode" data-isMobileHeader="false" class="croppable" src="' + url + '" style="width:' + previewWidth + 'px;" data-height="' + selectedHeight + '"/>');
            wrapperDiv.hide();
            $('#headerImageEditMode').croppable(function(data) {

                if (data == 'cancel') {
                    changeHeaderModule.size.initRadioHeight(changeHeaderModule.settings.selected.prevRadioHeight);
                    var wrapperDiv = $('#uxHeaderPreviewWrapper');
                    changeHeaderModule.size.setHeightClass(wrapperDiv, changeHeaderModule.size.actualHeaderSize, changeHeaderModule.settings.selected.prevRadioHeight, false, true);
                    return;
                }

                changeHeaderModule.settings.selected.type = changeHeaderModule.settings.backgroundTypeEnum.gallery;
            });
        }
    },
	color: {
		init: function() {
		    $('#headerBackgroundColor').simplecolorpicker({ picker: false });
			$('#headerBackgroundColor').on('change', function() {
				changeHeaderModule.background.color.colorChanged($(this).val());
			});
		},
		colorChanged: function (color) {
			var colorSpan = $('.color[data-color=' + color + ']');
			$('[id^="headerSelectedColorTick"]').remove();
			colorSpan.append('<img id="headerSelectedColorTick" src="/Content/images/check-tick-transparent.png" style="position:absolute;margin-left:2px;margin-top:2px;" />');
			var selectedHeight = changeHeaderModule.size.assertStaticHeight();
			var previewHeight = changeHeaderModule.background.scale.getScaledPreviewHeight(selectedHeight);
			var wrapperDiv = $('#uxHeaderPreviewWrapper');
			
			if (changeHeaderModule.settings.selected.noHeaderImage) {
			    wrapperDiv.css('background-image', '');
			    wrapperDiv.css('background-color', color);
			    wrapperDiv.css('height', previewHeight + 'px');
			}
			var heading = wrapperDiv.find('#headerPreviewHeading');
			heading.css('line-height', previewHeight + 'px');
            changeHeaderModule.settings.selected.headerColour = color;
            if ( Math.abs($("#uxBackgroundTransparencySlider").slider("option", "value")) == 1 ) {
                $("#uxBackgroundTransparencySlider").slider("option", "value", 0);
                $("#uxBackgroundTransparencyInput").val('0%');
            }
		}
	},
	changeTab: function(value) {
		switch (value) {
			case 'gallery':
				if (!changeHeaderModule.background.galleryInitialized) {
					sportsground.cms.imageGallery.init({
                        useHeaderThumbs: true,
                        container: $("#tabSwitchContainer"),
						loadThumbsCallback: function () {
							$('#cntGallery .gallery-thumb').off('click.headerthumbclick');
							$('#cntGallery .gallery-thumb').on('click.headerthumbclick', function () {
								changeHeaderModule.background.galleryThumbSelect($(this));
							});
						}
					});
					changeHeaderModule.background.galleryInitialized = true;
				}
				$('#cntLibrary').hide();
				$('#cntGallery').show();
				break;
			case 'color':
				$('#cntLibrary').hide();
				$('#cntGallery').hide();
				break;
			default:
				$('#cntGallery').hide();
				$('#cntLibrary').show();
		}
	}
};

changeHeaderModule.size = {
    actualHeaderSize: 1170,
    actualMobileHeaderSize: 585,
	init: function() {
		$("input[type='radio'][name='radioHeight']").on('change', changeHeaderModule.size.changeHeight);
        $("input[type='radio'][name='radioWidth']").on('change', changeHeaderModule.size.changeWidth);
        $('#customHeightPixels').change(function() {
            changeHeaderModule.size.setHeight($(this).val());
        });

		$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
			if (e.target.text === 'Size')
				changeHeaderModule.size.setRadioButtonStates();
		});

        changeHeaderModule.size.initRadioHeight(changeHeaderModule.settings.selected.height);

		changeHeaderModule.size.changeHeight();

		if (changeHeaderModule.settings.selected.width == 'full')
			$('#rbWidthFull').prop("checked", true);

		$("#customHeightPixels").on("click", function() {
			$("#rbHeightCustom").trigger('click');
			$("#customHeightPixels").focus();
		});
	},
	setRadioButtonStates: function() {
		if (changeHeaderModule.settings.selected.type === changeHeaderModule.settings.backgroundTypeEnum.color) {
			$('#rbHeightOriginal').attr('disabled', true);
			$('#rbHeightOriginalLabel').tooltip(
			{
				title: 'This option only applicable when you are using an image for the header.',
				trigger: 'hover',
				placement: 'right'
			});
		}
		else {
			$('#rbHeightOriginal').attr('disabled', false);
			$('#rbHeightOriginalLabel').tooltip('destroy');
		}
    },
    initRadioHeight: function(height) {
        if (height == 0)
            $('#rbHeightNone').prop("checked", true);
        else if (height == 100)
            $('#rbHeightSmall').prop("checked", true);
        else if (height == 150)
            $('#rbHeightMedium').prop("checked", true);
        else if (height == 250)
            $('#rbHeightLarge').prop("checked", true);
        else {
            $('#rbHeightCustom').prop("checked", true);
            $('#customHeightPixels').val(height);
        }
    },
	changeHeight: function() {
        var value = $("input[type='radio'][name='radioHeight']:checked").val();
        changeHeaderModule.settings.selected.prevRadioHeight = changeHeaderModule.settings.selected.height;
    
	    if (!changeHeaderModule.settings.selected.mobileView)
	    {
	        $('#uxHeaderPreviewWrapper').show();
	    }

		if (value === 'small')
			changeHeaderModule.size.setHeight(100);
		else if (value === 'medium')
			changeHeaderModule.size.setHeight(150);
		else if (value === 'large') 
			changeHeaderModule.size.setHeight(250);
		else if (value === 'original') {
			changeHeaderModule.size.setHeightAuto();
		}
		else if (value === 'none') {
		    $('#uxHeaderPreviewWrapper').hide();
		    $('#uxHeaderPreviewWrapperMobile').hide();
			changeHeaderModule.settings.selected.height = 0;
		}
		else if (value === 'custom') {
			var wrapperHeight = $('#uxHeaderPreviewWrapper').outerHeight();
			var fullHeight = changeHeaderModule.background.scale.getFullSizeFromPreviewHeight(wrapperHeight);
			if ($('#customHeightPixels').val().length == 0)
				$('#customHeightPixels').val(fullHeight);
			$('#customHeightPixels').trigger('blur');
			$('#customHeightPixels').focus();
		}

	},
    setHeightAuto: function() {
        var wrapperDiv = $('#uxHeaderPreviewWrapper');
        
        var imageSrc = wrapperDiv.css('background-image')
            .replace(/url\((['"])?(.*?)\1\)/gi, '$2')
            .split(',')[0];

		var image = new Image();
        image.src = imageSrc;
        image.onload = function() {
            changeHeaderModule.size.setHeightClass(wrapperDiv, this.width, this.height, true, false);
		}
	},
    setHeight: function(height) {
	    var wrapperDiv = $('#uxHeaderPreviewWrapper');

        changeHeaderModule.size.setHeightClass(wrapperDiv, changeHeaderModule.size.actualHeaderSize, height, false, false);
    },
    setHeightClass: function(wrapperDiv, width, height, isAuto, isCancel) {
        var heading = wrapperDiv.find('#headerPreviewHeading');
        if (changeHeaderModule.settings.selected.mobileView) {
            heading = wrapperDiv.find('#headerPreviewHeadingMobile');
        }

        var wrapperWidth = wrapperDiv.outerWidth();
        var scaledHeight = (wrapperWidth / width) * height;

        // set height to 100, if height is auto and on mobile view
        if (isAuto && changeHeaderModule.settings.selected.mobileView) {
            height = 100;
            scaledHeight = 100;
        }

        // set styles
        wrapperDiv.css('background-size', wrapperWidth + 'px ' + (isAuto ? 'auto' : scaledHeight + 'px'));
        wrapperDiv.css('height', scaledHeight + 'px');
        heading.css('line-height', scaledHeight + 'px');
        changeHeaderModule.settings.selected.height = height;

        // after computation of height, trigger a headerImageEdit, this will open edit mode after selecting a different height
        if (!isCancel && $('#hdnHeaderImage').attr('src')) {
            changeHeaderModule.background.headerImageEdit();
        }
    },
	changeWidth: function() {
		var value = $("input[type='radio'][name='radioWidth']:checked").val();
		changeHeaderModule.settings.selected.width = value;
	},
	assertStaticHeight: function () {
		var value = $("input[type='radio'][name='radioHeight']:checked").val();
		if (value === 'small')
			return 100;
		else if (value === 'medium')
			return 150;
		else if (value === 'large')
			return 250;
		else if (value === 'custom')
			return $('#customHeightPixels').val();
		else {
			$("#rbHeightMedium").prop("checked", true);
			return 150;
		}
	}
};

changeHeaderModule.save = function () {

    $("#btnSaveHeader i").addClass('fa-spinner');
    $("#btnSaveHeader").attr('disabled', 'disabled');

    changeHeaderModule.settings.selected.headerTransparencyLevel = Math.abs($("#uxBackgroundTransparencySlider").slider("option", "value"));
    changeHeaderModule.settings.selected.imageUrl = $('#hdnHeaderImage').attr('src');

	$.ajax({
		url: '/cms/site/' + $('#SiteId').val() + '/updateheader',
		type: 'POST',
		data: JSON.stringify(changeHeaderModule.settings.selected),
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			$("#myModal").modal('hide');
			location.reload(true);
		}
	});
};

changeHeaderModule.responsive = function () {      
	var h1 = $('#cmsHeader');
	var isTitleVis = $(h1).css("opacity") == "1" ? true : false;
	var isHeaderImageVis = $(".header-image").css("background").indexOf("cms") != -1;
	var wrapper = h1.closest('.header-image');
	var actualWidth = wrapper.outerWidth();
	var fullWidth = 1170;
	var fullPixelFontSize = 36;

	var fullScaleHeight = parseInt(wrapper.data('fullheight'));
	var scale = actualWidth / fullWidth;
	var calculatedHeight = scale * fullScaleHeight;


	if (isHeaderImageVis) {

		h1.css('line-height', calculatedHeight + 'px');
		h1.css('height', calculatedHeight + 'px');

		$(".header-image").css('height', calculatedHeight + 'px');
		$(".header-image").css('background-size', '100%' + calculatedHeight + 'px');

		var calculatedPixelSize = scale * fullPixelFontSize;
		h1.css('font-size', calculatedPixelSize + 'px');

	}
	else {
		$("#cmsHeader").trigger("destroy");
		$("#cmsHeader").css("display", "block")
		$("#cmsHeader").dotdotdot();
		$("#cmsHeader").css("display", "table-cell")
	}
    //need to do this after the header is resized
	changeHeaderModule.stickyMenuAfterHeader();

};

changeHeaderModule.stickyMenuAfterHeader = function () {

    if (!$('body').hasClass('edit') && $(".cms-editor-bar").length == 0) {

        if (!$('.navbar').length) {
            return;
        }

        var stickyNavTop = $('.navbar').offset().top;
        var stickyHeaderTop = $('.header-colour').offset().top;

        var stickyNav = function () {

            var isLocked = $('.navbar').data("islocked") == "False" ? false : true;
            var isMenuAboveHeader = $('.navbar').data("ismenuaboveheader") == "False" ? false : true;

            var screenHeight = $(window).height();
            var navHeight = $(".navbar").height();
            var headerHeight = $(".header-colour").height();

            // get the largest height in the sub menu
            var largestHeightInMenu = 0;
            $('#uxCmsSiteNavigation').find('ul.dropdown-menu').each(function () {
                if ($(this).height() > largestHeightInMenu) {
                    largestHeightInMenu = $(this).height();
                }
            });

            var heightOfMenu = $('#cmsNavigationContainer').height();
            // unlock the menu when any sub menu added with the height of actual menu is greater in height than the viewport height
            if (largestHeightInMenu + heightOfMenu >= $(window).height()) {
                isLocked = false;
            }

            if (isLocked) {

                var width = $(window).width();
                var scrollTop = $(window).scrollTop();

                //if the menu is below the header and sticky
                if (scrollTop > stickyNavTop) {
                    $('.navbar').addClass('sticky');

                    if (!isMenuAboveHeader && width > 767) {
                        $('#cmsContent').css("margin-top", $('.navbar').height());
                    }
    
                    if (width < 768) {

                        if (screenHeight > (navHeight + headerHeight)){
                            $('.navbar').addClass('sticky-mobile');
                        }
                        else {
                            $('.navbar').removeClass('sticky-mobile');
                        }
                    }
                }
                else {
                    $('.navbar').removeClass('sticky');
                    $('.navbar').removeClass('sticky-mobile');

                    if (!isMenuAboveHeader) {
                        $('#cmsContent').css("margin-top", 'auto');
                    }
                }

                //if the menu is above the header and sticky
                if (isMenuAboveHeader) {

                    var offset = ($('.navbar').height() + stickyNavTop) - scrollTop;
                    offset = offset < 0 ? 0 : offset;

                    if (width < 768) {
                        if (scrollTop > stickyNavTop) {
                           
                            if (screenHeight > (navHeight + headerHeight)) {
                                $('.navbar').removeClass('sticky');
                                $('.header-colour').css("margin-top", offset);
                                $('.navbar').addClass('sticky-mobile');
                            }
                            else {
                                $('.navbar').removeClass('sticky');
                                $('.navbar').removeClass('sticky-mobile');
                            }

                        }
                        else {
                            $('.header-colour').css("margin-top", 'auto');
                        }
                    }
                    else {
                        $('.navbar').addClass('sticky');
                        $('.header-colour').css("margin-top", $('.navbar').height());
                    }
                }
             }
        };

        stickyNav();

        $(window).scroll(function () {
            stickyNav();
        });
    }
};

changeHeaderModule.fileUploadCompletedCallback = function () {
    $('#cntGallery .cnt-images').find('.gallery-thumb').removeClass('selected');
    $('#cntGallery .cnt-images').find('.gallery-thumb:first').addClass('selected');

    var uploadedImage = $('#cntGallery .cnt-images').find('.gallery-thumb:first');
    changeHeaderModule.background.galleryThumbSelect($(uploadedImage));
};;
var changeMenuModule = extend(sportsground, 'sportsground.cms.settings.menu');

changeMenuModule.init = function () {
    
	// font select
	var selectedFont = $('#uxFontHidden').val();
	$('#fontSelect').fontSelector({
		'hide_fallbacks': true,
		'initial': selectedFont + ',' + selectedFont,
		'selected': function (style) {
			$('#uxFontHidden').val(style);
		}
	});
	$('#uxFontSelectTrigger').on('click', function () {
		$('#fontSelect').click();
		return false;
	});

	// font size select
	var selectedFontSize = $('#uxFontSizeHidden').val();
	$('#fontSizeSelect').fontSizeSelector({
		'initial': selectedFontSize,
		'selected': function (fontsize) {
			$('#uxFontSizeHidden').val(fontsize);
		}
	});
	$('#uxFontSizeSelectTrigger').on('click', function () {
		$('#fontSizeSelect').click();
		return false;
	});

	// text color
	$("#uxTextColor").simplecolorpicker({ trigger: 'uxTextColorTrigger', selectedColor: $("#uxTextColor").val() });

	// alignment
	var selectedMenuAlignment = $('#uxMenuAlignmentHidden').val();
	$('input[name=MenuAlignment][value=' + selectedMenuAlignment + ']').prop('checked', true).parent().addClass('active');

	// background color
	$("#uxBackgroundColor").simplecolorpicker({ trigger: 'uxBackgroundColorTrigger', selectedColor: $("#uxBackgroundColor").val() });

    //hover color
	$("#uxBackgroundHoverColor").simplecolorpicker({ trigger: 'uxBackgroundHoverColorTrigger', selectedColor: $("#uxBackgroundHoverColor").val() });

	// background tranparency
    $("#uxBackgroundTransparencySlider").slider({
        isRTL: true,
        range: 'false',
		value: -$("#uxBackgroundTransparencyInput").val(),
		min: -1,
		max: 0,
		step: 0.01,
        slide: function (event, ui) {
            $("#uxBackgroundTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
		}
    });
    $("#uxBackgroundTransparencyInput").val(Math.abs(Math.round($("#uxBackgroundTransparencyInput").val() * 100)) + '%');


    $("#uxBackgroundHoverTransparencySlider").slider({
        isRTL: true,
        range: 'false',
	    value: -$("#uxBackgroundHoverTransparencyInput").val(),
	    min: -1,
	    max: 0,
	    step: 0.01,
        slide: function (event, ui) {
            $("#uxBackgroundHoverTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
	    }
    });
    $("#uxBackgroundHoverTransparencyInput").val(Math.abs(Math.round($("#uxBackgroundHoverTransparencyInput").val() * 100)) + '%');

	// submit
    $('#uxSubmitMenuChangesButton').on('click', function () {
        $("#uxSubmitMenuChangesButton i").addClass('fa-spinner');
        $("#uxSubmitMenuChangesButton").attr("disabled", "disabled");

		changeMenuModule.save();
		return false;
    });  

    $("#IsMenuNavigationFullWidth").on('change', function () {
        if ($(this).is(':checked')) {
            $("#FullWidthMenu").prop('checked', 'checked');
        }
        return false;
    });

    changeMenuModule.uploadLogoInit();
   
};

changeMenuModule.setupLogoImage = function () {
    var logo = $(".menu-logo");
    var image = $(".menu-logo img");
    sportsground.cms.link.init(image);
    changeMenuModule.initLogoImage(logo, image);
};

changeMenuModule.initLogoImage = function (widget, image) {
    if (sportsground.cms.link.hasValue()) {
        if ( sportsground.cms.link.isDocument() || sportsground.cms.link.isOnlineForm()) {
            sportsground.cms.link.target = '_blank';
        }
    }
    changeMenuModule.wrapLinkOnImage(widget, image);
};

changeMenuModule.wrapLinkOnImage = function (widget, image) {
    var imageAnchor = $('a', widget);
    if (sportsground.cms.link.hasValue()) {
        if (imageAnchor.length == 0) {
            image.wrap('<a href=""></a>');
            imageAnchor = image.parent();
        }
    } else if (imageAnchor.length > 0) {
        image.unwrap();
    }

    sportsground.cms.link.updateWidget(image, imageAnchor);
};

changeMenuModule.uploadLogoInit = function () {

    var logo = $(".menu-logo img");

    sportsground.cms.link.initEdit(logo, {
        allowNone: false,
        modalLoadingBox: $("#modalLoadingBox"),
        modalLoadedBox: $("#modalLoadedBox")
    });
    
    if ($("#hdnMenuLogo").val() == ""){
        $("#menuLogoLinkCnt").hide();
    }   

    $('#menuLogoImage').click(function () {

        $('#inputUploadImages').trigger('click');
        return false;
    });

    $('.menu-logo-delete').click(function () {

        var model = {
            SiteId: $('#SiteId').val()           
        };

        $.ajax({
            url: '/cms/site/deletemenulogo',
            type: 'POST',
            data: JSON.stringify(model),
            contentType: 'application/json; charset=utf-8',
            success: function (data, textStatus, xhr) {
                var ticks = (($.now() * 10000) + 621355968000000000);
                var imageElem = $("#logo-container").find("img");
                imageElem.attr("src", '/Content/images/add-logo.png');

                $(".menu-logo-delete").hide();
                $("#menuLogoLinkCnt").hide();
            }
        });

        return false;
    });

    $('#inputUploadImages').fileupload({
        add: function (e, data) {
            var uploadErrors = [];
            var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
            if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                uploadErrors.push('Not an accepted file type');
            }
            if (data.originalFiles[0]['size'] > 20000000) {
                uploadErrors.push('Filesize is too big');
            }
            if (uploadErrors.length > 0) {
                alert(uploadErrors.join("\n"));
            } else {
                data.formData = {
                    organisationId: $("#OrganisationId").val(),
                    siteId: $("#SiteId").val(),
                    mimeType: data.originalFiles[0]['type']
                }
                data.submit();
            }
        },
        dataType: 'json',
        url: '/Asset/UploadMenuLogo',
        maxFileSize: 20000000,
        done: function (e, data) {
            $("#hdnHasUpdatedLogo").val(true);
            $("#hdnLogoFileExtension").val(data.result.substr((data.result.lastIndexOf('.') + 1)));

            // there are 10000 .net ticks per millisecond PLUS the number of .net ticks at the unix epoch
            var ticks = (($.now() * 10000) + 621355968000000000);
            var imageElem = $("#logo-container").find("img");
            imageElem.attr("src", data.result + "?ts=" + ticks);
            imageElem.show();

            $(".menu-logo-delete").show();
            $("#menuLogoLinkCnt").show();
        }
    });

}


changeMenuModule.save = function () {

    sportsground.cms.link.refresh();

	var model = {
		SiteId: $('#SiteId').val(),
		PageId: $('#PageId').val(),
		MenuTextFont: $('#uxFontHidden').val().split(',')[0],
		MenuTextColor: $('#uxTextColor').val(),
		MenuFontSize: $('#uxFontSizeHidden').val(),
		MenuAlignment: $('input[name=MenuAlignment]:checked').val(),
		MenuHide: $('#MenuHide').prop("checked"),
		BackgroundColor: $('#uxBackgroundColor').val(),
        BackgroundHoverColor: $('#uxBackgroundHoverColor').val(),
        BackgroundTransparency: Math.abs($("#uxBackgroundTransparencySlider").slider("option", "value")),
        MenuHoverTransparency: Math.abs($("#uxBackgroundHoverTransparencySlider").slider("option", "value")),
		IsMenuLockedToTop: $('#StickyMenu').prop("checked"),
		FullWidthMenu: $('#FullWidthMenu').prop("checked"),
        IsMenuAboveHeader: $('#IsMenuAboveHeader').prop("checked"),
        MenuLogoLinkType: sportsground.cms.link.type,
        MenuLogoLinkTarget: sportsground.cms.link.target,
        MenuLogoLinkData: sportsground.cms.link.data,
        IsMenuNavigationFullWidth: $('#IsMenuNavigationFullWidth').prop("checked"),
        IsMegaMenu: $('#IsMegaMenu').prop("checked")
    };
                
	$.ajax({
		url: '/cms/site/changemenu',
		type: 'POST',
		data: JSON.stringify(model),
		contentType: 'application/json; charset=utf-8',
		success: function (data, textStatus, xhr) {
			window.location.reload(true);
		}
	});
};
;
var changeButtonModule = extend(sportsground, 'sportsground.cms.settings.sitebutton');

changeButtonModule.init = function () {
    changeButtonModule.initTransparencies();
    changeButtonModule.initSimpleColor();
    sportsground.cms.stroke.init('sitebtn', 'button-stroke-indicator');
    changeButtonModule.InitFontSize();

    $("#btnChangeSiteButton").on('click', function () {
        changeButtonModule.save();
    });

    $("#buttonHeightDropDownList").on('change', function () {
        if ($(this).val() === "Custom") {
            $(".buttonCustomHeight").removeClass('hidden');
        }
        else {
            $(".buttonCustomHeight").addClass('hidden');
        }
        return false;
    });
};

changeButtonModule.initTransparencies = function () {

    //For Button Color
    $("#uxButtonColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round($("#uxButtonColorTransparencyInput").val() * 100)) + '%');

    //For Button Stroke Color
    $("#uxButtonStrokeTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonStrokeTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round($("#uxButtonStrokeTransparencyInput").val() * 100)) + '%');
};

changeButtonModule.initSimpleColor = function () {
    $("#uxbuttonColor").simplecolorpicker({ trigger: 'uxButtonColorTrigger', selectedColor: $("#uxbuttonColor").val() });
    $("#uxbuttonTextColor").simplecolorpicker({ trigger: 'uxButtonTextTrigger', selectedColor: $("#uxbuttonTextColor").val() });
    $("#uxstrokeColor").simplecolorpicker({ trigger: 'uxstrokeColorTrigger' });
};

changeButtonModule.InitFontSize = function () {
    var selectedFont = $('#uxFontHidden').val();
    if (selectedFont === "")
        selectedFont = $("#hdnFontFamily").val();

    $('#fontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedFont,
        'selected': function (style) {
            $('#uxFontHidden').val(style);
        }
    });
    $('#uxFontSelectTrigger').on('click', function () {
        $('#fontSelect').click();
        return false;
    });
};

changeButtonModule.save = function () {

    $("#btnChangeSiteButton i").addClass('fa-spinner');
    $("#btnChangeSiteButton").attr('disabled','disabled');

    var buttonHeight = $('#txtButtonCustomHeight').val();
    var buttonHeightOption = $("#buttonHeightDropDownList").val();
    if (buttonHeightOption === "Small")
        buttonHeight = 40;
    else if (buttonHeightOption === "Medium")
        buttonHeight = 60;
    else if (buttonHeightOption === "Medium")
        buttonHeight = 90;

    var buttonFont = $('#uxFontHidden').val();
    buttonFont = buttonFont.replace(/"/g, "'");

    var model = {
        SiteId: $('#SiteId').val(),
        ButtonColor: $('#uxbuttonColor').val(),
        ButtonColorTransparency: Math.abs( $('#uxButtonColorTransparencySlider').slider("option", "value") ),
        ButtonStrokeColor: $('#uxstrokeColor').val(),
        ButtonStrokeColorTransparency: Math.abs($('#uxButtonStrokeTransparencySlider').slider("option", "value") ),
        ButtonTextColor: $('#uxbuttonTextColor').val(),
        ButtonHeight: buttonHeightOption,
        ButtonCustomHeight: buttonHeight,
        ButtonFont: buttonFont,
        ButtonFontSize: $("#txtButtonFontSize").val(),
        ButtonUsingSquareCorners: $('#rbSquareCorner').is(':checked'),
        ButtonRadius: $('#txtButtonRadius_sitebtn').val()
    };

    $.ajax({
        url: '/cms/site/changesitebutton',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, xhr) {
            window.location.reload(true);
        }
    });
};


;
var stackerSettingsModule = extend(sportsground, 'sportsground.cms.settings.stacker');

stackerSettingsModule.init = function () {
	stackerSettingsModule.imageGalleryInitialised = false;
    stackerSettingsModule.images = [];
    stackerSettingsModule.tempImages = [];
	var imagesJson = $('#hdnStackerImagesJson').val();
	if (imagesJson.length > 0) {
        stackerSettingsModule.images = $.parseJSON(imagesJson);
        stackerSettingsModule.tempImages = $.parseJSON(imagesJson);
		stackerSettingsModule.loadSelectedImages();
	}

	$('#btnChooseSponsors').on('click', function() {
		$('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function() {
			$('#tabImages_SponsorSelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
		});

        $('#btnDoneSelectingSponsors').show();
        $('#btnCancelSelectingSponsors').show();
		$('#btnCancelStackerSettings').hide();
		$('#btnSaveStackerSettings').hide();

		$("#btnUploadSponsor").show();
		stackerSettingsModule.loadSponsors();
	});

	$('#btnChooseImages').on('click', function () {
		$('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
		});
		$('#modalOrganisationId').val($('#OrganisationId').val());
        $('#btnDoneSelectingImages').show();
        $('#btnCancelSelectingImages').show();
		$('#btnCancelStackerSettings').hide();
        $('#btnSaveStackerSettings').hide();

		
		var imageGallerySettings = {
            allowEditing: false,
            container: $("#tabImages_gallerySelect"),
			loadThumbsCallback: function () {
				$('.cbImageSelect').off('change.stackerselectimage');
				$('.cbImageSelect').on('change.stackerselectimage', function () {
					var galleryThumb = $(this).parent().parent();
					var id = galleryThumb.data('id');
					var link = galleryThumb.data('link');
					var linkType = "none";
					if (link != "")
						linkType = "url";
                    if (this.checked)
                        stackerSettingsModule.tempImages.push({ id: id, type: 'image', linkType: linkType, linkData: link });
					else if (!this.checked)
                        for (var index = 0; index < stackerSettingsModule.tempImages.length; index++) {
                            if (stackerSettingsModule.tempImages[index].id == id) {
                                stackerSettingsModule.tempImages.splice(index, 1);
								break;
							}
						}
				});

				$('.gallery-thumb-image img').off('click.stackerselectimage');
				$('.gallery-thumb-image img').on('click.stackerselectimage', function () {
					$(this).closest('.gallery-thumb-image').find('.cbImageSelect').trigger('click');
				});

				for (var i = 0; i < stackerSettingsModule.images.length; i++) {
					$('#item_' + stackerSettingsModule.images[i].id).find('input').attr('checked', 'checked');
				}
			}
		};
        sportsground.cms.imageGallery.init(imageGallerySettings);
        if (!stackerSettingsModule.imageGalleryInitialised) {
			sportsground.cms.imageGallery.fileupload.init();
			stackerSettingsModule.imageGalleryInitialised = true;
		}
		$(".gallery-action-buttons").show();

		return false;
	});

    $('#btnDoneSelectingImages').on('click', function () {
        stackerSettingsModule.images = stackerSettingsModule.tempImages.slice();
        stackerSettingsModule.hideImageModal();		
		return false;
    });

    $('#btnCancelSelectingImages').on('click', function () {
        stackerSettingsModule.tempImages = stackerSettingsModule.images.slice();
        stackerSettingsModule.hideImageModal();		
        return false;
    });

    $('#btnDoneSelectingSponsors').on('click', function () {
        stackerSettingsModule.images = stackerSettingsModule.tempImages.slice();
        stackerSettingsModule.hideSponsorModal();
        return false;
    });

    $('#btnCancelSelectingSponsors').on('click', function () {
        stackerSettingsModule.tempImages = stackerSettingsModule.images.slice();
        stackerSettingsModule.hideSponsorModal();
        return false;
    });

	$('#btnSaveStackerSettings').on('click', stackerSettingsModule.commitChanges);
};

stackerSettingsModule.hideImageModal = function () {
    $('#tabImages_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#tabImages_imageReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
    });
    $('#btnDoneSelectingImages').hide();
    $('#btnCancelSelectingImages').hide();
    $('#btnCancelStackerSettings').show();
    $('#btnSaveStackerSettings').show();
    stackerSettingsModule.loadSelectedImages();
    $(".gallery-action-buttons").hide();
};

stackerSettingsModule.hideSponsorModal = function () {
    $('#tabImages_SponsorSelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#tabImages_imageReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
    });
    $('#btnDoneSelectingSponsors').hide();
    $('#btnCancelSelectingSponsors').hide();
    $('#btnCancelStackerSettings').show();
    $('#btnSaveStackerSettings').show();
    $("#btnUploadSponsor").hide();
    stackerSettingsModule.loadSelectedImages();
};

stackerSettingsModule.loadSponsors = function() {
	$.ajax({
		url: "/cms/site/" + $("#OrganisationId").val() + "/sponsors",
		type: 'GET',
		success: function (data) {
			// Append sponsor html
			var sponsorListGroup = $('#sponsors-list-group');
			sponsorListGroup.html('');
			if (data.length > 0) {
				// We have sponsors to add. Dooo it
				var template = Handlebars.compile($('#hbtSponsor').html());
				for (var index = 0; index < data.length; index++) {
					var html = template(data[index]);
					sponsorListGroup.append(html);
				}

				$('.cbSponsorSelect').change(function () {
					var id = $(this).closest('div.sponsor').data('id');
                    if (this.checked)
                        stackerSettingsModule.tempImages.push({ id: id, type: 'sponsor', linkNewTab: true });
					else if (!this.checked)
                        for (var index = 0; index < stackerSettingsModule.tempImages.length; index++) {
                            if (stackerSettingsModule.tempImages[index].id == id) {
                                stackerSettingsModule.tempImages.splice(index, 1);
								break;
							}
						}
				});

				$('.sponsor-item img').off('click.stackerselectsponsor');
				$('.sponsor-item img').on('click.stackerselectsponsor', function () {
					$(this).closest('.sponsor-item').find('.cbSponsorSelect').trigger('click');
				});

				for (var i = 0; i < stackerSettingsModule.images.length; i++) {
					$('#sponsor_' + stackerSettingsModule.images[i].id).find('input').attr('checked', 'checked');
				}
			}
			else {
				// No sponsors. Add a message
				var message = "<li style='height:100%;'><h3>You currently have no sponsors loaded</h3></li>";
				sponsorListGroup.append(message);
			}
		}
	});

	$("#btnUploadSponsor").on("click", sportsground.cms.sponsorModule.addNewSponsor);
};

stackerSettingsModule.commitChanges = function () {
	var model = {
		imagesJson: JSON.stringify(stackerSettingsModule.images),
	};

	$.ajax({
		url: '/cms/site/' + $('#SiteId').val() + '/updatestacker',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model),
		success: function (data) {
			if (data.success) {
				$("#myModal").modal('hide');

				// todo: reload any page stackers
				window.location.reload();
			}
		}
	});

};

stackerSettingsModule.loadSelectedImages = function () {
	$('.selected-image-thumb').remove();
	$.ajax({
		url: '/cms/site/' + $('#SiteId').val() + '/getstackercontenturls',
		type: 'POST',
		data: JSON.stringify(stackerSettingsModule.images),
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			var rawHtml = $('#hbtSelectedThumb').html();
			var template = Handlebars.compile(rawHtml);

			for (var i = 0; i < data.length; i++) {
				$('#selectedImagesContainer').append(template(data[i]));
			}

			$('#selectedImagesContainer').sortable({
				cancel: 'input',
				cursor: 'move',
				items: '> .selected-image-thumb',
				handle: '.draghandle',
				update: function () {
					var sortedIds = $('#selectedImagesContainer').sortable('toArray');
					var sortedImages = [];
					for (var si = 0; si < sortedIds.length; si++) {
						for (var ui = 0; ui < stackerSettingsModule.images.length; ui++) {
							if (sortedIds[si] == stackerSettingsModule.images[ui].id) {
								sortedImages[si] = stackerSettingsModule.images[ui];
								break;
							}
						}
					}
					stackerSettingsModule.images = sortedImages;
				}
			});

			$(".selected-image-thumb-sponsor").find(".selected-image-settings").hide();

			$('.selected-image-settings').on('click', function () {
				var imageId = $(this).closest('.selected-image-thumb').attr('id');
				$.ajax({
                    url: '/asset/GetImageAssetUrls',
                    type: 'POST',
                    data: '["' + imageId + '"]',
					contentType: 'application/json; charset=utf-8',
					success: function (data) {
						$('#imgPreview').attr('src', data[0].Src);
					}
				});
				/* ---- Image Link Handlers Here ----- */
				for (var index = 0; index < stackerSettingsModule.images.length; index++) {
					if (stackerSettingsModule.images[index].id == imageId) {
						stackerSettingsModule.currentImageIndex = index;
						break;
					}
				}
				stackerSettingsModule.setLinkHtmlValuesFromJson();

				$("input[type='radio'][name='rbLinkType']").on('change', function () {
					$('.link-settings').hide();
					$('#linkSettings_' + $(this).val()).show();
					stackerSettingsModule.setLinkJsonValuesFromHtml();
				});

                $('#tbLinkUrlLocation').on('blur', function() {
                    sportsground.ui.attachHandlerPrependHttpOnWwwLinks(this);
					stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkData = url;
				});

				sportsground.cms.common.bindRemoveEditModeOnPaste();

				$('#cbLinkUrlNewTab').on('change', function () {
					stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkNewTab = $(this).is(':checked');
				});

				$('#tbLinkEmail').on('blur', function () {
					stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkData = $(this).val();
				});

				$('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
					$('#tabImages_imageSettings').effect('slide', { direction: 'right', mode: 'show' }, 500);
				});
			});

			$('#btnImageSettingsBack').on('click', function () {
				$('#tabImages_imageSettings').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
					$('#tabImages_imageReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
				});
				return false;
			});

			$('.selected-image-delete').on('click', function () {
				var imageId = $(this).closest('.selected-image-thumb').attr('id');
				bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected image from the stacker?</p>', function (result) {
					if (!result)
						return;

					$('#' + imageId).remove();
					for (var index = 0; index < stackerSettingsModule.images.length; index++) {
						if (stackerSettingsModule.images[index].id == imageId) {
							stackerSettingsModule.images.splice(index, 1);
							break;
						}
					}

				});
				return false;
			});
		}
	});
};

stackerSettingsModule.setLinkHtmlValuesFromJson = function () {
	$('.link-settings').hide();
	$('#linkSettings_' + stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkType).show();

	var currentImage = stackerSettingsModule.images[stackerSettingsModule.currentImageIndex];
	$("input[type='radio'][value='" + currentImage.linkType + "']").prop('checked', true);
	$('#tbLinkUrlLocation').val('');
	$('#cbLinkUrlNewTab').prop('checked', false);
	$('#tbLinkEmail').val('');

	switch (currentImage.linkType) {
		case 'url':
			$('#tbLinkUrlLocation').val(stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkData);
			$('#cbLinkUrlNewTab').prop('checked', currentImage.linkNewTab == true);
			break;
		case 'email':
			$('#tbLinkEmail').val(stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkData);
			break;
		default:
	}
};

stackerSettingsModule.setLinkJsonValuesFromHtml = function () {
	stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkType = $('input[name=rbLinkType]:checked').val();
	switch (stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkType) {
		case 'url':
			stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkData = $('#tbLinkUrlLocation').val();
			stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkNewTab = $('#cbLinkUrlNewTab').prop('checked');
			break;
		case 'email':
			stackerSettingsModule.images[stackerSettingsModule.currentImageIndex].linkData = $('#tbLinkEmail').val();
			break;
		default:
	}
};;
var textModule = extend(sportsground, 'sportsground.cms.settings.text');

textModule.init = function () {
	$("#uxTextColor").simplecolorpicker({ trigger: 'uxTextColorTrigger', selectedColor: $("#uxTextColor").val() });

	var selectedFont = $('#uxFontHidden').val();
	$('#fontSelect').fontSelector({
		'hide_fallbacks': true,
		'initial': selectedFont,
		'selected': function (style) {
			$('#uxFontHidden').val(style);
		}
	});

	$('#uxFontSelectTrigger').on('click', function () {
		$('#fontSelect').click();
		return false;
    });

    $('#btnSaveTextModal').on('click', function () {

        $("#btnSaveTextModal i").addClass('fa-spinner');
        $("#btnSaveTextModal").attr('disabled', 'disabled');

        $("#changeTextForm").submit();
    });
};;
var changeWallpaperModule = extend(sportsground, 'sportsground.cms.settings.wallpaper');

changeWallpaperModule.settings = {
	selected: {},
	/*
	 * e.g
	 *	{
	 *		tile: true,
	 *		type: 'gallery',
	 *		data: the wallpaper color of a list of urls of images that are use
	 *		imageIds: guids of images that are use
	 *		
	 *		...
	 *	}
	 */
	backgroundTypeEnum: {
		library: 1,
		color: 3,
        gallery: 2,
        video: 4
	}
};

changeWallpaperModule.init = function () {
	changeWallpaperModule.settings.selected.type = $('#hdnType').val();
    changeWallpaperModule.settings.selected.data = $('#hdnWallpaperData').val();
	changeWallpaperModule.settings.selected.imageId = $('#hdnImageId').val();
	changeWallpaperModule.settings.selected.tile = $('#chkTileWallpaper').is(':checked');
    changeWallpaperModule.settings.selected.bodyColor = $("#hdnBodyColor").val();
    changeWallpaperModule.settings.selected.systemBodyColor = $("#hdnSystemBodyColor").val();
    changeWallpaperModule.settings.selected.bodyTransparency = $("#hdnBodyTransparency").val();
    changeWallpaperModule.settings.selected.systemBodyTransparency = $("#hdnSystemBodyTransparency").val();
	changeWallpaperModule.settings.selected.useMobileColour = $("#hdnUseMobileColour").val();
	changeWallpaperModule.settings.selected.mobileColour = $("#hdnMobileBodyColour").val();
	changeWallpaperModule.settings.selected.isOverlayExcludedFromHomePage = $("#hdnIsOverlayExcludedFromHomePage").val();
	changeWallpaperModule.settings.selected.fullWidthOverlay = $("#hdnFullWidthOverlay").val();
    changeWallpaperModule.settings.selected.systemFullWidthOverlay = $("#hdnSystemFullWidthOverlay").val();

	changeWallpaperModule.galleryInitialized = false;
	changeWallpaperModule.library.init();
	changeWallpaperModule.tabs.init();
	changeWallpaperModule.homepageOverlay.init();
    sportsground.cms.imageGallery.fileupload.init(changeWallpaperModule.fileUploadCompletedCallback);
   
	$("#cntLibrary").on("click", ".library-folder", function () {
		if ($(this).data("mylibrary") == true) {
			sportsground.cms.library.attachEditIconVisibilityHandlers();
		} else {
			sportsground.cms.library.detachEditIconVisibilityHandlers();
		}
	});

	$('#chkTileWallpaper').on('change', function () {
		var isTiled = $('#chkTileWallpaper').is(':checked');
		changeWallpaperModule.setTileOption(isTiled);
	});
	changeWallpaperModule.setTileOption(changeWallpaperModule.settings.selected.tile);

	$('#chkUseMobileColour').on('change', function () {
	    var useMobileColour = $('#chkUseMobileColour').is(':checked');
	    changeWallpaperModule.setMobileColourOption(useMobileColour);
	});
	changeWallpaperModule.setMobileColourOption(changeWallpaperModule.settings.selected.useMobileColour);
       
	$('#btnSaveWallpaper').on('click', changeWallpaperModule.save);
	$("#btnCancelWallpaper").on('click', changeWallpaperModule.loadSettings);

	$('#wallpaperBackgroundColor').simplecolorpicker({ picker: false });
	$('#wallpaperBackgroundColor').on('change', function () {
		var color = $(this).val();
		changeWallpaperModule.settings.selected.type = changeWallpaperModule.settings.backgroundTypeEnum.color;
		changeWallpaperModule.settings.selected.data = color;
		changeWallpaperModule.applyStyling();

		$('#wallpaperSelectedColorTick').remove();
		$('#cntColor .color[data-color=' + color + ']').append('<img id="wallpaperSelectedColorTick" src="/Content/images/check-tick-transparent.png" style="position:absolute;margin-left:2px;margin-top:2px;" />');

	});
	
	$('#mobileWallpaperBackgroundColor').simplecolorpicker({ picker: false });
	$('#mobileWallpaperBackgroundColor').on('change', function () {
	    var color = $(this).val();
	    changeWallpaperModule.settings.selected.mobileColour = color;
	    changeWallpaperModule.setMobileColourOption(true);
	    changeWallpaperModule.applyMobileStyling();

	    $('#wallpaperSelectedColorTick').remove();
	    $('#mobileCntColor .color[data-color=' + color + ']').append('<img id="wallpaperSelectedColorTick" src="/Content/images/check-tick-transparent.png" style="position:absolute;margin-left:2px;margin-top:2px;" />');

	});

	$('#overlayPreview').css('opacity',(1 - changeWallpaperModule.settings.selected.bodyTransparency));
    $("#overlayTransparencySlider").slider({
        isRTL: true,
        range: 'false',
		value: -changeWallpaperModule.settings.selected.bodyTransparency,
		min: -1,
		max: 0,
		step: 0.01,
		slide: function (event, ui) {
            changeWallpaperModule.settings.selected.bodyTransparency = Math.abs( ui.value);
            $('#overlayPreview').css('opacity', (1 - Math.abs(ui.value)));
            $("#uxOverlayTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
		}
    });
    $("#uxOverlayTransparencyInput").val(Math.abs(Math.round($("#uxOverlayTransparencyInput").val() * 100)) + '%');

	$("input:radio[name=overlayColor]").on('change', function () {
		changeWallpaperModule.settings.selected.bodyColor = $(this).val();
		$('#overlayPreview').css('background-color', $(this).val());
    });

    if (changeWallpaperModule.settings.selected.bodyColor == 'black')
        $("#rbOverlayBlack").prop("checked", true).trigger("change");
    else
        $("#rbOverlayWhite").prop("checked", true).trigger("change");


    $('#systemOverlayPreview').css('opacity', (1 - changeWallpaperModule.settings.selected.systemBodyTransparency));
    $("#systemOverlayTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -changeWallpaperModule.settings.selected.systemBodyTransparency,
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            changeWallpaperModule.settings.selected.systemBodyTransparency = Math.abs(ui.value);
            $('#systemOverlayPreview').css('opacity', 1 - Math.abs(ui.value));
            $("#uxSystemOverlayTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxSystemOverlayTransparencyInput").val(Math.round(Math.abs($("#uxSystemOverlayTransparencyInput").val() * 100)) + '%');
    
    $("input:radio[name=systemOverlayColor]").on('change', function () {
        changeWallpaperModule.settings.selected.systemBodyColor = $(this).val();
        $('#systemOverlayPreview').css('background-color', $(this).val());
    });

    $("#rbGallery").on('click', function () {
        changeWallpaperModule.settings.selected.type = changeWallpaperModule.settings.backgroundTypeEnum.gallery;
    });
   

    if (changeWallpaperModule.settings.selected.systemBodyColor == 'black')
		$("#rbSystemOverlayBlack").prop("checked", true).trigger("change");
	else
		$("#rbSystemOverlayWhite").prop("checked", true).trigger("change");
};

changeWallpaperModule.selectImage = function (id, url) {
	var imageId = $(this).data('id');
	$('.selected-tick').hide();
    $('#item_' + imageId).find('.selected-tick').show();

    if (changeWallpaperModule.settings.selected.type == changeWallpaperModule.settings.backgroundTypeEnum.library || changeWallpaperModule.settings.selected.type == "Library") {
        if ($('.wallpaper-thumb').has('input:checked').length > 1) {
            url = $('.wallpaper-thumb').has('input:checked').map(function () { return $(this).find('img').prop('src'); }).get().join();
            var listOfImages = $('.wallpaper-thumb').has('input:checked').map(function () { return $(this).data('id'); }).get();
            id = listOfImages.join();

            if (listOfImages.length > 20) {
                $('#lblExceededMaxImages').show();
                $('#btnSaveWallpaper').attr("disabled", "disabled");
            }
            else {
                $('#lblExceededMaxImages').hide();
                $('#btnSaveWallpaper').removeAttr("disabled");
            }
        }
        changeWallpaperModule.settings.selected.data = url;
        changeWallpaperModule.settings.selected.imageId = id;
	} else {
		changeWallpaperModule.settings.selected.data = sportsground.utils.convertImageSrc(url, 'WEBOPTIMIZED');
		changeWallpaperModule.settings.selected.imageId = id;
	}

	changeWallpaperModule.applyStyling();
};

changeHeaderModule.removeImage = function (id, url) {
    var urls = changeWallpaperModule.settings.selected.data.split(',');
    for (var i = 0; i < urls.length; i++) {
        if (urls[i].replace('https:','') === url.replace(" ", "%20")) {
            urls.splice(i, 1);
        }
        else {
            if (urls[i].indexOf('_t') > 0) {
                urls[i] = urls[i].replace('_t', '');
            }
        }
    }
    changeWallpaperModule.settings.selected.data = urls.join(',');

    var ids = changeWallpaperModule.settings.selected.imageId.split(',');
    for (var i = 0; i < ids.length; i++) {
        if (ids[i] === id) {
            ids.splice(i, 1);
        }
    }
    changeWallpaperModule.settings.selected.imageId = ids.join(',');
};

changeWallpaperModule.library = {
	init: function () {
		sportsground.cms.library.init({
			type: 'Wallpaper',
			selector: 'wallpaper-thumb',
			click: changeWallpaperModule.library.select,
			selected: changeWallpaperModule.settings.selected.imageId
		});
	},
    select: function () {
        changeWallpaperModule.settings.selected.type = changeWallpaperModule.settings.backgroundTypeEnum.library;
        if ($(this).find('.cbImageSelect').is(':checked')) {
            var url = $(this).find('a > img').attr('src').replace('_t', '');
            changeWallpaperModule.selectImage($(this).data('id'), url);
        }
        else {
            if ($('.wallpaper-thumb').has('input:checked').length == 0) {
                changeWallpaperModule.settings.selected.data = $("#hdnWallpaperData").val();
                changeWallpaperModule.settings.selected.imageId = $('#hdnImageId').val();
            }
            else {
                changeHeaderModule.removeImage($(this).data('id'), $(this).find('a > img').attr('src'));
            }
        }
	}
};

changeWallpaperModule.homepageOverlay = {
    init: function () {
        var homepageOverlayCheckbox = $('#IsOverlayExcludedFromHomePage');
        homepageOverlayCheckbox.on('change', function () {
            changeWallpaperModule.homepageOverlay.homepageOverlayChanged($(this).is(':checked'));
        });
        var homepageFullWidthOverlayCheckbox = $('#FullWidthOverlay');
        homepageFullWidthOverlayCheckbox.on('change', function () {
            changeWallpaperModule.homepageOverlay.homepageFullWidthOverlayChanged($(this).is(':checked'));
        });
        var homepageSystemFullWidthOverlayCheckbox = $('#SystemFullWidthOverlay');
        homepageSystemFullWidthOverlayCheckbox.on('change', function () {
            changeWallpaperModule.homepageOverlay.homepageSystemFullWidthOverlayChanged($(this).is(':checked'));
        });
    },
    homepageOverlayChanged: function (value) {
        changeWallpaperModule.settings.selected.isOverlayExcludedFromHomePage = value;
    },
    homepageFullWidthOverlayChanged: function (value) {
        changeWallpaperModule.settings.selected.fullWidthOverlay = value;
    },
    homepageSystemFullWidthOverlayChanged: function (value) {
        changeWallpaperModule.settings.selected.systemFullWidthOverlay = value;
    }
};

changeWallpaperModule.tabs = {
	init: function () {
		$("input:radio[name=rbWallpaperSource]").click(function () {
			changeWallpaperModule.tabs.changeTab($(this).val());
        });

        if ($('#hdnType').val() == "Gallery") {
            $('#rbGallery').click();
        }
        else if ($('#hdnType').val() == "Color") {
            $('#rbColor').click();
        }
        else {
            $('#rbWallpaperLibrary').click();
        }
	},
	changeTab: function (value) {
		switch (value) {
			case 'gallery':
				if (!changeWallpaperModule.galleryInitialized) {
					sportsground.cms.imageGallery.init({
						loadThumbsCallback: function () {
							$('.gallery-thumb').off('click.wallpaperthumbclick');
							$('.gallery-thumb').on('click.wallpaperthumbclick', function () {
								changeWallpaperModule.settings.selected.type = changeWallpaperModule.settings.backgroundTypeEnum.gallery;
								var url = sportsground.utils.convertImageSrc($(this).find('a > img').attr('src'), 'WEBOPTIMIZED');
								changeWallpaperModule.selectImage($(this).data('id'), url);
							});
                        },
                        container: $("#tabSwitchContainer")
					});
					changeWallpaperModule.galleryInitialized = true;
				}
				$('#cntLibrary').hide();
				$('#cntColor').hide();
                $('#cntGallery').show();
                $('#cntVideo').hide();
				break;
			case 'color':
				$('#cntLibrary').hide();
				$('#cntGallery').hide();
                $('#cntColor').show();
                $('#cntVideo').hide();
                break;
            case 'video':
                $('#cntVideo').show();
                $('#cntLibrary').hide();
                $('#cntGallery').hide();
                $('#cntColor').hide();
                changeWallpaperModule.settings.selected.type = changeWallpaperModule.settings.backgroundTypeEnum.video;
                break;
			default:
				$('#cntGallery').hide();
				$('#cntColor').hide();
                $('#cntLibrary').show();
                $('#cntVideo').hide();
		}
	}
}

changeWallpaperModule.setTileOption = function (isChecked) {
	changeWallpaperModule.settings.selected.tile = isChecked;
	changeWallpaperModule.applyStyling();
	$('#hdnBackgroundRepeat').val(isChecked);
};

changeWallpaperModule.setMobileColourOption = function (isChecked) {
    changeWallpaperModule.settings.selected.useMobileColour = isChecked;
    changeWallpaperModule.applyMobileStyling();
    $('#hdnUseMobileColour').val(isChecked);

    if (isChecked == true || isChecked == "True") {
        $('#chkUseMobileColour').prop('checked', true);
        $('.mobileColourThumb').css("background-color", changeWallpaperModule.settings.selected.mobileColour);
        $(".mobileImageThumb").hide();
        $(".mobileColourThumb").show();
    }
    else {        
        $('#chkUseMobileColour').prop('checked', false);
        if (changeWallpaperModule.settings.selected.type == "Color") {
            
            $('.mobileColourThumb').css("background-color", '#' + changeWallpaperModule.settings.selected.data);
            $(".mobileImageThumb").hide();
            $(".mobileColourThumb").show();
        }
        else {
            var url = changeWallpaperModule.settings.selected.data.split(',')[0];           
            $(".mobileImageThumb").css("background", "url('" + url + "')");
            $(".mobileImageThumb").show();
            $(".mobileColourThumb").hide();
        }
    }   
};

changeWallpaperModule.save = function () {
    $("#btnSaveWallpaper i").addClass('fa-spinner');
    $("#btnSaveWallpaper").attr('disabled', 'disabled');
    
    var librarythumbs = $('.wallpaper-thumb').map(function () { return $(this).data('id'); }).get().join();

    if (changeWallpaperModule.settings.selected.type == changeWallpaperModule.settings.backgroundTypeEnum.library &&
        librarythumbs.indexOf($('#hdnImageId').val()) >= 0 ) {
        if ($('.wallpaper-thumb').has('input:checked').length == 0) {
            changeWallpaperModule.settings.selected.data = "";
            changeWallpaperModule.settings.selected.imageId = "";
        }
    }
    
    //save wallpaper urls without http or https
    if (changeWallpaperModule.settings.selected.data != "") {
        var find = 'https:';
        var re = new RegExp(find, 'g');
        changeWallpaperModule.settings.selected.data = changeWallpaperModule.settings.selected.data.replace(re, '');

        find = 'http:';
        re = new RegExp(find, 'g');
        changeWallpaperModule.settings.selected.data = changeWallpaperModule.settings.selected.data.replace(re, '');
    }

	$.ajax({
		url: '/cms/site/' + $('#SiteId').val() + '/updatebackground',
		type: 'POST',
		data: JSON.stringify(changeWallpaperModule.settings.selected),
		contentType: 'application/json; charset=utf-8',
		success: function () {
			$("#myModal").modal('hide');
			location.reload(true);
		}
	});
};

changeWallpaperModule.loadSettings = function () {   
	$.get('/cms/site/' + $('#SiteId').val() + '/wallpapersettings')
		.done(function (data) {
			changeWallpaperModule.settings.selected = data;
			changeWallpaperModule.applyStyling();
		});
};

changeWallpaperModule.applyStyling = function () {
    changeWallpaperModule.applyMobileStyling();
	if (changeWallpaperModule.settings.selected.type == changeWallpaperModule.settings.backgroundTypeEnum.color) {
		$('body').css('background', '');
		$('body').css('background-color', '#' + changeWallpaperModule.settings.selected.data);
	}
	else {
		var url = changeWallpaperModule.settings.selected.data.split(',')[0];
		$('body').css('background-color', '');
		var backgroundStyle = "background:url('" + url + "') ";
		if (changeWallpaperModule.settings.selected.tile)
			backgroundStyle += "repeat;";
		else
			backgroundStyle += "no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url + "', sizingMethod='scale'); -ms-filter: \"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + url + "', sizingMethod='scale')\";";
		$('body').attr('style', backgroundStyle);
	}
};

changeWallpaperModule.applyMobileStyling = function () {
    if (changeWallpaperModule.settings.selected.useMobileColour === true || changeWallpaperModule.settings.selected.useMobileColour === "True") {
        $('body').addClass('mobile-wallpaper');
        $('body').append("<style type='text/css'>@media (max-width: 768px) { .mobile-wallpaper {background: none !important; background-color: " + changeWallpaperModule.settings.selected.mobileColour + " !important;} #supersized { display:none !important; } }</style>");
    }
    else {
        $('body').removeClass('mobile-wallpaper');
        $("#mobileWallPaperStyle").remove();
    }
};

changeWallpaperModule.fileUploadCompletedCallback = function () {
    if ($('#rbWallpaperLibrary').is(':checked')) {
        var uploadedImage = $('#cntLibrary .cnt-images').find('.gallery-thumb:first');
        $(uploadedImage).find('.cbImageSelect').trigger('click');
        var url = $(uploadedImage).find('a > img').attr('src').replace('_t', '');
        //var url = $(uploadedImage).find('a > img').attr('src').replace('_sq', '');
        changeWallpaperModule.selectImage($(uploadedImage).data('id'), url);
    }
    else {
        $('#cntGallery .cnt-images').find('.gallery-thumb').removeClass('selected');
        $('#cntGallery .cnt-images').find('.gallery-thumb:first').addClass('selected');

        var uploadedImage = $('#cntGallery .cnt-images').find('.gallery-thumb:first');
        var url = sportsground.utils.convertImageSrc($(uploadedImage).find('a > img').attr('src'), 'WEBOPTIMIZED');
        changeWallpaperModule.selectImage($(uploadedImage).data('id'), url);
    }
};
;
var widgettoolboxModule = extend(sportsground, 'sportsground.cms.settings.widgettoolbox');

widgettoolboxModule.initEventHandlers = function () {

    // Widget Toolbox Modal - Click on a Widget
    $(document).on('click', '.add-widget-select', function () {
        if (sportsground.cms.widgets.addingState) return false;
        sportsground.cms.widgets.addingState = true;

        if ($(this).hasClass("disabled")) {
            sportsground.cms.widgets.addingState = false;
            return false;
        }

        sportsground.cms.widgets.create({
            widgetType: $(this).data('id'),
            splitterPlaceholder: $('#widgetToolboxModal').data('splitterPlaceholder'),
            splitterId: $('#widgetToolboxModal').data('splitterId'),
            splitterType: $('#widgetToolboxModal').data('splittertype'),
            containerId: $('#widgetToolboxModal').data('domId')
        });

        return false;
    });

    $(document).on('click', '#toolbox-widget-Directory.disabled', function () {
        bootbox.dialog({
            title: "Premium Feature",
            message: "<p>If enabled, this lets you display a searchable directory with up to two search filters (eg 'Suburb' and 'Sport')."
                + " Your website visitors can use these filters to return directory results relevant to them."
                + " You can display an input form and let people add themselves to your directory if you wish."
                + " Otherwise you can simply login to manage the directory database yourself.</p>"
                + "<p>This is a premium feature, priced at $950 + GST (once only set-up) plus $595 + GST per year ongoing.</p>",
            buttons: {
                cancel: {
                    label: 'Cancel',
                    className: "btn-info"
                },
                enquire: {
                    label: 'Enquire',
                    className: "btn-success",
                    callback: function () {
                        if (sportyApp.country == 'Nz') {
                            window.open('https://www.sporty.co.nz/viewform/76060?returnUrl=www.sporty.co.nz', '_blank');
                        }
                        else {
                            window.open('https://www.sporty.com.au/viewform/148?returnUrl=www.sporty.com.au', '_blank');
                        }
                    }
                }
            }
        });
    });

    $(document).on('click', '#toolbox-widget-CodeSnippet', function () {
        if ($(this).hasClass('disabled')) {
            bootbox.dialog({
                title: "Premium Feature",
                message: "There is the ability to add code within a page on your website to introduce extra functionality."
                    + " Contact support@sportsground.com for assistance if you wish to have a code snippet added to your web page. Support fees may apply.",
                buttons: {
                    close: {
                        label: 'Close',
                        className: "btn-info"
                    }
                }
            });
        }
    });

    $(document).on('click', '#toolbox-widget-KamarNotices.disabled', function () {
        bootbox.dialog({
            title: "Premium Feature",
            message: "<p>For schools using KAMAR. If enabled, this widget lets you display your KAMAR notices automatically within your website."
                + "When new notices are added to KAMAR they can instantly display in your KAMAR notice feed.</p> ",
            buttons: {
                cancel: {
                    label: 'Cancel',
                    className: "btn-info"
                },
                enquire: {
                    label: 'Enquire',
                    className: "btn-success",
                    callback: function () {
                        if (sportyApp.country == 'Nz') {
                            window.open('https://www.sporty.co.nz/viewform/1551?returnUrl=www.schoolground.co.nz', '_blank');
                        }
                    }
                }
            }
        });
    });

    $(document).on('click', '#toolbox-widget-KamarCalendar.disabled', function () {
        bootbox.dialog({
            title: "Premium Feature",
            message: "<p>Display your school calendar from KAMAR live within your website. Whenever you update your calendar in KAMAR it will automatically update on your site."
                + "This is a premium feature. Please contact the Sporty Sales team to activate.</p> ",
            buttons: {
                cancel: {
                    label: 'Cancel',
                    className: "btn-info"
                },
                enquire: {
                    label: 'Enquire',
                    className: "btn-success",
                    callback: function () {
                        if (sportyApp.country == 'Nz') {
                            window.open('https://www.sporty.co.nz/viewform/1551?returnUrl=www.schoolground.co.nz', '_blank');
                        }
                    }
                }
            }
        });
    });

};
;
var buttonModule = extend(sportsground, 'sportsground.cms.widgets.button');

buttonModule.create = function (widgetInstanceId) {

    buttonModule.selectedInitialImage = $("#hdnInitialImage-" + widgetInstanceId).val();
    buttonModule.selectedInitialImageId = $("#hdnInitialImageId-" + widgetInstanceId).val();

    buttonModule.selectedHoverImage = $("#hdnHoverImage-" + widgetInstanceId).val();
    buttonModule.selectedHoverImageId = $("#hdnHoverImageId-" + widgetInstanceId).val();

    var button = "";
    if (buttonModule.selectedInitialImage != "" && buttonModule.selectedInitialImage != undefined) {
        button = $("#dvImageBtnContainer-" + widgetInstanceId).find('a');
    }
    else {
        button = $("#btnButtonWidget-" + widgetInstanceId);
    }
    sportsground.cms.link.init(button);
    sportsground.cms.link.updateWidget(button, button, true);

    buttonModule.bindHoverStateOfTextButton(widgetInstanceId);
    buttonModule.bindHoveStateOfImage(widgetInstanceId);

    buttonModule.initialImage = true;
};

buttonModule.commitChanges = function (widgetInstanceId) {
    // Check the Url starts
    var updatedButtonHoverColor = $("#buttonHoverColorHidden").val();

    if ($("#urlLinkTypeRadio").is(':checked')) {
        var url = $("#urlText").val();
        if (!sportsground.utils.is_valid_url(url)) {
            $("#urlText").closest('.form-group').removeClass('has-success').addClass('has-error');
            return false;
        }
        else {
            $("#urlText").parent('.form-group').removeClass('has-error');
        }
    }

    var imageButtonTabActive = $("#ImageButton_" + widgetInstanceId).hasClass('active');
    var updatedButtonText = $.trim($("#buttonTextText").val());

    //if an Image Tab is active but user has not selected any image, revert to Text Button
    if (imageButtonTabActive && buttonModule.selectedInitialImage === "" && buttonModule.selectedInitialImageId === "") {
        imageButtonTabActive = false;

        if (updatedButtonText === "") { //if button text is not selected as well, show an alert
            bootbox.alert("Set a button text or button image to create a button");
            return false;
        }
    }

    if (!imageButtonTabActive) //we dont want to save these properties if button is a standard button
    {
        buttonModule.selectedInitialImage = "";
        $("#hdnInitialImage-" + widgetInstanceId).val("");
        buttonModule.selectedInitialImageId = "";
        $("#hdnInitialImageId-" + widgetInstanceId).val("");
        buttonModule.selectedHoverImage = "";
        $("#hdnHoverImage-" + widgetInstanceId).val("");
        buttonModule.selectedHoverImageId = "";
        $("#hdnHoverImageId-" + widgetInstanceId).val("");
        $("#chkDarkenOnHover").prop("checked", false);
    }

    var updatedButtonColorTransparency = Math.abs($('#uxButtonColorTransparencySlider').slider("option", "value"));

    $.ajax({
        url: "/cms/site/darkencolor/" + encodeURIComponent($("#buttonColorText").val()) + "?transparency=" + updatedButtonColorTransparency,
        success: function (data, textStatus, xhr) {
            sportsground.cms.link.refresh();

            var updatedButtonColor = $("#buttonColorText").val();
            var updatedButtonHeight = $("#buttonHeightDropDownList").val();
            var updatedButtonTextColor = $("#buttonTextColorText").val();

            var buttonUsingSquareCorners = $('#rbSquareCorner').is(':checked');
            if (updatedButtonHeight !== "Custom") {
                $("#txtButtonCustomHeight").val(0);
            }

            if (data !== "")
                updatedButtonHoverColor = data;

            var buttonWidth = $("#buttonWidthDropDownList").val();
            if (buttonWidth === "Automatic")
                $("#txtButtonCustomWidth").val(100);// so default for cutom always remain 100%

            if (updatedButtonColorTransparency === null || updatedButtonColorTransparency === undefined)
                updatedButtonColorTransparency = 0;

            var updatedButtonStrokeColorTransparency = Math.abs($('#uxButtonStrokeTransparencySlider').slider("option", "value"));
            if (updatedButtonStrokeColorTransparency === null || updatedButtonStrokeColorTransparency === undefined)
                updatedButtonStrokeColorTransparency = 0;

            var widgetSettings = {
                WidgetId: widgetInstanceId,
                WidgetType: 'Button',
                Settings: {
                    ButtonText: updatedButtonText,
                    ButtonColor: updatedButtonColor,
                    ButtonColorTransparency: updatedButtonColorTransparency,
                    ButtonHoverColor: updatedButtonHoverColor,
                    ButtonStrokeColor: $('#uxstrokeColor').val(),
                    ButtonStrokeColorTransparency: updatedButtonStrokeColorTransparency,
                    ButtonUsingSquareCorners: buttonUsingSquareCorners,
                    ButtonRadius: buttonUsingSquareCorners ? 0 : $("#txtButtonRadius_" + widgetInstanceId).val(),
                    ButtonHeight: updatedButtonHeight,
                    ButtonCustomHeight: $("#txtButtonCustomHeight").val(),
                    ButtonWidth: buttonWidth,
                    ButtonCustomWidth: $("#txtButtonCustomWidth").val(),
                    ButtonFont: $('#uxFontHidden').val(),
                    ButtonFontSize: $("#txtButtonFontSize").val(),
                    ButtonTextColor: updatedButtonTextColor,
                    ButtonLinkType: sportsground.cms.link.type,
                    ButtonLinkData: sportsground.cms.link.data,
                    ButtonLinkTarget: sportsground.cms.link.target,
                    ImageTabSelected: imageButtonTabActive,
                    InitialImageUrl: buttonModule.selectedInitialImage,
                    InitialImageId: buttonModule.selectedInitialImageId,
                    HoverImageUrl: buttonModule.selectedHoverImage,
                    HoverImageId: buttonModule.selectedHoverImageId,
                    DarkenOnHover: $("#chkDarkenOnHover").is(':checked')
                }
            };

            $.ajax({
                url: '/cms/widgets/settings',
                type: 'PUT',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(widgetSettings),
                success: function (data, textStatus, xhr) {
                    if (xhr.status === 202) {
                        $("#modal-dialog").modal('show');
                    }
                    else if (!imageButtonTabActive) { // for button widget we need to get the button color and stroke color after apllying transparency, so getting from backend
                        buttonModule.setUpdatedStyleOnButton(widgetInstanceId);
                    }
                }
            });

            // Update image button with the new fields
            if (imageButtonTabActive) {
                var $button = $("#dvImageBtnContainer-" + widgetInstanceId).find('a');
                $("#btnButtonWidget-" + widgetInstanceId).addClass('hidden');
                $("#dvImageBtnContainer-" + widgetInstanceId).removeClass('hidden');

                $("#hdnInitialImage-" + widgetInstanceId).val(buttonModule.selectedInitialImage);
                $("#hdnInitialImageId-" + widgetInstanceId).val(buttonModule.selectedInitialImageId);
                $button.find('img').attr('src', buttonModule.selectedInitialImage);
                $button.find('img').attr('data-id', buttonModule.selectedInitialImageId);

                if (buttonModule.selectedHoverImage != "") {
                    $("#hdnHoverImage-" + widgetInstanceId).val(buttonModule.selectedHoverImage);
                    $("#hdnHoverImageId-" + widgetInstanceId).val(buttonModule.selectedHoverImageId);
                }
                else {
                    $("#hdnHoverImage-" + widgetInstanceId).val('');
                    $("#hdnHoverImageId-" + widgetInstanceId).val('');
                }

                if (widgetSettings.Settings.DarkenOnHover) {
                    $("#dvImageBtnContainer-" + widgetInstanceId).addClass('black-background');
                    $button.find('img').addClass('hoverImg');
                }
                else {
                    $("#dvImageBtnContainer-" + widgetInstanceId).removeClass('black-background');
                    $button.find('img').removeClass('hoverImg');
                }
                sportsground.cms.link.updateWidget($button, $button, true);
                $("#myModal").modal('hide');
            }
        }
    });


};

buttonModule.setUpdatedStyleOnButton = function (widgetInstanceId) {
    $.ajax({
        url: "/cms/widgets/widgetSettings?id=" + widgetInstanceId,
        success: function (data, textStatus, xhr) {
            if (data !== null) {
                $("#dvImageBtnContainer-" + widgetInstanceId).addClass('hidden');
                var $button = $("#btnButtonWidget-" + widgetInstanceId);
                $button.removeClass('hidden');
                $button.html(data.ButtonText);

                $button.attr('style', '');
                $button.attr('style', data.ButtonWidgetStyle);

                $button.data("color", data.ButtonColorAfterTransparency);
                $button.data("text-color", data.ButtonTextColor);
                $button.data("hover-color", data.ButtonHoverColor);

                $button.removeClass().addClass("btn btnWidget");
                $button.addClass(data.ButtonHeightClass);
                $button.data("height", data.ButtonHeight);


                sportsground.cms.link.updateWidget($button, $button, true);

                $("#myModal").modal('hide');
            }
        }
    });
};

buttonModule.modalCreated = function (widgetInstanceId) {

    $("#widget-edit-modal-Button").addClass('modal-lg');
    buttonModule.imageGalleryInitialised = false;

    buttonModule.selectedInitialImage = $("#hdnInitialImage-" + widgetInstanceId).val();
    buttonModule.selectedInitialImageId = $("#hdnInitialImageId-" + widgetInstanceId).val();

    buttonModule.selectedHoverImage = $("#hdnHoverImage-" + widgetInstanceId).val();
    buttonModule.selectedHoverImageId = $("#hdnHoverImageId-" + widgetInstanceId).val();

    var $pageButton = "";
    if (buttonModule.selectedInitialImage !== "" && buttonModule.selectedInitialImage !== undefined) {
        $pageButton = $("#dvImageBtnContainer-" + widgetInstanceId).find('a');
    }
    else {
        $pageButton = $("#btnButtonWidget-" + widgetInstanceId);
    }

    buttonModule.InitTransparencies(widgetInstanceId);
    buttonModule.InitFontSize();

    // init simple color picker
    $("#buttonColorText").simplecolorpicker({ trigger: 'uxButtonColorTrigger' });
    $("#buttonTextColorText").simplecolorpicker({ trigger: 'uxButtonTextColorTrigger' });
    $("#uxstrokeColor").simplecolorpicker({ trigger: 'uxstrokeColorTrigger' });

    sportsground.cms.stroke.init(widgetInstanceId, 'btn-widget-stroke-indicator');

    $("#urlText").on('focusout', function () {
        var url = $("#urlText").val();
        if (!sportsground.utils.is_valid_url(url)) {
            $("#urlText").closest('.form-group').removeClass('has-success').addClass('has-error');
            return false;
        }
        else {
            $("#urlText").parent('.form-group').removeClass('has-error');
        }
    });

    $("#buttonHeightDropDownList").on('change', function () {
        if ($(this).val() === "Custom") {
            $(".buttonCustomHeight").removeClass('hidden');
        }
        else {
            $(".buttonCustomHeight").addClass('hidden');
        }
        return false;
    });

    $("#buttonWidthDropDownList").on('change', function () {
        if ($(this).val() === "Automatic") {
            $(".buttonCustomWidth").addClass('hidden');
        }
        else {
            $(".buttonCustomWidth").removeClass('hidden');
        }
        return false;
    });

    buttonModule.InitTabSettings(widgetInstanceId);
    buttonModule.InitImageUpload(widgetInstanceId);


    // init link editing
    sportsground.cms.link.initEdit($pageButton, {
        allowNone: false,
        modalLoadingBox: $("#modalLoadingBox"),
        modalLoadedBox: $("#modalLoadedBox")
    });
};

buttonModule.InitTransparencies = function (widgetInstanceId) {



    $("#uxButtonColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round($("#uxButtonColorTransparencyInput").val() * 100)) + '%');

    //For Button Stroke Color
    $("#uxButtonStrokeTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonStrokeTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round($("#uxButtonStrokeTransparencyInput").val() * 100)) + '%');
};

buttonModule.InitFontSize = function () {
    var selectedFont = $('#uxFontHidden').val();
    if (selectedFont === "")
        selectedFont = $("#hdnFontFamily").val();

    $('#fontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedFont,
        'selected': function (style) {
            $('#uxFontHidden').val(style);
        }
    });
    $('#uxFontSelectTrigger').on('click', function () {
        $('#fontSelect').click();
        return false;
    });
};

buttonModule.InitTabSettings = function (widgetInstanceId) {
    var imageTabSelected = $("#ImageTabSelected_" + widgetInstanceId).val();
    if (imageTabSelected) {

        $("#StandardButton_" + widgetInstanceId).removeClass('active');
        $("#tabStandardButton__" + widgetInstanceId).removeClass('active');
        $("#ImageButton_" + widgetInstanceId).addClass('active');
        $("#tabImageButton_" + widgetInstanceId).addClass('active');


    }
    else {
        $("#ImageButton_" + widgetInstanceId).removeClass('active');
        $("#tabImageButton_" + widgetInstanceId).removeClass('active');
        $("#StandardButton_" + widgetInstanceId).addClass('active');
        $("#tabStandardButton__" + widgetInstanceId).addClass('active');
    }
};

buttonModule.InitImageUpload = function (widgetInstanceId) {
    $('#myModal .modal-footer').append('<div class="pull-left gallery-action-buttons" style="display:none;"><a id="btnUploadImages" href="#"><i class="glyphicon glyphicon-cloud-upload" />&nbsp;&nbsp;Upload an Image</a></div>');

    $('.image-button').on('click', function () {

        if ($(this).attr('disabled') == 'disabled')
            return false;

        if ($(this).hasClass('initial-image-div')) {
            buttonModule.initialImage = true;
        }
        else {
            buttonModule.initialImage = false;
        }

        $('#modalLoadedBox').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
            $('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
        });

        if ($('#btnDoneSelectingImages').length === 0) {
            $('.widget-settings-update').after('<button id="btnCancelSelectingImages" class="btn btn-info">Cancel</button><button id="btnDoneSelectingImages" class="btn btn-primary">Save</button>');

            buttonModule.initGalleryClickHandlers(widgetInstanceId);
        }
        else {
            $('#btnDoneSelectingImages').show();
            $('#btnCancelSelectingImages').show();
        }

        $('.widget-settings-cancel-update').hide();
        $('.widget-settings-update').hide();


        var imageGallerySettings = {
            allowEditing: false,
            loadThumbsCallback: function () {
                buttonModule.setImageClickHandler();
            },
            container: $("#tabImages_gallerySelect")
        };
        var imageId = buttonModule.initialImage ? $('.initial-image').attr('data-id') : $('.hover-image').attr('data-id');
        if (imageId && imageId.length > 0) {
            $.ajax({
                url: '/asset/getcontainerid?assetId=' + imageId,
                type: 'GET',
                async: false,
                success: function (data) {
                    if (data.ContainerId > 0)
                        $('#modalContainerId').val(data.ContainerId);

                    imageGallerySettings.year = data.Year;
                    imageGallerySettings.preselectedFolderId = data.ContainerId;
                    imageGallerySettings.loadThumbsCallback = function () {
                        $('#item_' + imageId).addClass('selected');
                        buttonModule.setImageClickHandler();
                    };

                    sportsground.cms.imageGallery.init(imageGallerySettings);
                }
            });
        }
        else {
            sportsground.cms.imageGallery.init(imageGallerySettings);
        }

        if (!buttonModule.imageGalleryInitialised) {
            sportsground.cms.imageGallery.fileupload.init(buttonModule.fileUploadCompletedCallback);
            buttonModule.imageGalleryInitialised = true;
        }

        $('.gallery-action-buttons').show();

        return false;

    });
};

buttonModule.initGalleryClickHandlers = function (widgetInstanceId) {
    $('#btnCancelSelectingImages').on('click', function () {
        buttonModule.hideImageModal();
    });

    $('#btnDoneSelectingImages').on('click', function () {

        var imageUrl = sportsground.utils.convertImageSrc($(".gallery-thumb-image.selected").find('img').attr('src'), 'WEBOPTIMIZED');
        var imageId = $(".gallery-thumb-image.selected").data('id');
        if (imageUrl != "" && imageUrl != undefined) {

            if (buttonModule.initialImage) {
                if (buttonModule.selectedHoverImage != "" && buttonModule.selectedHoverImage != undefined) {
                    var tempHover = new Image();
                    tempHover.src = buttonModule.selectedHoverImage;
                    tempHover.onload = function () {

                        var tempInitial = new Image();
                        tempInitial.src = imageUrl;

                        tempInitial.onload = function () {
                            if (tempInitial.height == tempHover.height && tempInitial.width == tempHover.width) {
                                buttonModule.selectedInitialImage = imageUrl;
                                buttonModule.selectedInitialImageId = imageId;
                                buttonModule.SetInitialAndHoverImageAndHideModal(widgetInstanceId);
                            }
                            else {
                                bootbox.dialog({
                                    message: "The button image you have selected has greater dimensions than the hover state image previously selected (" + tempHover.width + "px x " + tempHover.height + "px). If you proceed, you will need to select a new hover image.  To choose a different button image, select cancel.",
                                    title: "Warning",
                                    buttons: {

                                        main: {
                                            label: "Cancel",
                                            className: "btn-info"
                                        },
                                        danger: {
                                            label: "Proceed",
                                            className: "btn-primary",
                                            callback: function () {
                                                $(".deleteHoverImage").trigger('click');
                                                buttonModule.selectedInitialImage = imageUrl;
                                                buttonModule.selectedInitialImageId = imageId;
                                                buttonModule.SetInitialAndHoverImageAndHideModal(widgetInstanceId);
                                            }
                                        }
                                    }
                                });
                                return false;
                            }
                        }
                    }
                }
                else {
                    buttonModule.selectedInitialImage = imageUrl;
                    buttonModule.selectedInitialImageId = imageId;
                    buttonModule.SetInitialAndHoverImageAndHideModal(widgetInstanceId);
                }
            }
            else {
                var tempInitial = new Image();
                tempInitial.src = buttonModule.selectedInitialImage;

                tempInitial.onload = function () {

                    var tempHover = new Image();
                    tempHover.src = imageUrl;

                    tempHover.onload = function () {
                        if (tempHover.height == tempInitial.height && tempHover.width == tempInitial.width) {
                            buttonModule.selectedHoverImage = imageUrl;
                            buttonModule.selectedHoverImageId = imageId;
                            buttonModule.SetInitialAndHoverImageAndHideModal(widgetInstanceId);
                        }
                        else {
                            bootbox.alert("Please select an image with dimensions of equal size to your button image(" + tempInitial.width + "px x " + tempInitial.width + "px)");
                            return false;
                        }
                    }
                }
            }

        }
        return false;
    });

    $(".deleteInitialImage").on('click', function () {
        buttonModule.selectedInitialImage = "";
        buttonModule.selectedInitialImageId = "";
        $('.initial-image').addClass('hidden');
        $('.initial-image').attr('data-id', '');
        $('.initial-image img').attr('src', '');
        $("#InitialImage_" + widgetInstanceId).removeClass('hidden');

        buttonModule.selectedHoverImage = "";
        buttonModule.selectedHoverImageId = "";
        $('.hover-image').addClass('hidden');
        $('.hover-image').attr('data-id', '');
        $('.hover-image img').attr('src', '');
        $("#HoverImage_" + widgetInstanceId).removeClass('hidden');
        $("#HoverImage_" + widgetInstanceId).attr('disabled', 'disabled');

        $("#chkDarkenOnHover").attr('disabled', false);

        return false;
    });

    $(".deleteHoverImage").on('click', function () {

        $("#chkDarkenOnHover").attr('disabled', false);

        buttonModule.selectedHoverImage = "";
        buttonModule.selectedHoverImageId = "";
        $('.hover-image').addClass('hidden');
        $('.hover-image').attr('data-id', '');
        $('.hover-image img').attr('src', '');
        $("#HoverImage_" + widgetInstanceId).removeClass('hidden');
        return false;
    });
};

buttonModule.setImageClickHandler = function () {
    $('.cbImageSelect').parent().hide();

    $('.gallery-thumb-image').on('click', function () {
        var id = $(this).closest('.gallery-thumb-image').data('id');
        $('.gallery-thumb-image').removeClass('selected');
        $(this).addClass('selected');
    });

    $('.gallery-thumb-image img').off('click.imageslideshowthumbimghandler');
    $('.gallery-thumb-image img').on('click.imageslideshowthumbimghandler', function () {
        $(this).closest('.gallery-thumb-image').find('.cbImageSelect').trigger('click');
    });
};

buttonModule.SetInitialAndHoverImageAndHideModal = function (widgetInstanceId) {
    if (buttonModule.selectedInitialImage != "") {
        $(".initial-image img").attr('src', buttonModule.selectedInitialImage);
        $(".initial-image").attr('data-id', buttonModule.selectedInitialImageId);

        $("#InitialImage_" + widgetInstanceId).addClass('hidden');
        $(".initial-image").removeClass('hidden');

        $("#HoverImage_" + widgetInstanceId).attr('disabled', false);

        if (sportsground.cms.link.type == "none" || sportsground.cms.link.type == "" || sportsground.cms.link.type == undefined) {
            $("#urlLinkTypeRadio").trigger('click');
        }
    }

    if (buttonModule.selectedHoverImage != "") {

        $("#chkDarkenOnHover").prop('checked', false);
        $("#chkDarkenOnHover").attr('disabled', 'disabled');

        $(".hover-image img").attr('src', buttonModule.selectedHoverImage);
        $(".hover-image").attr('data-id', buttonModule.selectedHoverImageId);

        $("#HoverImage_" + widgetInstanceId).addClass('hidden');
        $(".hover-image").removeClass('hidden');

        if (sportsground.cms.link.type == "none" || sportsground.cms.link.type == "" || sportsground.cms.link.type == undefined) {
            $("#urlLinkTypeRadio").trigger('click');
        }
    }

    buttonModule.hideImageModal();
};

buttonModule.hideImageModal = function () {
    $('#tabImages_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#modalLoadedBox').effect('slide', { direction: 'right', mode: 'show' }, 500);
    });
    $('#btnDoneSelectingImages').hide();
    $('#btnCancelSelectingImages').hide();
    $('.widget-settings-cancel-update').show();
    $('.widget-settings-update').show();
    $('.gallery-action-buttons').hide();
};

buttonModule.bindHoveStateOfImage = function (widgetInstanceId) {
    var button = $("#dvImageBtnContainer-" + widgetInstanceId).find('a');
    button.on({
        mouseenter: function () {
            //stuff to do on mouse enter
            var hoverImageUrl = $("#hdnHoverImage-" + widgetInstanceId).val();
            if (hoverImageUrl != "" && hoverImageUrl != undefined) {
                $(button).find('img').attr('src', hoverImageUrl);
            }
        },
        mouseleave: function () {
            //stuff to do on mouse leave
            var initialImageUrl = $("#hdnInitialImage-" + widgetInstanceId).val();
            if (initialImageUrl != "" && initialImageUrl != undefined) {
                $(button).find('img').attr('src', initialImageUrl);
            }
        }
    });
};

buttonModule.bindHoverStateOfTextButton = function (widgetInstanceId) {
    var button = $("#btnButtonWidget-" + widgetInstanceId);
    button.on({
        mouseenter: function () {
            //stuff to do on mouse enter
            $(this).css("background-color", button.data("hoverColor"));
        },
        mouseleave: function () {
            //stuff to do on mouse leave
            $(this).css("background-color", button.data("color"));
        }
    });
}

buttonModule.getOriginalHeightOfImage = function (url) {
    var height = "";
    $("<img/>", {
        load: function () {
            height = this.width;
        },
        src: url
    });
    return height;
};

buttonModule.fileUploadCompletedCallback = function () {
    $('#cntGallery .cnt-images').find('.gallery-thumb').removeClass('selected');
    $('#cntGallery .cnt-images').find('.gallery-thumb:first').addClass('selected');
};



;
var codeSnippet = extend(sportsground, 'sportsground.cms.widgets.codeSnippet');

codeSnippet.modalCreated = function(widgetInstanceId) {

}
codeSnippet.commitChanges = function (widgetInstanceId) {
	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'CodeSnippet',
		Settings: {
			RawHtml: $("#taCodeSnnipet").val()
		}
	};
	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			$("#myModal").modal('hide');
			$("#code-snippet-" + widgetInstanceId).html($("#taCodeSnnipet").val());
		}
	});
};

;
var clModule = extend(sportsground, 'sportsground.cms.widgets.contactList');

clModule.modalCreated = function (widgetInstanceId) {
	var contacts = [];
	var contactsJson = $('#hdnContacts').val();

	contactsJson = dashboard.htmlDecode(contactsJson);

	if (contactsJson.length > 0) {
		contacts = $.parseJSON(contactsJson);
	}

	var rawHtml = $('#hbtContactDisplay').html();
	var template = Handlebars.compile(rawHtml);
	for (var i = 0; i < contacts.length; i++) {
		contacts[i].sortOrder = i;
		var html = template(contacts[i]);
		$('#tbContacts').append(html);
	}

	clModule.contacts = contacts;
	clModule.handlers.init();
};

clModule.handlers = {
	init: function() {
		$('#tbContacts').on('click', '.btn-delete', clModule.handlers.deleteContactClick);
		$('#tbContacts').on('click', '.btn-edit', clModule.handlers.editContactClick);
		$('#btnAddContact').on('click', clModule.handlers.addContactClick);

		//var options = {
		//	attr: 'sort-n',
		//	order: 'asc'
		//};
		//$('.contact-display-row').tsort(options);
		//items: '> .contact-display-row',
		$('#contact-list-table tbody').sortable({
			cancel: 'input',
			revert: true,
			containment: '#contact-list-table',
			cursor: 'move',
			handle: '.btn-move',
			update: function () {
				var sortedIds = $('#contact-list-table tbody').sortable('toArray', { attribute: "sort-n" });
				var sortedContacts = [];
				for (var si = 0; si < sortedIds.length; si++) {
					for (var ui = 0; ui < clModule.contacts.length; ui++) {
						if (sortedIds[si] == clModule.contacts[ui].sortOrder) {
							sortedContacts[si] = clModule.contacts[ui];
							sortedContacts[si].sortOrder = si;
							break;
						}
					}
				}
				clModule.contacts = sortedContacts;
			}
		});

	},
	addContactClick: function(event) {
		clModule.setButtonStates(false);

		var contact = {
			firstName: '',
			lastName: '',
			designation: '',
			phone1: '',
			phone2: '',
			email: '',
			displayEmail: false
		};

		var rawHtml = $('#hbtContactEdit').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(contact);
		$('#tbContacts').append(html);

		$('#btnContactSave').on('click', clModule.handlers.saveContactClick);
		$('#btnContactCancel').on('click', clModule.handlers.deleteContactClick);

		$.validator.unobtrusive.parseDynamicContent('#myModal form');
		overrideUnobtrusiveDefaults();

		return false;
	},
	saveContactClick: function(event) {
		if (!$('#myModal form').valid())
			return false;

		if ($("#ncFirstName").val() === "" && $("#ncLastName").val() === "" && $("#ncDesignation").val() === "" &&
		  $("#ncPhone1").val() === "" && $("#ncPhone2").val() === "" && $("#ncEmail").val() === "") {
		  return false;
		}

		var contact = {
			firstName: $('#ncFirstName').val(),
			lastName: $('#ncLastName').val(),
			designation: $('#ncDesignation').val(),
			phone1: $('#ncPhone1').val(),
			phone2: $('#ncPhone2').val(),
			email: $('#ncEmail').val(),
			displayEmail: $('#ncDisplayEmail').is(':checked')
		};

		// Add display data to grid
		var rawHtml = $('#hbtContactDisplay').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(contact);
		$(event.currentTarget).closest('tr').replaceWith(html);

		clModule.setButtonStates(true);

		return false;
	},
	deleteContactClick: function(event) {
		$(event.currentTarget).closest('tr').remove();
		clModule.setButtonStates(true);
		return false;
	},
	editContactClick: function(event) {
		clModule.setButtonStates(false);

		var tr = $(event.currentTarget).closest('tr');
		var contact = {
			firstName: $('.tdFirstName', tr).text(),
			lastName: $('.tdLastName', tr).text(),
			designation: $('.tdDesignation', tr).text(),
			phone1: $('.tdPhone1', tr).text(),
			phone2: $('.tdPhone2', tr).text(),
			email: $('.tdEmail', tr).text(),
			displayEmail: $('.tdDisplayEmail input', tr).is(':checked')
		};

		clModule.tempContact = contact;

		var rawHtml = $('#hbtContactEdit').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(contact);
		tr.replaceWith(html);

		$('#btnContactSave').on('click', clModule.handlers.saveContactClick);
		$('#btnContactCancel').on('click', clModule.handlers.cancelEditContactClick);

		$.validator.unobtrusive.parseDynamicContent('#myModal form');
		overrideUnobtrusiveDefaults();

		return false;
	},
	cancelEditContactClick: function (event) {
		var contact = clModule.tempContact;

		var tr = $(event.currentTarget).closest('tr');
		var rawHtml = $('#hbtContactDisplay').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(contact);
		tr.replaceWith(html);

		clModule.setButtonStates(true);
		return false;
	}
}

clModule.setButtonStates = function(enabled) {
	if (enabled) {
		$('.widget-settings-update').removeAttr('disabled');
		$('.btn-delete').removeAttr('disabled');
		$('.btn-edit').removeAttr('disabled');
		$('#btnAddContact').removeAttr('disabled');
	}
	else {
		// disable other actions until this is saved or canceled
		$('#btnAddContact').attr('disabled', 'disabled');
		$('.widget-settings-update').attr('disabled', 'disabled');
		$('.btn-delete').attr('disabled', 'disabled');
		$('.btn-edit').attr('disabled', 'disabled');
	}
};

clModule.create = function (widgetInstanceId) {
	var widget = $('#widget_' + widgetInstanceId);

	var contacts = [];
	var contactsJson = $('.hdnContacts', widget).val();
	if (contactsJson.length > 0) {
		contacts = $.parseJSON(contactsJson);
	}

	var widgetWidth = widget.outerWidth();
	var isFlipTable = false;
	// Check if any contacts have more then 3 fields populated
	for (var i = 0; i < contacts.length; i++) {
		var j = 0;
		var numOfPopulatedFields = 0;
		for (var key in contacts[i]) {
			if (numOfPopulatedFields > 2) {
				break;
			}
			var field = contacts[i][key];
			if (field != null && field.length > 0) {
				numOfPopulatedFields++;
			}
		}
		if (numOfPopulatedFields > 2) {
			// we've made it here and no contacts have more then two fields filled out!
			isFlipTable = false;
			break;
		} else {
			isFlipTable = true;
		}
	}

	// Check if table is less than 760px wide
	widget.removeClass('flip-table-layout');
	if (widgetWidth <= 760 || isFlipTable) {
		widget.addClass('flip-table-layout');
	}

	
	Handlebars.registerHelper('EmailNotEmpty', function (val, options) {
		if (val == null || val == "")
			return options.inverse(this);
		return options.fn(this);
	});

	var rawHtml = $('.hbtContactDisplay', widget).html();
	var template = Handlebars.compile(rawHtml);
	


	$('tbody', widget).html("");
	for (var i = 0; i < contacts.length; i++) {
		var html = template(contacts[i]);
		$('tbody', widget).append(html);
	}

	$.each($(".contactEntry"), function () {
		var displayEmail = $(this).data("displayemail");
		var contactForm = $(this).find(".contact-form");
		var email = $(this).find(".contact-email");
		var contactButton = $(this).find(".btn-contact");
		var isFlipTableFound = $(this).closest(".wContactList").hasClass("flip-table-layout");

	  if (!displayEmail) {
	    //hide email
	    email.remove();
	  }

	  if (displayEmail || (contactButton.length === 0 && isFlipTableFound)) {
	    //hide contact form
	    contactForm.remove();
	  }
	});

	$(widget).find('.btn-contact').on('click', function () {
		var modal = $("#myModal");
		modal.data('eemail', $(this).data('eemail'));
		modal.data('name', $(this).data('name'));
		$('#loading-indicator').show();
		modal.load("/cms/contact", function () {
			modal.one('shown.bs.modal', function () {
				// Start bot timer, if the timer hasn't reached a certain value on form post, assume its a bot.
				clModule.botTimer.init(2);

				$('#contactName').html(modal.data('name'));
				//$('#contactForm').attr('action', '/cms/contact/' + modal.data('eemail'));
				$.validator.unobtrusive.parseDynamicContent('#contactForm');
				overrideUnobtrusiveDefaults();

                $('#btnContactEncryptedSubmit').on('click', function() {
                    if (!clModule.botTimer.isExpired) {
                        //$('#myModal').hide();
                        return false;
                    }

                    if (!$('#contactForm').valid())
                        return false;
                    $.ajax({
                        url: '/cms/contact/' + modal.data('eemail'),
                        type: 'POST',
                        data: $('#contactForm').serialize(),
                        success: function(data) {
                            if (data) {
                                $('#alertSuccess').show();
                                $('#btnContactEncryptedSubmit').hide();
                                $('#dismissButton').removeClass('btn-info').addClass('btn-primary').html('Done');
                            }
                        }
                    });
                });

                // allow multiple click events (btnContactEncryptedSubmit and apply-spinner), and prevent submit event from refreshing page.
                $('#contactForm').on('submit', function() {
                    return false;
                });
			});
			modal.modal({
				backdrop: 'static',
				keyboard: false  // to prevent closing with Esc button (if you want this too)
			}).modal('show');
		});
		return false;
	});
};

clModule.botTimer = {
	init: function(secondsValue) {
		clModule.botTimer.remaining = secondsValue;
		clModule.botTimer.isExpired = false;
		window.setTimeout(function () {
			clModule.botTimer.deduct();
		}, 1000);
	},
	deduct: function () {
		clModule.botTimer.remaining--;
		if (clModule.botTimer.remaining <= 0) {
			clModule.botTimer.isExpired = true;
			return false;
		}
		window.setTimeout(function () {
			clModule.botTimer.deduct();
		}, 1000);
	}
};

clModule.commitChanges = function (widgetInstanceId) {
	// serialise the table body to an array of contacts
	var contacts = $.map($('#tbContacts tr'), function(tr) {
		return {
			firstName: $('.tdFirstName', tr).html(),
			lastName: $('.tdLastName', tr).html(),
			designation: $('.tdDesignation', tr).html(),
			phone1: $('.tdPhone1', tr).html(),
			phone2: $('.tdPhone2', tr).html(),
			email: $('.tdEmail', tr).html(),
			displayEmail: $('.tdDisplayEmail input', tr).is(':checked')
		};
	});

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'ContactList',
		Settings: {
			ContactsJson: JSON.stringify(contacts)
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202)
				$("#modal-dialog").modal('show');
			else
				clModule.rebuildWidget(widgetInstanceId);
		}
	});

	$("#myModal").modal('hide');
};


clModule.rebuildWidget = function (widgetInstanceId) {
	$.ajax({
		url: '/cms/widgets/' + widgetInstanceId + '?em=1',
		type: 'GET',
		success: function (html, textStatus, xhr) {
			var container = $('#widget_' + widgetInstanceId);
			container.replaceWith(html);
			clModule.create(widgetInstanceId);
		}
	});
};;
var directoryModule = extend(sportsground, 'sportsground.cms.widgets.directory');

directoryModule.create = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);
    var organisationFormId = widget.find('.hdnOrgFormId').val();
    var formContainer = widget.find('.site-form-container');
    var formTitle = widget.find('.form-title');

    //set form post
    $.get('/cms/site/getEwa?orgId=' + $("#OrganisationId").val())
        .done(function (data) {

            widget.find('form').attr("action", "/" + data + "/directory");

        });

    //get distinct field responses
    var field1 = widget.find('.hdnFilterField1').val();

    widget.find('#field1').find('option').remove();
    widget.find('#field1').append('<option value="-1">Please Select...</option>');
    widget.find('#field1').append('<option value="0">Select All</option>');

    $.get('/cms/site/formfieldanswers?questionId=' + field1)
        .done(function (data) {
            if (data != null) {
                var fields = data;
                for (var index = 0; index < fields.length; index++) {
                    widget.find('#field1').append('<option value="' + fields[index] + '">' + fields[index] + '</option>');
                }
            }
        });

    widget.find(".filter-select").on("change", function (e) {

        if (widget.find("#field1").val() == -1 || widget.find("#field2").val() == -1 ) {
            widget.find(".directory-btn").attr("disabled", "disabled");
        }
        else {
            widget.find(".directory-btn").removeAttr("disabled");
        }

    });

    var field2 = widget.find('.hdnFilterField2').val();
    widget.find('#field2').find('option').remove();
    widget.find('#field2').append('<option value="-1">Please Select...</option>');
    widget.find('#field2').append('<option value="0">Select All</option>');

    $.get('/cms/site/formfieldanswers?questionId=' + field2)
        .done(function (data) {

            var fields = data;
            for (var index = 0; index < fields.length; index++) {
                widget.find('#field2').append('<option value="' + fields[index] + '">' + fields[index] + '</option>');
            }

        });

    //get field names

    $.get('/cms/site/FormFieldName?questionId=' + field1)
        .done(function (data) {

            widget.find("#field1-label").html(data);

        });

    $.get('/cms/site/FormFieldName?questionId=' + field2)
        .done(function (data) {

            widget.find("#field2-label").html(data);

        });

    widget.find('form').validate({
        submitHandler: function (form) {
            if (widget.find("#field1").val() == 0 && widget.find("#field2").val() == 0) {
                bootbox.dialog({
                    message: 'Please restrict your search to a single ' + widget.find("#field1-label").html() + ' or ' + widget.find("#field2-label").html(),
                    buttons: {
                        close: {
                            label: "Ok",
                            className: "btn-info"
                        }
                    }
                });
            }
            else {
                form.submit();
            }
        }
    });

};

directoryModule.commitChanges = function (widgetInstanceId) {
    var formId = $('#uxForms').val();
    var field1 = $('#uxFilter1').val();
    var field2 = $('#uxFilter2').val();
    var colour = $("#uxColour").val();

    var widget = $('#widget_' + widgetInstanceId);
    widget.find('.hdnOrgFormId').val(formId);
    widget.find('.hdnFilterField1').val(field1);
    widget.find('.hdnFilterField2').val(field2);

    directoryModule.create(widgetInstanceId);

    $("#myModal").modal('hide');

    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'Directory',
        Settings: {
            OrganisationFormId: formId,
            FilterField1: field1,
            FilterField2: field2,
            Colour: colour
        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            widget.find('.no-form-message').hide();
            if (xhr.status === 202) {
                $("#modal-dialog").modal('show');
            }

            location.href = location.href;
        }
    });
};

directoryModule.getFields = function (widgetInstanceId) {

    var widget = $('#widget_' + widgetInstanceId);
    var organisationFormId = $('#uxForms').val();
    var field1 = widget.find('.hdnFilterField1').val();
    var field2 = widget.find('.hdnFilterField2').val();

    if (organisationFormId != "0") {

        $('#uxFilter1').find('option').remove();
        $('#uxFilter1').append('<option value="0">Please Choose a Field</option>');
        $('#uxFilter2').find('option').remove();
        $('#uxFilter2').append('<option value="0">Please Choose a Field</option>');
        $.get('/cms/site/formfields?orgFormId=' + $('#uxForms').val())
            .done(function (data) {

                if (data !== null) {
                    var fields = data[0];
                    for (var index = 0; index < fields.length; index++) {
                        $('#uxFilter1').append('<option value="' + fields[index].Id + '">' + fields[index].Name + '</option>');
                    }

                    $('#uxFilter1').val(field1);

                    for (var index2 = 0; index2 < fields.length; index2++) {
                        $('#uxFilter2').append('<option value="' + fields[index2].Id + '">' + fields[index2].Name + '</option>');
                    }

                    $('#uxFilter2').val(field2);
                }
            });

    }
};

directoryModule.modalCreated = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);
    var organisationFormId = widget.find('.hdnOrgFormId').val();
    var field1 = widget.find('.hdnFilterField1').val();
    var field2 = widget.find('.hdnFilterField2').val();
    var colour = widget.find('.hdnColour').val();

    $("#uxColour").val(colour);

    $.get('/site/getorganisationforms?orgid=' + $('#OrganisationId').val())
        .done(function (data) {
            for (var index = 0; index < data.length; index++) {
                $('#uxForms').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
            }

            $('#uxForms').val(organisationFormId);
            directoryModule.getFields(widgetInstanceId);
        });

    $('#uxForms').change(function (e) {

        directoryModule.getFields(widgetInstanceId);

    });


    $("#uxColour").simplecolorpicker({ trigger: 'uxColourTrigger', selectedColor: colour });

};;
var documentListModule = extend(sportsground, 'sportsground.cms.widgets.documentList');

documentListModule.create = function(widgetInstanceId) {
    var documents = [];
    var documentsJson = "";
    if ($('#hdnDocuments_' + widgetInstanceId).val() != "") {
        documentsJson = $('#hdnDocuments_' + widgetInstanceId).val();
        if (documentsJson.length > 0) {
            documents = $.parseJSON(documentsJson);
            documentListModule.appendContainer(widgetInstanceId, documents);
        }
    }
    else {
        var widgetCategories = [];
        var widgetCategoriesjson = $('#hdnDocumentCategoryIds_' + widgetInstanceId).val();
        if (widgetCategoriesjson != "") {
            widgetCategories = widgetCategoriesjson.split(',');
        }
        documentListModule.getTaggedDocuments(widgetInstanceId, widgetCategories, false);
    }

   
};

documentListModule.appendContainer = function (widgetInstanceId, documents) {
    var widget = $('#widget_' + widgetInstanceId);
    var container = widget.find('.list-group');
    container.html('');

    var template = Handlebars.compile(widget.find('.hbt-document').html());

    for (var i = 0; i < documents.length; i++) {
        container.append(template(documents[i]));
    }

    widget.find('.document-list-item').on('click', function () {
        var url = $(this).data('link');
        if (sportsground.ui.isMobile()) {
            location.href = url;
        }
        else {
            window.open(url, '_blank');
        }
    });
}

documentListModule.modalCreated = function (widgetInstanceId) {
    documentListModule.documentManagerInitialised = false;
    documentListModule.documentsAlreadyAdded = false;
    documentListModule.documents = [];
    documentListModule.TaggedDocuments = [];
	var documentsJson = $('#hdnDocuments').val();
    if (documentsJson.length > 0) {
        documentListModule.documents = $.parseJSON(documentsJson);
        documentListModule.loadSelectedDocuments();
	}
    if ($("#rbSelectCategory").is(":checked")) {
        $('#dvselectCategories').removeClass('hidden');
        $('#dvSelectFiles').addClass('hidden');
    }
    else {
        $('#dvSelectFiles').removeClass('hidden');
        $('#dvselectCategories').addClass('hidden');
    }
    $("#rbSelectCategory").on('click', function () {
        $('#dvselectCategories').removeClass('hidden');
        $('#dvSelectFiles').addClass('hidden');
    });
    $("#rbSelectFiles").on('click', function () {
        $('#dvSelectFiles').removeClass('hidden');
        $('#dvselectCategories').addClass('hidden');
    });

    documentListModule.getDocumentCategories(widgetInstanceId);

	$('#myModal .modal-footer').append('<div class="pull-left gallery-action-buttons" style="display:none;"><a id="btnUploadImages" href="#"><i class="glyphicon glyphicon-cloud-upload" />&nbsp;&nbsp;Upload a Document</a></div>');
	$('#modalOrganisationId').val($('#OrganisationId').val());

	$('#btnChooseDocuments').on('click', function () {
		$('#tabDocuments_galleryReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$('#tabDocuments_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
        });

        if (documentListModule.documents.length > 0) {
            documentListModule.documentsAlreadyAdded = true;
        }
        else {
            documentListModule.documentsAlreadyAdded = false;
        }

		if ($('#btnDoneSelectingDocuments').length == 0) {
			$('.widget-settings-update').after('<button id="btnDoneSelectingDocuments" class="btn btn-primary">Done Selecting Documents</button>');
			$('#btnDoneSelectingDocuments').on('click', function () {
				$('#tabDocuments_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
					$('#tabDocuments_galleryReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
				});
				$('#btnDoneSelectingDocuments').hide();
				$('.widget-settings-cancel-update').show();
				$('.widget-settings-update').show();
				documentListModule.loadSelectedDocuments();
				$(".gallery-action-buttons").hide();
			});
		}
		else
			$('#btnDoneSelectingDocuments').show();

		$('.widget-settings-cancel-update').hide();
		$('.widget-settings-update').hide();

		if (!documentListModule.documentManagerInitialised) {
			var documentManagerSettings = {
                allowEditing: false,
                container: $('#tabDocuments_gallerySelect'),
				loadThumbsCallback: function () {
					var documentContainer = $('tbody.cnt-images');
					documentContainer.off('change.documentlistselect');
					documentContainer.on('change.documentlistselect', '.cbDocumentSelect', function (event) {
						event.stopPropagation();
						var row = $(this).closest('tr');
						var id = row.data('id');
                        if (this.checked) {
                            if (!documentListModule.documentsAlreadyAdded) {
                                documentListModule.documents.push({ id: id, cssClass: row.data('cssclass'), title: row.data('title'), description: '' });
                            }
                            else {
                                documentListModule.documents.unshift({ id: id, cssClass: row.data('cssclass'), title: row.data('title'), description: '' });
                            }
						}
						else if (!this.checked) {
							for (var index = 0; index < documentListModule.documents.length; index++) {
								if (documentListModule.documents[index].id == id) {
									documentListModule.documents.splice(index, 1);
									break;
								}
							}
						}
						return false;
					});

					for (var i = 0; i < documentListModule.documents.length; i++) {
						$('#item_' + documentListModule.documents[i].id).find('input').attr('checked', 'checked');
					}

					documentContainer.off('click.download-document');
					documentContainer.on('click.selectDocCheckbox', '.manager-item', function (e) {
						var documentCb = $(this).find(".cbDocumentSelect");
						if (documentCb.is(":checked")) {
							// uncheck this
							// Correct if removing the attribute is desired
							documentCb.removeAttr("checked");
							// Correct for clearing the checkbox
							documentCb.prop("checked", false);
							documentCb.change();
						} else {
							documentCb.attr("checked", true);
							documentCb.prop("checked", true);
							documentCb.change();
						}
						return false;
					});

					documentContainer.on('click', '.cbDocumentSelect', function(e) {
							e.stopPropagation();					
					});  
				}
			};
			sportsground.cms.documentManager.init(documentManagerSettings);
			documentListModule.documentManagerInitialised = true;
		}
		$(".gallery-action-buttons").show();

		return false;
	});
};

documentListModule.getTaggedDocuments = function (widgetInstanceId, widgetCategories, update) {
    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'DocumentList',
        Settings: {
            IsSelectFilesChecked: $("#rbSelectFiles").is(":checked"),
            DocumentsJson: JSON.stringify(documentListModule.documents),
            CategoryIds: JSON.stringify(widgetCategories)
        }
    };
    $.ajax({
        url: '/cms/documents/documentsbytag',
        type: 'GET',
        data: { tags: widgetCategories.toString() },
        success: function (result) {
            documentListModule.documents = [];
            documentListModule.TaggedDocuments = [];
            for (var i = 0; i < result.length; i++) {
                documentListModule.TaggedDocuments.push({ id: result[i].Id, cssClass: result[i].DocumentCssClass, title: result[i].Name, description: '' });
            }
            widgetSettings.Settings.DocumentsJson = "";
            if (update){
                documentListModule.updateWidgetSettings(widgetSettings);
            }
           
            $('#hdnDocuments_' + widgetInstanceId).val('');
            documentListModule.appendContainer(widgetInstanceId, documentListModule.TaggedDocuments);
        }
    });
}

documentListModule.commitChanges = function (widgetInstanceId) {
    var selectedCategories = [];
    $('#DocumentCategoryIds option:selected').each(function () {
        selectedCategories.push($(this).attr('value'));
    });
    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'DocumentList',
        Settings: {
            IsSelectFilesChecked: $("#rbSelectFiles").is(":checked"),
            DocumentsJson: JSON.stringify(documentListModule.documents),
            CategoryIds:""
        }
    };
    if ($("#rbSelectCategory").is(":checked")) {
        if (selectedCategories.length == 0) {
            bootbox.alert("Please select atleast one category.");
            return false;
        }
        documentListModule.getTaggedDocuments(widgetInstanceId, selectedCategories, true);
    }
    else {
        $("#hdnDocumentCategoryIds").val('');
        documentListModule.updateWidgetSettings(widgetSettings);
        $('#hdnDocuments_' + widgetInstanceId).val(JSON.stringify(documentListModule.documents));
        documentListModule.create(widgetInstanceId);
    }
    $("#myModal").modal('hide');
};

documentListModule.updateWidgetSettings = function (widgetSettings) {
   
    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202) {
                $("#modal-dialog").modal('show');
            }
        }
    });
}

documentListModule.getDocumentCategories = function (widgetInstanceId) {
    var selectList = $('#DocumentCategoryIds');
    selectList.hide();
    $('#dvselectCategories').find('.fa-spinner').show();

    var orgId = $('#OrganisationId').val();
    if (!$.isNumeric(orgId)) {
        return false;
    }

    $.ajax({
        url: '/cms/documents/tagswithcount?oid=' + orgId,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, xhr) {
            $.each(data, function (index, category) {
                selectList.append('<option value="' + category.Id + '">' + category.Name + '</option>');
            });

            selectList.multiselect({
                templates: {
                    button: '<button type="button" class="btn-primary multiselect dropdown-toggle" data-toggle="dropdown"></button>',
                    li: '<li><a href="javascript:void(0);"><label class="old"></label></a></li>'
                }
            }).multiselect('select', $('#hdnDocumentCategoryIds').val().split(','));

            $('#dvselectCategories').find('.fa-spinner').hide();
        }
    });
};

documentListModule.loadSelectedDocuments = function () {
	$('#selectedDocsTbody').html('');

	var template = Handlebars.compile($('#hbtSelectedThumb').html());
	for (var i = 0; i < documentListModule.documents.length; i++) {
		$('#selectedDocsTbody').append(template(documentListModule.documents[i]));
	}

	$('#selectedDocsTbody').sortable({
		cancel: 'input',
		cursor: 'move',
		handle: '.drag',
		update: function () {
			var sortedIds = $('#selectedDocsTbody').sortable('toArray');
			var sortedDocuments = [];
			for (var si = 0; si < sortedIds.length; si++) {
				for (var ui = 0; ui < documentListModule.documents.length; ui++) {
					if (sortedIds[si] == documentListModule.documents[ui].id) {
						sortedDocuments[si] = documentListModule.documents[ui];
						break;
					}
				}
			}
			documentListModule.documents = sortedDocuments;
		}
	});
    

	$(".btn-edit").on('click', function () {
		// Update document title to correspond with asset
		var row = $(this).closest('tr');
		// Hide displays
		row.find('.title').hide();
		var nameInput = row.find('.doc-name');
		// Display inputs and focus on name input
		nameInput.show();
		nameInput.focus();
		$(".btn-edit").hide();
		// Bind handlers for saving
		row.find(".btn-edit-save").show();
		row.find(".btn-edit-save").on('click', function () {
			var id = row.data('id');
			var nameVal = nameInput.val();	
			for (var i = 0; i < documentListModule.documents.length; i++) {
				if (documentListModule.documents[i].id == id) {
					if (nameVal == "") {
						nameVal = documentListModule.documents[i].title;
					}
					documentListModule.documents[i].name = nameVal;
					break;
				}
			}
			$(".btn-edit").show();
			$(this).hide();
			nameInput.hide();
			nameInput.hide();
			nameInput.val(nameVal);
			var titleDisplay = row.find('.title');
			titleDisplay.html(nameVal);
			titleDisplay.show();

			return false;
		});
		return false;
	});

	$(".btn-doc-delete").on('click', function () {
		var row = $(this).closest('tr');
		var id = row.data("id");
		for (var i = 0; i < documentListModule.documents.length; i++) {
			if (documentListModule.documents[i].id == id) {
				documentListModule.documents.splice(i, 1);
				break;
			}
		}
		row.remove();
	});
	//$('.selected-image-delete').on('click', function () {
	//	var imageId = $(this).closest('.selected-image-thumb').attr('id');
	//	bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected image from the slider?</p>', function (result) {
	//		if (!result)
	//			return;

	//		$('#' + imageId).remove();
	//		for (var index = 0; index < imageSlideshowModule.images.length; index++) {
	//			if (imageSlideshowModule.images[index].id == imageId) {
	//				imageSlideshowModule.images.splice(index, 1);
	//				break;
	//			}
	//		}

	//	});
	//	return false;
	//});

};;
var ddModule = extend(sportsground, 'sportsground.cms.widgets.dropdownList');

ddModule.modalCreated = function (widgetInstanceId) {
	var dropdownList = [];
	var dropdownItemsJson = $('#hdnDropdownItems').val();

	dropdownItemsJson = dashboard.htmlDecode(dropdownItemsJson);

	if (dropdownItemsJson.length > 0) {
		dropdownList = $.parseJSON(dropdownItemsJson);
	}

	var rawHtml = $('#hbtDropdownDisplay').html();
	var template = Handlebars.compile(rawHtml);
	for (var i = 0; i < dropdownList.length; i++) {
		dropdownList[i].sortOrder = i;
		var html = template(dropdownList[i]);
		$('#tbDropdownItems').append(html);
	}

	ddModule.dropdownList = dropdownList;
	ddModule.handlers.init();
	var widget = $('#widget_' + widgetInstanceId);	
	sportsground.cms.link.init(widget);

	ddModule.widget = $('#widget_' + widgetInstanceId + " .dropdown-widget");

};

ddModule.handlers = {
	init: function() {
		$('#tbDropdownItems').on('click', '.btn-delete', ddModule.handlers.deleteDropdownClick);
		$('#tbDropdownItems').on('click', '.btn-edit', ddModule.handlers.editDropdownClick);
		$('#btnAddDropdownItem').on('click', ddModule.handlers.addDropdownItemClick);
        		
		$('#dropdown-list-table tbody').sortable({
			cancel: 'input',
			revert: true,
			containment: '#dropdown-list-table',
			cursor: 'move',
			handle: '.btn-move',
			update: function () {
				var sortedIds = $('#dropdown-list-table tbody').sortable('toArray', { attribute: "sort-n" });
				var sortedDropdownlist = [];
				for (var si = 0; si < sortedIds.length; si++) {
					for (var ui = 0; ui < ddModule.dropdownList.length; ui++) {
						if (sortedIds[si] == ddModule.dropdownList[ui].sortOrder) {
							sortedDropdownlist[si] = ddModule.dropdownList[ui];
							sortedDropdownlist[si].sortOrder = si;
							break;
						}
					}
				}
				ddModule.dropdownList = sortedDropdownlist;
			}
		});		
	},
	addDropdownItemClick: function(event) {
		ddModule.setButtonStates(false);

		var dropdown = {
			name: '',
			link: ''
		};

		var rawHtml = $('#hbtDropdownEdit').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(dropdown);
		$('#tbDropdownItems').append(html);

		$('#btnDropdownSave').on('click', ddModule.handlers.saveDropdownClick);
		$('#btnDropdownCancel').on('click', ddModule.handlers.deleteDropdownClick);

		$.validator.unobtrusive.parseDynamicContent('#myModal form');
		overrideUnobtrusiveDefaults();
        	    
		var ddItem = $(this).closest("tr");
		ddModule.editLink(ddItem);

		return false;
	},
	saveDropdownClick: function(event) {
		if (!$('#myModal form').valid())
			return false;

		if ($("#ncName").val() === "" && $("#ncLink").val() === "") {
		  return false;
		}

		linkModule.refresh();
		var ddItem = $(this).closest("tr");
		var ddAnchor = $(this).closest(".dd-anchor");
		linkModule.updateWidget(ddItem, ddAnchor);
		var dropdown = {
		    name: $('#ncName').val(),
		    link: linkModule.url,
		    type: linkModule.type,
		    data: linkModule.data,
		    target: linkModule.target
		};

		// Add display data to grid
		var rawHtml = $('#hbtDropdownDisplay').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(dropdown);
		$(event.currentTarget).closest('tr').replaceWith(html);

		ddModule.setButtonStates(true);

		return false;
	},
	deleteDropdownClick: function(event) {
		$(event.currentTarget).closest('tr').remove();
		ddModule.setButtonStates(true);
		return false;
	},
	editDropdownClick: function(event) {
		ddModule.setButtonStates(false);

		var tr = $(event.currentTarget).closest('tr');
		var dropdown = {
			name: $('.tdName', tr).text(),
			link: $('.tdLink', tr).text()			
		};

		ddModule.tempDropdownItem = dropdown;

		var rawHtml = $('#hbtDropdownEdit').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(dropdown);
		tr.replaceWith(html);

		$('#btnDropdownSave').on('click', ddModule.handlers.saveDropdownClick);
		$('#btnDropdownCancel').on('click', ddModule.handlers.canceleditDropdownClick);

		$.validator.unobtrusive.parseDynamicContent('#myModal form');
		overrideUnobtrusiveDefaults();

		var ddItem = $(this).closest("tr");
		ddModule.editLink(ddItem);

		return false;
	},
	canceleditDropdownClick: function (event) {
		var dropdown = ddModule.tempDropdownItem;

		var tr = $(event.currentTarget).closest('tr');
		var rawHtml = $('#hbtDropdownDisplay').html();
		var template = Handlebars.compile(rawHtml);
		var html = template(dropdown);
		tr.replaceWith(html);

		ddModule.setButtonStates(true);
		return false;
	}
}

ddModule.editLink = function (ddItem) {
    
    // init link editing   
    sportsground.cms.link.initEdit(ddItem, {
        allowNone: true,
        modalLoadingBox: $("#modalLoadingBox"),
        modalLoadedBox: $("#modalLoadedBox")
    });

    $("input[type='radio'][name='linkTypeRadio']").on('change', function () {

        $('.link-settings').hide();
        $('#linkSettings_' + $(this).val()).show();

    });
}

ddModule.setButtonStates = function(enabled) {
	if (enabled) {
		$('.widget-settings-update').removeAttr('disabled');
		$('.btn-delete').removeAttr('disabled');
		$('.btn-edit').removeAttr('disabled');
		$('#btnAddDropdownItem').removeAttr('disabled');
	}
	else {
		// disable other actions until this is saved or canceled
		$('#btnAddDropdownItem').attr('disabled', 'disabled');
		$('.widget-settings-update').attr('disabled', 'disabled');
		$('.btn-delete').attr('disabled', 'disabled');
		$('.btn-edit').attr('disabled', 'disabled');
	}
};

ddModule.create = function (widgetInstanceId) {

    //go to the link when changing dropdown item
    $('#widget_' + widgetInstanceId + " .dropdown-widget").change(function (e) {

        var selected = $('#widget_' + widgetInstanceId + " .dropdown-widget option:selected");
        var target = selected.data("link-target");
        var data = selected.data("link-data");
        var type = selected.data("link-type");

        //do not redirect page when all data-property are empty
        if ( !target && !data && !type ) {
            e.preventDefault();
            return;
        }

        var url = $(this).val();
        //if safari browser (doesn't matter if desktop/mobile), only redirect to self works (onchange event of select html)
        if (sportsground.cms.common.isSafari()) {
            location.href = url;
        }
        else {
            //only use window open if is not mobile, and user has selected to open in a new tab/window on the dropdown widget settings
            if (!sportsground.ui.isMobile() && target == '_blank') {
                var newWin = window.open(url, '_blank');
                if (!newWin || newWin.closed || typeof newWin.closed == 'undefined') {
                    //POPUP BLOCKED
                    location.href = url;
                }
            }
            else {
                location.href = url;
            }
        }

    });

	var widget = $('#widget_' + widgetInstanceId);

	var dropdownList = [];
	var dropdownItemsJson = $('.hdnDropdownItems', widget).val();
	if (dropdownItemsJson.length > 0) {
		dropdownList = $.parseJSON(dropdownItemsJson);
	}

	var widgetWidth = widget.outerWidth();
	var isFlipTable = false;
	// Check if any dropdownList have more then 3 fields populated
	for (var i = 0; i < dropdownList.length; i++) {
		var j = 0;
		var numOfPopulatedFields = 0;
		for (var key in dropdownList[i]) {
			if (numOfPopulatedFields > 2) {
				break;
			}
			var field = dropdownList[i][key];
			if (field != null && field.length > 0) {
				numOfPopulatedFields++;
			}
		}
		if (numOfPopulatedFields > 2) {
			// we've made it here and no dropdownList have more then two fields filled out!
			isFlipTable = false;
			break;
		} else {
			isFlipTable = true;
		}
	}

	// Check if table is less than 760px wide
	widget.removeClass('flip-table-layout');
	if (widgetWidth <= 760 || isFlipTable) {
		widget.addClass('flip-table-layout');
	}
	
	Handlebars.registerHelper('EmailNotEmpty', function (val, options) {
		if (val == null || val == "")
			return options.inverse(this);
		return options.fn(this);
	});
    
	$.each($(".dropdownEntry"), function () {
		var displayEmail = $(this).data("displayemail");
		var dropdownForm = $(this).find(".dropdown-form");
		var email = $(this).find(".dropdown-email");
		var dropdownButton = $(this).find(".btn-dropdown");
		var isFlipTableFound = $(this).closest(".wDropdownList").hasClass("flip-table-layout");

	  if (!displayEmail) {
	    //hide email
	    email.remove();
	  }

	  if (displayEmail || (dropdownButton.length === 0 && isFlipTableFound)) {
	    //hide dropdown form
	      dropdownForm.remove();
	  }
	});
};

ddModule.commitChanges = function (widgetInstanceId) {
	// serialise the table body to an array of dropdownList
	var dropdownList = $.map($('#tbDropdownItems tr'), function(tr) {
		return {
			name: $('.tdName', tr).html(),
			link: $(tr).data("link"),
			type: $(tr).data("link-type"),
			data: $(tr).data("link-data"),
			target: $(tr).data("link-target")
		};
	});
	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'DropdownList',
		Settings: {
		    dropdownItemsJson: JSON.stringify(dropdownList),
		    dropdownplaceholder: $('#dropdownplaceholder').val()
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202)
				$("#modal-dialog").modal('show');
			else
				ddModule.rebuildWidget(widgetInstanceId);
		}
	});

	$("#myModal").modal('hide');
};


ddModule.rebuildWidget = function (widgetInstanceId) {
	$.ajax({
		url: '/cms/widgets/' + widgetInstanceId + '?em=1',
		type: 'GET',
		success: function (html, textStatus, xhr) {
			var container = $('#widget_' + widgetInstanceId);
			container.replaceWith(html);
			ddModule.create(widgetInstanceId);
		}
	});
};;
var FacebookFeedModule = extend(sportsground, 'sportsground.cms.widgets.facebookFeed');

FacebookFeedModule.create = function (widgetInstanceId) {
	if (!window.fbLoaded) {
        $.getScript(document.location.protocol + '//connect.facebook.net/en_GB/sdk.js', function (data, textStatus, jqxhr) {
			FacebookFeedModule.fbAsyncInit(widgetInstanceId);
			window.fbLoaded = true;
		});
	} else {
		FB._initialized = false;
		FacebookFeedModule.fbAsyncInit(widgetInstanceId);
	}	
};

FacebookFeedModule.fbAsyncInit = function (widgetInstanceId) {

    var appId = $('.fb-appid:first').val();

	var $pageWidget = $("#fbPageActivity-" + widgetInstanceId);
	var $columnWidth = $pageWidget.closest(".splitter-column-sortable").width();
	$pageWidget.attr('data-width', $columnWidth);

    FB.init({ status: true, cookie: true, xfbml: true, version: 'v3.2', appId: appId });
};

FacebookFeedModule.commitChanges = function (widgetInstanceId) {
	
	var fbUrl = $("#lnkFacebookUrl").val();

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'FacebookFeed',
		Settings: {
			FacebookUrl: fbUrl
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');
			}
		}
	});

	// Hide Modal
	$("#myModal").modal('hide');

	// Update the facebook activity element
	var $activityElement = $("#fbPageActivity-" + widgetInstanceId);
	$activityElement.attr('data-href', fbUrl);
	$activityElement.attr('href', fbUrl);

	FacebookFeedModule.create(widgetInstanceId);
};

FacebookFeedModule.modalCreated = function (widgetInstanceId) {

};
;
var fluidWidgetModule = extend(sportsground, 'sportsground.cms.widgets.fluid');

fluidWidgetModule.resizingSS = {};

//The way this works is that the tallest column in the supersplitter acts as the master or parent with the goal being
//that the shorter columns widgets are elegantly upsized to evenly align at the bottom edge of the supersplitter
fluidWidgetModule.applyFluidStyle = function (superSplitterId) {

    var isFluid = $("#superSplitter_" + superSplitterId).data('fluidwidgets');

    //check if section is fluid
    if (!sportsground.cms.utils.isTrue(isFluid)) {
        return;
    } 

    //handle resize - fallback to custom resize watcher if ResizeObserver not supported
    try {
        let container = $("#superSplitter_" + superSplitterId)[0];
        new ResizeObserver(function resize(container) {

            fluidWidgetModule.resizeCallback(container[0].target.id);

        }).observe(container);
    }
    catch(e) {
        new ResizeSensor($("#superSplitter_" + superSplitterId), function () {
            
            if (!fluidWidgetModule.resizingSS[superSplitterId]) {
               fluidWidgetModule.resizeCallback("superSplitter_" + superSplitterId);
            }

        });
    }    

    //handle slow image load
    $("#superSplitter_" + superSplitterId + " img").load(function () {
        setTimeout(function () { fluidWidgetModule.resizeCallback("superSplitter_" + superSplitterId); }, 1000);
    });

    //backup watch for window resize
    $(window).resize(function () {
        setTimeout(function () { fluidWidgetModule.resizeCallback("superSplitter_" + superSplitterId); }, 500);
    });
};

fluidWidgetModule.resizeCallback = function (superSplitterId) {

    //dont apply to mobile screen size
    if ($(window).width() < 768) {
        return;
    }

    let heightThreshold = 100;

    fluidWidgetModule.resizingSS[superSplitterId] = true;
    fluidWidgetModule.removeChanges(superSplitterId);    

    //the tallest column
    let height = $("#" + superSplitterId).outerHeight(true);
    let sectionWidgetMargin = $("#" + superSplitterId).data("desktopmargin");

    height -= (sectionWidgetMargin * 2);//margin top and bottom    

    //not loaded yet
    if (height < heightThreshold) {
        return;
    }
   
    //find the shorter column and manipulate the widgets to align to the bottom of the supersplitter
    var columns = $("#" + superSplitterId + " > .row > div");
    columns.each(function () {

        var column = $(this);
        var colHeight = $(column).outerHeight(true);

        if ($('body').hasClass('edit')) {
            colHeight += 4; //2px section border top and bottom
        }

        //find shorter columns
        if (colHeight > heightThreshold && colHeight < height) {

            fluidWidgetModule.handleResize(column, height, superSplitterId);

        }
        else {
            var hasSplitters = $(column).find(".wSplitter").length > 0;
            if (hasSplitters) {
                fluidWidgetModule.handleResize(column, height, superSplitterId);
            }
        }

    });

    fluidWidgetModule.resizingSS[superSplitterId] = false;

};


//reset changes back to defaults before calculating new heights
fluidWidgetModule.removeChanges = function (superSplitterId) {

    //remove image changes
    var images = $("#" + superSplitterId + " .wImage img");
    $(images).removeAttr("style");

    //remove photo slideshow changes
    var slideshow = $("#" + superSplitterId + " .wImageSlideshow .sy-box");
    slideshow.each(function () {

        var widget = $(this)[0];
        $(widget).height($(widget).data('height'));
        $(widget).find('img').height($(widget).data('height'));

    });
    

    //remove sponsor slideshow changes
    var sponsorSlideshow = $("#" + superSplitterId + " .wSponsorsSlideshow .sy-box");
    sponsorSlideshow.each(function () {

        var widget = $(this)[0];
        $(widget).height($(widget).data('height'));

    });    

    //remove news carousel changes
    var newsCarousel = $("#" + superSplitterId + " .wNewsCarousel .sy-box");
    newsCarousel.each(function () {

        var widget = $(this)[0];
        $(widget).height($(widget).data('height'));
        $(widget).find("img").height('100%');
        $(widget).find("img").width('100%');
        $(widget).find("img").css('margin-top', 0);
        $(widget).find("img").css('margin-left', 0);
        $(widget).find("img").css('object-fit', 'cover');

    });

};

//handle padding and margin set on section settings
fluidWidgetModule.handleResize = function (column, height, superSplitterId) {

    if ($(column).hasClass('resized')) {
        return;
    }
    
    var fluidWidgetsSelector = ".splitter-column-sortable > .wImage, ";
    fluidWidgetsSelector += ".splitter-column-sortable > .wNewsCarousel, ";
    fluidWidgetsSelector += ".splitter-column-sortable > .wSplitter, "; //special case, could contain anything
    fluidWidgetsSelector += ".splitter-column-sortable > .wImageSlideshow, ";
    fluidWidgetsSelector += ".splitter-column-sortable > .wSponsorsSlideshow";

    var nonFluidWidgets = $(column).find(".splitter-column-sortable-parent > .splitter-column-sortable > .widget").not(fluidWidgetsSelector);

    //widget counts
    var totalWidgetCount = $(column).find(".splitter-column-sortable").not(".splitter-column-sortable-parent").length;
    var nonFluidWidgetsCount = nonFluidWidgets.length;
    var netFluidWidgetCount = totalWidgetCount - nonFluidWidgetsCount;

    //heights
    var sectionWidgetMargin = $("#" + superSplitterId).data("widgetsmargin");
    var heightOfNonFluidWidgets = 0;    
    nonFluidWidgets.each(function () {

        var widget = $(this)[0];
        heightOfNonFluidWidgets += $(widget).outerHeight(true);
        heightOfNonFluidWidgets += sectionWidgetMargin;
    });

    heightOfNonFluidWidgets -= sectionWidgetMargin;

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

    //calculate net height to work from 
    var netHeight = height - heightOfNonFluidWidgets;

    //check if not in edit mode
    if ($('body').hasClass('edit')) {
        netHeight = netHeight - 44 - (2 * totalWidgetCount); //44px high add content button and 1px per dashed border per widget
        var subSplitterCount = $(column).find(".wSplitter").length;
        netHeight = netHeight - (77 * subSplitterCount); //account for supersplitter add content button, borders and toolbar

    }

    fluidWidgetModule.resizeWidget(column, netHeight, netFluidWidgetCount, false, superSplitterId);

    $(column).addClass('resized');

};

fluidWidgetModule.resizeWidget = function (column, netHeight, netFluidWidgetCount, isSubSplitter, superSplitterId) {

    var sectionWidgetMargin = $("#" + superSplitterId).data("widgetsmargin");

    var marginOffset = sectionWidgetMargin;

    if (netFluidWidgetCount > 2) {
        netHeight -= (marginOffset / 2) * (netFluidWidgetCount - 2);
    }

    if (marginOffset < 0) {
        marginOffset = 0;
    }
    else {
        marginOffset = marginOffset / 2;
    }

    var height = netHeight;
    if (netFluidWidgetCount > 1) {
        height = (netHeight / netFluidWidgetCount) - marginOffset;
    }

    //handle image widget resizes
    var images = $(column).find(".wImage img");
    var imageHeight = height;
    if ($('body').hasClass('edit')) {
        imageHeight = imageHeight - 4; //dotted border 2 px up 2 px down
    }
    $(images).height(imageHeight);
    $(images).css("max-width", "none");
    $(images).css('min-width', '100%');
    $(images).css('object-fit', 'cover');

    //handle photo slideshow resizes
    var slideshows = $(column).find(".wImageSlideshow");
    slideshows.each(function () {

        var widget = $(this);
        if (!$(widget).parent().hasClass("splitter-column-sortable-parent") || isSubSplitter) {

            var adjustedHeightImage = height;
            if ($('body').hasClass('edit')) {
                adjustedHeightImage = adjustedHeightImage - 42;

                if (isSubSplitter) {
                    adjustedHeightImage = adjustedHeightImage - 42;
                }
            }

            $(widget).find(".sy-box").height(adjustedHeightImage);
            $(widget).find("img").height(adjustedHeightImage);
            $(widget).find("img").css('margin-top', 0);
            $(widget).find("img").css('width', 'initial');
            $(widget).find("img").css('min-width', '100%');
            $(widget).find("img").css('object-fit', 'cover');
        }        

    });    

    //handle sponsor slideshow resizes
    var sponsorSlideshows = $(column).find(".wSponsorsSlideshow");
    sponsorSlideshows.each(function () {

        var widget = $(this);
        if (!$(widget).parent().hasClass("splitter-column-sortable-parent") || isSubSplitter) {

            var adjustedHeightImage = height;
            if ($('body').hasClass('edit')) {
                adjustedHeightImage = adjustedHeightImage - 42;

                if (isSubSplitter) {
                    adjustedHeightImage = adjustedHeightImage - 42;
                }
            }

            $(widget).find(".sy-box").height(adjustedHeightImage);
        }

    });

    //handle news carousel
    var newsCarousels = $(column).find(".wNewsCarousel");

    newsCarousels.each(function () {

        var widget = $(this);
        if (!$(widget).parent().hasClass("splitter-column-sortable-parent") || isSubSplitter) {

            var adjustedHeightImage = height;
            if ($('body').hasClass('edit')) {
                adjustedHeightImage = adjustedHeightImage - 42;

                if (isSubSplitter) {
                    adjustedHeightImage = adjustedHeightImage - 42;
                }
            }

            if (adjustedHeightImage > $(widget).outerHeight(true)) {
                $(widget).find(".sy-box").height(adjustedHeightImage);
                $(widget).find("img").height(adjustedHeightImage);
                $(widget).find("img").css('margin-top', 0);
                $(widget).find("img").css('width', 'initial');
                $(widget).find("img").css('min-width', '100%');
                $(widget).find("img").css('object-fit', 'cover');
            }

            
        }

    });

        

    //handle subsplitters content
    var subSplitters = $(column).find(".wSplitter");

    subSplitters.each(function () {

        var splitter = $(this);

        var columns = $(splitter).find("[class^=col-]");
        columns.each(function () {

            var column = $(this);

            var splitterHeight = $("#" + superSplitterId).outerHeight(true);
            var subSplitterHeight = $(splitter).outerHeight(true);

            if (subSplitterHeight < splitterHeight && $(column).closest('.splitter-column-sortable-parent').children().length > 1) {
                splitterHeight = subSplitterHeight;
            }

            if ($('body').hasClass('edit')) {
                splitterHeight = splitterHeight - 53;
            }

            var fluidWidgetsSelector = ".splitter-column-sortable > .wImage, ";
            fluidWidgetsSelector += ".splitter-column-sortable > .wNewsCarousel, ";
            //fluidWidgetsSelector += ".splitter-column-sortable > .wSplitter, "; //special case, could contain anything
            fluidWidgetsSelector += ".splitter-column-sortable > .wImageSlideshow, ";
            fluidWidgetsSelector += ".splitter-column-sortable > .wSponsorsSlideshow";

            var nonFluidWidgets = $(column).find(".splitter-column-sortable > .widget").not(fluidWidgetsSelector);

            //heights
            var heightOfNonFluidWidgets = 0;
            nonFluidWidgets.each(function () {

                var widget = $(this)[0];
                heightOfNonFluidWidgets += $(widget).outerHeight(true);

            });

            //calculate net height to work from 
            var netHeight = splitterHeight - heightOfNonFluidWidgets;   

            fluidWidgetModule.resizeWidget(column, netHeight, 1, true, superSplitterId);

        });
                

    });

};
;
var formModule = extend(sportsground, 'sportsground.cms.widgets.form');

formModule.create = function (widgetInstanceId) {
	var widget = $('#widget_' + widgetInstanceId);
	var organisationFormId = widget.find('.hdnOrgFormId').val();
	var formContainer = widget.find('.site-form-container');
	var formTitle = widget.find('.form-title');

	var response = sportsground.forms.rendering.updateHeading(organisationFormId, formTitle);

    if (response != undefined && response != null && response.haltProcessing) //Do not load any of the below logic
	    return;

	sportsground.forms.rendering.loadForm(organisationFormId, formContainer);
	widget.find('form').ajaxForm(
		{
			beforeSubmit: function () {
				var form = widget.find('form');
				if (!form.valid() || !formRendering.customValidationIsValid())
					return false;

				var hasTermsAndConditions = widget.find('.dvAcceptTermsCb').is(':visible');
				if (hasTermsAndConditions && !widget.find('.chkAcceptTerms').is(':checked')) {
					widget.find('.dvAcceptTermsCb').parent().addClass('has-error');
					bootbox.alert('<h3>Terms and Conditions Apply</h3><p>Please accept the terms and conditions</p>');
					return false;
				}

				if ($("body").hasClass("isnrdform"))
				    sportsground.ui.loadingNrdFullScreen();
				else
				    sportsground.ui.loadingFullScreen();

				widget.find('.submit-button').button("loading");
				widget.find('.submit-button').attr('disabled', 'disabled');				
				
				return true;
			},
			success: function (data) {
			    if (data.success) {
			        window.location = data.redirectUrl;
			    }
			    else if (data.success === false) {
			        sportsground.ui.loadingFullScreen(true);
			        if (data.message)
			            bootbox.alert(data.message);
			        else
			            bootbox.alert("I'm sorry but there was an issue. Please contact Sportsground support.");

			        widget.find('.submit-button').button("reset");
			        widget.find('.submit-button').removeAttr('disabled');
			    }

				//$('#loading-indicator').hide();
				//widget.find('form').hide();
				//widget.find('.form-submit-success').show();
			}
		}
	);
};

formModule.commitChanges = function (widgetInstanceId) {
    var formId = $('#uxForms').val();
    if ( formId === "0" )
    {
        $('#uxForms').parent('.form-group').addClass('has-error');
        return false;
    }
    else
        $('#uxForms').parent('.form-group').removeClass('has-error');

	var widget = $('#widget_' + widgetInstanceId);
	widget.find('.hdnOrgFormId').val(formId);
	
	formModule.create(widgetInstanceId);

	$("#myModal").modal('hide');

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'Form',
		Settings: {
			OrganisationFormId: formId
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			widget.find('.no-form-message').hide();
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');
			}
		}
	});
};

formModule.modalCreated = function (widgetInstanceId) {
	var widget = $('#widget_' + widgetInstanceId);
	var organisationFormId = widget.find('.hdnOrgFormId').val();
	$.get('/Site/getorganisationforms?orgid=' + $('#OrganisationId').val())
		.done(function (data) {
			for (var index = 0; index < data.length; index++) {
				$('#uxForms').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
			}
			if (organisationFormId != '0')
				$('#uxForms').val(organisationFormId);
	});
};;
var mapsModule = extend(sportsground, 'sportsground.cms.widgets.googleMaps');
var key = "AIzaSyBID0SddcUXp9rilqhrfqQy_H5vgcXmqjs";
mapsModule.create = function (widgetInstanceId) {
	var lattitude = parseFloat($('#hdnLat-' + widgetInstanceId).val());
	var longitude = parseFloat($('#hdnLong-' + widgetInstanceId).val());
	var centerLat = parseFloat($('#hdnCenterLat-' + widgetInstanceId).val());
	var centerLong = parseFloat($('#hdnCenterLong-' + widgetInstanceId).val());
	var zoom = parseInt($('#hdnZoom-' + widgetInstanceId).val());
	var hiddenHeight = $('#hdnHeight-' + widgetInstanceId).val();

	var height = "500";
	if (hiddenHeight == "Large") {
		height = "650";
	}
	else if (hiddenHeight == "Small") {
		height = "350";
	}

	var mapUrl = "https://maps.googleapis.com/maps/api/staticmap?" +
								 "center=" + centerLat + "," + centerLong +
								 "&zoom=" + zoom +
								 "&size=600x" + height +
								 "&maptype=roadmap" +
	               "&markers=color:red%7C" + lattitude + "," + longitude +
	                "&key=" + key;
	$("#map-canvas-" + widgetInstanceId).find("img").attr("src", mapUrl);
};

mapsModule.commitChanges = function (widgetInstanceId) {
	var lat = $('#hdnLat-' + widgetInstanceId).val();
	var long = $('#hdnLong-' + widgetInstanceId).val();
	var centerLat = $('#hdnCenterLat-' + widgetInstanceId).val();
	var centerLong = $('#hdnCenterLong-' + widgetInstanceId).val();
	var zoom = $('#hdnZoom-' + widgetInstanceId).val();
	var size = $("#settings_MapHeight :selected").val();

	$("#map-canvas-" + widgetInstanceId).removeClass().addClass(size);
	$('#hdnHeight-' + widgetInstanceId).val(size);

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'GoogleMaps',
		Settings: {
			Lat: lat,
			Long: long,
			CenterLat: centerLat,
			CenterLong: centerLong,
			Zoom: zoom,
			MapHeight: size
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function(data, textStatus, xhr) {
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');
			}
		}
	});

	$("#myModal").modal('hide');
	sportsground.cms.widgets.googleMaps.create(widgetInstanceId);
};

mapsModule.modalCreated = function (widgetInstanceId) {	
	var lattitude = parseFloat($('#hdnLat-' + widgetInstanceId).val());
	var longitude = parseFloat($('#hdnLong-' + widgetInstanceId).val());
	var centerLat = parseFloat($('#hdnCenterLat-' + widgetInstanceId).val());
	var centerLong = parseFloat($('#hdnCenterLong-' + widgetInstanceId).val());
	var zoom = parseInt($('#hdnZoom-' + widgetInstanceId).val());
	var mapHeight = $('#hdnHeight-' + widgetInstanceId).val();

	$("#modal-map-canvas").addClass(mapHeight);
	$("#settings_MapHeight").val(mapHeight);	
	$("#settings_MapHeight").change(function () {
		$("#modal-map-canvas").removeClass().addClass($(this).val());
		google.maps.event.trigger(map, 'resize');
	});
	
	// Get Organisation Address so we don't waste time setting to the default lat/long, IF!! It is available/not-null

	var mapOptions = {
		center: new google.maps.LatLng(centerLat, centerLong),
		zoom: zoom,
		streetViewControl: false, 
		mapTypeControl: false
	};

	var map = new google.maps.Map(document.getElementById("modal-map-canvas"), mapOptions);

	var marker = new google.maps.Marker({
		map: map,
		position: new google.maps.LatLng(lattitude, longitude),
		draggable: true,
		animation: google.maps.Animation.DROP
	});

	google.maps.event.addListener(marker, 'dragend', function () {
		var pos = marker.getPosition();
		$('#hdnLat-' + widgetInstanceId).val(pos.lat());
		$('#hdnLong-' + widgetInstanceId).val(pos.lng());
	});

	google.maps.event.addListener(map, 'zoom_changed', function() {
		var zoom = map.getZoom();
		$('#hdnZoom-' + widgetInstanceId).val(zoom);
	});

	google.maps.event.addListener(map, 'center_changed', function() {
		var pos = map.getCenter();
		$('#hdnCenterLat-' + widgetInstanceId).val(pos.lat());
		$('#hdnCenterLong-' + widgetInstanceId).val(pos.lng());
	});

	google.maps.event.addListener(map, 'click', function(event) {
		marker.setPosition(event.latLng);
		$('#hdnLat-' + widgetInstanceId).val(event.latLng.lat());
		$('#hdnLong-' + widgetInstanceId).val(event.latLng.lng());
    });

    $("#autoCompleteLocationInput").locationAutoComplete({
        map: map,
        marker: marker,
        latField: '#hdnLat-' + widgetInstanceId,
        lngField: '#hdnLong-' + widgetInstanceId
    });

	$.ajax({
		url: '/cms/organisation/' + $("#OrganisationId").val() + '/getorganisationaddress',
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
        success: function (data) {

            if (data == "" || $("#hdnIsInCreate").val() == "False")
                return;

			// Address has been set for this organisation.
            $('#autoCompleteLocationInput').val(data);
		}
	});
    
};;
var iFrameModule = extend(sportsground, 'sportsground.cms.widgets.iFrame');

iFrameModule.commitChanges = function (widgetInstanceId) {
	// Get new embedded URL
	var embedUrl = $("#IFrameEmbedUrl").val();

	// Check the Url is valid 
	if (!$("#IFrameEmbedUrl").closest("form").valid()) {
		return;
	}

	if (embedUrl && !embedUrl.match(/^http([s]?):\/\/.*/)) {
		embedUrl = 'http://' + embedUrl;
	}

	// Find the widget element based on the ID
	var embedContainer = $("#widget_" + widgetInstanceId).find("iframe");
    var iframeWidget = $("#widget_" + widgetInstanceId).find("#iframeWidget");

	// Set the src to the new URL
	$(embedContainer).attr('src', embedUrl);

	// Set Iframe to selected size
    var size = $("#settings_EmbedHeight :selected").text();
    var height = 0;

    if (size == "Automatic") {
        $(iframeWidget).removeClass();

        $(embedContainer).removeClass();
        height = embedContainer.context.body.offsetHeight + 'px';
        $(embedContainer).css('height', height); 
        $(embedContainer).css('overflow', 'hidden'); 
        $(embedContainer).css('min-height', height); //for IE
    }
    else {
        $(embedContainer).removeClass().addClass(size);
        $(embedContainer).removeAttr('style');
        $(iframeWidget).removeAttr('style');
        $(iframeWidget).removeClass().addClass(size);
    }

	// Hide popup modal
	$("#myModal").modal('hide');

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'IFrame',
		Settings: {
			EmbedUrl: embedUrl,
            EmbedHeight: size,
            EmbedAutoHeight: height
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function(data, textStatus, xhr) {
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');
			}
		}
	});
};

iFrameModule.modalCreated = function (widgetInstanceId) {
	// Check to see url/size hasn't changed since last save
	var modalVideoUrl = $("#IFrameEmbedUrl").val();
	var modalVideoSize = $("#settings_VideoHeight :selected").text();

    var pageIframe = $("#widget_" + widgetInstanceId).find("iframe");
    // $(pageIframe).attr('src') is the stripped http version; $(pageIframe).data('src') is the complete URL.
    var pageVideoUrl = $(pageIframe).data('src');
	var pageVideoSize = $(pageIframe).attr('class');

	if (pageVideoUrl != "" && pageVideoUrl != modalVideoUrl) {
		// The embed url has been updated but not committed via 'Save Page'
		$("#IFrameEmbedUrl").val(pageVideoUrl);
	}
	if (pageVideoSize != modalVideoSize) {
		// The embedded size has been updated 
		$('select[name^="settings.EmbedHeight"]').val(pageVideoSize);
	}
};

;
var imageModule = extend(sportsground, 'sportsground.cms.widgets.image');

imageModule.deskTopImage = [{}];
imageModule.mobileImage = [{}];
imageModule.isEditingMobile = false;

imageModule.create = function (widgetInstanceId) {
 
	var widget = $('#widget_' + widgetInstanceId);
    var image = $('img', widget);

    var windowWidth = $(window).width();

    if (windowWidth < 768) {
        var imageSrc = $("#hdnMobileImageSrc_" + widgetInstanceId).val();

        if (imageSrc !== "" && imageSrc !== undefined) {
            image.attr('src', imageSrc);
            var mobileImageJson = $('#hdnMobileImage_' + widgetInstanceId).val();
            var mobileImage = $.parseJSON(mobileImageJson);
            image.data('id', mobileImage.imageId);
            image.data('link-type', mobileImage.linkType);
            image.data('link-data', mobileImage.linkData);
            image.data('link-target', mobileImage.linkNewTab);
            image.data('has-caption', mobileImage.hasCaption);
            if (mobileImage.caption === undefined || mobileImage.caption == null)
                mobileImage.caption = "";
            image.data('caption', mobileImage.caption);
            widget.find('.img-caption').html(mobileImage.caption);
        }
    }

    var id = image.data('id');

    if (!id || id.length <= 0) {
        image.attr('src', '/Content/images/cms/defaultsite/placeholder.png?v=1');
    }
    else {
        sportsground.cms.link.init(image);
        var hasCaption = sportsground.cms.utils.isTrue(image.data('has-caption'));
        imageModule.initImage(widget, image, hasCaption, widgetInstanceId);
        
    }
};

imageModule.modalCreated = function (widgetInstanceId) {

    imageModule.imageGalleryInitialised = false;

    //desktop image setup
    imageModule.deskTopImage = [{}];
    var imageJson = $('#hdnImage').val();
    if (imageJson.length > 0) {
        imageModule.deskTopImage[0] = $.parseJSON(imageJson);
    }
    var desktopImageId = $("#hdnImageId").val();
    if ( desktopImageId && desktopImageId.length > 0 ) {
        imageModule.deskTopImage[0].imageId = desktopImageId;
        imageModule.deskTopImage[0].linkType = $("#hdnLinkType").val();
        imageModule.deskTopImage[0].linkData = $("#hdnLinkData").val();
        imageModule.deskTopImage[0].linkNewTab = $("#hdnLinkTarget").val();
        imageModule.deskTopImage[0].hasCaption = $("#hdnCaptionInWidget").val();
        imageModule.deskTopImage[0].caption = $("#hdnCaption").val();
        imageModule.deskTopImage[0].darkenOnHover = $("#hdnDarkenOnHover").val();
    }
    imageModule.loadSelectedImage();

    //mobile image setup
    imageModule.mobileImage = [{}];
    var mobileImageJson = $('#hdnMobileImage').val();
    if (mobileImageJson.length > 0) {
        imageModule.mobileImage[0] = $.parseJSON(mobileImageJson);
        imageModule.loadSelectedMobileImage();
    }

    $('#modalOrganisationId').val($('#OrganisationId').val());

    imageModule.setAddImageClickHandler();
    imageModule.setAddMobileImageClickHandler();

    imageModule.setImageSettingsClickHandler();

    $('#myModal .modal-header').append('<div class="pull-right hideWidgetDiv"><input type="checkbox" id="hideWidget"/><label for="hideWidget" class="hideWidget control-label">Hide on Mobile</label></div>');
    $('#myModal .modal-footer').append('<div class="pull-left gallery-action-buttons" style="display:none;"><a id="btnUploadImages" href="#"><i class="glyphicon glyphicon-cloud-upload" />&nbsp;&nbsp;Upload an Image</a></div>');

    var isHiddenOnMobile = $("#hdnHideOnMobile_" + widgetInstanceId).val();
    if (isHiddenOnMobile === "True") {
        $("#hideWidget").prop('checked', 'checekd');
    }
    else
        $("#hideWidget").prop('checked', false);
};

imageModule.setLinkHtmlValuesFromJson = function () {
    $('.link-settings').hide();
    $('#linkSettings_' + imageModule.deskTopImage[0].linkType).show();
    $('#button1LinkSettings_' + imageModule.deskTopImage[0].button1LinkType).show();
    $('#button2LinkSettings_' + imageModule.deskTopImage[0].button2LinkType).show();

    var currentImage = imageModule.deskTopImage[0];
    $('input[type="radio"][name="rbLinkType"][value="' + currentImage.linkType + '"]').prop('checked', true);
    $('#tbLinkUrlLocation').val('');
    $('#cbLinkUrlNewTab').prop('checked', false);
    $('#tbLinkEmail').val('');
    $('#slLinkPageOptions')[0].selectedIndex = 0;
    $('#slLinkDocumentOptions')[0].selectedIndex = 0;
    $('#slLinkFormOptions')[0].selectedIndex = 0;

    if (currentImage.linkType !== "none" && currentImage.linkType !== "")
        $("#chkDarkenOnHover").prop('disabled', false);

    switch (currentImage.linkType) {
        case 'url':
            $('#tbLinkUrlLocation').val(imageModule.deskTopImage[0].linkData);
            $('#cbLinkUrlNewTab').prop('checked', currentImage.linkNewTab === true || currentImage.linkNewTab === "True");
            break;
        case 'page':
            $('#slLinkPageOptions').val(imageModule.deskTopImage[0].linkData);
            break;
        case 'document':
            $('#slLinkDocumentOptions').val(imageModule.deskTopImage[0].linkData);
            break;
        case 'onlineForm':
            $('#slLinkFormOptions').val(imageModule.deskTopImage[0].linkData);
            break;
        case 'email':
            $('#tbLinkEmail').val(imageModule.deskTopImage[0].linkData);
            break;
        default:
    }

    $('input[type="radio"][name="rbButton1LinkType"][value="' + currentImage.button1LinkType + '"]').prop('checked', true);
    $('#tbButton1LinkUrlLocation').val('');
    $('#cbButton1LinkUrlNewTab').prop('checked', false);
    $('#tbButton1LinkEmail').val('');
    $('#slButton1LinkPageOptions')[0].selectedIndex = 0;
    $('#slButton1LinkDocumentOptions')[0].selectedIndex = 0;
    $('#slButton1LinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.button1LinkType) {
        case 'url':
            $('#tbButton1LinkUrlLocation').val(imageModule.deskTopImage[0].button1LinkData);
            $('#cbButton1LinkUrlNewTab').prop('checked', currentImage.button1LinkNewTab === true || currentImage.button1LinkNewTab === "True");
            break;
        case 'page':
            $('#slButton1LinkPageOptions').val(imageModule.deskTopImage[0].button1LinkData);
            break;
        case 'document':
            $('#slButton1LinkDocumentOptions').val(imageModule.deskTopImage[0].button1LinkData);
            break;
        case 'onlineForm':
            $('#slButton1LinkFormOptions').val(imageModule.deskTopImage[0].button1LinkData);
            break;
        case 'email':
            $('#tbButton1LinkEmail').val(imageModule.deskTopImage[0].button1LinkData);
            break;
        default:
    }

    $('input[type="radio"][name="rbButton2LinkType"][value="' + currentImage.button2LinkType + '"]').prop('checked', true);
    $('#tbButton2LinkUrlLocation').val('');
    $('#cbButton2LinkUrlNewTab').prop('checked', false);
    $('#tbButton2LinkEmail').val('');
    $('#slButton2LinkPageOptions')[0].selectedIndex = 0;
    $('#slButton2LinkDocumentOptions')[0].selectedIndex = 0;
    $('#slButton2LinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.button2LinkType) {
        case 'url':
            $('#tbButton2LinkUrlLocation').val(imageModule.deskTopImage[0].button2LinkData);
            $('#cbButton2LinkUrlNewTab').prop('checked', currentImage.button2LinkNewTab === true || currentImage.button2LinkNewTab === "True");
            break;
        case 'page':
            $('#slButton2LinkPageOptions').val(imageModule.deskTopImage[0].button2LinkData);
            break;
        case 'document':
            $('#slButton2LinkDocumentOptions').val(imageModule.deskTopImage[0].button2LinkData);
            break;
        case 'onlineForm':
            $('#slButton2LinkFormOptions').val(imageModule.deskTopImage[0].button2LinkData);
            break;
        case 'email':
            $('#tbButton2LinkEmail').val(imageModule.deskTopImage[0].button2LinkData);
            break;
        default:
    }
};

imageModule.setMobileLinkHtmlValuesFromJson = function () {
    $('.link-settings').hide();
    $('#linkSettings_' + imageModule.mobileImage[0].linkType).show();

    var currentImage = imageModule.mobileImage[0];
    $('input[type="radio"][name="rbLinkType"][value="' + currentImage.linkType + '"]').prop('checked', true);
    $('#tbLinkUrlLocation').val('');
    $('#cbLinkUrlNewTab').prop('checked', false);
    $('#tbLinkEmail').val('');
    $('#slLinkPageOptions')[0].selectedIndex = 0;
    $('#slLinkDocumentOptions')[0].selectedIndex = 0;
    $('#slLinkFormOptions')[0].selectedIndex = 0;

    if (currentImage.linkType !== "none" && currentImage.linkType !== "")
        $("#chkDarkenOnHover").prop('disabled', false);

    switch (currentImage.linkType) {
        case 'url':
            $('#tbLinkUrlLocation').val(imageModule.mobileImage[0].linkData);
            $('#cbLinkUrlNewTab').prop('checked', currentImage.linkNewTab === true || currentImage.linkNewTab === "True");
            break;
        case 'page':
            $('#slLinkPageOptions').val(imageModule.mobileImage[0].linkData);
            break;
        case 'document':
            $('#slLinkDocumentOptions').val(imageModule.mobileImage[0].linkData);
            break;
        case 'onlineForm':
            $('#slLinkFormOptions').val(imageModule.mobileImage[0].linkData);
            break;
        case 'email':
            $('#tbLinkEmail').val(imageModule.mobileImage[0].linkData);
            break;
        default:
    }

    $('input[type="radio"][name="rbButton1LinkType"][value="' + currentImage.button1LinkType + '"]').prop('checked', true);
    $('#tbButton1LinkUrlLocation').val('');
    $('#cbButton1LinkUrlNewTab').prop('checked', false);
    $('#tbButton1LinkEmail').val('');
    $('#slButton1LinkPageOptions')[0].selectedIndex = 0;
    $('#slButton1LinkDocumentOptions')[0].selectedIndex = 0;
    $('#slButton1LinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.button1LinkType) {
        case 'url':
            $('#tbButton1LinkUrlLocation').val(imageModule.mobileImage[0].button1LinkData);
            $('#cbButton1LinkUrlNewTab').prop('checked', currentImage.button1LinkNewTab === true || currentImage.button1LinkNewTab === "True");
            break;
        case 'page':
            $('#slButton1LinkPageOptions').val(imageModule.mobileImage[0].button1LinkData);
            break;
        case 'document':
            $('#slButton1LinkDocumentOptions').val(imageModule.mobileImage[0].button1LinkData);
            break;
        case 'onlineForm':
            $('#slButton1LinkFormOptions').val(imageModule.mobileImage[0].button1LinkData);
            break;
        case 'email':
            $('#tbButton1LinkEmail').val(imageModule.mobileImage[0].button1LinkData);
            break;
        default:
    }

    $('input[type="radio"][name="rbButton2LinkType"][value="' + currentImage.button2LinkType + '"]').prop('checked', true);
    $('#tbButton2LinkUrlLocation').val('');
    $('#cbButton2LinkUrlNewTab').prop('checked', false);
    $('#tbButton2LinkEmail').val('');
    $('#slButton2LinkPageOptions')[0].selectedIndex = 0;
    $('#slButton2LinkDocumentOptions')[0].selectedIndex = 0;
    $('#slButton2LinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.button2LinkType) {
        case 'url':
            $('#tbButton2LinkUrlLocation').val(imageModule.mobileImage[0].button2LinkData);
            $('#cbButton2LinkUrlNewTab').prop('checked', currentImage.button2LinkNewTab === true || currentImage.button2LinkNewTab === "True");
            break;
        case 'page':
            $('#slButton2LinkPageOptions').val(imageModule.mobileImage[0].button2LinkData);
            break;
        case 'document':
            $('#slButton2LinkDocumentOptions').val(imageModule.mobileImage[0].button2LinkData);
            break;
        case 'onlineForm':
            $('#slButton2LinkFormOptions').val(imageModule.mobileImage[0].button2LinkData);
            break;
        case 'email':
            $('#tbButton2LinkEmail').val(imageModule.mobileImage[0].button2LinkData);
            break;
        default:
    }
};

imageModule.setLinkJsonValuesFromHtml = function () {


    if (imageModule.isEditingMobile) {

        imageModule.mobileImage[0].linkType = $('input[name=rbLinkType]:checked').val();

        switch (imageModule.mobileImage[0].linkType) {
            case 'url':
                imageModule.mobileImage[0].linkData = $('#tbLinkUrlLocation').val();
                imageModule.mobileImage[0].linkNewTab = $('#cbLinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageModule.mobileImage[0].linkData = $('#slLinkPageOptions').val();
                break;
            case 'document':
                imageModule.mobileImage[0].linkData = $('#slLinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageModule.mobileImage[0].linkData = $('#slLinkFormOptions').val();
                break;
            case 'email':
                imageModule.mobileImage[0].linkData = $('#tbLinkEmail').val();
                break;
            default:
        }

    }
    else {
        imageModule.deskTopImage[0].linkType = $('input[name=rbLinkType]:checked').val();

        switch (imageModule.deskTopImage[0].linkType) {
            case 'url':
                imageModule.deskTopImage[0].linkData = $('#tbLinkUrlLocation').val();
                imageModule.deskTopImage[0].linkNewTab = $('#cbLinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageModule.deskTopImage[0].linkData = $('#slLinkPageOptions').val();
                break;
            case 'document':
                imageModule.deskTopImage[0].linkData = $('#slLinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageModule.deskTopImage[0].linkData = $('#slLinkFormOptions').val();
                break;
            case 'email':
                imageModule.deskTopImage[0].linkData = $('#tbLinkEmail').val();
                break;
            default:
        }
    }
};

imageModule.setButton1LinkJsonValuesFromHtml = function () {

    if (imageModule.isEditingMobile) {
        imageModule.mobileImage[0].button1LinkType = $('input[name=rbButton1LinkType]:checked').val();

        switch (imageModule.mobileImage[0].button1LinkType) {
            case 'url':
                imageModule.mobileImage[0].button1LinkData = $('#tbButton1LinkUrlLocation').val();
                imageModule.mobileImage[0].button1LinkNewTab = $('#cbButton1LinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageModule.mobileImage[0].button1LinkData = $('#slButton1LinkPageOptions').val();
                break;
            case 'document':
                imageModule.mobileImage[0].button1LinkData = $('#slButton1LinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageModule.mobileImage[0].button1LinkData = $('#slButton1LinkFormOptions').val();
                break;
            case 'email':
                imageModule.mobileImage[0].button1LinkData = $('#tbButton1LinkEmail').val();
                break;
            default:
        }
    }
    else {
        imageModule.deskTopImage[0].button1LinkType = $('input[name=rbButton1LinkType]:checked').val();

        switch (imageModule.deskTopImage[0].button1LinkType) {
            case 'url':
                imageModule.deskTopImage[0].button1LinkData = $('#tbButton1LinkUrlLocation').val();
                imageModule.deskTopImage[0].button1LinkNewTab = $('#cbButton1LinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageModule.deskTopImage[0].button1LinkData = $('#slButton1LinkPageOptions').val();
                break;
            case 'document':
                imageModule.deskTopImage[0].button1LinkData = $('#slButton1LinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageModule.deskTopImage[0].button1LinkData = $('#slButton1LinkFormOptions').val();
                break;
            case 'email':
                imageModule.deskTopImage[0].button1LinkData = $('#tbButton1LinkEmail').val();
                break;
            default:
        }
    }
};

imageModule.setButton2LinkJsonValuesFromHtml = function () {

    if (imageModule.isEditingMobile) {
        imageModule.mobileImage[0].button2LinkType = $('input[name=rbButton2LinkType]:checked').val();

        switch (imageModule.mobileImage[0].button2LinkType) {
            case 'url':
                imageModule.mobileImage[0].button2LinkData = $('#tbButton2LinkUrlLocation').val();
                imageModule.mobileImage[0].button2LinkNewTab = $('#cbButton2LinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageModule.mobileImage[0].button2LinkData = $('#slButton2LinkPageOptions').val();
                break;
            case 'document':
                imageModule.mobileImage[0].button2LinkData = $('#slButton2LinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageModule.mobileImage[0].button2LinkData = $('#slButton2LinkFormOptions').val();
                break;
            case 'email':
                imageModule.mobileImage[0].button2LinkData = $('#tbButton2LinkEmail').val();
                break;
            default:
        }
    }
    else {
        imageModule.deskTopImage[0].button2LinkType = $('input[name=rbButton2LinkType]:checked').val();

        switch (imageModule.deskTopImage[0].button2LinkType) {
            case 'url':
                imageModule.deskTopImage[0].button2LinkData = $('#tbButton2LinkUrlLocation').val();
                imageModule.deskTopImage[0].button2LinkNewTab = $('#cbButton2LinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageModule.deskTopImage[0].button2LinkData = $('#slButton2LinkPageOptions').val();
                break;
            case 'document':
                imageModule.deskTopImage[0].button2LinkData = $('#slButton2LinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageModule.deskTopImage[0].button2LinkData = $('#slButton2LinkFormOptions').val();
                break;
            case 'email':
                imageModule.deskTopImage[0].button2LinkData = $('#tbButton2LinkEmail').val();
                break;
            default:
        }
    }
};

imageModule.setAddImageClickHandler = function () {
    $(document).on('click', '.btnChooseImages', function (e) {
        imageModule.isEditingMobile = false;

        $('#tabAddImage').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
            $('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
        });

        if ($('#btnDoneSelectingImages').length === 0) {
            $('.widget-settings-update').after('<button id="btnCancelSelectingImages" class="btn btn-info">Cancel</button><button id="btnDoneSelectingImages" class="btn btn-primary">Save</button>');
            $('#btnCancelSelectingImages').on('click', function () {
                imageModule.hideImageModal();
            });
            $('#btnDoneSelectingImages').on('click', function () {
                imageModule.hideImageModal();
            });
        }
        else {
            $('#btnDoneSelectingImages').show();
            $('#btnCancelSelectingImages').show();
        }

        $('.widget-settings-cancel-update').hide();
        $('.widget-settings-update').hide();

        var imageGallerySettings = {
            allowEditing: false,
            loadThumbsCallback: function () {
                imageModule.setImageClickHandler();
            },
            container: $("#tabImages_gallerySelect")
        };

        var imageId = imageModule.deskTopImage[0].imageId;
        if (imageId !== undefined && imageId && imageId.length > 0) {
            $.ajax({
                url: '/asset/getcontainerid?assetId=' + imageId,
                type: 'GET',
                async: false,
                success: function (data) {
                    if (data.ContainerId > 0)
                        $('#modalContainerId').val(data.ContainerId);

                    imageGallerySettings.year = data.Year;
                    imageGallerySettings.preselectedFolderId = data.ContainerId;
                    imageGallerySettings.loadThumbsCallback = function () {
                        $('#item_' + imageId).addClass('selected');
                        imageModule.setImageClickHandler();
                    };
                }
            });
        }
       
        sportsground.cms.imageGallery.init(imageGallerySettings);
        if (!imageModule.imageGalleryInitialised) {
            sportsground.cms.imageGallery.fileupload.init(imageModule.fileUploadCompletedCallback);
            imageModule.imageGalleryInitialised = true;
        }

        $('.gallery-action-buttons').show();

        e.stopImmediatePropagation();
        return false;
    });
};

imageModule.setAddMobileImageClickHandler = function () {
    $(document).on('click', '.btnChooseMobileImages', function (e) {
        imageModule.isEditingMobile = true;

        $('#tabAddImage').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
            $('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
        });

        if ($('#btnDoneSelectingImages').length === 0) {
            $('.widget-settings-update').after('<button id="btnCancelSelectingImages" class="btn btn-info">Cancel</button><button id="btnDoneSelectingImages" class="btn btn-primary">Save</button>');
            $('#btnCancelSelectingImages').on('click', function () {
                imageModule.hideImageModal();
            });
            $('#btnDoneSelectingImages').on('click', function () {
                imageModule.hideImageModal();
            });
        }
        else {
            $('#btnDoneSelectingImages').show();
            $('#btnCancelSelectingImages').show();
        }

        $('.widget-settings-cancel-update').hide();
        $('.widget-settings-update').hide();

        var imageGallerySettings = {
            allowEditing: false,
            loadThumbsCallback: function () {
                imageModule.setImageClickHandler();
            },
            container: $("#tabImages_gallerySelect")
        };

        var imageId = imageModule.mobileImage[0].imageId;
        if (imageId !== undefined && imageId && imageId.length > 0) {
            $.ajax({
                url: '/asset/getcontainerid?assetId=' + imageId,
                type: 'GET',
                async: false,
                success: function (data) {
                    if (data.ContainerId > 0)
                        $('#modalContainerId').val(data.ContainerId);

                    imageGallerySettings.year = data.Year;
                    imageGallerySettings.preselectedFolderId = data.ContainerId;
                    imageGallerySettings.loadThumbsCallback = function () {
                        $('#item_' + imageId).addClass('selected');
                        imageModule.setImageClickHandler();
                    };
                }
            });
        }

        sportsground.cms.imageGallery.init(imageGallerySettings);
        if (!imageModule.imageGalleryInitialised) {
            sportsground.cms.imageGallery.fileupload.init(imageModule.fileUploadCompletedCallback);
            imageModule.imageGalleryInitialised = true;
        }

        $('.gallery-action-buttons').show();

        e.stopImmediatePropagation();
        return false;
    });
};

imageModule.hideImageModal = function () {
    $('#tabImages_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#tabAddImage').effect('slide', { direction: 'right', mode: 'show' }, 500);
    });
    $('#btnDoneSelectingImages').hide();
    $('#btnCancelSelectingImages').hide();
    $('.widget-settings-cancel-update').show();
    $('.widget-settings-update').show();
    imageModule.loadSelectedImage();
    imageModule.loadSelectedMobileImage();
    $('.gallery-action-buttons').hide();
};

imageModule.loadSelectedImage = function () {
    if (imageModule.deskTopImage[0] === undefined )
        return;

    $('.selected-image-thumb').remove();
    var imageIds = [];
    imageIds.push(imageModule.deskTopImage[0].imageId);

    $.ajax({
        url: '/asset/GetImageAssetUrls',
        type: 'POST',
        data: JSON.stringify(imageIds),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var rawHtml = $('#hbtSelectedThumb').html();
            var template = Handlebars.compile(rawHtml);

            if (data.length > 0) {
                data[0].BtnClass = "btnChooseImages";
                $("#desktop-image-logo").addClass('hidden');
                $("#desktop-image").append(template(data[0]));
                $("#desktop-image").removeClass('hidden');
                imageModule.deskTopImage[0].caption = data[0].Alt;
            }
            else {
                $("#desktop-image").html('');
                $("#desktop-image").addClass('hidden');
                $("#desktop-image-logo").removeClass('hidden');
            }
           

            $('#selectedImagesContainer .selected-image-settings').on('click', function () {

                $("#chkDarkenOnHover").parent().removeClass('hidden');

                var imageId = $(this).closest('.selected-image-thumb').attr('id');
                imageModule.isEditingMobile = false;

                $.ajax({
                    url: '/asset/GetImageAssetDetails',
                    type: 'GET',
                    data: { imageId: imageId },
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        $('#imgPreview').attr('src', data.WebOptSrc);
                    }
                });

                $('#taImageCaption').val(imageModule.deskTopImage[0].caption);
                $('#tbButton1Text').val(imageModule.deskTopImage[0].button1Text);
                $('#tbButton2Text').val(imageModule.deskTopImage[0].button2Text);

                if (imageModule.deskTopImage[0].hasCaption === "True" || imageModule.deskTopImage[0].hasCaption === true )
                    $("#hasPhotoCaption").prop("checked", "checked");
                else
                    $("#hasPhotoCaption").prop("checked", false);

                if (imageModule.deskTopImage[0].darkenOnHover === "True" || imageModule.deskTopImage[0].darkenOnHover === true)
                    $("#chkDarkenOnHover").prop("checked", "checked");
                else
                    $("#chkDarkenOnHover").prop("checked", false);
                

                // text alignment
                if (imageModule.deskTopImage[0].alignTextOverlay === undefined)
                    imageModule.deskTopImage[0].alignTextOverlay = "bottom";

                if (imageModule.deskTopImage[0].textOverlayMargin === undefined)
                    imageModule.deskTopImage[0].textOverlayMargin = "25";

                if (imageModule.deskTopImage[0].alignTextOverlay === "top")
                    $("#txtAlignTop").prop('checked', 'checked');
                else
                    $("#txtAlignBottom").prop('checked', 'checked');

                $("#txtTextOverlayMargin").val(imageModule.deskTopImage[0].textOverlayMargin);

                // button alignment
                if (imageModule.deskTopImage[0].alignButtonOverlay === undefined)
                    imageModule.deskTopImage[0].alignButtonOverlay = "left";

                var alignButtonOverlay = imageModule.deskTopImage[0].alignButtonOverlay;

                $(".image-slideshow-btnaligns").removeClass('selected');
                $(".image-slideshow-btnaligns[data-align='" + alignButtonOverlay + "']").addClass('selected');

                if (imageModule.deskTopImage[0].alignButtonOverlay === undefined)
                    imageModule.deskTopImage[0].alignButtonOverlay = "left";

                // button type
                if (imageModule.deskTopImage[0].buttonType === undefined)
                    imageModule.deskTopImage[0].buttonType = "button";

                if (imageModule.deskTopImage[0].buttonType === "button") {
                    $("#dvHyperlinkColor").addClass('hidden');
                    $("#rbTypeButton").prop('checked', 'checked');
                }
                else {
                    $("#dvHyperlinkColor").removeClass('hidden');
                    $("#rbTypeHyperlink").prop('checked', 'checked');
                }

                // hyperlink color
                var hyperlinkColor = $("#hdnFontFamilyColor").val();
                if ($("#hdnSiteButtonColor").length > 0)
                    hyperlinkColor = $("#hdnSiteButtonColor").val();

                if (imageModule.deskTopImage[0].hyperlinkColor === undefined)
                    imageModule.deskTopImage[0].hyperlinkColor = hyperlinkColor;

                $("#txtHyperLinkColor").val(imageModule.deskTopImage[0].hyperlinkColor);

                $("#dvHyperlinkColor").find('.icon').css('background-color', imageModule.deskTopImage[0].hyperlinkColor);

                try {
                    CKEDITOR.instances["photoSlideShowCkEditor"].destroy();
                }
                catch (e) { }

                $('#photoSlideShowCkEditor').val(imageModule.deskTopImage[0].textOverlay);

                // Init CKEditor for text overlay
                setTimeout(function () {
                    var cachebuster = Math.round(new Date().getTime() / 1000);
                    CKEDITOR.replace('photoSlideShowCkEditor', {
                        customConfig: '/Content/ckeditor/photoslideshow_config.js?cb=' + cachebuster
                    });

                    CKEDITOR.instances["photoSlideShowCkEditor"].on('change', function (e) {
                        imageModule.deskTopImage[0].textOverlay = CKEDITOR.instances['photoSlideShowCkEditor'].getData()
                    });

                }, 2000);

                imageModule.setLinkHtmlValuesFromJson();

                $('#tabAddImage').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
                    $('#tabImages_imageSettings').effect('slide', { direction: 'right', mode: 'show' }, 500);
                });
            });

            $('#selectedImagesContainer .selected-image-delete').on('click', function () {
                bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove this image?</p>', function (result) {
                    if (!result)
                        return;

                    $('#desktop-image').html('');
                    $('#desktop-image').addClass('hidden');
                    $("#desktop-image-logo").removeClass('hidden');
                    imageModule.deskTopImage = [{}];
                });
                return false;
            });
        }
    });
};

imageModule.loadSelectedMobileImage = function () {
    if (imageModule.mobileImage[0] === undefined)
        return;

    $('.selected-image-thumb').remove();
    var imageIds = [];
    imageIds.push(imageModule.mobileImage[0].imageId);
    $.ajax({
        url: '/asset/GetImageAssetUrls',
        type: 'POST',
        data: JSON.stringify(imageIds),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var rawHtml = $('#hbtSelectedThumb').html();
            var template = Handlebars.compile(rawHtml);
            if (data.length > 0) {
                data[0].BtnClass = "btnChooseMobileImages";
                $("#mobile-image-logo").addClass('hidden');
                $("#mobile-image").append(template(data[0]));
                $("#mobile-image").removeClass('hidden');
            }
            else {
                $("#mobile-image").html('');
                $("#mobile-image").addClass('hidden');
                $("#mobile-image-logo").removeClass('hidden');
            }

            $('#selectedMobileImagesContainer .selected-image-settings').on('click', function () {
                $("#chkDarkenOnHover").parent().addClass('hidden');

                var imageId = $(this).closest('.selected-image-thumb').attr('id');
                imageModule.isEditingMobile = true;
                $.ajax({
                    url: '/asset/GetImageAssetDetails',
                    type: 'GET',
                    data: { imageId: imageId },
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        $('#imgPreview').attr('src', data.WebOptSrc);
                    }
                });

                $('#taImageCaption').val(imageModule.mobileImage[0].caption);
                $('#tbButton1Text').val(imageModule.mobileImage[0].button1Text);
                $('#tbButton2Text').val(imageModule.mobileImage[0].button2Text);

                if (imageModule.mobileImage[0].hasCaption === "True" || imageModule.mobileImage[0].hasCaption === true )
                    $("#hasPhotoCaption").prop("checked", "checked");
                else
                    $("#hasPhotoCaption").prop("checked", false);

                // text alignment
                if (imageModule.mobileImage[0].alignTextOverlay === undefined)
                    imageModule.mobileImage[0].alignTextOverlay = "bottom";

                if (imageModule.mobileImage[0].textOverlayMargin === undefined)
                    imageModule.mobileImage[0].textOverlayMargin = "25";

                if (imageModule.mobileImage[0].alignTextOverlay === "top")
                    $("#txtAlignTop").prop('checked', 'checked');
                else
                    $("#txtAlignBottom").prop('checked', 'checked');

                $("#txtTextOverlayMargin").val(imageModule.mobileImage[0].textOverlayMargin);

                // button alignment
                if (imageModule.mobileImage[0].alignButtonOverlay === undefined)
                    imageModule.mobileImage[0].alignButtonOverlay = "left";

                var alignButtonOverlay = imageModule.mobileImage[0].alignButtonOverlay;

                $(".image-slideshow-btnaligns").removeClass('selected');
                $(".image-slideshow-btnaligns[data-align='" + alignButtonOverlay + "']").addClass('selected');

                if (imageModule.mobileImage[0].alignButtonOverlay === undefined)
                    imageModule.mobileImage[0].alignButtonOverlay = "left";

                // button type
                if (imageModule.mobileImage[0].buttonType === undefined)
                    imageModule.mobileImage[0].buttonType = "button";

                if (imageModule.mobileImage[0].buttonType === "button") {
                    $("#dvHyperlinkColor").addClass('hidden');
                    $("#rbTypeButton").prop('checked', 'checked');
                }
                else {
                    $("#dvHyperlinkColor").removeClass('hidden');
                    $("#rbTypeHyperlink").prop('checked', 'checked');
                }

                // hyperlink color
                var hyperlinkColor = $("#hdnFontFamilyColor").val();
                if ($("#hdnSiteButtonColor").length > 0)
                    hyperlinkColor = $("#hdnSiteButtonColor").val();

                if (imageModule.mobileImage[0].hyperlinkColor === undefined)
                    imageModule.mobileImage[0].hyperlinkColor = hyperlinkColor;

                $("#txtHyperLinkColor").val(imageModule.mobileImage[0].hyperlinkColor);

                $("#dvHyperlinkColor").find('.icon').css('background-color', imageModule.mobileImage[0].hyperlinkColor);

                try {
                    CKEDITOR.instances["photoSlideShowCkEditor"].destroy();
                }
                catch (e) { }

                $('#photoSlideShowCkEditor').val(imageModule.mobileImage[0].textOverlay);

                // Init CKEditor for text overlay
                setTimeout(function () {
                    var cachebuster = Math.round(new Date().getTime() / 1000);
                    CKEDITOR.replace('photoSlideShowCkEditor', {
                        customConfig: '/Content/ckeditor/noncms_config.js?cb=' + cachebuster
                    });

                    CKEDITOR.instances["photoSlideShowCkEditor"].on('change', function (e) {
                        imageModule.mobileImage[0].textOverlay = CKEDITOR.instances['photoSlideShowCkEditor'].getData();
                    });

                }, 2000);

                imageModule.setMobileLinkHtmlValuesFromJson();

                $('#tabAddImage').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
                    $('#tabImages_imageSettings').effect('slide', { direction: 'right', mode: 'show' }, 500);
                });
            });

            $('#selectedMobileImagesContainer .selected-image-delete').on('click', function () {
                bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected mobile image from the slider?</p>', function (result) {
                    if (!result)
                        return;

                    $('#mobile-image').html('');
                    $('#mobile-image').addClass('hidden');
                    $("#mobile-image-logo").removeClass('hidden');
                    imageModule.mobileImage = [{}];
                });
                return false;
            });
        }
    });
};

imageModule.setImageSettingsClickHandler = function () {
    $('#btnImageSettingsBack').on('click', function () {
        $('#tabImages_imageSettings').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
            $('#tabAddImage').effect('slide', { direction: 'right', mode: 'show' }, 500);
        });
        return false;
    });

    $('input[type="radio"][name="rbLinkType"]').on('change', function () {
        $('#divLinkSettings .link-settings').hide();
        $('#linkSettings_' + $(this).val()).show();
        imageModule.setLinkJsonValuesFromHtml();

        if (!imageModule.isEditingMobile) {
            if ($(this).val() === "none") {
                $("#chkDarkenOnHover").attr("disabled", "disabled");
                $("#chkDarkenOnHover").attr("checked", false);
                imageModule.deskTopImage[0].darkenOnHover = false;
            }
            else {
                $("#chkDarkenOnHover").prop("disabled", false);
                $("#chkDarkenOnHover").prop("checked", "checked");
                imageModule.deskTopImage[0].darkenOnHover = true;
            }
        }
    });

    $("#chkDarkenOnHover").on('change', function () {
        if ($(this).is(':checked'))
            imageModule.deskTopImage[0].darkenOnHover = true;
        else
            imageModule.deskTopImage[0].darkenOnHover = false;
    });

    $("#hasPhotoCaption").on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].hasCaption = $(this).is(':checked');
        else
            imageModule.deskTopImage[0].hasCaption = $(this).is(':checked');
    });

    $('#taImageCaption').on('blur', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].caption = $(this).val();
        else
            imageModule.deskTopImage[0].caption = $(this).val();
    });

    $('#tbButton1Text').on('blur', function () {
        var hideLinksAndErrors = false;
        if (imageModule.isEditingMobile) {
            imageModule.mobileImage[0].button1Text = $(this).val();
            if ($(this).val() === "") {
                hideLinksAndErrors = true;
                imageModule.mobileImage[0].button1LinkType = "";
                imageModule.mobileImage[0].button1LinkData = "";
            }
        }
        else {
            imageModule.deskTopImage[0].button1Text = $(this).val();
            if ($(this).val() === "") {
                hideLinksAndErrors = true;
                imageModule.deskTopImage[0].button1LinkType = "";
                imageModule.deskTopImage[0].button1LinkData = "";
            }
        }
        if (hideLinksAndErrors) {
            $('input[type="radio"][name="rbButton1LinkType"]').prop('checked', false);
            $("#button1LinkSettings .link-settings").css('display', 'none');
            $("#errorButton1Text").addClass('hidden');
            $('#tbButton1Text').removeClass('input-has-error');
        }
    });

    $('#tbButton2Text').on('blur', function () {
        var hideLinksAndErrors = false;
        if (imageModule.isEditingMobile) {
            imageModule.mobileImage[0].button2Text = $(this).val();
            if ($(this).val() === "") {
                hideLinksAndErrors = true;
                imageModule.mobileImage[0].button2LinkType = "";
                imageModule.mobileImage[0].button2LinkData = "";
            }
        }
        else {
            imageModule.deskTopImage[0].button2Text = $(this).val();
            if ($(this).val() === "") {
                hideLinksAndErrors = true;
                imageModule.deskTopImage[0].button2LinkType = "";
                imageModule.deskTopImage[0].button2LinkData = "";
            }
        }
        if (hideLinksAndErrors) {
            $('input[type="radio"][name="rbButton2LinkType"]').prop('checked', false);
            $("#button2LinkSettings .link-settings").css('display', 'none');
            $("#errorButton2Text").addClass('hidden');
            $('#tbButton2Text').removeClass('input-has-error');
        }
    });

    $('input[type="radio"][name="rbButton1LinkType"]').on('change', function () {
        $('#button1LinkSettings .link-settings').hide();
        $('#button1LinkSettings_' + $(this).val()).show();
        imageModule.setButton1LinkJsonValuesFromHtml();
    });

    $('input[type="radio"][name="rbButton2LinkType"]').on('change', function () {
        $('#button2LinkSettings .link-settings').hide();
        $('#button2LinkSettings_' + $(this).val()).show();
        imageModule.setButton2LinkJsonValuesFromHtml();
    });

    $('#tbLinkUrlLocation').on('blur', function () {
        sportsground.ui.attachHandlerPrependHttpOnWwwLinks(this);
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].linkData = $(this).val();
        else
            imageModule.deskTopImage[0].linkData = $(this).val();
    });

    $('#tbButton1LinkUrlLocation').on('blur', function () {
        sportsground.ui.attachHandlerPrependHttpOnWwwLinks(this);

        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button1LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button1LinkData = $(this).val();
    });

    $('#tbButton2LinkUrlLocation').on('blur', function () {
        sportsground.ui.attachHandlerPrependHttpOnWwwLinks(this);

        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button2LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button2LinkData = $(this).val();
    });

    sportsground.cms.common.bindRemoveEditModeOnPaste();

    $('#tbLinkEmail').on('blur', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].linkData = $(this).val();
        else
            imageModule.deskTopImage[0].linkData = $(this).val();
    });

    $('#tbButton1LinkEmail').on('blur', function () {
        if (imageModule.isEditingMobile)
            imageModule.deskTopImage[0].button1LinkData = $(this).val();
        else
            imageModule.mobileImage[0].button1LinkData = $(this).val();
    });

    $('#tbButton2LinkEmail').on('blur', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button2LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button2LinkData = $(this).val();
    });

    $('#slLinkPageOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].linkData = $(this).val();
        else
            imageModule.deskTopImage[0].linkData = $(this).val();
    });

    $('#slButton1LinkPageOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button1LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button1LinkData = $(this).val();
    });

    $('#slButton2LinkPageOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button2LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button2LinkData = $(this).val();
    });

    $('#slLinkDocumentOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].linkData = $(this).val();
        else
            imageModule.deskTopImage[0].linkData = $(this).val();
    });

    $('#slLinkButton1DocumentOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button1LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button1LinkData = $(this).val();

    });

    $('#slLinkButton2DocumentOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button2LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button2LinkData = $(this).val();
    });

    $('#slLinkFormOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].linkData = $(this).val();
        else
            imageModule.deskTopImage[0].linkData = $(this).val();
    });

    $('#slButton1LinkFormOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button1LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button1LinkData = $(this).val();
    });

    $('#slButton2LinkFormOptions').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button2LinkData = $(this).val();
        else
            imageModule.deskTopImage[0].button2LinkData = $(this).val();
    });

    $('#cbLinkUrlNewTab').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].linkNewTab = $(this).is(':checked');
        else
            imageModule.deskTopImage[0].linkNewTab = $(this).is(':checked');
    });

    $('#cbButton1LinkUrlNewTab').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button1LinkNewTab = $(this).is(':checked');
        else
            imageModule.deskTopImage[0].button1LinkNewTab = $(this).is(':checked');
    });

    $('#cbButton2LinkUrlNewTab').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].button2LinkNewTab = $(this).is(':checked');
        else
            imageModule.deskTopImage[0].button2LinkNewTab = $(this).is(':checked');
    });

    $.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/getsitepages?showHiddenPages=false',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

            var html = '';
            for (var mainPage = 0; mainPage < data.length; mainPage++) {
                var mainPageItem = data[mainPage];

                if (mainPageItem.Type == 'section') {

                    html += '<option disabled style="font-weight:bold;">' + mainPageItem.Title + '</option>';
                    var subPages = mainPageItem.Children;

                    for (var subPage = 0; subPage < subPages.length; subPage++) {
                        var subPageItem = subPages[subPage];

                        if (subPageItem.Type == 'section') {
                            html += '<option disabled >&nbsp;&nbsp;&nbsp;&nbsp;' + subPageItem.Title + '</option>';
                            var subsubPages = subPageItem.Children;
                            for (var subsubPage = 0; subsubPage < subsubPages.length; subsubPage++) {
                                var subsubPageItem = subsubPages[subsubPage];
                                html += '<span>-</span><option class="subsubpage" value="' + subsubPageItem.Id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- ' + subsubPageItem.Title + '</option>';
                            }
                        }
                        else {
                            html += '<option value="' + subPageItem.Id + '">&nbsp;&nbsp;&nbsp;&nbsp;' + subPageItem.Title + '</option>';
                        }

                    }
                    html += '</optgroup>';
                }
                else {
                    html += '<option value="' + mainPageItem.Id + '" style="font-weight:bold;">' + mainPageItem.Title + '</option>';
                }
            }

            $('#slLinkPageOptions').append(html);
            $('#slButton1LinkPageOptions').append(html);
            $('#slButton2LinkPageOptions').append(html);
        }
    });

    $.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/documents',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            for (var folderIndex = 0; folderIndex < data.length; folderIndex++) {

                var folder = data[folderIndex];
                var assets = folder.Assets;

                $('#slLinkDocumentOptions').append('<option disabled value="parent" class="mainfolder>' + folder.FolderName + '</option>');
                $('#slButton1LinkDocumentOptions').append('<option disabled value="parent" class="mainfolder>' + folder.FolderName + '</option>');
                $('#slButton2LinkDocumentOptions').append('<option disabled value="parent" class="mainfolder>' + folder.FolderName + '</option>');

                for (var docIndex = 0; docIndex < folder.Assets.length; docIndex++) {
                    $('#slLinkDocumentOptions').append('<option value="' + folder.Assets[docIndex].Value + '">&nbsp;&nbsp;' + folder.Assets[docIndex].Key + '</option>');
                    $('#slButton1LinkDocumentOptions').append('<option value="' + folder.Assets[docIndex].Value + '">&nbsp;&nbsp;' + folder.Assets[docIndex].Key + '</option>');
                    $('#slButton2LinkDocumentOptions').append('<option value="' + folder.Assets[docIndex].Value + '">&nbsp;&nbsp;' + folder.Assets[docIndex].Key + '</option>');
                }

                for (var i = 0; i < folder.SubFolders.length; i++) {
                    var subfolder = folder.SubFolders[i];
                    var subfolderAssets = subfolder.Assets;
                    $('#slLinkDocumentOptions').append('<option disabled value="parent" class="subfolder">&nbsp;&nbsp;&nbsp;&nbsp;' + subfolder.FolderName + '</option>');
                    $('#slButton1LinkDocumentOptions').append('<option disabled value="parent" class="subfolder">&nbsp;&nbsp;&nbsp;&nbsp;' + subfolder.FolderName + '</option>');
                    $('#slButton2LinkDocumentOptions').append('<option disabled value="parent" class="subfolder">&nbsp;&nbsp;&nbsp;&nbsp;' + subfolder.FolderName + '</option>');
                    for (var j = 0; j < subfolderAssets.length; j++) {
                        $('#slLinkDocumentOptions').append('<option value="' + subfolderAssets[j].Value + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + subfolderAssets[j].Key + '</option>');
                        $('#slButton1LinkDocumentOptions').append('<option value="' + subfolderAssets[j].Value + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + subfolderAssets[j].Key + '</option>');
                        $('#slButton2LinkDocumentOptions').append('<option value="' + subfolderAssets[j].Value + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + subfolderAssets[j].Key + '</option>');
                    }
                }
            }
        }
    });

    //populate forms drop down
    $.ajax({
        url: '/Site/getorganisationforms?orgid=' + $('#OrganisationId').val(),
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            for (var index = 0; index < data.length; index++) {

                $('#slLinkFormOptions').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                $('#slButton1LinkFormOptions').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                $('#slButton2LinkFormOptions').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
            }
        }
    });

    $('.advanced-options-header').on('click', function () {
        $('.advanced-options').toggle();
    });

    $('input[type="radio"][name="text-alignment"]').on('change', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].alignTextOverlay = $(this).val();
        else
            imageModule.deskTopImage[0].alignTextOverlay = $(this).val();

        return false;
    });

    $('#txtTextOverlayMargin').on('blur', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].textOverlayMargin = $(this).val();
        else
            imageModule.deskTopImage[0].textOverlayMargin = $(this).val();

        return false;
    });

    $(".image-slideshow-btnaligns").on('click', function () {
        $(".image-slideshow-btnaligns").removeClass('selected');
        $(this).addClass('selected');

        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].alignButtonOverlay = $(this).data('align');
        else
            imageModule.deskTopImage[0].alignButtonOverlay = $(this).data('align');

        return false;
    });

    $('input[type="radio"][name="buttonType"]').on('change', function () {

        var buttonType = $(this).val();
        if (buttonType === "button")
            $("#dvHyperlinkColor").addClass('hidden');
        else
            $("#dvHyperlinkColor").removeClass('hidden');

        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].buttonType = buttonType;
        else
            imageModule.deskTopImage[0].buttonType = buttonType;
    });

    $("#txtHyperLinkColor").simplecolorpicker({
        trigger: 'uxHyperLinkColorTrigger'
    });

    $("#dvHyperlinkColor .picker").on('click', function () {
        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].hyperlinkColor = $("#txtHyperLinkColor").val();
        else
            imageModule.deskTopImage[0].hyperlinkColor = $("#txtHyperLinkColor").val();
    });
};

imageModule.setImageClickHandler = function () {

    $('.cbImageSelect').parent().hide();

    $('.gallery-thumb').off('click.imagewidget-select');
    $('.gallery-thumb').on('click.imagewidget-select', function () {
        $('.gallery-thumb').removeClass('selected');
        $(this).addClass('selected');

        var id = $(this).data('id');
       
        var captionText = $(this).closest('.gallery-thumb').find('.imgThumbnail').data('caption');

        if (imageModule.isEditingMobile)
            imageModule.mobileImage[0].imageId = id;
        else
            imageModule.deskTopImage[0].imageId = id;

        if ($('#hdnCaptionInWidget').val() === '') {
            var caption = $(this).data('title');
            if (caption !== '') {
                if (imageModule.isEditingMobile)
                    imageModule.mobileImage[0].caption = captionText;
                else
                    imageModule.deskTopImage[0].caption = captionText;
            }
        }
    });
};

imageModule.fileUploadCompletedCallback = function () {
    $('#cntGallery .cnt-images').find('.gallery-thumb').removeClass('selected');
    $('#cntGallery .cnt-images').find('.gallery-thumb:first').addClass('selected');

    var id = $('#cntGallery .cnt-images').find('.gallery-thumb:first').data('id');
    if (imageModule.isEditingMobile)
        imageModule.mobileImage[0].imageId = id;
    else
        imageModule.deskTopImage[0].imageId = id;

    var caption = $('#cntGallery .cnt-images').find('.gallery-thumb:first').data('title');
    if (caption !== '') {
        $('#taImageCaption').val(caption);
        $('#hasPhotoCaption').prop('checked', true);
        if (imageModule.isEditingMobile) {
            imageModule.mobileImage[0].caption = caption;
            imageModule.mobileImage[0].hasCaption = true;
        }
        else {
            imageModule.deskTopImage[0].caption = caption;
            imageModule.deskTopImage[0].hasCaption = true;
        }
    }
    else {
        $('#taImageCaption').val('');
        $('#hasPhotoCaption').prop('checked', false);
        if (imageModule.isEditingMobile) {
            imageModule.mobileImage[0].caption = '';
            imageModule.mobileImage[0].hasCaption = false;
        }
        else {
            imageModule.deskTopImage[0].caption = '';
            imageModule.deskTopImage[0].hasCaption = false;
        }
    }
};

imageModule.commitChanges = function (widgetInstanceId) {

    if ( !imageModule.validateLinks() ) {
        return;
    }
	
    var id = imageModule.deskTopImage[0].imageId;

	// Make sure an image was selected. TODO: Add an error message
	if (undefined === id) return;
    var url = sportsground.utils.convertImageSrc($("#selectedImagesContainer .image-thumb").find('img').attr('src'), 'WEBOPTIMIZED');
    var alt = $("#selectedImagesContainer .image-thumb").find('img').attr('alt');

    var mobileImageid = imageModule.mobileImage[0].imageId;
    var mobileUrl = "";
    if (mobileImageid !== undefined) {
        mobileUrl = sportsground.utils.convertImageSrc($("#selectedMobileImagesContainer .image-thumb").find('img').attr('src'), 'WEBOPTIMIZED');
    }
    
    var hasCaption = imageModule.deskTopImage[0].hasCaption;
    if (hasCaption === "" || hasCaption === undefined)
        hasCaption = false;

    var caption = imageModule.deskTopImage[0].caption;
    var darkenOnHover = imageModule.deskTopImage[0].darkenOnHover;
    if (darkenOnHover === "" || darkenOnHover === undefined)
        darkenOnHover = false;
 
	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'Image',
		Settings: {
            Src: url,
            MobileImageSrc : mobileUrl,
            Alt: alt,
            ImageId: id,
            HasCaption: hasCaption,
            Caption: caption,
            LinkType: imageModule.deskTopImage[0].linkType,
            LinkData: imageModule.deskTopImage[0].linkData,
            LinkTarget: imageModule.deskTopImage[0].linkNewTab,
            DarkenOnHover: darkenOnHover,
            DesktopImageAdvancedSettingsJson: JSON.stringify(imageModule.deskTopImage[0]),
            MobileImageJson: JSON.stringify(imageModule.mobileImage[0]),
            HideOnMobile: $("#hideWidget").is(':checked')
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function(data, textStatus, xhr) {
			if (xhr.status !== 202 && xhr.status !== 200) {
				alert('image commit error');
            }
            imageModule.rebuildWidget(widgetInstanceId);
		}
	});

	$('#myModal').modal('hide');
};

imageModule.rebuildWidget = function (widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function (html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            imageModule.create(widgetInstanceId);
        }
    });
};

imageModule.validateLinks = function () {

    var valid = true;

    var button1Text = $("#tbButton1Text").val();
    var button2Text = $("#tbButton2Text").val();

    if (button1Text !== "" && !$('input[type="radio"][name="rbButton1LinkType"]').is(":checked")) {
        valid = false;
        $("#tbButton1Text").addClass('input-has-error');
        $("#errorButton1Text").removeClass('hidden');
    }
    else {
        $("#tbButton1Text").removeClass('input-has-error');
        $("#errorButton1Text").addClass('hidden');
    }

    if (button2Text !== "" && !$('input[type="radio"][name="rbButton2LinkType"]').is(":checked")) {
        valid = false;
        $("#tbButton2Text").addClass('input-has-error');
        $("#errorButton2Text").removeClass('hidden');
    }
    else {
        $("#tbButton2Text").removeClass('input-has-error');
        $("#errorButton2Text").addClass('hidden');
    }

    //validate url links exist of ticked
    if ($("#rbLinkWebUrl").is(':checked')) {
        var url = $("#tbLinkUrlLocation").val();
        if (!sportsground.utils.is_valid_url(url)) {
            $("#tbLinkUrlLocation").closest('.form-group').removeClass('has-success').addClass('has-error');
            valid = false;
        }
        else {
            $("#tbLinkUrlLocation").parent('.form-group').removeClass('has-error');
        }
    }

    if ($("#rbButton1LinkWebUrl").is(':checked')) {
        var url2 = $("#tbButton1LinkUrlLocation").val();
        if (!sportsground.utils.is_valid_url(url2)) {
            $("#tbButton1LinkUrlLocation").closest('.form-group').removeClass('has-success').addClass('has-error');
            $("#errorButton1Text").removeClass('hidden');
            valid = false;
        }
        else {
            $("#errorButton1Text").addClass('hidden');
            $("#tbButton1LinkUrlLocation").parent('.form-group').removeClass('has-error');
        }
    }

    if ($("#rbButton2LinkWebUrl").is(':checked')) {
        var url3 = $("#tbButton2LinkUrlLocation").val();
        if (!sportsground.utils.is_valid_url(url3)) {
            $("#tbButton2LinkUrlLocation").closest('.form-group').removeClass('has-success').addClass('has-error');
            $("#errorButton2Text").removeClass('hidden');
            valid = false;
        }
        else {
            $("#errorButton2Text").addClass('hidden');
            $("#tbButton2LinkUrlLocation").parent('.form-group').removeClass('has-error');
        }
    }

    if ($("#rbButton1LinkEmail").is(':checked')) {
        var email1 = $("#tbButton1LinkEmail").val();
        if (!sportsground.utils.validateEmailAddress(email1)) {
            $("#errorButton1Text").removeClass('hidden');
            $("#tbButton1LinkEmail").closest('.form-group').removeClass('has-success').addClass('has-error');
            valid = false;
        }
        else {
            $("#errorButton1Text").addClass('hidden');
            $("#tbButton1LinkEmail").parent('.form-group').removeClass('has-error');
        }
    }

    if ($("#rbButton2LinkEmail").is(':checked')) {
        var email2 = $("#tbButton2LinkEmail").val();
        if (!sportsground.utils.validateEmailAddress(email2)) {
            $("#errorButton2Text").removeClass('hidden');
            $("#tbButton2LinkEmail").closest('.form-group').removeClass('has-success').addClass('has-error');
            valid = false;
        }
        else {
            $("#errorButton2Text").addClass('hidden');
            $("#tbButton2LinkEmail").parent('.form-group').removeClass('has-error');
        }
    }

    return valid;
};

imageModule.initImage = function (widget, image, hasCaption, widgetInstanceId) {
    if ( sportsground.cms.link.hasValue() ) {
        if ( sportsground.cms.link.isDocument() || sportsground.cms.link.isOnlineForm() ) {
            sportsground.cms.link.target = '_blank';
        }
    }

    imageModule.applyCaption(widget, image, hasCaption);
    imageModule.wrapLinkOnImage(widget, image);

    var windowWidth = $(window).width();

    var images = [];
    var imagesJson = [];

    var mobileImagesJson = $('#hdnMobileImage_' + widgetInstanceId).val();

    if (windowWidth < 768 && mobileImagesJson && mobileImagesJson.length > 0) {

        imagesJson = mobileImagesJson;
        
        if (imagesJson.length > 0) 
            images = $.parseJSON(imagesJson);
    }
    else {

        imagesJson = $('#hdnImage_' + widgetInstanceId).val();

        if (imagesJson.length > 0)
            images = $.parseJSON(imagesJson);
    }

    var textOverlayHtml = imageModule.addOverlay(images);
    $(widget).find('.imageWidget-Div').append(textOverlayHtml);

    var buttonsOverlayHtml = imageModule.addButtons(images);
    $(widget).find('.imageWidget-Div').append(buttonsOverlayHtml);
};

imageModule.wrapLinkOnImage = function ( widget, image ) {
    var imageAnchor = $( 'a', widget );
    if ( sportsground.cms.link.hasValue() ) {
        if ( imageAnchor.length == 0 ) {
            image.wrap( '<a href=""></a>' );
            imageAnchor = image.parent();
        }
    } else if ( imageAnchor.length > 0 ) {
        image.unwrap();
    }

    sportsground.cms.link.updateWidget( image, imageAnchor );
};

imageModule.applyCaption = function (widget, image, hasCaption) {
    if (sportsground.cms.utils.isTrue(hasCaption) && image.data('caption') && image.data('caption').length > 0) {
        widget.find('.img-caption').parent().show();
        widget.find('.img-caption').html(image.data('caption'));
    } else {
        // hide the transparent overlay when the caption is empty
        widget.find('.img-caption').parent().hide();
    }
};

imageModule.addOverlay = function (image) {

    if (image.textOverlayMargin === undefined)
        image.textOverlayMargin = 25;

    var style = "";
    if (image.alignTextOverlay === "top")
        style += "top:" + image.textOverlayMargin + "% !important;";
    else
        style += "top:auto !important;bottom:" + image.textOverlayMargin + "% !important;";

    var html = '<div class="image-overlay-wrapper" style="' + style + '">';

    if (image.textOverlay) {
        html += image.textOverlay;
    }

    html += "</div>";

    return html;
};


imageModule.addButtons = function (image) {

    var style = "";
    if (image.alignButtonOverlay !== undefined)
        style += "text-align:" + image.alignButtonOverlay;
    else
        style += "text-align:left";

    var slideShowInnerWrapper = "image-button-wrapper-inner";
    if (image.buttonType === "hyperlink")
        slideShowInnerWrapper += " image-hyperlink-wrapper";

    var html = '<div style="' + style + '" class="image-button-wrapper"><div class="' + slideShowInnerWrapper + '">';

    var buttonClass = "image-button site-wide-btn";
    var hyperlinkStyle = "";
    if (image.buttonType === "hyperlink") {
        buttonClass = "image-hyperlink site-wide-btn-font";
        hyperlinkStyle = "color:" + image.hyperlinkColor + " !important";
    }

    if (image.button1LinkType !== 'none' && image.button1Text) {
        html += '<a class="' + buttonClass + '" style="' + hyperlinkStyle + '" href="';
        if (image.button1LinkType === 'url') {
            html += image.button1LinkData + '" ';
            if (image.button1LinkNewTab)
                html += 'target="_blank" ';
            html += '>';
        }
        else if (image.button1LinkType === 'page') {
            $.ajax({
                url: '/cms/page/' + image.button1LinkData + '/geturl',
                async: false,
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    html += data + '">';
                }
            });
        }
        else if (image.button1LinkType === 'document') {
            html += '/asset/downloadasset?id=' + image.button1LinkData + '">';
        }
        else if (image.button1LinkType === 'onlineForm') {
            html += '/viewform/' + image.button1LinkData + '">';
        }
        else if (image.button1LinkType === 'email') {
            html += 'mailto:' + image.button1LinkData + '">';
        }

        html += image.button1Text;

        html += '</a>';
    }

    if (image.button2LinkType !== 'none' && image.button2Text) {
        html += '<a class="' + buttonClass + '" style="' + hyperlinkStyle + '" href="';
        if (image.button2LinkType === 'url') {
            html += image.button2LinkData + '" ';
            if (image.button2LinkNewTab)
                html += 'target="_blank" ';
            html += '>';
        }
        else if (image.button2LinkType === 'page') {
            $.ajax({
                url: '/cms/page/' + image.button2LinkData + '/geturl',
                async: false,
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    html += data + '">';
                }
            });
        }
        else if (image.button2LinkType === 'document') {
            html += '/asset/downloadasset?id=' + image.button2LinkData + '">';
        }
        else if (image.button2LinkType === 'onlineForm') {
            html += '/viewform/' + image.button2LinkData + '">';
        }
        else if (image.button2LinkType === 'email') {
            html += 'mailto:' + image.button2LinkData + '">';
        }

        html += image.button2Text;

        html += '</a>';
    }

    html += "</div></div>";

    return html;

};

function is_valid_url(url) {
    return /^http(s)?:\/\/?(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(url);
};
var imageSlideshowModule = extend(sportsground, 'sportsground.cms.widgets.imageSlideshow');

imageSlideshowModule.create = function (widgetInstanceId) {

    var windowWidth = $(window).width();

	var widget = $('#widget_' + widgetInstanceId);
	var slippryContainer = widget.find('.sy-box');
	slippryContainer.html('');
	var images = [];
    var imagesJson = [];

    var mobileImagesJson = $('#hdnMobileImages_' + widgetInstanceId).val();
    var mobileLayout = $('#hdnMobileLayout_' + widgetInstanceId).val();

    if (windowWidth < 768 && mobileImagesJson && mobileImagesJson.length > 5) {        

        imagesJson = mobileImagesJson;

        if (imagesJson.length > 0)
            images = $.parseJSON(imagesJson);        

    }
    else {

        imagesJson = $('#hdnImages_' + widgetInstanceId).val();

        if (imagesJson.length > 0)
            images = $.parseJSON(imagesJson);        

    }

    if (windowWidth < 768 && mobileLayout) {

        imageSlideshowModule.layout = mobileLayout;
        if (imageSlideshowModule.layout === '')
            imageSlideshowModule.layout = 'portrait';
    }
    else {

        imageSlideshowModule.layout = $('#hdnLayout_' + widgetInstanceId).val();
        if (imageSlideshowModule.layout === '')
            imageSlideshowModule.layout = 'portrait';

    }

	imageSlideshowModule.crop = $('#hdnCrop_' + widgetInstanceId).val();
	if (imageSlideshowModule.crop === '')
		imageSlideshowModule.crop = 'False';

	imageSlideshowModule.randomize = $('#hdnRandomize_' + widgetInstanceId).val();
	if (imageSlideshowModule.randomize === '')
		imageSlideshowModule.randomize = 'False';

	if (imageSlideshowModule.randomize === 'True')
		shuffle(images);

	var width = slippryContainer.outerWidth();

	// decide which image size to use
	var imageWidth = 1122;
	if (width <= 539) {
		imageWidth = 539;
	}
	if (width <= 248) {
		imageWidth = 248;
	}

	var height;
	switch (imageSlideshowModule.layout) {
		case 'panorama':
			height = Math.round(0.35 * width);
			break;
		case 'landscape':
            height = Math.round(0.71 * width);
			break;
		case 'portrait':
            height = Math.round(1.4 * width);
            break;
        case 'originalimage':
            height = 'auto';
            break;
		case 'square':
		default:
            height = width;
			break;
	}

    var maxAllowedImages = images.length > 20 ? 20 : images.length;
    for (var i = 0; i < maxAllowedImages; i++) {
		var html = '<li>';
        if (images[i].linkType !== 'none') {
            html += '<a href="';
            if (images[i].linkType === 'url') {
                html += images[i].linkData + '" ';
                if (images[i].linkNewTab)
                    html += 'target="_blank" ';
                html += '>';
            }
            else if (images[i].linkType === 'page') {
                $.ajax({
                    url: '/cms/page/' + images[i].linkData + '/geturl',
                    async: false,
                    type: 'GET',
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        html += data + '">';
                    }
                });
            }
            else if (images[i].linkType === 'document') {
                html += '/asset/downloadasset?id=' + images[i].linkData + '">';
            }
            else if (images[i].linkType === 'onlineForm') {
                html += '/viewform/' + images[i].linkData + '">';
            }
            else if (images[i].linkType === 'email') {
                html += 'mailto:' + images[i].linkData + '">';
            }
        }
        else {
            html += '<a href="javascript:void(0);" style="cursor:default" >';
        }

		var src = sportsground.utils.convertImageSrc(images[i].id, 'WEBOPTIMIZED');
		html += '<img title="' + images[i].caption + '" src="' + src + '" alt="sportsground" />';

		html += '</a>';

        html += imageSlideshowModule.addOverlay(images[i]);
        html += imageSlideshowModule.addButtons(images[i]);

		html += '</li>';
		slippryContainer.append(html);
	}


	slippryContainer.slippry({
		adaptiveHeight: false, // height of the sliders adapts to current slide
        captions: 'overlay', // Position: overlay, below, custom, false

		responsive: false, // setting this to false stops the overlay going over elements below, preventing button clicks

		// pager
		pager: true,

		// controls
		controls: true,
		autoHover: false,

		// transitions
		transition: 'fade', // fade, horizontal, kenburns, false
		speed: 2000, // time the transition takes (ms)
        pause: 6000,
		onSlideBefore: function (slide, old_index, new_index) {
            var crop = $('#hdnCrop_' + widgetInstanceId).val() ? $('#hdnCrop_' + widgetInstanceId).val().toLowerCase() === 'true' : false;
            var originalLayout = $('#hdnLayout_' + widgetInstanceId).val() ? $('#hdnLayout_' + widgetInstanceId).val().toLowerCase() === 'originalimage' : false;
			var image = slide.find('img');
            var src = image.attr('src');

            var slideShowId = $(slide).closest('.wImageSlideshow').data('id');
            var slideShowItem = {
                "layout": $('#hdnLayout_' + slideShowId).val(),
                "crop": $('#hdnCrop_' + slideShowId).val(),
                "scale": $('#hdnScale_' + slideShowId).val()
            };

            var slideshowImageReady = function () {

                var isFluid = $("#widget_" + widgetInstanceId).closest(".supersplitter").data('fluidwidgets');

                //check if section is fluid
                if (sportsground.cms.utils.isTrue(isFluid) && crop && windowWidth > 768) {
                    image.css('object-fit', 'cover');
                    image.css('width', '100%');
                    return;
                } 

				// reset the image
				image.css('width', 'auto'); // IE does not support initial, so auto will be applied to width
				image.css('width', 'initial'); // Chrome, Edge, FireFox will replace auto to initial
				image.css('margin-left', '0');
				image.css('margin-top', '0');

				// calculate aspect ratios
				var sliderAspect = width / height;
				var imageAspect = image.width() / image.height();

                if (originalLayout) {
                    image.css('max-width', '100%');
                    image.css('width', 'auto');
                    image.css('height', 'auto');
                    $("#widget_1079538").find('.sy-slides-wrap').css('position', 'inherit');
                    $("#widget_1079538").find('.sy-slides-crop').css('position', 'inherit');
                    $("#widget_1079538").find('.sy-list').css('position', 'inherit');
                    $("#widget_1079538").find('.sy-slide').css('position', 'inherit');
                }
				else if (crop) {
					if (sliderAspect > imageAspect) {
						// crop vertically
						image.css('width', width);
						var margin = (height - image.height()) / 2;
						image.css('margin-top', margin);
					}
					else {
						// crop horizontally
						image.css('height', height);
						var margin = (width - image.width()) / 2;
						image.css('margin-left', margin);
					}
                }
                else if (slideShowItem.scale && slideShowItem.scale.toLowerCase() === 'true')//scale
                {
                    var spheight = image.height();
                    var orgheight = image.height();
                    var spwidth = image.width();
                    var orgwidth = image.width();
                    var attrheight = slide.find('img').attr('height');
                    var attrwidth = slide.find('img').attr('width');
                    if ((attrheight != undefined) && (attrwidth != undefined)) {
                        spheight = Number(attrheight);
                        orgheight = Number(attrheight);
                        spwidth = Number(attrwidth);
                        orgwidth = Number(attrwidth);
                    }

                    var ratio = 0;
                    image.css('height', '100%');
                    image.css('width', 'auto'); // IE does not support initial, so auto will be applied to width
                    image.css('width', 'initial'); // Chrome, Edge, FireFox will replace auto to initial
                    image.css('margin', 'auto');

                    var imageAnchor = slide.find('a');
                    imageAnchor.css('height', '100%');

                    slide.css('height', '100%');                   
                    slide.css('display', 'table');

                    if (imageSlideshowModule.layout != "panorama") {

                        if (spwidth >= spheight) {
                            imageAnchor.css('display', 'table-cell');
                        }
                            
                    }
                        
                    imageAnchor.css('vertical-align', 'middle');

                    ratio = width / spwidth;
                    spwidth = spwidth * ratio;
                    spheight = spheight * ratio;

                    if (spheight > height) {
                        ratio = height / spheight;
                        spwidth = spwidth * ratio;
                        spheight = spheight * ratio;
                    }

                    image.css('width', spwidth);
                    image.css('height', spheight);
                    image.css('height', spheight);
                    
                    slide.find('img').attr('width', orgwidth);
                    slide.find('img').attr('height', orgheight);
                }
				else if (sliderAspect > imageAspect) {
					// scroll vertically
					image.css('width', width);
					var margin = height - image.height();
					// only scroll if there's enough to scroll, otherwise crop
					if (margin < -height / 10) {
						image.animate({ 'margin-top': margin + 'px' }, 4500);
					}
					else {
						image.css('margin-top', margin / 2);
					}
				}
				else {
					// scroll horizontally
                    image.css('height', height + "px");
					var margin = width - image.width();
					// only scroll if there's enough to scroll, otherwise crop
					if (margin < -width / 10) {
						image.animate({ 'margin-left': margin + 'px' }, 4500);
					}
					else {
						image.css('margin-left', margin / 2);
					}
				}
			};

			var isIE11 = cmsModule.isIE11OrBelow();

			//ready not working in IE 10 or 11 so use load
			if (isIE11) {
				image.load(function () {
					slideshowImageReady();
				});
			}
			else {
				image.ready(function () {
					slideshowImageReady();
				});
			}

			image.attr('src', src);
		}

	});
    widget.find('.sy-box').css('height', height + "px" );
    widget.find('.sy-box').data('height', height + "px");

    imageSlideshowModule.applyControls(widgetInstanceId);

    //apply original aspect style
    if (imageSlideshowModule.layout == 'originalimage') {
        $("#widget_" + widgetInstanceId + " .sy-box").addClass('original-aspect-ratio');
    }

};

imageSlideshowModule.addOverlay = function (image) {

    if (image.textOverlayMargin === undefined)
        image.textOverlayMargin = 25;

    var style = "";
    if (image.alignTextOverlay === "top")
        style += "top:" + image.textOverlayMargin + "% !important;";
    else
        style += "top:auto !important;bottom:" + image.textOverlayMargin + "% !important;";

    var html = '<div class="slideshow-overlay-wrapper" style="' + style + '">';

    if (image.textOverlay) {
        html += image.textOverlay;
    }

    html += "</div>";

    return html;
};

imageSlideshowModule.addButtons = function(image){

    var style = "";
    if (image.alignButtonOverlay !== undefined)
        style += "text-align:" + image.alignButtonOverlay;
    else
        style += "text-align:left";

    var slideShowInnerWrapper = "slideshow-button-wrapper-inner";
    if (image.buttonType === "hyperlink")
        slideShowInnerWrapper += " slideshow-hyperlink-wrapper";

    var html = '<div style="' + style + '" class="slideshow-button-wrapper"><div class="' + slideShowInnerWrapper + '">';

    var buttonClass = "slideshow-button site-wide-btn";
    var hyperlinkStyle = "";
    if (image.buttonType === "hyperlink") {
        buttonClass = "imageslideshow-hyperlink site-wide-btn-font";
        hyperlinkStyle = "color:" + image.hyperlinkColor + " !important";
    }

    if (image.button1LinkType !== 'none' && image.button1Text) {
        html += '<a class="' + buttonClass + '" style="' + hyperlinkStyle + '" href="';
        if (image.button1LinkType === 'url') {
            html += image.button1LinkData + '" ';
            if (image.button1LinkNewTab)
                html += 'target="_blank" ';
            html += '>';
        }
        else if (image.button1LinkType === 'page') {
            $.ajax({
                url: '/cms/page/' + image.button1LinkData + '/geturl',
                async: false,
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    html += data + '">';
                }
            });
        }
        else if (image.button1LinkType === 'document') {
            html += '/asset/downloadasset?id=' + image.button1LinkData + '">';
        }
        else if (image.button1LinkType === 'onlineForm') {
            html += '/viewform/' + image.button1LinkData + '">';
        }
        else if (image.button1LinkType === 'email') {
            html += 'mailto:' + image.button1LinkData + '">';
        }

        html += image.button1Text;

        html += '</a>';
    }

    if (image.button2LinkType !== 'none' && image.button2Text) {
        html += '<a class="' + buttonClass + '" style="' + hyperlinkStyle + '" href="';
        if (image.button2LinkType === 'url') {
            html += image.button2LinkData + '" ';
            if (image.button2LinkNewTab)
                html += 'target="_blank" ';
            html += '>';
        }
        else if (image.button2LinkType === 'page') {
            $.ajax({
                url: '/cms/page/' + image.button2LinkData + '/geturl',
                async: false,
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    html += data + '">';
                }
            });
        }
        else if (image.button2LinkType === 'document') {
            html += '/asset/downloadasset?id=' + image.button2LinkData + '">';
        }
        else if (image.button2LinkType === 'onlineForm') {
            html += '/viewform/' + image.button2LinkData + '">';
        }
        else if (image.button2LinkType === 'email') {
            html += 'mailto:' + image.button2LinkData + '">';
        }

        html += image.button2Text;

        html += '</a>';
    }

    html += "</div></div>";

    return html;

};

imageSlideshowModule.applyControls = function (widgetInstanceId) {

    imageSlideshowModule.noControls = sportsground.cms.utils.isTrue($('#hdnNoControls_' + widgetInstanceId).val());
    imageSlideshowModule.progressDots = sportsground.cms.utils.isTrue($('#hdnProgressDots_' + widgetInstanceId).val());
    imageSlideshowModule.leftArrow = sportsground.cms.utils.isTrue($('#hdnLeftArrow_' + widgetInstanceId).val());
    imageSlideshowModule.rightArrow = sportsground.cms.utils.isTrue($('#hdnRightArrow_' + widgetInstanceId).val());

    if (imageSlideshowModule.noControls) {
        $("#widget_" + widgetInstanceId + " .sy-controls").hide();
        $("#widget_" + widgetInstanceId + " .sy-pager").hide();        
    }
    else {

        if (!imageSlideshowModule.progressDots) {
            $("#widget_" + widgetInstanceId + " .sy-pager").hide();
        }

        if (!imageSlideshowModule.leftArrow) {
            $("#widget_" + widgetInstanceId + " .sy-controls .sy-prev").hide();
        }

        if (!imageSlideshowModule.rightArrow) {
            $("#widget_" + widgetInstanceId + " .sy-controls .sy-next").hide();
        }
    }

};

imageSlideshowModule.hideImageModal = function () {
    $('#tabImages_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#tabImages_imageReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
    });
    $('#btnDoneSelectingImages').hide();
    $('#btnCancelSelectingImages').hide();
    $('.widget-settings-cancel-update').show();
    $('.widget-settings-update').show();
    imageSlideshowModule.loadSelectedImages();
    imageSlideshowModule.loadSelectedMobileImages();
    $('.gallery-action-buttons').hide();
};

imageSlideshowModule.modalCreated = function (widgetInstanceId) {

    imageSlideshowModule.imageGalleryInitialised = false;      

    //desktop image setup
    imageSlideshowModule.images = [];
    imageSlideshowModule.tempImages = [];  
	var imageJson = $('#hdnImages').val();
	if (imageJson.length > 0) {
        imageSlideshowModule.images = $.parseJSON(imageJson);
        imageSlideshowModule.tempImages = $.parseJSON(imageJson);
        imageSlideshowModule.loadSelectedImages();
    }

    $('#lblExceededMaxImages').hide();
    $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').removeAttr("disabled");
    if (imageSlideshowModule.images.length > 20) {
        $('#lblExceededMaxImages').show();
        $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
    }

    //mobile image setup
    imageSlideshowModule.mobileImages = [];
    imageSlideshowModule.tempMobileImages = [];
    var mobileImageJson = $('#hdnMobileImages').val();
    if (mobileImageJson.length > 0) {
        imageSlideshowModule.mobileImages = $.parseJSON(mobileImageJson);
        imageSlideshowModule.tempMobileImages = $.parseJSON(mobileImageJson);
        imageSlideshowModule.loadSelectedMobileImages();
    }

    $('#lblMobileExceededMaxImages').hide();
    $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').removeAttr("disabled");
    if (imageSlideshowModule.mobileImages.length > 20) {
        $('#lblMobileExceededMaxImages').show();
        $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
    }    

    $('#myModal .modal-header').append('<div class="pull-right hideWidgetDiv"><input type="checkbox" id="hideWidget"/><label for="hideWidget" class="hideWidget control-label">Hide on Mobile</label></div>');
    $('#myModal .modal-footer').append('<div class="pull-left gallery-action-buttons" style="display:none;"><a id="btnUploadImages" href="#"><i class="glyphicon glyphicon-cloud-upload" />&nbsp;&nbsp;Upload an Image</a></div>');
	$('#modalOrganisationId').val($('#OrganisationId').val());

    imageSlideshowModule.handleAddImageBtnClick();
    imageSlideshowModule.handleAddMobileImageBtnClick();

    var isHiddenOnMobile = $("#hdnHideOnMobile_" + widgetInstanceId).val();
    if ( isHiddenOnMobile === "True" ) {
        $("#hideWidget").prop('checked', 'checekd');
    }
    else
        $("#hideWidget").prop('checked', false);

    //desktop layout
	$('input[type="radio"][name="rbLayout"]').on('change', function () {
		imageSlideshowModule.layout = $(this).val();
    });

	imageSlideshowModule.layout = $('#hdnLayout').val();
	if (imageSlideshowModule.layout === '')
		imageSlideshowModule.layout = 'portrait';
    $('input[type="radio"][name="rbLayout"][value="' + imageSlideshowModule.layout + '"]').prop('checked', true);

    //mobile layout
    $('input[type="radio"][name="rbMobileLayout"]').on('change', function () {
        imageSlideshowModule.mobileLayout = $(this).val();
    });

    imageSlideshowModule.mobileLayout = $('#hdnMobileLayout').val();
    if (imageSlideshowModule.mobileLayout === '')
        imageSlideshowModule.mobileLayout = 'landscape';
    $('input[type="radio"][name="rbMobileLayout"][value="' + imageSlideshowModule.mobileLayout + '"]').prop('checked', true);

    	
    $('input[type="radio"][name="rbDisplay"]').on('change', function () {

        if ($(this).prop("id") == "rbDisplayScroll") {
            imageSlideshowModule.scroll = $(this).val();
            imageSlideshowModule.crop = 'False';
            imageSlideshowModule.scale = 'False';
        }

        if ($(this).prop("id") == "rbDisplayCrop") {
            imageSlideshowModule.crop = $(this).val();
            imageSlideshowModule.scroll = 'False';
            imageSlideshowModule.scale = 'False';
        }

        if ($(this).prop("id") == "rbDisplayScale") {
            imageSlideshowModule.scale = $(this).val();
            imageSlideshowModule.scroll = 'False';
            imageSlideshowModule.crop = 'False';
        }

    });

    imageSlideshowModule.crop = $('#hdnCrop').val();
    imageSlideshowModule.scale = $('#hdnScale').val();

    if (imageSlideshowModule.crop === '')
        imageSlideshowModule.crop = 'False';

    if (imageSlideshowModule.scale === '')
        imageSlideshowModule.scale = 'False';

    imageSlideshowModule.crop = $('#hdnCrop').val();
    if (imageSlideshowModule.crop === '')
        imageSlideshowModule.crop = 'False';

    if (imageSlideshowModule.crop === 'True')
        $('#rbDisplayCrop').prop('checked', true);
    else if (imageSlideshowModule.scale === 'True')
        $('#rbDisplayScale').prop('checked', true);
    else
        $('#rbDisplayScroll').prop('checked', true);


	if ($('#hdnRandomize').val() === 'True') {
		$('#cbDisplayRandom').prop('checked', true);
		imageSlideshowModule.randomize = 'True';
    }

    //user controls
    if (sportsground.cms.utils.isTrue($('#hdnNoControls').val())) {
        $('#cbControlNone').prop('checked', true);
		imageSlideshowModule.noControls = 'True';
    }

    $('#cbControlNone').on('change', function () {
        if ($(this).is(":checked")) {
            $('#cbControlProgressDots').prop('checked', false);
            $('#cbControlLeftArrow').prop('checked', false);
            $('#cbControlRightArrow').prop('checked', false);
        }
    });

    $('#cbControlProgressDots, #cbControlLeftArrow, #cbControlRightArrow').on('change', function () {
        if ($(this).is(":checked")) {
            $('#cbControlNone').prop('checked', false);
        }
    });

    if (sportsground.cms.utils.isTrue($('#hdnProgressDots').val())) {
        $('#cbControlProgressDots').prop('checked', true);
        imageSlideshowModule.progressDots = 'True';
    }

    if (sportsground.cms.utils.isTrue($('#hdnLeftArrow').val())) {
        $('#cbControlLeftArrow').prop('checked', true);
        imageSlideshowModule.leftArrow = 'True';
    }

    if (sportsground.cms.utils.isTrue($('#hdnRightArrow').val())) {
        $('#cbControlRightArrow').prop('checked', true);
        imageSlideshowModule.rightArrow = 'True';
    }

    if (!sportsground.cms.utils.isTrue(imageSlideshowModule.progressDots) &&
        !sportsground.cms.utils.isTrue(imageSlideshowModule.leftArrow) &&
        !sportsground.cms.utils.isTrue(imageSlideshowModule.rightArrow)) {

        $('#cbControlNone').prop('checked', true);
        imageSlideshowModule.noControls = 'True';

    }

    $('#taImageCaption').on('blur', function () {

        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].caption = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].caption = $(this).val();
    });

    $('#tbButton1Text').on('blur', function () {
        var hideLinksAndErrors = false;
        if (imageSlideshowModule.isEditingMobile) {
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1Text = $(this).val();
            if ($(this).val() === "") {
                hideLinksAndErrors = true;
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkType = "";
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = "";
            }
        }
        else {
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1Text = $(this).val();
            if ($(this).val() === "") {
                hideLinksAndErrors = true;
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkType = "";
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = "";
            }
        }

        if ( hideLinksAndErrors ) {
            $('input[type="radio"][name="rbButton1LinkType"]').prop('checked', false);
            $("#button1LinkSettings .link-settings").css('display', 'none');
            $("#errorButton1Text").addClass('hidden');
            $('#tbButton1Text').removeClass('input-has-error');
        }
    });

    $('#tbButton2Text').on('blur', function () {
        var hideLinksAndErrors = false;
        if (imageSlideshowModule.isEditingMobile) {
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2Text = $(this).val();
            if ($(this).val() === "") {
                hideLinksAndErrors = true;
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkType = "";
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = "";
            }
        }
        else {
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2Text = $(this).val();
            if ($(this).val() === "") {
                hideLinksAndErrors = true;
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkType = "";
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = "";
            }
        }

        if (hideLinksAndErrors) {
            $('input[type="radio"][name="rbButton2LinkType"]').prop('checked', false);
            $("#button2LinkSettings .link-settings").css('display', 'none');
            $("#errorButton2Text").addClass('hidden');
            $('#tbButton2Text').removeClass('input-has-error');
        }
    });
       
	$('#imageSettings_Prev').on('click', function () {
		imageSlideshowModule.currentImageIndex--;
		if (imageSlideshowModule.currentImageIndex < 0)
			imageSlideshowModule.currentImageIndex = imageSlideshowModule.images.length - 1;

		var imageId = imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].id;
		$.ajax({
			url: '/asset/GetImageAssetDetails',
            type: 'GET',
            data: { imageId: imageId },
			contentType: 'application/json; charset=utf-8',
            success: function(data) {
                $('#imgPreview').attr('src', data.WebOptSrc);
			}
		});
		$('#taImageCaption').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].caption);
		imageSlideshowModule.setLinkHtmlValuesFromJson();
		return false;
	});

	$('#imageSettings_Next').on('click', function () {
		imageSlideshowModule.currentImageIndex++;
		if (imageSlideshowModule.currentImageIndex >= imageSlideshowModule.images.length)
			imageSlideshowModule.currentImageIndex = 0;

		var imageId = imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].id;
		$.ajax({
			url: '/asset/GetImageAssetDetails',
            type: 'GET',
            data: { imageId: imageId },
			contentType: 'application/json; charset=utf-8',
            success: function(data) {
                $('#imgPreview').attr('src', data.WebOptSrc);
			}
		});
		$('#taImageCaption').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].caption);
		imageSlideshowModule.setLinkHtmlValuesFromJson();
		return false;
	});

	$('#btnImageSettingsBack').on('click', function () {
		$('#tabImages_imageSettings').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$('#tabImages_imageReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
		});
		return false;
	});

	$('input[type="radio"][name="rbLinkType"]').on('change', function () {
        $('#divLinkSettings .link-settings').hide();
		$('#linkSettings_' + $(this).val()).show();
		imageSlideshowModule.setLinkJsonValuesFromHtml();
    });

    $('input[type="radio"][name="rbButton1LinkType"]').on('change', function () {
        $('#button1LinkSettings .link-settings').hide();
        $('#button1LinkSettings_' + $(this).val()).show();
        imageSlideshowModule.setButton1LinkJsonValuesFromHtml();
    });

    $('input[type="radio"][name="rbButton2LinkType"]').on('change', function () {
        $('#button2LinkSettings .link-settings').hide();
        $('#button2LinkSettings_' + $(this).val()).show();
        imageSlideshowModule.setButton2LinkJsonValuesFromHtml();
    });

    $('#tbLinkUrlLocation').on('blur', function() {
        sportsground.ui.attachHandlerPrependHttpOnWwwLinks(this);
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
    });

    $('#tbButton1LinkUrlLocation').on('blur', function () {
        sportsground.ui.attachHandlerPrependHttpOnWwwLinks(this);

        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
    });

    $('#tbButton2LinkUrlLocation').on('blur', function () {
        sportsground.ui.attachHandlerPrependHttpOnWwwLinks(this);

        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
    });

	sportsground.cms.common.bindRemoveEditModeOnPaste();

    $('#tbLinkEmail').on('blur', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
    });

    $('#tbButton1LinkEmail').on('blur', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
    });

    $('#tbButton2LinkEmail').on('blur', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
    });


    $('#slLinkPageOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
    });

    $('#slButton1LinkPageOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
    });

    $('#slButton2LinkPageOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
    });


    $('#slLinkDocumentOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
    });

    $('#slLinkButton1DocumentOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();

    });

    $('#slLinkButton2DocumentOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
    });


    $('#slLinkFormOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $(this).val();
    });

    $('#slButton1LinkFormOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
        else 
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $(this).val();
    });

    $('#slButton2LinkFormOptions').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $(this).val();
    });

    $('#cbLinkUrlNewTab').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkNewTab = $(this).is(':checked');
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkNewTab = $(this).is(':checked');
    });

    $('#cbButton1LinkUrlNewTab').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkNewTab = $(this).is(':checked');
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkNewTab = $(this).is(':checked');
    });

    $('#cbButton2LinkUrlNewTab').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkNewTab = $(this).is(':checked');
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkNewTab = $(this).is(':checked');
    });

	$.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/getsitepages?showHiddenPages=false',
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
        success: function (data) {
            
            var html = '';
            for (var mainPage = 0; mainPage < data.length; mainPage++) {
                var mainPageItem = data[mainPage];

                if (mainPageItem.Type == 'section') {

                    html += '<option disabled style="font-weight:bold;">' + mainPageItem.Title + '</option>';
                    var subPages = mainPageItem.Children;

                    for (var subPage = 0; subPage < subPages.length; subPage++) {
                        var subPageItem = subPages[subPage];

                        if (subPageItem.Type == 'section') {
                            html += '<option disabled >&nbsp;&nbsp;&nbsp;&nbsp;' + subPageItem.Title + '</option>';
                            var subsubPages = subPageItem.Children;
                            for (var subsubPage = 0; subsubPage < subsubPages.length; subsubPage++) {
                                var subsubPageItem = subsubPages[subsubPage];
                                html += '<span>-</span><option class="subsubpage" value="' + subsubPageItem.Id + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- ' + subsubPageItem.Title + '</option>';
                            }
                        }
                        else {
                            html += '<option value="' + subPageItem.Id + '">&nbsp;&nbsp;&nbsp;&nbsp;' + subPageItem.Title + '</option>';
                        }

                    }
                    html += '</optgroup>';
                }
                else {
                    html += '<option value="' + mainPageItem.Id + '" style="font-weight:bold;">' + mainPageItem.Title + '</option>';
                }
            }

            $('#slLinkPageOptions').append(html);
            $('#slButton1LinkPageOptions').append(html);
            $('#slButton2LinkPageOptions').append(html);
        }
    });

    $.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/documents',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            for (var folderIndex = 0; folderIndex < data.length; folderIndex++) {

                var folder = data[folderIndex];
                var assets = folder.Assets;

                $('#slLinkDocumentOptions').append('<option disabled value="parent" class="mainfolder>' + folder.FolderName + '</option>');
                $('#slButton1LinkDocumentOptions').append('<option disabled value="parent" class="mainfolder>' + folder.FolderName + '</option>');
                $('#slButton2LinkDocumentOptions').append('<option disabled value="parent" class="mainfolder>' + folder.FolderName + '</option>');

                for (var docIndex = 0; docIndex < folder.Assets.length; docIndex++) {
                    $('#slLinkDocumentOptions').append('<option value="' + folder.Assets[docIndex].Value + '">&nbsp;&nbsp;' + folder.Assets[docIndex].Key + '</option>');
                    $('#slButton1LinkDocumentOptions').append('<option value="' + folder.Assets[docIndex].Value + '">&nbsp;&nbsp;' + folder.Assets[docIndex].Key + '</option>');
                    $('#slButton2LinkDocumentOptions').append('<option value="' + folder.Assets[docIndex].Value + '">&nbsp;&nbsp;' + folder.Assets[docIndex].Key + '</option>');
                }

                for (var i = 0; i < folder.SubFolders.length; i++) {
                    var subfolder = folder.SubFolders[i];
                    var subfolderAssets = subfolder.Assets;
                    $('#slLinkDocumentOptions').append('<option disabled value="parent" class="subfolder">&nbsp;&nbsp;&nbsp;&nbsp;' + subfolder.FolderName + '</option>');
                    $('#slButton1LinkDocumentOptions').append('<option disabled value="parent" class="subfolder">&nbsp;&nbsp;&nbsp;&nbsp;' + subfolder.FolderName + '</option>');
                    $('#slButton2LinkDocumentOptions').append('<option disabled value="parent" class="subfolder">&nbsp;&nbsp;&nbsp;&nbsp;' + subfolder.FolderName + '</option>');
                    for (var j = 0; j < subfolderAssets.length; j++) {
                        $('#slLinkDocumentOptions').append('<option value="' + subfolderAssets[j].Value + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + subfolderAssets[j].Key + '</option>');
                        $('#slButton1LinkDocumentOptions').append('<option value="' + subfolderAssets[j].Value + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + subfolderAssets[j].Key + '</option>');
                        $('#slButton2LinkDocumentOptions').append('<option value="' + subfolderAssets[j].Value + '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + subfolderAssets[j].Key + '</option>');
                    }
                }
            }
        }
    });

    //populate forms drop down
    $.ajax({
        url: '/Site/getorganisationforms?orgid=' + $('#OrganisationId').val(),
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            for (var index = 0; index < data.length; index++) {

                $('#slLinkFormOptions').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                $('#slButton1LinkFormOptions').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                $('#slButton2LinkFormOptions').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
            }
        }
    });

    $('.advanced-options-header').on('click', function () {
        $('.advanced-options').toggle();
    });

    $('input[type="radio"][name="text-alignment"]').on('change', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignTextOverlay = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignTextOverlay = $(this).val();

        return false;
    });

    $('#txtTextOverlayMargin').on('blur', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].textOverlayMargin = $(this).val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].textOverlayMargin = $(this).val();

        return false;
    });

    $(".image-slideshow-btnaligns").on('click', function () {
        $(".image-slideshow-btnaligns").removeClass('selected');
        $(this).addClass('selected');

        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignButtonOverlay = $(this).data('align');
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignButtonOverlay = $(this).data('align');

        return false;
    });

    $('input[type="radio"][name="buttonType"]').on('change', function () {

        var buttonType = $(this).val();
        if (buttonType === "button") 
            $("#dvHyperlinkColor").addClass('hidden');
        else
            $("#dvHyperlinkColor").removeClass('hidden');

        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].buttonType = buttonType;
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].buttonType = buttonType;
    });

    $("#txtHyperLinkColor").simplecolorpicker({
        trigger: 'uxHyperLinkColorTrigger'
    });

    $("#dvHyperlinkColor .picker").on('click', function () {
        if (imageSlideshowModule.isEditingMobile)
            imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].hyperlinkColor = $("#txtHyperLinkColor").val();
        else
            imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].hyperlinkColor = $("#txtHyperLinkColor").val();
    });
};



imageSlideshowModule.handleAddImageBtnClick = function () {

    $('#btnChooseImages').on('click', function () {
        $('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
            $('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
        });

        if ($('#btnDoneSelectingImages').length === 0) {
            $('.widget-settings-update').after('<button id="btnCancelSelectingImages" class="btn btn-info">Cancel</button><button id="btnDoneSelectingImages" class="btn btn-primary">Save</button>');
            $('#btnCancelSelectingImages').on('click', function () {
                imageSlideshowModule.tempImages = imageSlideshowModule.images.slice();
                imageSlideshowModule.tempMobileImages = imageSlideshowModule.mobileImages.slice();
                imageSlideshowModule.hideImageModal();
            });
            $('#btnDoneSelectingImages').on('click', function () {
                imageSlideshowModule.images = imageSlideshowModule.tempImages.slice();
                imageSlideshowModule.mobileImages = imageSlideshowModule.tempMobileImages.slice();
                imageSlideshowModule.hideImageModal();

                if (imageSlideshowModule.images.length > 20) {
                    $('#lblExceededMaxImages').show();
                    $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
                }
                else {
                    $('#lblExceededMaxImages').hide();
                    $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').removeAttr("disabled");
                }

                if (imageSlideshowModule.mobileImages.length > 20) {
                    $('#lblMobileExceededMaxImages').show();
                    $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
                }
                else {
                    $('#lblMobileExceededMaxImages').hide();
                    $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').removeAttr("disabled");
                }
            });
        }
        else {
            $('#btnDoneSelectingImages').show();
            $('#btnCancelSelectingImages').show();
        }


        $('.widget-settings-cancel-update').hide();
        $('.widget-settings-update').hide();

        var imageGallerySettings = {
            allowEditing: false,
            loadThumbsCallback: function () {
                $('.cbImageSelect').off('change.imageslideshowthumbhandler');
                $('.cbImageSelect').on('change.imageslideshowthumbhandler', function () {
                    var id = $(this).closest('.gallery-thumb').data('id');
                    if (this.checked) {
                        var captionText = $(this).closest('.gallery-thumb').find('.imgThumbnail').data('caption');
                        imageSlideshowModule.tempImages.unshift({ id: id, caption: captionText, linkType: 'none' });
                    }
                    else if (!this.checked) {
                        for (var index = 0; index < imageSlideshowModule.tempImages.length; index++) {
                            if (imageSlideshowModule.tempImages[index].id === id) {
                                imageSlideshowModule.tempImages.splice(index, 1);
                                break;
                            }
                        }                       
                    }
                });

                $('.gallery-thumb-image img').off('click.imageslideshowthumbimghandler');
                $('.gallery-thumb-image img').on('click.imageslideshowthumbimghandler', function () {
                    $(this).closest('.gallery-thumb-image').find('.cbImageSelect').trigger('click');
                });

                for (var i = 0; i < imageSlideshowModule.images.length; i++) {
                    $('#item_' + imageSlideshowModule.images[i].id).find('input').attr('checked', 'checked');
                }
            },
            container: $("#tabImages_gallerySelect")
        };
        sportsground.cms.imageGallery.init(imageGallerySettings);
        if (!imageSlideshowModule.imageGalleryInitialised) {
            sportsground.cms.imageGallery.fileupload.init();
            imageSlideshowModule.imageGalleryInitialised = true;
        }

        $('.gallery-action-buttons').show();


        return false;
    });
};

imageSlideshowModule.handleAddMobileImageBtnClick = function () {

    $('#btnChooseMobileImages').on('click', function () {
        $('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
            $('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
        });

        if ($('#btnDoneSelectingImages').length === 0) {
            $('.widget-settings-update').after('<button id="btnCancelSelectingImages" class="btn btn-info">Cancel</button><button id="btnDoneSelectingImages" class="btn btn-primary">Save</button>');
            $('#btnCancelSelectingImages').on('click', function () {
                imageSlideshowModule.tempMobileImages = imageSlideshowModule.mobileImages.slice();
                imageSlideshowModule.hideImageModal();
            });
            $('#btnDoneSelectingImages').on('click', function () {
                imageSlideshowModule.mobileImages = imageSlideshowModule.tempMobileImages.slice();
                imageSlideshowModule.hideImageModal();

                if (imageSlideshowModule.mobileImages.length > 20) {
                    $('#lblExceededMaxImages').show();
                    $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
                }
                else {
                    $('#lblExceededMaxImages').hide();
                    $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').removeAttr("disabled");
                }
            });
        }
        else {
            $('#btnDoneSelectingImages').show();
            $('#btnCancelSelectingImages').show();
        }


        $('.widget-settings-cancel-update').hide();
        $('.widget-settings-update').hide();

        var imageGallerySettings = {
            allowEditing: false,
            loadThumbsCallback: function () {
                $('.cbImageSelect').off('change.imageslideshowthumbhandler');
                $('.cbImageSelect').on('change.imageslideshowthumbhandler', function () {
                    var id = $(this).closest('.gallery-thumb').data('id');
                    if (this.checked) {
                        var captionText = $(this).closest('.gallery-thumb').find('.imgThumbnail').data('caption');
                        imageSlideshowModule.tempMobileImages.unshift({ id: id, caption: captionText, linkType: 'none' });
                    }
                    else if (!this.checked)
                        for (var index = 0; index < imageSlideshowModule.tempMobileImages.length; index++) {
                            if (imageSlideshowModule.tempMobileImages[index].id === id) {
                                imageSlideshowModule.tempMobileImages.splice(index, 1);
                                break;
                            }
                        }
                });

                $('.gallery-thumb-image img').off('click.imageslideshowthumbimghandler');
                $('.gallery-thumb-image img').on('click.imageslideshowthumbimghandler', function () {
                    $(this).closest('.gallery-thumb-image').find('.cbImageSelect').trigger('click');
                });

                for (var i = 0; i < imageSlideshowModule.mobileImages.length; i++) {
                    $('#item_' + imageSlideshowModule.mobileImages[i].id).find('input').attr('checked', 'checked');
                }
            },
            container: $("#tabImages_gallerySelect")
        };
        sportsground.cms.imageGallery.init(imageGallerySettings);
        if (!imageSlideshowModule.imageGalleryInitialised) {
            sportsground.cms.imageGallery.fileupload.init();
            imageSlideshowModule.imageGalleryInitialised = true;
        }

        $('.gallery-action-buttons').show();

        return false;
    });

};

imageSlideshowModule.setLinkHtmlValuesFromJson = function () {
	$('.link-settings').hide();
    $('#linkSettings_' + imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkType).show();
    $('#button1LinkSettings_' + imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkType).show();
    $('#button2LinkSettings_' + imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkType).show();

	var currentImage = imageSlideshowModule.images[imageSlideshowModule.currentImageIndex];
	$('input[type="radio"][name="rbLinkType"][value="' + currentImage.linkType + '"]').prop('checked', true);
	$('#tbLinkUrlLocation').val('');
	$('#cbLinkUrlNewTab').prop('checked', false);
	$('#tbLinkEmail').val('');
	$('#slLinkPageOptions')[0].selectedIndex = 0;
	$('#slLinkDocumentOptions')[0].selectedIndex = 0;
	$('#slLinkFormOptions')[0].selectedIndex = 0;

	switch (currentImage.linkType) {
		case 'url':
			$('#tbLinkUrlLocation').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData);
			$('#cbLinkUrlNewTab').prop('checked', currentImage.linkNewTab === true);
			break;
		case 'page':
			$('#slLinkPageOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData);
			break;
		case 'document':
			$('#slLinkDocumentOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData);
			break;
	    case 'onlineForm':
	        $('#slLinkFormOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData);
	        break;
		case 'email':
			$('#tbLinkEmail').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData);
			break;
		default:
    }

    $('input[type="radio"][name="rbButton1LinkType"][value="' + currentImage.button1LinkType + '"]').prop('checked', true);
    $('#tbButton1LinkUrlLocation').val('');
    $('#cbButton1LinkUrlNewTab').prop('checked', false);
    $('#tbButton1LinkEmail').val('');
    $('#slButton1LinkPageOptions')[0].selectedIndex = 0;
    $('#slButton1LinkDocumentOptions')[0].selectedIndex = 0;
    $('#slButton1LinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.button1LinkType) {
        case 'url':
            $('#tbButton1LinkUrlLocation').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData);
            $('#cbButton1LinkUrlNewTab').prop('checked', currentImage.button1LinkNewTab === true);
            break;
        case 'page':
            $('#slButton1LinkPageOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData);
            break;
        case 'document':
            $('#slButton1LinkDocumentOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData);
            break;
        case 'onlineForm':
            $('#slButton1LinkFormOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData);
            break;
        case 'email':
            $('#tbButton1LinkEmail').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData);
            break;
        default:
    }

    $('input[type="radio"][name="rbButton2LinkType"][value="' + currentImage.button2LinkType + '"]').prop('checked', true);
    $('#tbButton2LinkUrlLocation').val('');
    $('#cbButton2LinkUrlNewTab').prop('checked', false);
    $('#tbButton2LinkEmail').val('');
    $('#slButton2LinkPageOptions')[0].selectedIndex = 0;
    $('#slButton2LinkDocumentOptions')[0].selectedIndex = 0;
    $('#slButton2LinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.button2LinkType) {
        case 'url':
            $('#tbButton2LinkUrlLocation').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData);
            $('#cbButton2LinkUrlNewTab').prop('checked', currentImage.button2LinkNewTab === true);
            break;
        case 'page':
            $('#slButton2LinkPageOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData);
            break;
        case 'document':
            $('#slButton2LinkDocumentOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData);
            break;
        case 'onlineForm':
            $('#slButton2LinkFormOptions').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData);
            break;
        case 'email':
            $('#tbButton2LinkEmail').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData);
            break;
        default:
    }
};


imageSlideshowModule.setMobileLinkHtmlValuesFromJson = function () {
    $('.link-settings').hide();
    $('#linkSettings_' + imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkType).show();

    var currentImage = imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex];
    $('input[type="radio"][name="rbLinkType"][value="' + currentImage.linkType + '"]').prop('checked', true);
    $('#tbLinkUrlLocation').val('');
    $('#cbLinkUrlNewTab').prop('checked', false);
    $('#tbLinkEmail').val('');
    $('#slLinkPageOptions')[0].selectedIndex = 0;
    $('#slLinkDocumentOptions')[0].selectedIndex = 0;
    $('#slLinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.linkType) {
        case 'url':
            $('#tbLinkUrlLocation').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData);
            $('#cbLinkUrlNewTab').prop('checked', currentImage.linkNewTab === true);
            break;
        case 'page':
            $('#slLinkPageOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData);
            break;
        case 'document':
            $('#slLinkDocumentOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData);
            break;
        case 'onlineForm':
            $('#slLinkFormOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData);
            break;
        case 'email':
            $('#tbLinkEmail').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData);
            break;
        default:
    }

    $('input[type="radio"][name="rbButton1LinkType"][value="' + currentImage.button1LinkType + '"]').prop('checked', true);
    $('#tbButton1LinkUrlLocation').val('');
    $('#cbButton1LinkUrlNewTab').prop('checked', false);
    $('#tbButton1LinkEmail').val('');
    $('#slButton1LinkPageOptions')[0].selectedIndex = 0;
    $('#slButton1LinkDocumentOptions')[0].selectedIndex = 0;
    $('#slButton1LinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.button1LinkType) {
        case 'url':
            $('#tbButton1LinkUrlLocation').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData);
            $('#cbButton1LinkUrlNewTab').prop('checked', currentImage.button1LinkNewTab === true);
            break;
        case 'page':
            $('#slButton1LinkPageOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData);
            break;
        case 'document':
            $('#slButton1LinkDocumentOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData);
            break;
        case 'onlineForm':
            $('#slButton1LinkFormOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData);
            break;
        case 'email':
            $('#tbButton1LinkEmail').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData);
            break;
        default:
    }

    $('input[type="radio"][name="rbButton2LinkType"][value="' + currentImage.button2LinkType + '"]').prop('checked', true);
    $('#tbButton2LinkUrlLocation').val('');
    $('#cbButton2LinkUrlNewTab').prop('checked', false);
    $('#tbButton2LinkEmail').val('');
    $('#slButton2LinkPageOptions')[0].selectedIndex = 0;
    $('#slButton2LinkDocumentOptions')[0].selectedIndex = 0;
    $('#slButton2LinkFormOptions')[0].selectedIndex = 0;

    switch (currentImage.button2LinkType) {
        case 'url':
            $('#tbButton2LinkUrlLocation').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData);
            $('#cbButton2LinkUrlNewTab').prop('checked', currentImage.button2LinkNewTab === true);
            break;
        case 'page':
            $('#slButton2LinkPageOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData);
            break;
        case 'document':
            $('#slButton2LinkDocumentOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData);
            break;
        case 'onlineForm':
            $('#slButton2LinkFormOptions').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData);
            break;
        case 'email':
            $('#tbButton2LinkEmail').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData);
            break;
        default:
    }
};

imageSlideshowModule.setLinkJsonValuesFromHtml = function () {


    if (imageSlideshowModule.isEditingMobile) {

        imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkType = $('input[name=rbLinkType]:checked').val();

        switch (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkType) {
            case 'url':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $('#tbLinkUrlLocation').val();
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkNewTab = $('#cbLinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $('#slLinkPageOptions').val();
                break;
            case 'document':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $('#slLinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $('#slLinkFormOptions').val();
                break;
            case 'email':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].linkData = $('#tbLinkEmail').val();
                break;
            default:
        }

    }
    else {
        imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkType = $('input[name=rbLinkType]:checked').val();

        switch (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkType) {
            case 'url':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $('#tbLinkUrlLocation').val();
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkNewTab = $('#cbLinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $('#slLinkPageOptions').val();
                break;
            case 'document':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $('#slLinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $('#slLinkFormOptions').val();
                break;
            case 'email':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].linkData = $('#tbLinkEmail').val();
                break;
            default:
        }
    }
};


imageSlideshowModule.setButton1LinkJsonValuesFromHtml = function () {

    if (imageSlideshowModule.isEditingMobile) {
        imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkType = $('input[name=rbButton1LinkType]:checked').val();

        switch (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkType) {
            case 'url':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $('#tbButton1LinkUrlLocation').val();
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkNewTab = $('#cbButton1LinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $('#slButton1LinkPageOptions').val();
                break;
            case 'document':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $('#slButton1LinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $('#slButton1LinkFormOptions').val();
                break;
            case 'email':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1LinkData = $('#tbButton1LinkEmail').val();
                break;
            default:
        }
    }
    else {
        imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkType = $('input[name=rbButton1LinkType]:checked').val();

        switch (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkType) {
            case 'url':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $('#tbButton1LinkUrlLocation').val();
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkNewTab = $('#cbButton1LinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $('#slButton1LinkPageOptions').val();
                break;
            case 'document':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $('#slButton1LinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $('#slButton1LinkFormOptions').val();
                break;
            case 'email':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1LinkData = $('#tbButton1LinkEmail').val();
                break;
            default:
        }
    }
};


imageSlideshowModule.setButton2LinkJsonValuesFromHtml = function () {

    if (imageSlideshowModule.isEditingMobile) {
        imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkType = $('input[name=rbButton2LinkType]:checked').val();

        switch (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkType) {
            case 'url':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $('#tbButton2LinkUrlLocation').val();
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkNewTab = $('#cbButton2LinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $('#slButton2LinkPageOptions').val();
                break;
            case 'document':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $('#slButton2LinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $('#slButton2LinkFormOptions').val();
                break;
            case 'email':
                imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2LinkData = $('#tbButton2LinkEmail').val();
                break;
            default:
        }
    }
    else {
        imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkType = $('input[name=rbButton2LinkType]:checked').val();

        switch (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkType) {
            case 'url':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $('#tbButton2LinkUrlLocation').val();
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkNewTab = $('#cbButton2LinkUrlNewTab').prop('checked');
                break;
            case 'page':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $('#slButton2LinkPageOptions').val();
                break;
            case 'document':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $('#slButton2LinkDocumentOptions').val();
                break;
            case 'onlineForm':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $('#slButton2LinkFormOptions').val();
                break;
            case 'email':
                imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2LinkData = $('#tbButton2LinkEmail').val();
                break;
            default:
        }
    }
};

imageSlideshowModule.validateLinks = function () {

    var valid = true;

    var button1Text = $("#tbButton1Text").val();
    var button2Text = $("#tbButton2Text").val();

    if ( button1Text !== "" && !$('input[type="radio"][name="rbButton1LinkType"]').is(":checked") ) {
        valid = false;
        $("#tbButton1Text").addClass('input-has-error');
        $("#errorButton1Text").removeClass('hidden');
    }
    else {
        $("#tbButton1Text").removeClass('input-has-error');
        $("#errorButton1Text").addClass('hidden');
    }

    if ( button2Text !== "" && !$('input[type="radio"][name="rbButton2LinkType"]').is(":checked") ) {
        valid = false;
        $("#tbButton2Text").addClass('input-has-error');
        $("#errorButton2Text").removeClass('hidden');
    }
    else {
        $("#tbButton2Text").removeClass('input-has-error');
        $("#errorButton2Text").addClass('hidden');
    }

    //validate url links exist of ticked
    if ($("#rbLinkWebUrl").is(':checked')) {
        var url = $("#tbLinkUrlLocation").val();
        if (!sportsground.utils.is_valid_url(url)) {
            $("#tbLinkUrlLocation").closest('.form-group').removeClass('has-success').addClass('has-error');
            valid = false;
        }
        else {
            $("#tbLinkUrlLocation").parent('.form-group').removeClass('has-error');
        }
    }

    if ($("#rbButton1LinkWebUrl").is(':checked')) {
        var url2 = $("#tbButton1LinkUrlLocation").val();
        if (!sportsground.utils.is_valid_url(url2)) {
            $("#tbButton1LinkUrlLocation").closest('.form-group').removeClass('has-success').addClass('has-error');
            $("#errorButton1Text").removeClass('hidden');
            valid = false;
        }
        else {
            $("#errorButton1Text").addClass('hidden');
            $("#tbButton1LinkUrlLocation").parent('.form-group').removeClass('has-error');            
        }
    }

    if ($("#rbButton2LinkWebUrl").is(':checked')) {
        var url3 = $("#tbButton2LinkUrlLocation").val();
        if (!sportsground.utils.is_valid_url(url3)) {
            $("#tbButton2LinkUrlLocation").closest('.form-group').removeClass('has-success').addClass('has-error');
            $("#errorButton2Text").removeClass('hidden');
            valid = false;
        }
        else {
            $("#errorButton2Text").addClass('hidden');
            $("#tbButton2LinkUrlLocation").parent('.form-group').removeClass('has-error');
        }
    }

    if ($("#rbButton1LinkEmail").is(':checked')) {
        var email1 = $("#tbButton1LinkEmail").val();
        if (!sportsground.utils.validateEmailAddress(email1)) {
            $("#errorButton1Text").removeClass('hidden');
            $("#tbButton1LinkEmail").closest('.form-group').removeClass('has-success').addClass('has-error');
            valid = false;
        }
        else {
            $("#errorButton1Text").addClass('hidden');
            $("#tbButton1LinkEmail").parent('.form-group').removeClass('has-error');
        }
    }

    if ($("#rbButton2LinkEmail").is(':checked')) {
        var email2 = $("#tbButton2LinkEmail").val();
        if (!sportsground.utils.validateEmailAddress(email2)) {
            $("#errorButton2Text").removeClass('hidden');
            $("#tbButton2LinkEmail").closest('.form-group').removeClass('has-success').addClass('has-error');
            valid = false;
        }
        else {
            $("#errorButton2Text").addClass('hidden');
            $("#tbButton2LinkEmail").parent('.form-group').removeClass('has-error');
        }
    }

    return valid;

};

imageSlideshowModule.commitChanges = function (widgetInstanceId) {

    if (!imageSlideshowModule.validateLinks()) {
        return;
    }

    //remove any nulls from image data
    imageSlideshowModule.images = imageSlideshowModule.images.filter(function (x) {
        return x !== null;
    });

    imageSlideshowModule.mobileImages = imageSlideshowModule.mobileImages.filter(function (x) {
        return x !== null;
    });

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'ImageSlideshow',
		Settings: {
            ImagesJson: JSON.stringify(imageSlideshowModule.images),
            MobileImagesJson: JSON.stringify(imageSlideshowModule.mobileImages),
            Layout: imageSlideshowModule.layout,
            MobileLayout: imageSlideshowModule.mobileLayout,
            Crop: imageSlideshowModule.crop,
            Scale: imageSlideshowModule.scale,
            Randomize: $('#cbDisplayRandom').is(':checked'),
            NoControls: $('#cbControlNone').is(':checked'),
            ProgressDots: $('#cbControlProgressDots').is(':checked'),
            LeftArrow: $('#cbControlLeftArrow').is(':checked'),
            RightArrow: $('#cbControlRightArrow').is(':checked'),
            HideOnMobile: $("#hideWidget").is(':checked')
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202) {
				$('#modal-dialog').modal('show');
            }


            imageSlideshowModule.rebuildWidget(widgetInstanceId);
		}
	});

	$('#myModal').modal('hide');
    $('#hdnLayout_' + widgetInstanceId).val(imageSlideshowModule.layout);
    $('#hdnMobileLayout_' + widgetInstanceId).val(imageSlideshowModule.mobileLayout);

	$('#hdnCrop_' + widgetInstanceId).val(imageSlideshowModule.crop);

};

imageSlideshowModule.rebuildWidget = function (widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function (html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            imageSlideshowModule.create(widgetInstanceId);
        }
    });
};

imageSlideshowModule.loadSelectedImages = function () {
	$('.selected-image-thumb').remove();
	var imageIds = $.map(imageSlideshowModule.images, function (val) { return val.id; });
	$.ajax({
        url: '/asset/GetImageAssetUrls',
        type: 'POST',
        data: JSON.stringify(imageIds),
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			var rawHtml = $('#hbtSelectedThumb').html();
			var template = Handlebars.compile(rawHtml);
			for (var i = 0; i < data.length; i++) {
				$('#selectedImagesContainer').append(template(data[i]));
			}

			$('#selectedImagesContainer').sortable({
				cancel: 'input',
				cursor: 'move',
				items: '> .selected-image-thumb',
				handle: '.draghandle',
				update: function () {
					var sortedIds = $('#selectedImagesContainer').sortable('toArray');
					var sortedImages = [];
					for (var si = 0; si < sortedIds.length; si++) {
						for (var ui = 0; ui < imageSlideshowModule.images.length; ui++) {
							if (sortedIds[si] == imageSlideshowModule.images[ui].id) {
								sortedImages[si] = imageSlideshowModule.images[ui];
								break;
							}
						}
					}
					imageSlideshowModule.images = sortedImages;
				}
			});

            $('#selectedImagesContainer .selected-image-settings').on('click', function () {
                var imageId = $(this).closest('.selected-image-thumb').attr('id');
                imageSlideshowModule.isEditingMobile = false;

				$.ajax({
                    url: '/asset/GetImageAssetDetails',
                    type: 'GET',
                    data: { imageId: imageId },
					contentType: 'application/json; charset=utf-8',
                    success: function(data) {
                        $('#imgPreview').attr('src', data.WebOptSrc);
					}
				});

				for (var index = 0; index < imageSlideshowModule.images.length; index++) {
					if (imageSlideshowModule.images[index].id === imageId) {
						imageSlideshowModule.currentImageIndex = index;
						break;
					}
				}

                $('#taImageCaption').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].caption);
                $('#tbButton1Text').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button1Text);
                $('#tbButton2Text').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].button2Text);

                // text alignment
                if (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignTextOverlay === undefined)
                    imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignTextOverlay = "bottom";

                if (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].textOverlayMargin === undefined)
                    imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].textOverlayMargin = "25";
               
                if (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignTextOverlay === "top")
                    $("#txtAlignTop").prop('checked', 'checked');
                else
                    $("#txtAlignBottom").prop('checked', 'checked');

                $("#txtTextOverlayMargin").val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].textOverlayMargin);

                // button alignment
                if (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignButtonOverlay === undefined)
                    imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignButtonOverlay = "left";

                var alignButtonOverlay = imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignButtonOverlay;

                $(".image-slideshow-btnaligns").removeClass('selected');
                $(".image-slideshow-btnaligns[data-align='" + alignButtonOverlay + "']").addClass('selected');

                if (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignButtonOverlay === undefined)
                    imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].alignButtonOverlay = "left";

                // button type
                if (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].buttonType === undefined)
                    imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].buttonType = "button";

                if (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].buttonType === "button") {
                    $("#dvHyperlinkColor").addClass('hidden');
                    $("#rbTypeButton").prop('checked', 'checked');
                }
                else {
                    $("#dvHyperlinkColor").removeClass('hidden');
                    $("#rbTypeHyperlink").prop('checked', 'checked');
                }

                // hyperlink color
                var hyperlinkColor = $("#hdnFontFamilyColor").val();
                if ( $("#hdnSiteButtonColor").length > 0 )
                    hyperlinkColor = $("#hdnSiteButtonColor").val();

                if (imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].hyperlinkColor === undefined)
                    imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].hyperlinkColor = hyperlinkColor;

                $("#txtHyperLinkColor").val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].hyperlinkColor);

                $("#dvHyperlinkColor").find('.icon').css('background-color', imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].hyperlinkColor);

                try {
                    CKEDITOR.instances["photoSlideShowCkEditor"].destroy();
                }
                catch (e) {}
                
                $('#photoSlideShowCkEditor').val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].textOverlay);

                // Init CKEditor for text overlay
                setTimeout(function () {
                    var cachebuster = Math.round(new Date().getTime() / 1000);
                    CKEDITOR.replace('photoSlideShowCkEditor', {
                        customConfig: '/Content/ckeditor/photoslideshow_config.js?cb=' + cachebuster
                    });

                    CKEDITOR.instances["photoSlideShowCkEditor"].on('change', function (e) {
                        imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].textOverlay = CKEDITOR.instances['photoSlideShowCkEditor'].getData()
                    });

                }, 2000);

				imageSlideshowModule.setLinkHtmlValuesFromJson();

				$('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
					$('#tabImages_imageSettings').effect('slide', { direction: 'right', mode: 'show' }, 500);
                });

			});

            $('#selectedImagesContainer .selected-image-delete').on('click', function () {
				var imageId = $(this).closest('.selected-image-thumb').attr('id');
				bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected image from the slider?</p>', function (result) {
					if (!result)
						return;

                    $('#selectedImagesContainer #' + imageId).remove();
					for (var index = 0; index < imageSlideshowModule.images.length; index++) {
						if (imageSlideshowModule.images[index].id === imageId) {
							imageSlideshowModule.images.splice(index, 1);
							break;
						}
                    }

                    if (imageSlideshowModule.images.length > 20) {
                        $('#lblExceededMaxImages').show();
                        $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
                    }
                    else {
                        $('#lblExceededMaxImages').hide();
                        $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').removeAttr("disabled");
                    }
				});
				return false;
			});
		}
    });
        
};

imageSlideshowModule.loadSelectedMobileImages = function () {
    $('.selected-image-thumb').remove();
    var imageIds = $.map(imageSlideshowModule.mobileImages, function (val) { return val.id; });
    $.ajax({
        url: '/asset/GetImageAssetUrls',
        type: 'POST',
        data: JSON.stringify(imageIds),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var rawHtml = $('#hbtSelectedThumb').html();
            var template = Handlebars.compile(rawHtml);
            for (var i = 0; i < data.length; i++) {
                $('#selectedMobileImagesContainer').append(template(data[i]));
            }

            $('#selectedMobileImagesContainer').sortable({
                cancel: 'input',
                cursor: 'move',
                items: '> .selected-image-thumb',
                handle: '.draghandle',
                update: function () {
                    var sortedIds = $('#selectedMobileImagesContainer').sortable('toArray');
                    var sortedImages = [];
                    for (var si = 0; si < sortedIds.length; si++) {
                        for (var ui = 0; ui < imageSlideshowModule.mobileImages.length; ui++) {
                            if (sortedIds[si] == imageSlideshowModule.mobileImages[ui].id) {
                                sortedImages[si] = imageSlideshowModule.mobileImages[ui];
                                break;
                            }
                        }
                    }
                    imageSlideshowModule.mobileImages = sortedImages;
                }
            });

            $('#selectedMobileImagesContainer .selected-image-settings').on('click', function () {
                var imageId = $(this).closest('.selected-image-thumb').attr('id');
                imageSlideshowModule.isEditingMobile = true;
                $.ajax({
                    url: '/asset/GetImageAssetDetails',
                    type: 'GET',
                    data: { imageId: imageId },
                    contentType: 'application/json; charset=utf-8',
                    success: function (data) {
                        $('#imgPreview').attr('src', data.WebOptSrc);
                    }
                });

                for (var index = 0; index < imageSlideshowModule.mobileImages.length; index++) {
                    if (imageSlideshowModule.mobileImages[index].id === imageId) {
                        imageSlideshowModule.currentImageIndex = index;
                        break;
                    }
                }

                $('#taImageCaption').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].caption);
                $('#tbButton1Text').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button1Text);
                $('#tbButton2Text').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].button2Text);


                // text alignment
                if (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignTextOverlay === undefined)
                    imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignTextOverlay = "bottom";

                if (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].textOverlayMargin === undefined)
                    imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].textOverlayMargin = "25";

                if (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignTextOverlay === "top")
                    $("#txtAlignTop").prop('checked', 'checked');
                else
                    $("#txtAlignBottom").prop('checked', 'checked');

                $("#txtTextOverlayMargin").val(imageSlideshowModule.images[imageSlideshowModule.currentImageIndex].textOverlayMargin);

                // button alignment
                if (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignButtonOverlay === undefined)
                    imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignButtonOverlay = "left";

                var alignButtonOverlay = imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignButtonOverlay;

                $(".image-slideshow-btnaligns").removeClass('selected');
                $(".image-slideshow-btnaligns[data-align='" + alignButtonOverlay + "']").addClass('selected');

                if (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignButtonOverlay === undefined)
                    imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].alignButtonOverlay = "left";

                // button type
                if (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].buttonType === undefined)
                    imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].buttonType = "button";

                if (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].buttonType === "button") {
                    $("#dvHyperlinkColor").addClass('hidden');
                    $("#rbTypeButton").prop('checked', 'checked');
                }
                else {
                    $("#dvHyperlinkColor").removeClass('hidden');
                    $("#rbTypeHyperlink").prop('checked', 'checked');
                }

                // hyperlink color
                var hyperlinkColor = $("#hdnFontFamilyColor").val();
                if ($("#hdnSiteButtonColor").length > 0)
                    hyperlinkColor = $("#hdnSiteButtonColor").val();

                if (imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].hyperlinkColor === undefined)
                    imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].hyperlinkColor = hyperlinkColor;

                $("#txtHyperLinkColor").val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].hyperlinkColor);

                $("#dvHyperlinkColor").find('.icon').css('background-color', imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].hyperlinkColor);

                try {
                    CKEDITOR.instances["photoSlideShowCkEditor"].destroy();
                }
                catch (e) { }

                $('#photoSlideShowCkEditor').val(imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].textOverlay);

                // Init CKEditor for text overlay
                setTimeout(function () {
                    var cachebuster = Math.round(new Date().getTime() / 1000);
                    CKEDITOR.replace('photoSlideShowCkEditor', {
                        customConfig: '/Content/ckeditor/noncms_config.js?cb=' + cachebuster
                    });

                    CKEDITOR.instances["photoSlideShowCkEditor"].on('change', function (e) {
                        imageSlideshowModule.mobileImages[imageSlideshowModule.currentImageIndex].textOverlay = CKEDITOR.instances['photoSlideShowCkEditor'].getData();
                    });

                }, 2000);

                imageSlideshowModule.setMobileLinkHtmlValuesFromJson();

                $('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
                    $('#tabImages_imageSettings').effect('slide', { direction: 'right', mode: 'show' }, 500);
                });
            });

            $('#selectedMobileImagesContainer .selected-image-delete').on('click', function () {
                var imageId = $(this).closest('.selected-image-thumb').attr('id');
                bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected mobile image from the slider?</p>', function (result) {
                    if (!result)
                        return;

                    $('#selectedMobileImagesContainer #' + imageId).remove();
                    for (var index = 0; index < imageSlideshowModule.mobileImages.length; index++) {
                        if (imageSlideshowModule.mobileImages[index].id === imageId) {
                            imageSlideshowModule.mobileImages.splice(index, 1);
                            break;
                        }
                    }

                    if (imageSlideshowModule.mobileImages.length > 20) {
                        $('#lblMobileExceededMaxImages').show();
                        $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
                    }
                    else {
                        $('#lblMobileExceededMaxImages').hide();
                        $('#widget-edit-modal-ImageSlideshow').find('.widget-settings-update').removeAttr("disabled");
                    }
                });
                return false;
            });
        }
    });

};

imageSlideshowModule.showAdvancedOptions = function () {

};;
var kamarCalendarModule = extend(sportsground, 'sportsground.cms.widgets.kamarCalendar');

kamarCalendarModule.create = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);

    kamarCalendarModule.maxSummaryLength = 150;

    kamarCalendarModule.clientEvents = [];

    var isAgendaViewSelected = widget.find('.hdnIsAgendaSelected').val();
    if (isAgendaViewSelected == "True") {
        widget.find('.calendarview').addClass('hidden');
        kamarCalendarModule.getEvents(widgetInstanceId, false, true);
    }
    else {
        widget.find('.agendaview').addClass('hidden');
        kamarCalendarModule.createKamarCalendar(widgetInstanceId);
        kamarCalendarModule.getEvents(widgetInstanceId, false, false);
    }

    $("#prevEventMonth_" + widgetInstanceId).on('click', function () {
        var eventDate = $("#hdnEventDate_" + widgetInstanceId).val();
        var prevDate = moment(eventDate).subtract(1, 'months').toDate();
        $("#hdnEventDate_" + widgetInstanceId).val(prevDate);
        kamarCalendarModule.createKamarCalendar(widgetInstanceId);
    });

    $("#nextEventMonth_" + widgetInstanceId).on('click', function () {
        var eventDate = $("#hdnEventDate_" + widgetInstanceId).val();
        var nextDate = moment(eventDate).add(1, 'months').toDate();
        $("#hdnEventDate_" + widgetInstanceId).val(nextDate);
        kamarCalendarModule.createKamarCalendar(widgetInstanceId);
    });

    $("#prevAgnedaMonth_" + widgetInstanceId).on('click', function () {
        var eventDate = $("#hdnEventDate_" + widgetInstanceId).val();
        var prevDate = moment(eventDate).subtract(1, 'months').toDate();
        $("#hdnEventDate_" + widgetInstanceId).val(prevDate);

        var events = kamarCalendarModule.clientEvents;
        if (events.length > 0) {
            kamarCalendarModule.loadEventsInAgendaView(widgetInstanceId);
        } else {
            kamarCalendarModule.getEvents(widgetInstanceId, false, true);
        }
    });

    $("#nextAgnedaMonth_" + widgetInstanceId).on('click', function () {
        var eventDate = $("#hdnEventDate_" + widgetInstanceId).val();
        var nextDate = moment(eventDate).add(1, 'months').toDate();
        $("#hdnEventDate_" + widgetInstanceId).val(nextDate);

        var events = kamarCalendarModule.clientEvents;
        if (events.length > 0) {
            kamarCalendarModule.loadEventsInAgendaView(widgetInstanceId);
        } else {
            kamarCalendarModule.getEvents(widgetInstanceId, false, true);
        }
    });
};

kamarCalendarModule.createKamarCalendar = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);

    widget.find(".eventText").html('');
    $(".eventContent").removeClass('presentDate');
    $(".eventContent").removeClass('kamarSelectedDay');

    var loadEvents = true;
    var todayDate = $("#hdnEventDate_" + widgetInstanceId).val();

    if (todayDate == "" || todayDate == undefined) {
        todayDate = new Date();
        loadEvents = false;
    }

    var month = moment(todayDate).format('MMMM YYYY');

    if (!sportsground.ui.isMobile()) {
        widget.find("#calendarHeader").html('<h3>' + month + '</h3>');
    }
    else {
        var monthOnly = moment(todayDate).format('MMMM');
        var yearOnly = moment(todayDate).format('YYYY');
        var html = monthOnly + "<br/>" + yearOnly;
        widget.find("#calendarHeader").html('<h3>' + html + '</h3>');
    }

    var numOfDaysInMonth = moment(todayDate).daysInMonth()
    var currentDay = moment(todayDate).format('ddd');
    var currentMonth = moment(todayDate).format('MM');
    var currentYear = moment(todayDate).format('YYYY');

    var startOfMonth = moment(todayDate).startOf('month').format('ddd');

    var html = '';
    var dayscount = 1;
    var td = 1;

    if (startOfMonth == 'Mon') {
        td = 2;
    }
    else if (startOfMonth == 'Tue') {
        td = 3;
    }
    else if (startOfMonth == 'Wed') {
        td = 4;
    }
    else if (startOfMonth == 'Thu') {
        td = 5;
    }
    else if (startOfMonth == 'Fri') {
        td = 6;
    }
    else if (startOfMonth == 'Sat') {
        td = 7;
    }

    var lastmonthLastDay = 0;
    if (td != 1) {
        lastmonthDays = moment(todayDate).subtract(1, 'months').daysInMonth();
    }

    var lastMonth = moment(todayDate).subtract(1, 'months').format('MM');
    var nextMonth = moment(todayDate).add(1, 'months').format('MM');
    var nextmonthdays = 1;

    widget.find("#bodyKamarCalendar").find('tr').each(function () {
        if (!$(this).hasClass('row1')) {
            td = 1;
        }
        if (td != 1) {
            var prevtd = td - 1;

            for (var j = prevtd; j <= prevtd; j--) {
                $(this).find('td[data-day=' + j + ']').find('.daytext').html(lastmonthDays);
                $(this).find('td[data-day=' + j + ']').addClass('disabledtd');

                var lastYear = currentYear;
                if (lastMonth == 12) {
                    lastYear = currentYear - 1;
                }
                var lastmonthDate = lastmonthDays;
                if (lastmonthDays.toString().length == 1) {
                    lastmonthDate = '0' + lastmonthDays;
                }
                $(this).find('td[data-day=' + j + ']').attr('date', '' + lastYear + '' + '' + lastMonth + '' + '' + lastmonthDate + '');

                lastmonthDays--;
                if (j == 0)
                    break;
            }
        }
        if (dayscount > numOfDaysInMonth) {
            for (var l = 1; l <= 7; l++) {
                $(this).find('td[data-day=' + l + ']').find('.daytext').html(nextmonthdays);
                $(this).find('td[data-day=' + l + ']').addClass('disabledtd');
                var nextYear = currentYear;
                if (nextMonth == 1) {
                    nextYear = currentYear + 1;
                }
                var nextmonthDate = nextmonthdays;
                if (nextmonthdays.toString().length == 1) {
                    nextmonthDate = '0' + nextmonthdays;
                }
                $(this).find('td[data-day=' + l + ']').attr('date', '' + nextYear + '' + '' + nextMonth + '' + '' + nextmonthDate + '');
                nextmonthdays++;
            }
        }
        else {
            for (var i = td; i <= 7; i++) {
                $(this).find('td[data-day=' + i + ']').find('.daytext').html(dayscount);
                $(this).find('td[data-day=' + i + ']').removeClass('disabledtd');
                var date = dayscount;
                if (dayscount.toString().length == 1) {
                    date = '0' + dayscount;
                }
                $(this).find('td[data-day=' + i + ']').attr('date', '' + currentYear + '' + '' + currentMonth + '' + '' + date + '');
                dayscount++;
                if (dayscount > numOfDaysInMonth) {
                    if (i != 7) {
                        for (var k = i + 1; k <= 7; k++) {
                            $(this).find('td[data-day=' + k + ']').find('.daytext').html(nextmonthdays);
                            $(this).find('td[data-day=' + k + ']').addClass('disabledtd');

                            var nextYear = currentYear;
                            if (nextMonth == 1) {
                                nextYear = currentYear + 1;
                            }
                            var nextmonthDate = nextmonthdays;
                            if (nextmonthdays.toString().length == 1) {
                                nextmonthDate = '0' + nextmonthdays;
                            }
                            $(this).find('td[data-day=' + k + ']').attr('date', '' + nextYear + '' + '' + nextMonth + '' + '' + nextmonthDate + '');
                            nextmonthdays++;
                        }
                    }
                    break;
                }
            }
        }

    });

    if (loadEvents) {
        var events = [];
        events = kamarCalendarModule.clientEvents;
        if (events.length > 0) {
            kamarCalendarModule.loadEventsInCalendarView(widgetInstanceId, true);
        }
        else {
            kamarCalendarModule.getEvents(widgetInstanceId, true);
        }
    }

    if (sportsground.ui.isMobile()) {
        $("#bodyKamarCalendar td").css('border', 'none');
        $("#bodyKamarCalendar td").css('height', '20px');
        $("#bodyKamarCalendar .eventText").css('float', 'none');
        $("#bodyKamarCalendar .eventText").css('height', '30%');
        $(".daytext").css('float', 'inherit');
        $(".daytext").css('text-align', 'center');
    }

};

kamarCalendarModule.getEvents = function (widgetInstanceId, flag, agendaView) {
    var widget = $('#widget_' + widgetInstanceId);
    widget.find(".eventText").html('');

    if (sportsground.ui.isMobile()) {
        $(".eventContent").removeClass('kamarSelectedDay');
        widget.find('.mobileEvenDesc').html('');
        widget.find('.mobileEvenDesc').addClass('hidden');
    }

    if (agendaView) {
        widget.find('#bodyKamarAgenda').html('');
    }

    $.ajax({
        url: '/cms/kamarwidget/getCalendarEvents?WidgetInstanceId=' + widgetInstanceId,
        type: 'GET',
        success: function (data) {
            if (data != null) {
                if (data.success == false) {
                    bootbox.alert("Please set up Kamar to use this widget.");
                    sportsground.cms.widgets.remove(widgetInstanceId);
                    $("#myModal").modal('hide');
                    return false;
                }

                var result = $.parseJSON(data.result);
                var dataEvents = result[0].Events;

                kamarCalendarModule.clientEvents = dataEvents;
                if (!agendaView) {
                    kamarCalendarModule.loadEventsInCalendarView(widgetInstanceId, flag);
                }
                else {
                    kamarCalendarModule.loadEventsInAgendaView(widgetInstanceId, flag)
                }
            }
        }
    });
}

kamarCalendarModule.loadEventsInCalendarView = function (widgetInstanceId, flag) {
    var dataEvents = kamarCalendarModule.clientEvents;

    var widget = $('#widget_' + widgetInstanceId);
    
    var selectedCategories = widget.find('.categoriesForModal').val();
    if (selectedCategories != "") {
        var filterdEvents = [];

        var aeroEvents = [];
        if (selectedCategories.indexOf('Aero') >= 0) {
            aeroEvents = dataEvents.filter(function (x) {
                return x.Colour == "Aero";
            });
            filterdEvents = filterdEvents.concat(aeroEvents);
        }

        var amazonEvents = [];
        if (selectedCategories.indexOf('Amazon') >= 0) {
            amazonEvents = dataEvents.filter(function (x) {
                return x.Colour == "Amazon";
            });
            filterdEvents = filterdEvents.concat(amazonEvents);
        }

        var auburnEvents = [];
        if (selectedCategories.indexOf('Auburn') >= 0) {
            auburnEvents = dataEvents.filter(function (x) {
                return x.Colour == "Auburn";
            });
            filterdEvents = filterdEvents.concat(auburnEvents);
        }

        var blackEvents = [];
        if (selectedCategories.indexOf('Black') >= 0) {
            blackEvents = dataEvents.filter(function (x) {
                return x.Colour == "Black";
            });
            filterdEvents = filterdEvents.concat(blackEvents);
        }

        var blueEvents = [];
        if (selectedCategories.indexOf('Blue') >= 0) {
            blueEvents = dataEvents.filter(function (x) {
                return x.Colour == "Blue";
            });
            filterdEvents = filterdEvents.concat(blueEvents);
        }

        var greenEvents = [];
        if (selectedCategories.indexOf('Green') >= 0) {
            greenEvents = dataEvents.filter(function (x) {
                return x.Colour == "Green";
            });
            filterdEvents = filterdEvents.concat(greenEvents);
        }

        var orangeEvents = [];
        if (selectedCategories.indexOf('Orange') >= 0) {
            orangeEvents = dataEvents.filter(function (x) {
                return x.Colour == "Orange";
            });
                filterdEvents = filterdEvents.concat(orangeEvents);
        }

        var purpleEvents = [];
        if (selectedCategories.indexOf('Purple') >= 0) {
            purpleEvents = dataEvents.filter(function (x) {
                return x.Colour == "Purple";
            });
            filterdEvents = filterdEvents.concat(purpleEvents);
        }

        var redEvents = [];
        if (selectedCategories.indexOf('Red') >= 0) {
            redEvents = dataEvents.filter(function (x) {
                return x.Colour == "Red";
            });
                filterdEvents = filterdEvents.concat(redEvents);
            }

        var tangerineEvents = [];
        if (selectedCategories.indexOf('Tangerine') >= 0) {
            tangerineEvents = dataEvents.filter(function (x) {
                return x.Colour == "Tangerine";
            });
                filterdEvents = filterdEvents.concat(tangerineEvents);
        }

        var tealEvents = [];
        if (selectedCategories.indexOf('Teal') >= 0) {
            tealEvents = dataEvents.filter(function (x) {
                return x.Colour == "Teal";
            });
            filterdEvents = filterdEvents.concat(tealEvents);
        }

        var violetEvents = [];
        if (selectedCategories.indexOf('Violet') >= 0) {
            violetEvents = dataEvents.filter(function (x) {
                return x.Colour == "Violet";
            });
            filterdEvents = filterdEvents.concat(violetEvents);
        }

        dataEvents = filterdEvents;
    }

    var todayDate = $("#hdnEventDate_" + widgetInstanceId).val();
    if (todayDate == "" || todayDate == undefined) {
        todayDate = new Date();
        $("#hdnEventDate_" + widgetInstanceId).val(todayDate);
    }

    var currentMonth = moment(todayDate).format('MM');
    var currentYear = moment(todayDate).format('YYYY');

    var lastMonth = moment(todayDate).subtract(1, 'months').format('MM');
    var lastYear = currentYear;
    if (lastMonth == 12) {
        lastYear = lastYear - 1;
    }

    var nextMonth = moment(todayDate).add(1, 'months').format('MM');
    var nextYear = currentYear;
    if (nextMonth == 1) {
        nextYear = nextYear + 1;
    }

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

        if (dataEvents[i].Summary != undefined && dataEvents[i].Summary != null && dataEvents[i].Summary.length > kamarCalendarModule.maxSummaryLength) {
            dataEvents[i].Summary = dataEvents[i].Summary.substring(0, kamarCalendarModule.maxSummaryLength);
        }

        var startDate = moment(dataEvents[i].DateStart, "YYYYMMDD").toDate().toDateOnlyLocalISOString();

        var finishDate = "";
        if (dataEvents[i].DateFinish != null) {
            finishDate = moment(dataEvents[i].DateFinish, "YYYYMMDD").toDate().toDateOnlyLocalISOString();
        }

        var match = false;
        if (moment(startDate).format('MM') == currentMonth && moment(startDate).format('YYYY') == currentYear) {
            match = true;
        }
        else if (finishDate != "" && moment(finishDate).format('MM') == currentMonth && moment(finishDate).format('YYYY') == currentYear) {
            match = true;
        }
        else if (moment(startDate).format('MM') == lastMonth && moment(startDate).format('YYYY') == lastYear) {
            match = true;
        }
        else if (finishDate != "" && moment(finishDate).format('MM') == lastMonth && moment(finishDate).format('YYYY') == lastYear) {
            match = true;
        }
        else if (moment(startDate).format('MM') == nextMonth && moment(startDate).format('YYYY') == nextYear) {
            match = true;
        }
        else if (finishDate != "" && moment(finishDate).format('MM') == nextMonth && moment(finishDate).format('YYYY') == nextYear) {
            match = true;
        }

        var presentDate = moment(new Date()).format("YYYYMMDD");

        if (match) {
            widget.find("#bodyKamarCalendar").find('td').each(function () {
                var tdDate = $(this).attr('date');

                if (tdDate == presentDate) {
                    $(this).addClass('presentDate');
                }

                tdDate = moment(tdDate, "YYYYMMDD").toDate().toDateOnlyLocalISOString();
                var append = false;

                if (finishDate != "") {
                    if (tdDate >= startDate && tdDate <= finishDate) {
                        append = true;
                    }
                }
                else if (tdDate == startDate) {
                    append = true;
                }

                if (append) {
                    var startTime = dataEvents[i].TimeStart;
                    var finishTime = dataEvents[i].TimeFinish;
                    var description = dataEvents[i].Description;
                    var location = dataEvents[i].Location;
                    var content = '';
                    if (startTime != null && finishTime != null) {
                        startTime = moment(startTime, 'HH:mm').format('hh:mm a');
                        finishTime = moment(finishTime, 'HH:mm').format('hh:mm a');
                        content += '<p>' + startTime + ' to ' + finishTime + '</p>';
                    }
                    if (location != null) {
                        content += '<p>' + location + '</p>';
                    }
                    if (description != null) {
                        content += '<p><i>' + description + '</i></p>';
                    }
                        
                    var cssColor = dataEvents[i].Colour;

                    if (dataEvents[i].Colour == "Tangerine") {
                        cssColor = "#E57E5C";
                    }
                    else if (dataEvents[i].Colour == "Aero") {
                        cssColor = "#009DC1";
                    }
                    else if (dataEvents[i].Colour == "Amazon") {
                        cssColor = "#337F36";
                    }
                    else if (dataEvents[i].Colour == "Auburn") {
                        cssColor = "#992202";
                    }
                    else if (dataEvents[i].Colour == "Blue") {
                        cssColor = "#2366C9";
                    }
                    else if (dataEvents[i].Colour == "Green") {
                        cssColor = "#15AF15";
                    }
                    else if (dataEvents[i].Colour == "Purple") {
                        cssColor = "#6620A8";
                    }
                    else if (dataEvents[i].Colour == "Red") {
                        cssColor = "#F41721";
                    }
                    else if (dataEvents[i].Colour == "Teal") {
                        cssColor = "#16B8A0";
                    }
                    else if (dataEvents[i].Colour == "Violet") {
                        cssColor = "#9377AE";
                    }

                    if (!sportsground.ui.isMobile()) {
                        $(this).find('.eventText').append('<p class="eventpop" data-container="body" data-toggle="popover" data-placement="top" data-original-title="' + dataEvents[i].Summary + '" data-content="' + content + '"><span style="background-color:' + cssColor + '"></span>' + dataEvents[i].Summary + '</p><br/>');
                    }
                    else {
                        $(this).find('.eventText').append('<p class="hidden" title="' + dataEvents[i].Summary + '" starttime="' + dataEvents[i].TimeStart + '" finishtime="' + dataEvents[i].TimeStart + '" location="' + dataEvents[i].Location + '" description="' + dataEvents[i].Description + '" color="' + dataEvents[i].Colour + '"></p>');
                        if ($(this).find('.eventText').find('span[color="' + dataEvents[i].Colour + '"]').length == 0) {
                            $(this).find('.eventText').append('<span color="' + dataEvents[i].Colour + '" style="background-color:' + cssColor + '" class="dot"></span>');
                        }
                    }
                }
            });
        }
    }

    $(".eventpop").popover({ trigger: "manual", html: true, animation: false })
        .on("mouseenter", function () {
            var _this = this;
            $(this).addClass("eventhovercolor");
            $(this).popover("show");
            $(".popover").on("mouseleave", function () {
                $(_this).popover('hide');
            });
        }).on("mouseleave", function () {
            var _this = this;
            $(_this).removeClass("eventhovercolor");
            $(_this).popover("hide");
        });

    if (sportsground.ui.isMobile()) {
        $(".eventContent").on('click', function () {

            $(".eventContent").removeClass('kamarSelectedDay');
            $(this).addClass('kamarSelectedDay');
            var date = $(this).attr('date');
            date = moment(moment(date, "YYYYMMDD").toDate()).format("dddd Do");

            var html = '<div class="row"><h3><b>' + date + '</b></h3></div>';

            $(this).find('p').each(function () {
                html += '<div class="row">';
                var startTime = $(this).attr('starttime');
                var finishTime = $(this).attr('finishtime');
                var summary = $(this).attr('title');
                var description = $(this).attr('description');
                var location = $(this).attr('location');
                var color = $(this).attr('color');

                if (color == "Tangerine") {
                    color = "#F2D600";
                }
                else if (color == "Aero") {
                    cssColour = "#BFE6D7";
                }
                else if (color == "Amazon") {
                    cssColour = "#7CFC00";
                }
                else if (color == "Auburn") {
                    cssColour = "#A52A2A";
                }

                html += '<div class="row" style="display: inline-flex;"><div style="background-color:' + color + ';width: 5px;"></div>';
                html += '<div style="padding: 5px;"><p><b>' + summary + '</b>';
                if (startTime != 'null' && finishTime != 'null') {
                    startTime = moment(startTime, 'HH:mm').format('h:mma');
                    finishTime = moment(finishTime, 'HH:mm').format('h:mma');
                    html += ' - ' + startTime + ' to ' + finishTime;
                }
                html += '</p></div></div>';
                if (location != 'null') {
                    html += '<div class="row location-description"><p>' + location + '</p></div>';
                }

                if (description != 'null') {
                    html += '<div class="row location-description">' + description + '</div>';
                }
                html += "</div>";
            });
            html += '</table></div>';
            widget.find('.mobileEvenDesc').removeClass('hidden');
            widget.find('.mobileEvenDesc').html('');
            widget.find('.mobileEvenDesc').html(html);

            $([document.documentElement, document.body]).animate({
                scrollTop: widget.find('.calendarview').offset().top + 30
            }, 500);
        });
    }
};

kamarCalendarModule.loadEventsInAgendaView = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);
    widget.find('#bodyKamarAgenda').html('');
    var todayDate = $("#hdnEventDate_" + widgetInstanceId).val();

    if (todayDate == "" || todayDate == undefined) {
        todayDate = new Date();
        $("#hdnEventDate_" + widgetInstanceId).val(todayDate);
    }

    var month = moment(todayDate).format('MMMM YYYY');

    if (!sportsground.ui.isMobile()) {
        widget.find("#agendaHeader").html('<h3>' + month + '</h3>');
    }
    else {
        var monthOnly = moment(todayDate).format('MMMM');
        var yearOnly = moment(todayDate).format('YYYY');
        var html = monthOnly + "<br/>" + yearOnly;
        widget.find("#agendaHeader").html('<h3>' + html + '</h3>');
    }

    
    var dataEvents = kamarCalendarModule.clientEvents;

    var selectedCategories = widget.find('.categoriesForModal').val();
    if (selectedCategories != "") {
        var filterdEvents = [];

        var aeroEvents = [];
        if (selectedCategories.indexOf('Aero') >= 0) {
            aeroEvents = dataEvents.filter(function (x) {
                return x.Colour == "Aero";
            });
            filterdEvents = filterdEvents.concat(aeroEvents);
        }

        var amazonEvents = [];
        if (selectedCategories.indexOf('Amazon') >= 0) {
            amazonEvents = dataEvents.filter(function (x) {
                return x.Colour == "Amazon";
            });
            filterdEvents = filterdEvents.concat(amazonEvents);
        }

        var auburnEvents = [];
        if (selectedCategories.indexOf('Auburn') >= 0) {
            auburnEvents = dataEvents.filter(function (x) {
                return x.Colour == "Auburn";
            });
            filterdEvents = filterdEvents.concat(auburnEvents);
        }

        var blackEvents = [];
        if (selectedCategories.indexOf('Black') >= 0) {
            blackEvents = dataEvents.filter(function (x) {
                return x.Colour == "Black";
            });
            filterdEvents = filterdEvents.concat(blackEvents);
        }

        var blueEvents = [];
        if (selectedCategories.indexOf('Blue') >= 0) {
            blueEvents = dataEvents.filter(function (x) {
                return x.Colour == "Blue";
            });
            filterdEvents = filterdEvents.concat(blueEvents);
        }

        var greenEvents = [];
        if (selectedCategories.indexOf('Green') >= 0) {
            greenEvents = dataEvents.filter(function (x) {
                return x.Colour == "Green";
            });
            filterdEvents = filterdEvents.concat(greenEvents);
        }

        var orangeEvents = [];
        if (selectedCategories.indexOf('Orange') >= 0) {
            orangeEvents = dataEvents.filter(function (x) {
                return x.Colour == "Orange";
            });
            filterdEvents = filterdEvents.concat(orangeEvents);
        }

        var purpleEvents = [];
        if (selectedCategories.indexOf('Purple') >= 0) {
            purpleEvents = dataEvents.filter(function (x) {
                return x.Colour == "Purple";
            });
            filterdEvents = filterdEvents.concat(purpleEvents);
        }

        var redEvents = [];
        if (selectedCategories.indexOf('Red') >= 0) {
            redEvents = dataEvents.filter(function (x) {
                return x.Colour == "Red";
            });
            filterdEvents = filterdEvents.concat(redEvents);
        }

        var tangerineEvents = [];
        if (selectedCategories.indexOf('Tangerine') >= 0) {
            tangerineEvents = dataEvents.filter(function (x) {
                return x.Colour == "Tangerine";
            });
            filterdEvents = filterdEvents.concat(tangerineEvents);
        }

        var tealEvents = [];
        if (selectedCategories.indexOf('Teal') >= 0) {
            tealEvents = dataEvents.filter(function (x) {
                return x.Colour == "Teal";
            });
            filterdEvents = filterdEvents.concat(tealEvents);
        }

        var violetEvents = [];
        if (selectedCategories.indexOf('Violet') >= 0) {
            violetEvents = dataEvents.filter(function (x) {
                return x.Colour == "Violet";
            });
            filterdEvents = filterdEvents.concat(violetEvents);
        }

        dataEvents = filterdEvents;
    }

    var currentMonth = moment(todayDate).format('MM');
    var currentYear = moment(todayDate).format('YYYY');

    var numOfDaysInMonth = moment(todayDate).daysInMonth();

    var html = '';
    for (var i = 1; i <= numOfDaysInMonth; i++) {
        var date = i;
        if (date.toString().length == 1) {
            date = '0' + date;
        }

        var dayDate = '' + currentYear + '' + '' + currentMonth + '' + date;
        dayDate = moment(dayDate, "YYYYMMDD").toDate().toDateOnlyLocalISOString();


        var matchedEvents = dataEvents.filter(function (x) {
            return moment(x.DateStart, "YYYYMMDD").toDate().toDateOnlyLocalISOString() == dayDate ||
                x.DateFinish != null &&
                dayDate >= moment(x.DateStart, "YYYYMMDD").toDate().toDateOnlyLocalISOString() &&
                                  dayDate <= moment(x.DateFinish, "YYYYMMDD").toDate().toDateOnlyLocalISOString();
        });

        if (matchedEvents.length > 0) {

            var titleDate = '' + currentYear + '' + '' + currentMonth + '' + date;
            titleDate = moment(moment(titleDate, "YYYYMMDD").toDate()).format('dddd, Do MMMM')

            html += '<tr class="agendaDay kamarAgendaViewDayTitle"><td colspan="2">' + titleDate + '</td>';
            html += '<td class="time-desc">Time</td>';
            html += '<td class="time-desc">Location</td>';
            html += '</tr >';
            for (var j = 0; j < matchedEvents.length; j++) {

                if (matchedEvents[j].Summary != undefined && matchedEvents[j].Summary != null && matchedEvents[j].Summary.length > kamarCalendarModule.maxSummaryLength) {
                    matchedEvents[j].Summary = matchedEvents[j].Summary.substring(0, kamarCalendarModule.maxSummaryLength);
                }

                var cssColour = matchedEvents[j].Colour;
                if (matchedEvents[j].Colour == "Tangerine") {
                    cssColour = "#F2D600";
                }
                else if (matchedEvents[j].Colour == "Aero") {
                    cssColour = "#BFE6D7";
                }
                else if (matchedEvents[j].Colour == "Amazon") {
                    cssColour = "#7CFC00";
                }
                else if (matchedEvents[j].Colour == "Auburn") {
                    cssColour = "#A52A2A";
                }


                html += '<tr style="height:80px;">';
                html += '<td style="width:1%;background-color:' + cssColour + '"></td>';
                html += '<td style="width:59%;"><p class="title">' + matchedEvents[j].Summary + '</p>';

                if (matchedEvents[j].Description != null) {
                    html += '<p>' + matchedEvents[j].Description + '</p>';
                }
                html += '</td>';

                html += '<td style="width:15%;">';
                if (matchedEvents[j].TimeStart != null && matchedEvents[j].TimeFinish != null) {
                    var startTime = moment(matchedEvents[j].TimeStart, 'HH:mm').format('h:mma');
                    var finishTime = moment(matchedEvents[j].TimeFinish, 'HH:mm').format('h:mma');
                    html += startTime + ' - ' + finishTime;
                }
                html += '</td>';

                html += '<td style="width:25%;">';
                if (matchedEvents[j].Location != null) {
                    html += matchedEvents[j].Location;
                }
                html += '</td>';

                html += '</tr>';
            }
        }
    }

    if (html == '') {
        html = '<tr><td class="align-center" colspan="4">No events scheduled - please check back soon</td></tr>';
    }

    widget.find('#bodyKamarAgenda').html(html);
}

kamarCalendarModule.modalCreated = function (widgetInstanceId) {
    var widgetDom = $("#widget_" + widgetInstanceId);

    var selectedFilters = widgetDom.find('.categoriesForModal').val();

    var selectList = $("#calendarCategoryIds_" + widgetInstanceId);
    selectList.multiselect({
        templates: {
            button: '<button type="button" class="btn-primary multiselect dropdown-toggle" data-toggle="dropdown"></button>',
            li: '<li><a href="javascript:void(0);"><span class="kamar-settings-colors"></span><label class="old"></label></a></li>'
        }
    }).multiselect('select', selectedFilters.split(','));

    var settingsClass = $('.kamar-settings-colors');
    $.each(settingsClass, function () {
        var color = $(this).next('label').find('input').val();
        var newColorClass = "kamar-" + color.toLowerCase();
        $(this).addClass(newColorClass);
    });

};

kamarCalendarModule.commitChanges = function (widgetInstanceId) {
    var widget = $("#widget_" + widgetInstanceId);

    if ($("#rbSelectCalendarView").is(":checked")) {
        widget.find(".hdnIsAgendaSelected").val("False");
        widget.find('.calendarview').removeClass('hidden');
        widget.find('.agendaview').addBack('hidden');
    }
    if ($("#rbSelectAgendaView").is(":checked")) {
        widget.find(".hdnIsAgendaSelected").val("True");
        widget.find('.agendaview').removeClass('hidden');
        widget.find('.calendarview').addClass('hidden');
    }

    var selectedCategories = [];
    $('#calendarCategoryIds_' + widgetInstanceId + ' option:selected').each(function () {
        selectedCategories.push($(this).attr('value'));
    });
    widget.find('.categoriesForModal').val(selectedCategories);

    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'KamarCalendar',
        Settings: {
            isAgendaViewSelected: $("#rbSelectAgendaView").is(":checked"),
            SelectedCategories: JSON.stringify(selectedCategories)
        }
    };

    kamarCalendarModule.unbindFilterClickEvents(widgetInstanceId);

    $("#hdnEventDate_" + widgetInstanceId).val('');
    widget.find(".eventText").html('');
    kamarCalendarModule.updateWidgetSettings(widgetSettings);
    kamarCalendarModule.create(widgetInstanceId);
    $("#myModal").modal('hide');
};

kamarCalendarModule.updateWidgetSettings = function (widgetSettings) {
    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202) {
                $("#modal-dialog").modal('show');
            }
        }
    });
};

kamarCalendarModule.unbindFilterClickEvents = function (widgetInstanceId) {
    $("#prevEventMonth_" + widgetInstanceId).unbind("click");
    $("#nextEventMonth_" + widgetInstanceId).unbind("click");
    $("#prevAgnedaMonth_" + widgetInstanceId).unbind("click");
    $("#nextAgnedaMonth_" + widgetInstanceId).unbind("click");
};
var kamarNoticesModule = extend(sportsground, 'sportsground.cms.widgets.kamarNotices');

kamarNoticesModule.create = function (widgetInstanceId) {
    
    $('#prevNotice_' + widgetInstanceId).click(function () {
        var currentDate = $('#hdnNoticeDate_' + widgetInstanceId).val();
        currentDate = moment(currentDate, "YYYYMMDD").toDate();
        currentDate = moment(currentDate).subtract(1, 'days').format('YYYYMMDD');
        $('#hdnNoticeDate_' + widgetInstanceId).val(currentDate);
        kamarNoticesModule.loadNotices(widgetInstanceId);
    });

    $('#nextNotice_' + widgetInstanceId).click(function () {
        var currentDate = $('#hdnNoticeDate_' + widgetInstanceId).val();
        currentDate = moment(currentDate, "YYYYMMDD").toDate();
        currentDate = moment(currentDate).add(1, 'days').format('YYYYMMDD');
        $('#hdnNoticeDate_' + widgetInstanceId).val(currentDate);
        kamarNoticesModule.loadNotices(widgetInstanceId);
    });

    kamarNoticesModule.loadNotices(widgetInstanceId);
};
kamarNoticesModule.loadNotices = function (widgetInstanceId) {

    $.ajax({
        url: '/cms/kamarwidget/getNotices?WidgetInstanceId=' + widgetInstanceId,
        type: 'GET',
        success: function (data) {
            if (data != null) {

                if (data.success == false) {
                    bootbox.alert("Please set up Kamar to use this widget.");
                    sportsground.cms.widgets.remove(widgetInstanceId);
                    return false;
                }

                var result = $.parseJSON(data.result);
                kamarNoticesModule.Notices = [];

                var PrevOrNextDate = $('#hdnNoticeDate_' + widgetInstanceId).val();
                var currentDate = new Date();
                if (PrevOrNextDate != undefined && PrevOrNextDate != "") {
                    currentDate = PrevOrNextDate;
                } else {
                    currentDate = moment(new Date()).format("YYYYMMDD");
                }

                var headerDisplayDate = moment(currentDate, "YYYYMMDD").toDate();

                if (!sportsground.ui.isMobile()) {
                    $("#currentNoticeDateOnly_" + widgetInstanceId).addClass('hidden');
                    headerDisplayDate = moment(headerDisplayDate).format('dddd DD MMMM YYYY');
                    $("#currentNoticeDate_" + widgetInstanceId).html(headerDisplayDate);
                }
                else {
                    $("#currentNoticeDateOnly_" + widgetInstanceId).removeClass('hidden');
                    $('#prevNotice_' + widgetInstanceId).addClass('left-mobile-arrow');
                    $('#nextNotice_' + widgetInstanceId).addClass('right-mobile-arrow');

                    var headerDisplayDayOnly = moment(headerDisplayDate).format('dddd');
                    $("#currentNoticeDate_" + widgetInstanceId).html(headerDisplayDayOnly);

                    var headerDisplayDateOnly = moment(headerDisplayDate).format('DD MMMM YYYY');
                    $("#currentNoticeDateOnly_" + widgetInstanceId).html(headerDisplayDateOnly);
                }


                $('#hdnNoticeDate_' + widgetInstanceId).val(currentDate);

                for (var i = 0; i < result.length; i++) {
                    var insertData = false;
                    if (result[i].DateFinish != "") {
                        var noticeDate = moment(result[i].Date, "YYYYMMDD").toDate().toDateOnlyLocalISOString();
                        var noticeFinishDate = moment(result[i].DateFinish, "YYYYMMDD").toDate().toDateOnlyLocalISOString();
                        var dateToCompare = moment(currentDate, "YYYYMMDD").toDate().toDateOnlyLocalISOString(); 

                        if (dateToCompare >= noticeDate && dateToCompare <= noticeFinishDate) {
                            insertData = true;
                        }
                    }
                    else if (result[i].Date == currentDate) {
                        insertData = true;
                    }

                    if (insertData) {
                        var date = moment(result[i].Date, "YYYYMMDD").toString().substring(0, 10);
                        var meetingDate = "";
                        if (result[i].MeetingDate != null && result[i].MeetingDate != "") {
                            meetingDate = moment(result[i].MeetingDate, "YYYYMMDD").toString().substring(0, 10);
                        }
                        var widgetWidth = $("#widget_" + widgetInstanceId).width();
                        var mobileMeetingClass = "";
                        var webMeetingClass = "";
                        if (widgetWidth < 300 || sportsground.ui.isMobile()) {
                            webMeetingClass = "hidden";
                        }
                        else {
                            mobileMeetingClass = "hidden";
                        }
                        kamarNoticesModule.Notices.push({
                            id: result[i].Id,
                            schollId: result[i].SchoolId,
                            Date: date,
                            Body: result[i].Body,
                            Subject: result[i].Subject,
                            Level: result[i].Level,
                            MeetingPlace: result[i].MeetingPlace,
                            MeetingDate: meetingDate,
                            MeetingTime: result[i].MeetingTime,
                            Teacher: result[i].Teacher,
                            webMeetingClass: webMeetingClass,
                            mobileMeetingClass: mobileMeetingClass
                        });
                    }
                }

                Handlebars.registerHelper({
                    or: function () {
                        return Array.prototype.slice.call(arguments, 0, -1).some(Boolean);
                    }
                });

                var widget = $('#widget_' + widgetInstanceId);
                var container = widget.find('.noticeContent');
                var template = Handlebars.compile(widget.find('.hbt-kamarNotices').html());

                container.html('');
                container.removeClass('align-text-center');
                if (kamarNoticesModule.Notices.length == 0) {
                    container.append("No notices for this date.");
                    container.addClass('align-text-center');
                }
                else {

                    kamarNoticesModule.Notices.sort(function (a, b) {
                        var nameA = a.Level.toLowerCase(), nameB = b.Level.toLowerCase()
                        if (nameA < nameB) //sort string ascending
                            return -1
                        if (nameA > nameB)
                            return 1
                        return 0 
                    });

                    for (var i = 0; i < kamarNoticesModule.Notices.length; i++) {
                        container.append(template(kamarNoticesModule.Notices[i]));
                    }
                }
            }
        }
    });


};

;
var marqeeModule = extend(sportsground, 'sportsground.cms.widgets.marquee');

marqeeModule.create = function (widgetInstanceId) {
    var text = sportsground.cms.common.replaceLinkWithClickHere($("#MarqueeText_" + widgetInstanceId).text());
    text = sportsground.cms.common.removeEditModeLinkParam(text);
	$("#MarqueeText_" + widgetInstanceId).find('p').html(text);
}

marqeeModule.modalCreated = function (widgetInstanceId) {
	$("#MarqueeTextInput").val($("#hdnEmbedText_" + widgetInstanceId).val());

	// Wire up font select
	var selectedFont = $('#uxFontHidden').val();
	if (selectedFont == "")
		selectedFont = $("#hdnFontFamily").val();

	$('#fontSelect').fontSelector({
		'hide_fallbacks': true,
		'initial': selectedFont,
		'selected': function (style) {
			$('#uxFontHidden').val(style);
		}
	});
	$('#uxFontSelectTrigger').on('click', function () {
		$('#fontSelect').click();
		return false;
    });

    var selectedFontSize = $('#uxFontSizeHidden').val();
    if (selectedFontSize == "")
        selectedFontSize = "8px";

    $('#fontSizeSelect').sportyfontSizeSelector({
        'hide_fallbacks': true,
        'initial': selectedFontSize,
        'selected': function (style) {
            $('#uxFontSizeHidden').val(style);
        }
    });
    $('#uxFontSizeSelectTrigger').on('click', function () {
        $('#fontSizeSelect').click();
        return false;
    });

	if ($("#uxTextColor").val() == "")
		$("#uxTextColor").val($("#hdnFontFamilyColor").val());

	// Wire up color picker
	$("#uxTextColor").simplecolorpicker({ trigger: 'uxTextColorTrigger', selectedColor: $("#uxTextColor").val() });
};

marqeeModule.commitChanges = function (widgetInstanceId) {
    var marqueeWidgetText = $("#MarqueeText_" + widgetInstanceId).find('p');
	var modalText = $("#MarqueeTextInput").val();

	modalText = sportsground.cms.common.replaceLinkWithClickHere(modalText);
	modalText = sportsground.cms.common.removeEditModeLinkParam(modalText);

    marqueeWidgetText.html(modalText);
    marqueeWidgetText.css("color", $('#uxTextColor').val());
    marqueeWidgetText.css("font-family", $('#uxFontHidden').val());
    marqueeWidgetText.css("font-size", $('#uxFontSizeHidden').val());

    marqueeWidgetText.removeClass('slow');
    marqueeWidgetText.removeClass('medium');
    marqueeWidgetText.removeClass('fast');

    marqueeWidgetText.addClass($("#scrollingSpeed").val());

	$("#hdnEmbedText_" + widgetInstanceId).val($("#MarqueeTextInput").val());

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'Marquee',
		Settings: {
			Font: $('#uxFontHidden').val(),
			Color: $('#uxTextColor').val(),
            EmbedText: $("#MarqueeTextInput").val(),
            FontSize: $('#uxFontSizeHidden').val(),
            ScrollingSpeed: $("#scrollingSpeed").val()
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function(data, textStatus, xhr) {
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');
			}
		}
	});

	// Hide popup modal
	$("#myModal").modal('hide');
};


;
var menuModule = extend(sportsground, 'sportsground.cms.widgets.menuWidget');

menuModule.create = function (widgetInstanceId) {
    var pageOrSectionId = $(".cms-nav-link-root.active").data('id');
    if (pageOrSectionId === undefined || pageOrSectionId === null || pageOrSectionId === 0)
        return false;

    var isSection = $(".cms-nav-link-root.active").data("type") === "section";

    menuModule.GetRootPageWithSubPages(pageOrSectionId, isSection, widgetInstanceId);
};

menuModule.GetRootPageWithSubPages = function (pageOrSectionId, isSection, widgetInstanceId) {
    $.ajax({
        url: '/cms/menuwidget/getrootpagewithsubpages?pageOrSectionId=' + pageOrSectionId + '&isSection=' + isSection,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data !== null) {
                if (data.Url === "")
                    data.Url = "#";

                var currentPageId = $("#hdnCurrentPageId").val();

                var widget = $('#widget_' + widgetInstanceId);
                var container = widget.find('.list-group');
                var template = Handlebars.compile(widget.find('.hbt-menuWidget').html());
                container.append(template(data));

                for (var i = 0; i < data.subPages.length; i++) {
                    if ( !isNaN(currentPageId) && parseInt(currentPageId) === data.subPages[i].Id )
                        data.subPages[i].IsCurrentPage = true;

                    container.append( template(data.subPages[i]) );
                }
            }
        }
    });
};

menuModule.modalCreated = function (widgetInstanceId) {

    $('#myModal .modal-header').append('<div class="pull-right hideWidgetDiv"><input type="checkbox" id="hideWidget"/><label for="hideWidget" class="hideWidget control-label">Hide on Mobile</label></div>');
    var isHiddenOnMobile = $("#hdnHideOnMobile").val();
    if ( sportsground.cms.utils.isTrue(isHiddenOnMobile) ) {
        $("#hideWidget").prop('checked', 'checekd');
    }
    else
        $("#hideWidget").prop('checked', false);

    menuModule.initColorFields();
    menuModule.initTransparencies();
    menuModule.initFonts();

    $('#rbShowDivider').on('click', function () {
        $(".dividerInputs").removeClass('hidden');
    });

    $('#rbHideDivider').on('click', function () {
        $(".dividerInputs").addClass('hidden');
    });

    $(".menuAlign").on('click', function () {
        $(".menuAlign").removeClass('selected');
        $(this).addClass('selected');
    });
};

menuModule.initColorFields = function () {
    $("#txtMenuColor").simplecolorpicker({ trigger: 'uxMenuColorTrigger' });
    $("#txtsubMenuColor").simplecolorpicker({ trigger: 'uxsubMenuColorTrigger' });
    $("#uxBackgroundColor").simplecolorpicker({ trigger: 'uxBackgroundColorTrigger' });
    $("#uxHoverColor").simplecolorpicker({ trigger: 'uxHoverColorTrigger' });
    $("#uxDividerColor").simplecolorpicker({ trigger: 'uxDividerColorTrigger' });
};

menuModule.initTransparencies = function () {
    $("#uxBackgroundColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxBackgroundColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxBackgroundColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxBackgroundColorTransparencyInput").val(Math.abs(Math.round($("#uxBackgroundColorTransparencyInput").val() * 100)) + '%');

    $("#uxHoverColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxHoverColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxHoverColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxHoverColorTransparencyInput").val(Math.abs(Math.round($("#uxHoverColorTransparencyInput").val() * 100)) + '%');

    $("#uxDividerColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxDividerColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxDividerColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxDividerColorTransparencyInput").val(Math.abs(Math.round($("#uxDividerColorTransparencyInput").val() * 100)) + '%');
};

menuModule.initFonts = function () {
    var selectedMenuFont = $('#uxMenuFontHidden').val();
    if (selectedMenuFont === "")
        selectedMenuFont = $("#hdnFontFamily").val();

    $('#menuFontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedMenuFont,
        'selected': function (style) {
            $('#uxMenuFontHidden').val(style);
        }
    });
    $('#uxMenuFontSelectTrigger').on('click', function () {
        $('#menuFontSelect').click();
        return false;
    });

    var selectedSubMenuFont = $('#uxsubMenuFontHidden').val();
    if (selectedSubMenuFont === "")
        selectedSubMenuFont = $("#hdnFontFamily").val();

    $('#subMenuFontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedSubMenuFont,
        'selected': function (style) {
            $('#uxsubMenuFontHidden').val(style);
        }
    });
    $('#uxsubMenuFontSelectTrigger').on('click', function () {
        $('#subMenuFontSelect').click();
        return false;
    });
};

menuModule.commitChanges = function (widgetInstanceId) {

    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'MenuWidget',
        Settings: {
            MenuFontFamily: $("#uxMenuFontHidden").val(),
            MenuFontColor: $("#txtMenuColor").val(),
            MenuFontSize: $("#ddlMenuFontSize").val(),
            SubMenuFontFamily: $("#uxsubMenuFontHidden").val(),
            SubMenuFontColor: $("#txtsubMenuColor").val(),
            SubMenuFontSize: $("#ddlSubMenuFontSize").val(),
            Alignment: $(".btn-group.active .active .menuAlign").val(),
            BackgroundColor: $("#uxBackgroundColor").val(),
            BackgroundColorTransparency: Math.abs($('#uxBackgroundColorTransparencySlider').slider("option", "value")),
            HoverColor: $("#uxHoverColor").val(),
            HoverColorTransparency: Math.abs($('#uxHoverColorTransparencySlider').slider("option", "value")),
            HideDivider: $("#rbHideDivider").is(':checked'),
            DividerColor: $("#uxDividerColor").val(),
            DividerTransparency: Math.abs($('#uxDividerColorTransparencySlider').slider("option", "value")),
            HideOnMobile: $("#hideWidget").is(':checked')
        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202) {
                $("#modal-dialog").modal('show');
            }
            else {
                menuModule.rebuildWidget(widgetInstanceId);
            }
        }
    });

    $("#myModal").modal('hide');
};

menuModule.rebuildWidget = function (widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function (html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            menuModule.create(widgetInstanceId);
        }
    });
};;
var newsArticleModule = extend(sportsground, 'sportsground.cms.widgets.newsArticle');

newsArticleModule.create = function(widgetInstanceId) {
    var widgetDomElement = $('#widget_' + widgetInstanceId);
    var articleId = sportsground.utils.getQueryStringParameterByName('aid');
    var url;
    if (articleId) {
        url = '/cms/news/article/' + articleId;
    }
    else if (widgetDomElement.find("#hdnIsStaticArticle").val().toLowerCase() == "true") {
        url = '/cms/news/article/' + widgetDomElement.find("#hdnStaticArticleId").val();
    }
    else {
        url = '/cms/news/latest?organisationId=' + $('#OrganisationId').val() + '&categoryIds=' + widgetDomElement.find('#hdnCategoryIds').val();
    }

    $.get(url, function(data) {
        newsArticleModule.loadArticle(widgetInstanceId, data);
    });

    if ($("#isWebmaster").val() == "False") {
        $(".add-news-button").remove();
    }
};

newsArticleModule.loadArticle = function(widgetInstanceId, article) {
    var widgetDomElement = $('#widget_' + widgetInstanceId);
    if (article.HasVideoUrl)
        article.VideoUrl = sportsground.ui.generateIFrameHtmlForVideo(article.VideoUrl, 200, 300);

    var template = Handlebars.compile(widgetDomElement.find('.hbt-newsarticle-widget').html());
    var html = template(article);

    widgetDomElement.find('.article-wrapper').html(html);

    widgetDomElement.find('.article-wrapper-readmore-link a').attr('href', article.ArticleUrl);

    $(".clsShareWidgetNewsOnFB_" + widgetInstanceId).on('click', function () {
        var fbAppId = $(".clsFacebookAppId").val();
        var url = $("#hdnArticleUrl_" + widgetInstanceId).val();
        window.open('https://www.facebook.com/dialog/share?app_id=' + fbAppId + '&display=popup&href=' + url);
        return false;
    });

    $(".clsShareWidgetNewsOnTwitter_" + widgetInstanceId).on('click', function () {
        var url = $("#hdnArticleUrl_" + widgetInstanceId).val();
        var title = $("#hdnArticleTitle_" + widgetInstanceId).val();
        window.open('https://twitter.com/share?url=' + url + '&text=' + title);
        return false;
    });

    $(".clsShareWidgetNewsOnMail_" + widgetInstanceId).on('click', function () {
        var url = $("#hdnArticleUrl_" + widgetInstanceId).val();
        var title = $("#hdnArticleTitle_" + widgetInstanceId).val();
        var baseurl = $("#hdnArticleSiteUrl_" + widgetInstanceId).val();
        window.location.href = 'mailto:?subject=' + title + '&body=I found this article from ' + baseurl + ' that you might be interested in: ' + url;
        return false;
    });

    newsArticleModule.checkArticleContentAndEmbedMediaToAdjustThumbnails(widgetInstanceId);
};

newsArticleModule.commitChanges = function(widgetInstanceId) {
    var widgetDomElement = $('#widget_' + widgetInstanceId);
    var height = "0";
    if ($("#rbHeightCustom").is(":checked")) {
        height = $("#customHeightPixels").val();
    }

    var selectedCategories = [];
    $('#CategoryIds option:selected').each(function() {
        selectedCategories.push($(this).attr('value'));
    });
    widgetDomElement.find('#hdnCategoryIds').val(selectedCategories);

    var staticNewsArticleId = $("#article-widget-news-list").val();
    if (staticNewsArticleId === null || staticNewsArticleId === undefined)
        staticNewsArticleId = 0;

    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'NewsArticle',
        Settings: {
            IsStaticArticle: $("#rbIsStaticArticle").is(":checked"),
            StaticArticleId: staticNewsArticleId,
            Height: height,
            CategoryIds: JSON.stringify(selectedCategories)
        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function(data, textStatus, xhr) {
            if (xhr.status === 200 || xhr.status === 202) {
                $("#modal-dialog").modal('show');

                // Update DOM fields
                widgetDomElement.find('#hdnIsStaticArticle').val(widgetSettings.Settings.IsStaticArticle);
                widgetDomElement.find('#hdnStaticArticleId').val(widgetSettings.Settings.StaticArticleId);

                if ($("#rbHeightCustom").is(":checked")) {
                    widgetDomElement.find('.article-wrapper').addClass('custom-height');
                    widgetDomElement.find('.article-wrapper').attr('style', 'max-height:' + height + 'px;');

                    if (!widgetDomElement.find('.article-wrapper-readmore-link').length) {
                        var readMoreContent = document.createElement('div');
                        readMoreContent.className = 'article-wrapper-readmore-link';
                        var readMoreLink = document.createElement('a');
                        var articleUrl = "/" + $(location).attr("pathname").split("/")[1] + "/newsarticle/" + $("#article-widget-news-list").val();
                        readMoreLink.setAttribute('href', articleUrl);
                        readMoreLink.setAttribute('target', '_blank');
                        readMoreLink.innerText = 'read more';
                        readMoreContent.appendChild(readMoreLink);
                        widgetDomElement.find('.article-wrapper').after(readMoreContent);
                    }
                }
                else {
                    widgetDomElement.find('.article-wrapper').removeClass('custom-height');
                    widgetDomElement.find('.article-wrapper').removeAttr('style');
                    widgetDomElement.find('.article-wrapper-readmore-link').remove();
                }

                newsArticleModule.create(widgetInstanceId);
            }
        }
    });

    $("#myModal").modal('hide');
};

newsArticleModule.modalCreated = function(widgetInstanceId) {
    if ($("#rbIsStaticArticle").is(":checked")) {
        $('.show-latest-article-panel').hide();
        $('.show-static-article-panel').show();
    }
    else {
        $('.show-latest-article-panel').show();
        $('.show-static-article-panel').hide();
    }

    $("#rbIsStaticArticle").on('click', function() {
        $('.show-latest-article-panel').hide();
        $('.show-static-article-panel').show();
    });
    $("#rbIsLatestArticle").on('click', function() {
        $('.show-latest-article-panel').show();
        $('.show-static-article-panel').hide();
    });

    newsArticleModule.getArticleDropdown(widgetInstanceId);
    newsArticleModule.getCategoryMultiselect(widgetInstanceId);

    $("#customHeightPixels").on("click keypress", function() {
        $("#rbHeightCustom").trigger('click');
        $("#customHeightPixels").focus();
    });

    if ($("#customHeightPixels").val() > 0) {
        $("#rbHeightCustom").trigger('click');
    }
}

newsArticleModule.getArticleDropdown = function(widgetInstanceId) {
    var widgetDomElement = $('#widget_' + widgetInstanceId);
    var selectList = $('#article-widget-news-list');
    selectList.hide();
    $('.show-static-article-panel').find('.fa-spinner').show();

    var model = {
        pageNumber: 0,
        categories: "",
        excludeHidden: true
    }

    // Populate dropdownlist with available news articles
    $.ajax({
        url: '/cms/site/' + $('#OrganisationId').val() + '/news/list',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            var template = Handlebars.compile($("#hbtArticle").html());
            for (var i = 0; i < data.length; i++) {
                var html = template(data[i]);
                selectList.append(html);
            }
            if (widgetDomElement.find("#hdnIsStaticArticle").val().toLowerCase() == "true")
                selectList.val(widgetDomElement.find("#hdnStaticArticleId").val());

            $('.show-static-article-panel').find('.fa-spinner').hide();
            selectList.show();
        }
    });
};

newsArticleModule.getCategoryMultiselect = function(widgetInstanceId) {
    var widgetDomElement = $('#widget_' + widgetInstanceId);
    var selectList = $('#CategoryIds');
    selectList.hide();
    $('.show-latest-article-panel').find('.fa-spinner').show();

    $.ajax({
        url: '/cms/news/categories?oid=' + $('#OrganisationId').val(),
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function(data, textStatus, xhr) {
            $.each(data, function(index, category) {
                selectList.append('<option value="' + category.Id + '">' + category.Name + '</option>');
            });
            selectList.multiselect({
                templates: {
                    button: '<button type="button" class="btn-primary multiselect dropdown-toggle" data-toggle="dropdown"></button>',
                    li: '<li><a href="javascript:void(0);"><label class="old"></label></a></li>'
                }
            }).multiselect('select', widgetDomElement.find('#hdnCategoryIds').val().split(','));

            $('.show-latest-article-panel').find('.fa-spinner').hide();
        }
    });
};

//this method checks if there is any text in news article or it only has embed media
//if it only has embed media, it makes the thumbnail to have 100% width of container
//also handles other scenario like if text if short then adjust then push the embed media down so it doesn't overlap with thumbnail
newsArticleModule.checkArticleContentAndEmbedMediaToAdjustThumbnails = function (widgetInstanceId) {

    var mainContainer = "";
    if (widgetInstanceId == "newslist") //called from special news page
        mainContainer = $("#div-specialNewsArticlePage");
    else
        mainContainer = $("#widget_" + widgetInstanceId);

    var contentElems = mainContainer.find(".newsContent").children();
    if (contentElems.length > 0)
        newsArticleModule.GetImageThumbnailHeightAndAdjustContent(mainContainer, widgetInstanceId, contentElems);
};

newsArticleModule.GetImageThumbnailHeightAndAdjustContent = function (mainContainer, widgetInstanceId, contentElems) {
    var imgThumnail = mainContainer.find(".article-image-thumb").find('img');
    if (imgThumnail.length > 0 && widgetInstanceId != "newslist") { //thumbnail loads late in widgets
        imgThumnail.bind('load', function () {
            var thumbnailHeight = imgThumnail.height();
            newsArticleModule.AdjustArticleContent(mainContainer, widgetInstanceId, contentElems, thumbnailHeight);
        });
    }
    else {
        var thumbnailHeight = imgThumnail.height();
        newsArticleModule.AdjustArticleContent(mainContainer, widgetInstanceId, contentElems, thumbnailHeight);
    }
};

newsArticleModule.AdjustArticleContent = function (mainContainer, widgetInstanceId, contentElems, thumbnailHeight) {
    var contentHeight = 0;
    var hasText = false;
    for (var i = 0; i < contentElems.length; i++) {

        var elem = $(contentElems[i]);
        if (elem[0].tagName == "P" || elem[0].tagName == "UL" || elem[0].tagName == "OL") {
            if (elem[0].innerText.trim() != "" && !hasText && elem.find('i').length <= 0) {
                hasText = true;
            }
            contentHeight = contentHeight + elem.height();
            if (contentHeight > thumbnailHeight)
                break;
        }
        else if (elem[0].tagName == "DIV") {
            if (elem.data('oembed-url')) {
                var divHeight = elem.height();

                if (divHeight > thumbnailHeight && hasText) {
                    var margin = thumbnailHeight - contentHeight;
                    elem.css('margin-top', (margin + 15) + 'px');
                    break;
                }
                else if ($(elem[0]).find('iframe').length > 0 && !hasText) {
                    mainContainer.find(".newsContent").css('float', 'left');
                    mainContainer.find(".newsContent").css('width', '100%');
                    break;
                }
                contentHeight = contentHeight + divHeight;
            }
        }
    }

    if (!hasText) {

        if (widgetInstanceId != "newslist") { //changes only for article widget
            mainContainer.find(".article-content").attr('style', 'margin-left: 0px !important');
            if (mainContainer.find(".article-content").find('iframe').length > 0) { //if article has video thumbnail, make iframe 100% instead of 66%
                mainContainer.find(".article-content").css('width', '100%');
            }
        }

        mainContainer.find(".article-content").css('max-width', '100%');
        mainContainer.find(".article-content").find('img').css('height', 'auto');
        mainContainer.find(".article-content").removeClass('pull-right');
        mainContainer.find(".article-content").find('img').css('width', '100%');
        mainContainer.find(".article-wrapper img").css('max-height', 'none');
    }
};;
var newsCarouselModule = extend(sportsground, 'sportsground.cms.widgets.newsCarousel');

newsCarouselModule.create = function (widgetInstanceId) {
	var widget = $('#widget_' + widgetInstanceId);
	var slippryContainer = widget.find('.sy-box');
    slippryContainer.html('');

    if (!newsCarouselModule.layout){
        newsCarouselModule.layout = {};
    }

    newsCarouselModule.layout[widgetInstanceId] = $('#hdnLayout_' + widgetInstanceId).val();
    if (newsCarouselModule.layout[widgetInstanceId] === '')
        newsCarouselModule.layout[widgetInstanceId] = 'portrait';

	newsCarouselModule.crop = $('#hdnCrop_' + widgetInstanceId).val();
	if (newsCarouselModule.crop === '')
		newsCarouselModule.crop = 'False';

    newsCarouselModule.noArticles = $('#hdnNoArticles_' + widgetInstanceId).val();
    newsCarouselModule.secondsBetweenSlides = $('#hdnSecondsBetweenSlides_' + widgetInstanceId).val();
    newsCarouselModule.showTextSnippet = $('#hdnShowTextSnippet_' + widgetInstanceId).val();

    newsCarouselModule.loadArticles(0, widgetInstanceId);

};

newsCarouselModule.initCarousel = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);
    var slippryContainer = widget.find('.sy-box');

    var width = slippryContainer.outerWidth();

    // decide which image size to use
    var imageWidth = 1122;
    if (width <= 539) {
        imageWidth = 539;
    }
    if (width <= 248) {
        imageWidth = 248;
    }

    var height;
    var lay = newsCarouselModule.layout[widgetInstanceId];
    if (lay == 'panorama') {
      
        height = Math.round(0.35 * width);
        if (width <= 350) {
            height = width;
        }
        else if (width <= 529) {
            height = Math.round(0.71 * width); 
        }
    }
    else if (lay == 'landscape') {
        height = Math.round(0.71 * width); 
    }
    else if (lay == 'portrait'){
        height = Math.round(1.4 * width);
    }
    else if (lay == 'square'){
        height = width;
    }
    else {
        height = width;
    }
        
   

    slippryContainer.slippry({
        adaptiveHeight: false, // height of the sliders adapts to current slide
        captions: false, // Position: overlay, below, custom, false

        responsive: false, // setting this to false stops the overlay going over elements below, preventing button clicks

        // pager
        pager: true,
        // controls
        controls: false,
        autoHover: false,

        // transitions
        transition: 'fade', // fade, horizontal, kenburns, false
        speed: 2000, // time the transition takes (ms)
        pause: newsCarouselModule.secondsBetweenSlides * 1000,
        onSlideBefore: function (slide, old_index, new_index) {
            var crop = $('#hdnCrop_' + widgetInstanceId).val().toLowerCase() === 'true';
            var image = slide.find('img');
            var src = image.attr('src');

            var slideshowImageReady = function () {

                var isFluid = $("#widget_" + widgetInstanceId).closest(".supersplitter").data('fluidwidgets');

                //check if section is fluid
                if (sportsground.cms.utils.isTrue(isFluid)) {
                    return;
                } 

                // reset the image
                image.css('width', 'auto'); // IE does not support initial, so auto will be applied to width
                image.css('width', 'initial'); // Chrome, Edge, FireFox will replace auto to initial
                image.css('margin-left', '0');
                image.css('margin-top', '0');

                // calculate aspect ratios
                var sliderAspect = width / height;
                var imageAspect = image.width() / image.height();

                if (crop) {
                    if (sliderAspect > imageAspect) {
                        // crop vertically
                        image.css('width', width);
                        var margin = (height - image.height()) / 2;
                        image.css('margin-top', margin);
                    }
                    else {
                        // crop horizontally
                        image.css('height', height);
                        var margin = (width - image.width()) / 2;
                        image.css('margin-left', margin);
                    }
                }
                else if (sliderAspect > imageAspect) {
                    // scroll vertically
                    image.css('width', width);
                    var margin = height - image.height();
                    // only scroll if there's enough to scroll, otherwise crop
                    if (margin < -height / 10) {
                        image.animate({ 'margin-top': margin + 'px' }, 4500);
                    }
                    else {
                        image.css('margin-top', margin / 2);
                    }
                }
                else {
                    // scroll horizontally
                    image.css('height', height);
                    var margin = width - image.width();
                    // only scroll if there's enough to scroll, otherwise crop
                    if (margin < -width / 10) {
                        image.animate({ 'margin-left': margin + 'px' }, 4500);
                    }
                    else {
                        image.css('margin-left', margin / 2);
                    }
                }
            };

            var isIE11 = cmsModule.isIE11OrBelow();

            //ready not working in IE 10 or 11 so use load
            if (isIE11) {
                image.load(function () {
                    slideshowImageReady();
                });
            }
            else {
                image.ready(function () {
                    slideshowImageReady();
                });
            }

            image.attr('src', src);
        }

    });
    widget.find('.sy-box').css('height', height + 'px');
    widget.find('.sy-box').data('height', height + 'px');

}

newsCarouselModule.loadArticles = function (pagenumber, widgetInstanceId) {
    var url;
    // If custom Domain
    if ($('#isCustomDomain').val() == 'True') {
        url = "/newsarticle/{{{Id}}}";

        if ($(location).attr("search").indexOf("em=1") > 0)
            url += "?em=1";
    }
    else {
        // no news viewer so link
        url = "/" + $(location).attr("pathname").split("/")[1] + "/newsarticle/{{{Id}}}";

        if ($(location).attr("search").indexOf("em=1") > 0)
            url += "?em=1";
    }
    
    var model = {
        take: newsCarouselModule.noArticles,
        pageNumber: 0,
        categories: $('#widget_' + widgetInstanceId + ' .categoryIds').val(),
        excludeHidden: true
    }

    if (model.categories === "")
        model.categories = $('.globalCategoryIds').val();
    
    $.ajax({
        url: '/cms/site/' + $('#OrganisationId').val() + '/news/list',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 200) {
                // Store values for displaying/hiding summary and thumbnail in list
                var hasTextSnippet = true;
                var hdnHasTextSnippet = $('#widget_' + widgetInstanceId + ' .hdnHasTextSnippet').val();
                var hasShowThumbnails = true;
                var hdnHasShowThumbnails = $('#widget_' + widgetInstanceId + ' .hdnHasShowThumbnails').val();
                if (hdnHasTextSnippet != null && hdnHasTextSnippet.toLowerCase() == "false")
                    hasTextSnippet = false;
                if (hdnHasShowThumbnails != null && hdnHasShowThumbnails.toLowerCase() == "false")
                    hasShowThumbnails = false;
                // Remove any existing article markup
                // Append News Articles
                for (var i = 0; i < data.length; i++) {
                    data[i].TitleWrapped = "<a class='article-title' href='" + url + "'>" + data[i].Title + "</a>";
                    data[i].Url = url;
                    // Attach display preferences to article (data[i]) 
                    var thumbnailElement = "";
                    if (!hasTextSnippet)
                        data[i].Summary = "";
                    if (hasShowThumbnails && data[i].HasThumbnailImage) {
                        // append the web optimized version of image to view whole image, and use news-list-article-image-thumbnail class to fit into thumbnail
                        thumbnailElement = '<div class="pull-right"><div class="news-list-article-thumbnail">' +
                            '<img src="{{ThumbnailPath}}" data-src-web-opt="{{WebOptimisedPath}}"/>' +
                            '</div></div>';
                    }
                    if (hasShowThumbnails && data[i].HasVideoUrl) {
                        thumbnailElement = '<div class="pull-right"><div class="news-list-article-thumbnail">' +
                            sportsground.ui.generateIFrameHtmlForVideo('{{VideoUrl}}', 100, 100) +
                            '</div></div>';
                    }
                    newsCarouselModule.appendArticle(data[i], thumbnailElement, widgetInstanceId);
                }

                newsCarouselModule.initCarousel(widgetInstanceId);
                
                for (var i = 0; i < data.length; i++) {
                    $('#widget_' + widgetInstanceId).find(".sy-pager a[href='#" + (i+1) + "']").html(data[i].Title);
                }
              
                var widgetDomElement = $("#widget_" + widgetInstanceId);
                var pageCount = widgetDomElement.find(".hdnPageCount").val();
                var pageNumber = widgetDomElement.find(".hdnPageNumber").val();
                // Hide next/prev buttons if we are at the end/start of the articles list
                var nextButton = widgetDomElement.find(".news-list-next");
                var prevButton = widgetDomElement.find(".news-list-prev");
                if (parseInt(pageNumber) + 1 >= pageCount) {
                    nextButton.addClass('hidden');
                } else {
                    nextButton.removeClass('hidden');
                }

                if (parseInt(pageNumber) > 0) {
                    prevButton.removeClass('hidden');
                } else {
                    prevButton.addClass('hidden');
                }
            }
        }
    });
};

newsCarouselModule.appendArticle = function (article, imageElement, widgetInstanceId) {
    
        var widget = $('#widget_' + widgetInstanceId);
        var slippryContainer = widget.find('.sy-box');

        var width = slippryContainer.outerWidth();

        // decide which image size to use
        var imageWidth = 1122;
        if (width <= 539) {
            imageWidth = 539;
        }
        if (width <= 248) {
            imageWidth = 248;
        }
    
        var html = '<li class="news-slide-item">';
        html += '<a href="' + article.Url.replace("{{{Id}}}", article.Id) + '"><div class="news-slide-mask"></div></a>';
        // replace the #### placeholder with the correct width     

        html += '<div class="news-slide-content">';

        html += article.TitleWrapped.replace("{{{Id}}}", article.Id);
        
        if (newsCarouselModule.showTextSnippet && newsCarouselModule.showTextSnippet != "false"){
            html += "<div class='article-summary'>" + article.Summary + "</div>";
        }
        else {
            html += "<br/>";
        }

        var btnStyle = "news-carousel-btn-" + widgetInstanceId;
        html += '<a class="' + btnStyle + ' article-read-more" href="' + article.Url.replace("{{{Id}}}", article.Id) + '">Read More</a>';

        html += '</div>';

        if (article.HasVideoUrl) {

            var splitVideoUrl = article.VideoUrl.split("/embed/");
            var splitVideoUrl2 = splitVideoUrl[1].split("?");
            var youtubeVidThumbnail = "https://img.youtube.com/vi/" + splitVideoUrl2[0] + "/0.jpg";
            html += '<img title="' + article.caption + '" src="' + youtubeVidThumbnail + '" alt="sportsground" />';
        }
        else if (article.FileExtension){
            html += '<img title="' + article.caption + '" src="' + article.WebOptimisedPath + '" alt="sportsground" />';
        }
        else {
            html += '<img title="' + article.caption + '" src="/Content/images/transparent.png" alt="sportsground" />';
        }
       
        html += '</li>';
        slippryContainer.append(html);
    
};

newsCarouselModule.modalCreated = function (widgetInstanceId) {

	$('#myModal .modal-footer').append('<div class="pull-left gallery-action-buttons" style="display:none;"><a id="btnUploadImages" href="#"><i class="glyphicon glyphicon-cloud-upload" />&nbsp;&nbsp;Upload an Image</a></div>');
	$('#modalOrganisationId').val($('#OrganisationId').val());

	$('#btnChooseImages').on('click', function () {
		$('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
		});

		if ($('#btnDoneSelectingImages').length === 0) {
			$('.widget-settings-update').after('<button id="btnDoneSelectingImages" class="btn btn-primary">Done Selecting Images</button>');
			$('#btnDoneSelectingImages').on('click', function () {
				$('#tabImages_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
					$('#tabImages_imageReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
				});
				$('#btnDoneSelectingImages').hide();
				$('.widget-settings-cancel-update').show();
				$('.widget-settings-update').show();
				newsCarouselModule.loadSelectedImages();
				$('.gallery-action-buttons').hide();
			});
		}
		else
			$('#btnDoneSelectingImages').show();

		$('.widget-settings-cancel-update').hide();
		$('.widget-settings-update').hide();

		if (!newsCarouselModule.imageGalleryInitialised) {
			var imageGallerySettings = {
				allowEditing: false,
				loadThumbsCallback: function () {
					$('.cbImageSelect').off('change.imageslideshowthumbhandler');
					$('.cbImageSelect').on('change.imageslideshowthumbhandler', function () {
						var id = $(this).parent().parent().data('id');
						if (this.checked)
							newsCarouselModule.images.push({ id: id, caption: '', linkType: 'none' });
						else if (!this.checked)
							for (var index = 0; index < newsCarouselModule.images.length; index++) {
								if (newsCarouselModule.images[index].id === id) {
									newsCarouselModule.images.splice(index, 1);
									break;
								}
							}
					});

					$('.gallery-thumb-image img').off('click.imageslideshowthumbimghandler');
					$('.gallery-thumb-image img').on('click.imageslideshowthumbimghandler', function () {
						$(this).closest('.gallery-thumb-image').find('.cbImageSelect').trigger('click');
					});

					for (var i = 0; i < newsCarouselModule.images.length; i++) {
						$('#item_' + newsCarouselModule.images[i].id).find('input').attr('checked', 'checked');
					}
				}
			};
			sportsground.cms.imageGallery.init(imageGallerySettings);
			sportsground.cms.imageGallery.fileupload.init();
			newsCarouselModule.imageGalleryInitialised = true;
		}
		$('.gallery-action-buttons').show();

		return false;
	});

	$('input[type="radio"][name="rbLayout"]').on('change', function () {
        newsCarouselModule.layout[widgetInstanceId] = $(this).val();
	});
    newsCarouselModule.layout[widgetInstanceId] = $('#hdnLayout').val();
    if (newsCarouselModule.layout[widgetInstanceId] === '')
        newsCarouselModule.layout[widgetInstanceId] = 'landscape';
    $('input[type="radio"][value="' + newsCarouselModule.layout[widgetInstanceId] + '"]').prop('checked', true);

	newsCarouselModule.crop = $('#hdnCrop').val();
	if (newsCarouselModule.crop === '')
		newsCarouselModule.crop = 'True';

	if (newsCarouselModule.crop === 'False')
		$('#rbDisplayScroll').prop('checked', true);
	else
		$('#rbDisplayCrop').prop('checked', true);

	$('input[type="radio"][name="rbDisplay"]').on('change', function () {
		newsCarouselModule.crop = $(this).val();
	});

	if ($('#hdnShowTextSnippet').val() === 'True') {
        $('#cbShowTextSnippet').prop('checked', true);
		newsCarouselModule.showTextSnippet = true;
    }
    else {
        newsCarouselModule.showTextSnippet = false;
    }

    if ($('#hdnShowImages').val() === 'True') {
        $('#cbShowImages').prop('checked', true);
        newsCarouselModule.showImages = 'True';
    }

    $.ajax({
        url: '/cms/news/categories?oid=' + $('#OrganisationId').val(),
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, xhr) {
            var selectList = $('#CategoryIds_' + widgetInstanceId);
            $.each(data, function (index, category) {
                selectList.append('<option value="' + category.Id + '">' + category.Name + '</option>');
            });
            selectList.multiselect({
                templates: {
                    button: '<button type="button" class="btn-primary multiselect dropdown-toggle" data-toggle="dropdown"></button>',
                    li: '<li><a href="javascript:void(0);"><label class="old"></label></a></li>'
                }
            }).multiselect('select', $('#hdnCategoryIds_' + widgetInstanceId).val().split(','));
        }
    });

    changeButtonModule.initTransparencies();
    changeButtonModule.initSimpleColor();
    sportsground.cms.stroke.init('newsCarouselbtn', 'button-stroke-indicator');
    changeButtonModule.InitFontSize();
};

newsCarouselModule.initTransparencies = function () {

    //For Button Color
    $("#uxButtonColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round($("#uxButtonColorTransparencyInput").val() * 100)) + '%');

    //For Button Stroke Color
    $("#uxButtonStrokeTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonStrokeTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round($("#uxButtonStrokeTransparencyInput").val() * 100)) + '%');
};

newsCarouselModule.initSimpleColor = function () {
    $("#uxbuttonColor").simplecolorpicker({ trigger: 'uxButtonColorTrigger', selectedColor: $("#uxbuttonColor").val() });
    $("#uxbuttonTextColor").simplecolorpicker({ trigger: 'uxButtonTextTrigger', selectedColor: $("#uxbuttonTextColor").val() });
    $("#uxstrokeColor").simplecolorpicker({ trigger: 'uxstrokeColorTrigger' });
};

newsCarouselModule.InitFontSize = function () {
    var selectedFont = $('#uxFontHidden').val();
    if (selectedFont === "")
        selectedFont = $("#hdnFontFamily").val();

    $('#fontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedFont,
        'selected': function (style) {
            $('#uxFontHidden').val(style);
        }
    });
    $('#uxFontSelectTrigger').on('click', function () {
        $('#fontSelect').click();
        return false;
    });
};

newsCarouselModule.setLinkHtmlValuesFromJson = function () {
	$('.link-settings').hide();
	$('#linkSettings_' + newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkType).show();

	var currentImage = newsCarouselModule.images[newsCarouselModule.currentImageIndex];
	$('input[type="radio"][value="' + currentImage.linkType + '"]').prop('checked', true);
	$('#tbLinkUrlLocation').val('');
	$('#cbLinkUrlNewTab').prop('checked', false);
	$('#tbLinkEmail').val('');
	$('#slLinkPageOptions')[0].selectedIndex = 0;
	$('#slLinkDocumentOptions')[0].selectedIndex = 0;
	$('#slLinkFormOptions')[0].selectedIndex = 0;

	switch (currentImage.linkType) {
		case 'url':
			$('#tbLinkUrlLocation').val(newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData);
			$('#cbLinkUrlNewTab').prop('checked', currentImage.linkNewTab === true);
			break;
		case 'page':
			$('#slLinkPageOptions').val(newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData);
			break;
		case 'document':
			$('#slLinkDocumentOptions').val(newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData);
			break;
	    case 'onlineForm':
	        $('#slLinkFormOptions').val(newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData);
	        break;
		case 'email':
			$('#tbLinkEmail').val(newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData);
			break;
		default:
	}
};

newsCarouselModule.setLinkJsonValuesFromHtml = function () {
    newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkType = $('input[name=rbLinkType]:checked').val();

	switch (newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkType) {
		case 'url':
			newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData = $('#tbLinkUrlLocation').val();
			newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkNewTab = $('#cbLinkUrlNewTab').prop('checked');
			break;
		case 'page':
			newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData = $('#slLinkPageOptions').val();
			break;
		case 'document':
			newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData = $('#slLinkDocumentOptions').val();
			break;
	    case 'onlineForm':
	        newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData = $('#slLinkFormOptions').val();
	        break;
		case 'email':
			newsCarouselModule.images[newsCarouselModule.currentImageIndex].linkData = $('#tbLinkEmail').val();
			break;
		default:
	}
};

newsCarouselModule.commitChanges = function (widgetInstanceId) {

    var selectedCategories = [];
    $('#CategoryIds_' + widgetInstanceId + ' option:selected').each(function () {
        selectedCategories.push($(this).attr('value'));
    });

    newsCarouselModule.secondsBetweenSlides = $('#SecondsBetweenSlides').val();
    newsCarouselModule.showTextSnippet = $('#cbShowTextSnippet').is(':checked');

    var buttonHeight = $('#txtButtonCustomHeight').val();
    var buttonHeightOption = $("#buttonHeightDropDownList").val();
    if (buttonHeightOption === "Small")
        buttonHeight = 40;
    else if (buttonHeightOption === "Medium")
        buttonHeight = 60;
    else if (buttonHeightOption === "Medium")
        buttonHeight = 90;

    var buttonFont = $('#uxFontHidden').val();
    buttonFont = buttonFont.replace(/"/g, "'");

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'NewsCarousel',
		Settings: {
			ImagesJson: JSON.stringify(newsCarouselModule.images),
            Layout: newsCarouselModule.layout[widgetInstanceId],
            Crop: newsCarouselModule.crop,
            CategoryIds: JSON.stringify(selectedCategories),
            ShowTextSnippet: newsCarouselModule.showTextSnippet,
            ShowImages: $('#cbShowImages').is(':checked'),
            NoArticles: $('#NoArticles').val(),
            SecondsBetweenSlides: newsCarouselModule.secondsBetweenSlides,
            ButtonColor: $('#uxbuttonColor').val(),
            ButtonColorTransparency: Math.abs($('#uxButtonColorTransparencySlider').slider("option", "value")),
            ButtonStrokeColor: $('#uxstrokeColor').val(),
            ButtonStrokeColorTransparency: Math.abs($('#uxButtonStrokeTransparencySlider').slider("option", "value")),
            ButtonTextColor: $('#uxbuttonTextColor').val(),
            ButtonHeight: buttonHeightOption,
            ButtonCustomHeight: buttonHeight,
            ButtonFont: buttonFont,
            ButtonFontSize: $("#txtButtonFontSize").val(),
            ButtonUsingSquareCorners: $('#rbSquareCorner').is(':checked'),
            ButtonRadius: $('#txtButtonRadius_sitebtn').val()
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202) {
				$('#modal-dialog').modal('show');
            }
            
            newsCarouselModule.rebuildWidget(widgetInstanceId);
		}
	});

	$('#myModal').modal('hide');
	
};

newsCarouselModule.rebuildWidget = function (widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function (html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            newsCarouselModule.create(widgetInstanceId);
        }
    });
};

newsCarouselModule.loadSelectedImages = function () {
	$('.selected-image-thumb').remove();
	var imageIds = $.map(newsCarouselModule.images, function (val) { return val.id; });
	$.ajax({
		url: '/asset/GetImageAssetUrls',
		type: 'POST',
		data: JSON.stringify(imageIds),
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			var rawHtml = $('#hbtSelectedThumb').html();
			var template = Handlebars.compile(rawHtml);
			for (var i = 0; i < data.length; i++) {
				$('#selectedImagesContainer').append(template(data[i]));
			}

			$('#selectedImagesContainer').sortable({
				cancel: 'input',
				cursor: 'move',
				items: '> .selected-image-thumb',
				handle: '.draghandle',
				update: function () {
					var sortedIds = $('#selectedImagesContainer').sortable('toArray');
					var sortedImages = [];
					for (var si = 0; si < sortedIds.length; si++) {
						for (var ui = 0; ui < newsCarouselModule.images.length; ui++) {
							if (sortedIds[si] == newsCarouselModule.images[ui].id) {
								sortedImages[si] = newsCarouselModule.images[ui];
								break;
							}
						}
					}
					newsCarouselModule.images = sortedImages;
				}
			});

			$('.selected-image-settings').on('click', function () {
				var imageId = $(this).closest('.selected-image-thumb').attr('id');
				$.ajax({
                    url: '/asset/GetImageAssetDetails',
                    type: 'POST',
                    data: JSON.stringify( { imageId: imageId } ),
					contentType: 'application/json; charset=utf-8',
                    success: function ( data ) {
                        $( '#imgPreview' ).attr( 'src', sportsground.utils.convertImageSrc( data.imageDetails.Src, 'WEBOPTIMIZED' ) );
					}
				});

				for (var index = 0; index < newsCarouselModule.images.length; index++) {
					if (newsCarouselModule.images[index].id === imageId) {
						newsCarouselModule.currentImageIndex = index;
						break;
					}
				}

				$('#taImageCaption').val(newsCarouselModule.images[newsCarouselModule.currentImageIndex].caption);

				newsCarouselModule.setLinkHtmlValuesFromJson();

				$('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
					$('#tabImages_imageSettings').effect('slide', { direction: 'right', mode: 'show' }, 500);
				});
			});

			$('.selected-image-delete').on('click', function () {
				var imageId = $(this).closest('.selected-image-thumb').attr('id');
				bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected image from the slider?</p>', function (result) {
					if (!result)
						return;

					$('#' + imageId).remove();
					for (var index = 0; index < newsCarouselModule.images.length; index++) {
						if (newsCarouselModule.images[index].id === imageId) {
							newsCarouselModule.images.splice(index, 1);
							break;
						}
					}
				});
				return false;
			});
		}
	});
};
;
var newsListModule = extend(sportsground, 'sportsground.cms.widgets.newsList');

newsListModule.create = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);
    var newsContainer = "";
    var categories = "";

    if (widget.find(".hdnUseGridLayout").val() !== undefined && widget.find(".hdnUseGridLayout").val().toLowerCase() === "true") {
        newsContainer = widget.find('.news-tiles');
        widget.find('.news-list').addClass('hidden');
        widget.find('.news-tiles').removeClass('hidden');
        categories = $('#widget_' + widgetInstanceId + ' .gridcategoryIds').val();
    }
    else {
        categories = $('#widget_' + widgetInstanceId + ' .categoryIds').val();
        newsContainer = widget.find('.news-list');
        widget.find('.news-tiles').addClass('hidden');
        widget.find('.news-list').removeClass('hidden');
    }

	newsListModule.attachPaginationHandlers(widgetInstanceId);

	// Set the page count
    var model = {
        take: newsContainer.data('take'),
        categories: categories
    };

    if (parseInt(model.take) <= 0) {
        sportsground.cms.widgets.newsArticle.checkArticleContentAndEmbedMediaToAdjustThumbnails(widgetInstanceId);
        return false;
    }

    if (model.categories === "")
        model.categories = $('.globalCategoryIds').val();

    var orgId = $('#OrganisationId').val();
    if (!$.isNumeric(orgId)) {
        return false;
    }

	$.ajax({
        url: '/cms/site/' + $('#OrganisationId').val() + '/news/list/pagecount',
		type: 'GET',
		data: model,
		success: function(data, textStatus, xhr) {
            var pageCountDomElement = $("#widget_" + widgetInstanceId).find(".hdnPageCount");
            var hdnPageNumVal = $("#widget_" + widgetInstanceId).find(".hdnPageNumber").val();
            pageCountDomElement.val(data);
            var pnum = 0;
            if (hdnPageNumVal != undefined && hdnPageNumVal != "") {
                pnum = hdnPageNumVal;
            }
            var newsfeedId = $("#widget_" + widgetInstanceId).find(".hdnNewsfeedId").val();
            newsListModule.loadArticles(pnum, widgetInstanceId, newsfeedId);
		}
	});

    if ($("#isWebmaster").val() == "False") {
		$(".add-news-button").remove();
	}

    $("#newsArticleImage").click(function () {
        $('#newsArticleImageModal').modal('show');
    });

};

newsListModule.attachPaginationHandlers = function (widgetInstanceId) {
	var pageNumberDomObject = $("#widget_" + widgetInstanceId).find(".hdnPageNumber");

	$("#widget_" + widgetInstanceId).on("click", ".news-list-next", function () {
        var pageNumber = parseInt(pageNumberDomObject.val());
        var newsfeedId = $("#widget_" + widgetInstanceId).find(".hdnNewsfeedId").val();
        newsListModule.loadArticles(pageNumber + 1, widgetInstanceId, newsfeedId);
		pageNumberDomObject.val(pageNumber + 1);
	});
	$("#widget_" + widgetInstanceId).on("click", ".news-list-prev", function () {
        var pageNumber = parseInt(pageNumberDomObject.val());
        var newsfeedId = $("#widget_" + widgetInstanceId).find(".hdnNewsfeedId").val();
        newsListModule.loadArticles(pageNumber - 1, widgetInstanceId, newsfeedId);
		pageNumberDomObject.val(pageNumber - 1);
	});
};

newsListModule.detachPaginationHandlers = function (widgetInstanceId) {
	$("#widget_" + widgetInstanceId).off("click", ".news-list-next");
	$("#widget_" + widgetInstanceId).off("click", ".news-list-prev");
};

newsListModule.loadArticles = function (pagenumber, widgetInstanceId, newsfeedId) {

    if (newsfeedId == undefined || newsfeedId == null || newsfeedId == 'undefined' || newsfeedId == 'null') {
        newsfeedId = 0;
    }

	var url;
    // If custom Domain
	if ($('#isCustomDomain').val() == 'True') {
		url = "/newsarticle/{{{Id}}}";
	}
	else {
		// no news viewer so link
		url = "/" + $(location).attr("pathname").split("/")[1] + "/newsarticle/{{{Id}}}";
    }

    if (newsfeedId != 0) {
        url += "?newsfeedId=" + newsfeedId;
    } else {
        url += "?newsfeedId=" + widgetInstanceId;
    }

    if (pagenumber != "0") {
        url += "&newsfeedPageNum=" + pagenumber;
    }

    if ($(location).attr("search").indexOf("em=1") > 0) {
        url += "&em=1";
    }

    var widget = $('#widget_' + widgetInstanceId);
    var newsContainer = "";
    var categories = "";
    if (widget.find(".hdnUseGridLayout").val() !== undefined && widget.find(".hdnUseGridLayout").val().toLowerCase() === "true") {
        newsContainer = widget.find('.news-tiles');
        categories = $('#widget_' + widgetInstanceId + ' .gridcategoryIds').val();
    }
    else {
        newsContainer = widget.find('.news-list');
        categories = $('#widget_' + widgetInstanceId + ' .categoryIds').val();
    }

    var model = {
        take: newsContainer.data('take'),
        pageNumber: pagenumber,
        categories: categories,
        excludeHidden: true,
        newsfeedId: newsfeedId
    };

	if (model.categories === "")
	    model.categories = $('.globalCategoryIds').val();

	$.ajax({
		url: '/cms/site/' + $('#OrganisationId').val() + '/news/list',
		type: 'POST',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 200) {
                if ( data.length > 0 ) {
                    var rssfeedUrl = data[0].RssFeedUrl;
                    $('#widget_' + widgetInstanceId).find('.newslist-rss').attr('href', rssfeedUrl);

                    if (data[0].newsfeedHeader != "") {
                        $("#newsfeedHeader").html(data[0].newsfeedHeader);
                    }
                }

				// Remove any existing article markup
                newsContainer.hide().html("");
                newsContainer.show("fast");

                if (widget.find(".hdnUseGridLayout").val() !== undefined && widget.find(".hdnUseGridLayout").val().toLowerCase() === "false")
                    newsListModule.loadArticlesInList(widgetInstanceId, url, newsContainer, data);
                else
                    newsListModule.loadArticlesInGrid(widgetInstanceId, url, newsContainer, data);

				// If there are no articles then display a small message
				if (data.length === 0)
					newsContainer.html("<br/><p>No news articles currently available. Sorry!</p>");

				var widgetDomElement = $("#widget_" + widgetInstanceId);
				var pageCount = widgetDomElement.find(".hdnPageCount").val();
				var pageNumber = widgetDomElement.find(".hdnPageNumber").val();
				// Hide next/prev buttons if we are at the end/start of the articles list
				var nextButton = widgetDomElement.find(".news-list-next");
				var prevButton = widgetDomElement.find(".news-list-prev");
				if (parseInt(pageNumber) + 1 >= pageCount) {
                    nextButton.addClass( 'hidden' );
				} else {
                    nextButton.removeClass( 'hidden' );
				}
						
				if (parseInt(pageNumber) > 0) {
                    prevButton.removeClass( 'hidden' );
				} else {
                    prevButton.addClass( 'hidden' );
				}

                $(newsContainer).show("fast");

                if (widgetInstanceId === 'newslist') {
                    sportsground.cms.widgets.newsArticle.checkArticleContentAndEmbedMediaToAdjustThumbnails(widgetInstanceId);
                }
			}
		}
	});
};

newsListModule.loadArticlesInList = function (widgetInstanceId, url, newsContainer, data) {
    for (var i = 0; i < data.length; i++) {
        data[i].Url = url;

        var hasTextSnippet = true;
        var hdnHasTextSnippet = $('#widget_' + widgetInstanceId + ' .hdnHasTextSnippet').val();
        var hasShowThumbnails = true;
        var hdnHasShowThumbnails = $('#widget_' + widgetInstanceId + ' .hdnHasShowThumbnails').val();
        if (hdnHasTextSnippet !== undefined && hdnHasTextSnippet !== null && hdnHasTextSnippet.toLowerCase() === "false")
            hasTextSnippet = false;
        if (hdnHasShowThumbnails !== undefined && hdnHasShowThumbnails !== null && hdnHasShowThumbnails.toLowerCase() === "false")
            hasShowThumbnails = false;

        if (!hasTextSnippet)
            data[i].Summary = "";

        newsListModule.CreateNewsList(data[i], url, hasShowThumbnails, newsContainer);
    }
    newsContainer.show("fast");
};

newsListModule.loadArticlesInGrid = function (widgetInstanceId, url, newsContainer, data) {
    var newsTilesHtml = "";
    var widget = $('#widget_' + widgetInstanceId);
    for (var i = 0; i < data.length; i++) {

        var appendHtml = false;
        data[i].Url = url;

        data[i].Url = data[i].Url.replace('{{{Id}}}', data[i].Id);

        if (!data[i].HasThumbnailImage)
            data[i].WebOptimisedPath = "/Content/images/transparent.png";

        if (data[i].HasVideoUrl) {
            var splitVideoUrl = data[i].VideoUrl.split("/embed/");
            var splitVideoUrl2 = splitVideoUrl[1].split("?");
            var youtubeVidThumbnail = "https://img.youtube.com/vi/" + splitVideoUrl2[0] + "/0.jpg";
            data[i].WebOptimisedPath = youtubeVidThumbnail;
        }

        if ( widget.find('.hdnGridHasArticleHeader').val().toLowerCase() === "false" )
            data[i].Title = "";

        if ( widget.find('.hdnGridHasTextSnippet').val().toLowerCase() === "false" )
            data[i].Summary = "";

        if ( widget.find('.hdnGridHasPublishedDate').val().toLowerCase() === "false" )
            data[i].PublishedDate = "";

        if ( widget.find('.hdnGridHasDivider').val().toLowerCase() === "false" )
            data[i].ShowDivider = false;
        else
            data[i].ShowDivider = true;

        if ( widget.find('.GridButtonUsingHyperLink').val().toLowerCase() === "false" )
            data[i].ButtonClass = "white-color";
        else
            data[i].ButtonClass = "site-wide-btn-font grid-hyperlink";

        data[i].ButtonText = $('#widget_' + widgetInstanceId + ' .hdnGridButtonText').val();

        var template = Handlebars.compile(widget.find('.hbt-NewsFeedTiles').html());

        var dvstartRow = "";
        var number = i + 1;
        if (number === 1 || (number - 1) % 3 === 0)
            dvstartRow = "<div class='row'>";

        var dvEndRow = "";
        if (number % 3 === 0 || number === data.length) {
            dvEndRow = "</div>";
            appendHtml = true;
        }

        var html = template(data[i]);
        newsTilesHtml += dvstartRow + html + dvEndRow;

        if (appendHtml) {
            newsContainer.append(newsTilesHtml);
            newsTilesHtml = "";
        }
    }
    setTimeout(function () {
        newsListModule.ApplyLayoutStyles(widgetInstanceId);
    }, 400);
    newsContainer.show("fast");
};

newsListModule.ApplyLayoutStyles = function (widgetInstanceId) {
    var widget = $("#widget_" + widgetInstanceId);

    var windowWidth = $(window).width();
    var gridLayout = '';

    if (windowWidth < 768) {
        gridLayout = widget.find('.hdnGridMobileLayout').val();
    }
    else {
        gridLayout = widget.find('.hdnGridLayout').val();
    }

    var gridContainers = widget.find('.news-tiles').find('.news-slide-item');

    var width = gridContainers[0].offsetWidth;
    var height = 0;
    switch (gridLayout) {
        case 'panorama':
            height = Math.round(0.35 * width);
            break;
        case 'landscape':
            height = Math.round(0.71 * width);
            break;
        case 'stackedimgtop':
            height = Math.round(0.71 * width);
            break;
        case 'portrait':
            height = Math.round(1.4 * width);
            break;
        case 'square':
        default:
            height = width;
            break;
    }

    widget.find('.news-tiles').find('.news-slide-item img').css('min-height', height + 'px'); //fix for broken images, so text overlay does not overlap other grids
    widget.find('.news-tiles').find('.news-slide-item img').css('height', height + 'px');

    if (gridLayout === "stackedimgtop") {
        widget.find('.news-tiles').find('.news-slide-mask').addClass('hidden');
        widget.find('.news-tiles').find('.newsfeed-overlay-wrapper').css('position', 'inherit');
        //widget.find('.news-tiles').find('.newsfeed-overlay-wrapper').css('height', '155px');
    }
    else {
        widget.find('.news-tiles').find('.newsfeed-overlay-wrapper .article-date').css('color', 'white');
        widget.find('.news-tiles').find('.newsfeed-overlay-wrapper .article-date').css('text-shadow', '0 1px 2px rgba(0,0,0,.6)');
    }
    widget.find('.news-tiles').show("fast");
};

newsListModule.CreateNewsList = function (data, url, hasShowThumbnails, newsContainer) {

    data.Title = "<a class='article-title' href='" + url + "'>" + data.Title + "</a>";
    // Attach display preferences to article (data[i]) 
    var thumbnailElement = "";
    
    if (hasShowThumbnails && data.HasThumbnailImage) {
        // append the web optimized version of image to view whole image, and use news-list-article-thumbnail class to fit into thumbnail
        thumbnailElement = '<div class="pull-right newsfeed-thumbContainer"><div class="news-list-article-thumbnail">' +
            '<img {{#unless HasScaledThumbnail}} class="imgThumbnail" {{/unless}} src="{{ThumbnailPath}}" data-src-web-opt="{{WebOptimisedPath}}" />' +
            '</div></div>';
    }
    if (hasShowThumbnails && data.HasVideoUrl) {
        thumbnailElement = '<div class="pull-right newsfeed-thumbContainer"><div class="news-list-article-thumbnail">' +
            sportsground.ui.generateIFrameHtmlForVideo('{{VideoUrl}}', 100, 100) +
            '</div></div>';
    }

    newsListModule.appendArticle(newsContainer, data, thumbnailElement);
};

newsListModule.appendArticle = function(newsContainer, article, imageElement) {
    var templateString = '<div class="row news-list-widget-article">'
        + '<dt data-aid="{{Id}}">'
        + '<div class="newsfeed-title">' + article.Title + '</div>' + imageElement
        + '</dt>'
        + '<dd>{{#if Summary}}'
        + '<p>{{{Summary}}}&nbsp;<a class="article-readmore-link" href="' + article.Url + '">read more</a></p>'
        + '{{/if}}</dd>'
        + '</div>';
    var template = Handlebars.compile(templateString);
    var html = template(article);
    newsContainer.append(html);

    $(document).off('click', '.news-list-widget-article');
    $(document).on('click', '.news-list-widget-article', function(e) {
        if (e.target.tagName == 'A' || e.target.tagName == 'IFRAME' || $(this).hasClass('rss')) {
            return;
        }

        var modalDiv = $(document.createElement('div'));
        modalDiv.attr('id', 'myModal');
        modalDiv.addClass('modal fade');

        var articleBody = '';
        if ($(this).find('img').length) {
            articleBody = '<img src="' + $(this).find('img').data('src-web-opt') + '" class="pull-right" />';
        }
        if ($(this).find('iframe').length) {
            articleBody = '<div>' + sportsground.ui.generateIFrameHtmlForVideo($(this).find('iframe').attr('src'), "100%", 200) + '</div>';
        }

        var articleHtml = '<div class="article-wrapper">'
            + '<h3>' + $(this).find('.article-title').html() + '</h3>'
            + '<hr/>'
            + '<div class="article-content">'
            + articleBody
            + '<p>' + $(this).find('p').html() + '</p>'
            + '</div>'
            + '</div>';

        modalDiv.html('<div class="modal-dialog"><div class="modal-content"><div class="modal-body">' + articleHtml + '</div></div></div>');
        modalDiv.modal('show');
    });
};

newsListModule.commitChanges = function (widgetInstanceId) {
    var take = $('#uxNewsTakeDropdown').val();

    var widget = $('#widget_' + widgetInstanceId);

	var selectedCategories = [];
	$('#CategoryIds option:selected').each(function() {
		selectedCategories.push($(this).attr('value'));
    });

    var selectedGridCategories = [];
    $('#GridCategoryIds option:selected').each(function () {
        selectedGridCategories.push($(this).attr('value'));
    });

    var buttonHeight = $('#txtButtonCustomHeight').val();
    var buttonHeightOption = $("#buttonHeightDropDownList").val();
    if (buttonHeightOption === "Small")
        buttonHeight = 40;
    else if (buttonHeightOption === "Medium")
        buttonHeight = 60;
    else if (buttonHeightOption === "Medium")
        buttonHeight = 90;

    var buttonFont = $('#uxFontHidden').val();
    buttonFont = buttonFont.replace(/"/g, "'");

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'NewsList',
		Settings: {
			Take: take,
			CategoryIds: JSON.stringify(selectedCategories),
			HasTextSnippet: $("#chkTextSnippet").is(':checked'),
			HasShowThumbnails: $("#chkShowThumbnails").is(':checked'),
            HasHeader: $("#chkShowHeader").is(':checked'),
            HeaderText: $("#HeaderText").val(),
            ShowRssIcon: $("#chkShowRssIcon").is(':checked'),
            UseGridLayout: $("#rbUseGridLayout").is(':checked'),
            GridLayout: $('input[type="radio"][name="rbLayout"]:checked').val(),
            GridMobileLayout: $('input[type="radio"][name="rbMobileLayout"]:checked').val(),
            GridImagePadding: $("#txtGridImagePadding").val(),
            GridContentAlignment: $('input[type="radio"][name="gridContentAlignment"]:checked').val(),
            GridContentColor: $("#txtGridContentColor").val(),
            GridHasArticleHeader: $("#chkGridArticleHeader").is(':checked'),
            GridHasTextSnippet: $("#chkGridTextSnippet").is(':checked'),
            GridHasPublishedDate: $("#chkGridPublishedDate").is(':checked'),
            GridHasDivider: $("#chkGridDivider").is(':checked'),
            GridContentPadding: $("#txtGridContentPadding").val(),
            GridBorderSize: $("#txtGridBorderSize").val(),
            GridBorderColor: $("#txtGridBorderColor").val(),
            GridBorderColorTransparency: Math.abs($('#uxGridBorderColorTransparencySlider').slider("option", "value")),
            GridBackgroundColor: $("#txtGridBackgroundColor").val(),
            GridBackgroundColorTransparency: Math.abs($('#uxGridBackgroundColorTransparencySlider').slider("option", "value")),
            GridHasDropShadow: $("#chkGridShadow").is(':checked'),
            GridButtonText: $("#txtGridButtonText").val(),
            GridButtonUsingHyperLink: $("#rbTypeHyperlink").is(':checked'),
            GridHyperlinkColor: $("#txtHyperLinkColor").val(),
            GridTake: $("#uxNewsGridTakeDropdown").val(),
            GridCategoryIds: JSON.stringify(selectedGridCategories),
            HideListPagination: !$("#chkDisplayListPagination").is(':checked'),
            HideGridPagination: !$("#chkDisplayGridPagination").is(':checked'),
            ShowRssIconInGrid: $("#chkShowRssIconInGrid").is(':checked'),
            HideOnMobile: $("#hideWidget").is(':checked'),
            ButtonColor: $('#uxbuttonColor').val(),
            ButtonColorTransparency: Math.abs($('#uxButtonColorTransparencySlider').slider("option", "value")),
            ButtonStrokeColor: $('#uxstrokeColor').val(),
            ButtonStrokeColorTransparency: Math.abs($('#uxButtonStrokeTransparencySlider').slider("option", "value")),
            ButtonTextColor: $('#uxbuttonTextColor').val(),
            ButtonHeight: buttonHeightOption,
            ButtonCustomHeight: buttonHeight,
            ButtonFont: buttonFont,
            ButtonFontSize: $("#txtButtonFontSize").val(),
            ButtonUsingSquareCorners: $('#rbSquareCorner').is(':checked'),
            ButtonRadius: $('#txtButtonRadius_sitebtn').val()
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 200 || xhr.status === 202) {
				$("#modal-dialog").modal('show');

                newsListModule.rebuildWidget(widgetInstanceId);
			}
		}
	});

	$("#myModal").modal('hide');
};

newsListModule.rebuildWidget = function (widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function (html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            newsListModule.create(widgetInstanceId);
        }
    });
};

newsListModule.modalCreated = function (widgetInstanceId) {
    $('#myModal .modal-header').append('<div class="pull-right hideWidgetDiv"><input type="checkbox" id="hideWidget"/><label for="hideWidget" class="hideWidget control-label">Hide on Mobile</label></div>');
    var isHiddenOnMobile = $("#hdnHideOnMobile").val();
    if (sportsground.cms.utils.isTrue(isHiddenOnMobile)) {
        $("#hideWidget").prop('checked', 'checekd');
    }
    else
        $("#hideWidget").prop('checked', false);

	$.ajax({
		url: '/cms/news/categories?oid=' + $('#OrganisationId').val(),
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
		success: function (data, textStatus, xhr) {
            var selectList = $('#CategoryIds');
            var selectGridList = $('#GridCategoryIds');
			$.each(data, function(index, category) {
                selectList.append('<option value="' + category.Id + '">' + category.Name + '</option>');
                selectGridList.append('<option value="' + category.Id + '">' + category.Name + '</option>');
			});
			selectList.multiselect({
				templates: {
					button: '<button type="button" class="btn-primary multiselect dropdown-toggle" data-toggle="dropdown"></button>',
					li: '<li><a href="javascript:void(0);"><label class="old"></label></a></li>'
				}
            }).multiselect('select', $('#hdnCategoryIds_' + widgetInstanceId).val().split(','));

            selectGridList.multiselect({
                templates: {
                    button: '<button type="button" class="btn-primary multiselect dropdown-toggle" data-toggle="dropdown"></button>',
                    li: '<li><a href="javascript:void(0);"><label class="old"></label></a></li>'
                }
            }).multiselect('select', $('#hdnGridCategoryIds_' + widgetInstanceId).val().split(','));
		}
    });

    newsListModule.addClickHandlersForGridSettings();

    newsListModule.initTransparencies();
    newsListModule.initSimpleColor();
    sportsground.cms.stroke.init('newsFeedbtn', 'button-stroke-indicator');
    newsListModule.initFontSize();
};

newsListModule.initTransparencies = function () {

    //For Button Color
    $("#uxButtonColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round($("#uxButtonColorTransparencyInput").val() * 100)) + '%');

    //For Button Stroke Color
    $("#uxButtonStrokeTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonStrokeTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round($("#uxButtonStrokeTransparencyInput").val() * 100)) + '%');
};

newsListModule.initSimpleColor = function () {
    $("#uxbuttonColor").simplecolorpicker({ trigger: 'uxButtonColorTrigger', selectedColor: $("#uxbuttonColor").val() });
    $("#uxbuttonTextColor").simplecolorpicker({ trigger: 'uxButtonTextTrigger', selectedColor: $("#uxbuttonTextColor").val() });
    $("#uxstrokeColor").simplecolorpicker({ trigger: 'uxstrokeColorTrigger' });
};

newsListModule.initFontSize = function () {
    var selectedFont = $('#uxFontHidden').val();
    if (selectedFont === "")
        selectedFont = $("#hdnFontFamily").val();

    $('#fontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedFont,
        'selected': function (style) {
            $('#uxFontHidden').val(style);
        }
    });
    $('#uxFontSelectTrigger').on('click', function () {
        $('#fontSelect').click();
        return false;
    });
};

newsListModule.addClickHandlersForGridSettings = function () {
    $("#rbUseListLayout").on('change', function () {
        $("#gridLayout").addClass('hidden');
        $("#listLayout").removeClass('hidden');
    });

    $("#rbUseGridLayout").on('change', function () {
        $("#listLayout").addClass('hidden');
        $("#gridLayout").removeClass('hidden');
    });

    var gridLayout = $("#hdnGridLayout").val();
    $('input[name="rbLayout"][value="' + gridLayout + '"]').prop('checked', 'checked');

    var mobileGridLayout = $("#hdnMobileGridLayout").val();
    $('input[name="rbMobileLayout"][value="' + mobileGridLayout + '"]').prop('checked', 'checked');

    $("#txtGridBorderColor").simplecolorpicker({ trigger: 'txtGridBorderColorTrigger' });
    $("#txtHyperLinkColor").simplecolorpicker({ trigger: 'uxHyperLinkColorTrigger' });
    $("#txtGridContentColor").simplecolorpicker({ trigger: 'txtGridContentColorTrigger' });
    $("#txtGridBackgroundColor").simplecolorpicker({ trigger: 'txtGridBackgroundColorTrigger' });

    $("#rbTypeButton").on('change', function () {
        $("#dvButtonHyperlinkColor").addClass('hidden');
    });

    $("#rbTypeHyperlink").on('change', function () {
        $("#dvButtonHyperlinkColor").removeClass('hidden');
    });

    $("#uxGridBorderColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxGridBorderColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxGridBorderColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxGridBorderColorTransparencyInput").val(Math.abs(Math.round($("#uxGridBorderColorTransparencyInput").val() * 100)) + '%');

    $("#uxGridBackgroundColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxGridBackgroundColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxGridBackgroundColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxGridBackgroundColorTransparencyInput").val(Math.abs(Math.round($("#uxGridBackgroundColorTransparencyInput").val() * 100)) + '%');
};
;
var noticesModule = extend(sportsground, 'sportsground.cms.widgets.notices');

noticesModule.commitChanges = function (widgetInstanceId) {

    var widget = $("#taNoticesContent-" + widgetInstanceId);

    // if no changes have been made then do not save
    if (widget.html() == $("#notices-prevContent-" + widgetInstanceId).val())
        return false;

    var html = widget.html();
    html = sportsground.cms.common.replaceLinkWithClickHere(html);

    var editorElem = $('<p>').append(html); 
    if ( editorElem.length === 1 && editorElem.find('a').length > 0 ) { //set the anchors to inherit child element color
        html = sportsground.cms.common.setAnchorToHaveChildColor(editorElem, html);
    }
    
    html = sportsground.cms.common.removeEditModeLinkParam(html);
    widget.html(html);
    $("#notices-prevContent-" + widgetInstanceId).html(html);

    var updatedNoticeText = CKEDITOR.instances["taNoticesContent-" + widgetInstanceId].getData();

    noticesModule.saveNotice(widgetInstanceId, updatedNoticeText);

};

noticesModule.saveNotice = function (widgetInstanceId, noticeText) {
    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'Notices',
        Settings: {
            NoticeText: noticeText
        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202 || xhr.status === 200) {
                //do nothing
            }
        }
    });
};

noticesModule.hasSubscribers = function () {

    $.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/notices/hassubscribers',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (!data) {
                $('.btnRemoveSubscribers').hide();
                $('.alertNoSubscribers').show();
            }
        }
    });

};

noticesModule.modalCreated = function (widgetInstanceId) {
    $(".widget-settings-update").html("Send Notices<i class='fa'></i>");
    $(".widget-settings-update").addClass("btnSendout");
    $(".widget-settings-cancel-update").html("Done");

    $(".btnRemoveSubscribers").remove();
    $(".btnAddSubscriber").remove();
    $('#myModal .modal-footer').append('<button id="btnAddSubscriber" class="btn btn-primary pull-left btnAddSubscriber">Add Subscriber</button> ');
    $('#myModal .modal-footer').append('<button id="btnRemoveSubscribers" class="btn btn-danger btn-sm pull-left btnRemoveSubscribers">Remove Subscribers</button>');

    noticesModule.hasSubscribers();

    var footer = $('#myModal .modal-footer').clone(true);
    footer.insertAfter($('#myModal .modal-header'));

    $('#myModal .modal-footer:eq(1)').remove();

    $('.btnRemoveSubscribers').on('click', function () {
        bootbox.confirm('<h3>Are you sure?</h3><p>This will delete the list of email addresses associated with receiving Notices from anywhere on this website (but does not impact other sites or subsites).', function (result) {
            if (!result)
                return;

            $.ajax({
                url: '/cms/site/' + $('#SiteId').val() + '/notices/removesubscribers',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    $('.btnRemoveSubscribers').hide();
                    $('.alertNoSubscribers').show();
                    $(".notice-subscribers-wrapper").remove();
                }
            });
        });
        return false;
    });

    // removing existing click before adding a new click event
    $('.btnSendout').off('click').on('click', function () {
        $('.btnSendout').prop("disabled", true);
        $('.btnSendout i').addClass('fa-spinner');

        if (CKEDITOR.instances["taNoticesContent-" + widgetInstanceId].getData().length == 0) {
            $("#taNoticesContent-" + widgetInstanceId).closest(".form-group").removeClass("has-success").addClass("has-error");
            return false;
        }

        if (!noticesModule.pushPacketSizeValid( CKEDITOR.instances["taNoticesContent-" + widgetInstanceId].getData())) {

            bootbox.confirm({
                message: "This message is too large to be transmitted as a push notification, so will only be sent as an email to your email subscribers.",
                buttons: {
                    confirm: {
                        label: 'Proceed',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: 'Cancel',
                        className: 'btn-danger'
                    }
                },
                callback: function (result) {
                   
                    if (result) {
                        noticesModule.sendEmail(widgetInstanceId, function () {
                            $('.btnSendout').hide();
                            $('.alertSent').show();
                            $('.btnSendout').prop("disabled", false);
                            $('.btnSendout i').removeClass('fa-spinner');
                        });
                    }
                }
            });

            return false;
        }

        noticesModule.sendEmail(widgetInstanceId, function () {
            $('.btnSendout').hide();
            $('.alertSent').show();
            $('.btnSendout').prop("disabled", false);
            $('.btnSendout i').removeClass('fa-spinner');
        });
     
        return false;
    });

    noticesModule.loadInclusions();

};

noticesModule.create = function (widgetInstanceId) {
    // Natural <form> behaviour is for an  enter key to post form. We don't want this! press the submit button please.
    $("#noticeSubscriptionEmailForm").find("input").keypress(function (e) {
        if (e.which == 13) {
            e.preventDefault();
            e.stopPropagation();
            $("#btnNoticeSubscribe").click();
        }
    });


    $("#subscribeNoticeModal").on('shown.bs.modal', function () {
        $('#noticeSubscribeEmail').focus();
        $.validator.unobtrusive.parseDynamicContent('#noticeSubscriptionEmailForm');
        overrideUnobtrusiveDefaults();
    });

    $("#subscribeNoticeModal").on('hidden.bs.modal', function () {
        $('#btnNoticeSubscribe').removeAttr('disabled');
    });

    var widget = $('#widget_' + widgetInstanceId);

    $("#notices-prevContent-" + widgetInstanceId).html($("#taNoticesContent-" + widgetInstanceId).html());

    if (!CKEDITOR.instances["taNoticesContent-" + widgetInstanceId] && $("#taNoticesContent-" + widgetInstanceId).attr("contenteditable") == "true") {
        // This richtext has been asyncronously loaded and we must bind ckeditor to new dom element
        var editor = CKEDITOR.inline("taNoticesContent-" + widgetInstanceId);
        editor.on('paste', function (e) {
            e.stop();
            var text = sportsground.cms.common.replaceLinkWithClickHere(e.data.dataValue);
            text = sportsground.cms.common.removeEditModeLinkParam(text);
            e.editor.insertHtml(text);
        });

        var googleFonts = ['Amatic SC', 'Montserrat', 'Raleway', 'Playfair Display', 'Nunito', 'Nunito Sans', 'Arvo', 'Open Sans', 'Roboto Slab', 'Quicksand', 'Lato', 'Oswald'];

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

            var fontName = googleFonts[i].replace(' ', '+');

            if (googleFonts[i] === "Amatic SC") {
                fontName = "Amatic+SC:700&display=swap";
            }
            else if (googleFonts[i] === "Nunito Sans") {
                fontName = "Nunito+Sans&display=swap";
            }

            googleFonts[i] = '//fonts.googleapis.com/css?family=' + fontName;
            $("head").append("<link href='" + googleFonts[i] + "' rel='stylesheet' type='text/css'>");
        }

        editor.config.contentsCss = ['/Content/ckeditor/contents.css'].concat(googleFonts);

    }
   
    var subscribeButton = widget.find('.subscribe-notice-button');
   
    subscribeButton.on('click', function () {
        // reset modal content
        $('#msgAlreadySubscribed').hide();
        $('#subscribeSuccess').hide();
        $("#noticeSubscriptionEmailForm").show();
        $('#noticeSubscribeEmail').removeAttr('readonly');
        var modalFooter = $('#subscribeNoticeModal').find('.modal-footer');
        modalFooter.find(".noticesDismissSubscribeModal").hide();
        modalFooter.find(".noticesSubscribeButtonsContainer").show();
        $("#noticeSubscribeEmail").val("");

    });

    $('#btnNoticeSubscribe').unbind('click');

    $('#btnNoticeSubscribe').on('click', function () {
        $('#msgAlreadySubscribed').hide();
        if ($('#noticeSubscriptionEmailForm').valid()) {
            $('#btnNoticeSubscribe').attr('disabled', 'disabled');
            $.ajax({
                url: '/cms/site/' + $('#SiteId').val() + '/notices/optin',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: '{email:"' + $('#noticeSubscribeEmail').val() + '"}',
                success: function (data) {
                    if (data) {
                        $('#emailFeedbackSpan').html($('#noticeSubscribeEmail').val());
                        $('#subscribeSuccess').show();
                        $('#noticeSubscribeEmail').attr('readonly', 'readonly');
                        $('#noticeSubscribeEmail').blur();
                        $("#noticeSubscriptionEmailForm").hide();

                        var modalFooter = $('#subscribeNoticeModal').find('.modal-footer');
                        modalFooter.find(".noticesDismissSubscribeModal").show();
                        modalFooter.find(".noticesSubscribeButtonsContainer").hide();
                    }
                    else {
                        $('#msgAlreadySubscribed').show();
                        $('#btnNoticeSubscribe').removeAttr('disabled');
                    }
                }
            });
        }
        return false;
    });


    $('#noticesModal_' + widgetInstanceId).on('shown.bs.modal', function (e) {

        $("#sendNoticeTab_" + widgetInstanceId).click();

        if (!CKEDITOR.instances["modalNoticesContent-" + widgetInstanceId]) {
            CKEDITOR.replace('modalNoticesContent-' + widgetInstanceId, {
                on: {
                    instanceReady: function (evt) {
                        $("#cke_modalNoticesContent-" + widgetInstanceId).find('.cke_top').addClass('hidden');
                        var editor = evt.editor;

                        editor.on('focus', function (e) {
                            $("#cke_modalNoticesContent-" + widgetInstanceId).find('.cke_top').removeClass('hidden');
                        });
                    }
                },
                customConfig: '/Content/ckeditor/noncms_config.js',
            });
        } else {
            $("#cke_modalNoticesContent-" + widgetInstanceId).find('.cke_top').addClass('hidden');
        }

        var noticeData = CKEDITOR.instances["taNoticesContent-" + widgetInstanceId].getData();
        CKEDITOR.instances['modalNoticesContent-' + widgetInstanceId].setData(noticeData);

        $('#notice-history_' + widgetInstanceId).html('');
        noticesModule.getNoticeHistory(noticesModule.page, widgetInstanceId);
        e.stopImmediatePropagation();
        return false;
    });

    $('#notice-history_' + widgetInstanceId).bind('scroll', function (e) {
          if ($(this).scrollTop() + $(this).innerHeight() >= ($(this)[0].scrollHeight - 1) &&
              noticesModule.page < noticesModule.maxPages) {

              noticesModule.getNoticeHistory(noticesModule.page, widgetInstanceId);
              return false;

          }
          e.stopImmediatePropagation();
    });

    noticesModule.saveAndSendNotice = function(widgetInstanceId) {
       
        var widgetData = CKEDITOR.instances["taNoticesContent-" + widgetInstanceId].getData();
        var modalData = CKEDITOR.instances["modalNoticesContent-" + widgetInstanceId].getData();
        if (widgetData != modalData) {
            var html = sportsground.cms.common.replaceLinkWithClickHere(modalData);
            html = sportsground.cms.common.removeEditModeLinkParam(html);
            $("#taNoticesContent-" + widgetInstanceId).html(html);
            noticesModule.saveNotice(widgetInstanceId, modalData);
        }

        noticesModule.sendEmail(widgetInstanceId, function () {

            $("#btnSendNotice_" + widgetInstanceId).find('.fa').removeClass('fa-spinner');
            $("#btnSendNotice_" + widgetInstanceId).attr('disabled', false);
            $("#noticesModal_" + widgetInstanceId).modal('hide');

            bootbox.alert({
                title: "Send Notices",
                message: "Your notice has been sent successfully."
            });
        });
    };

    $("#btnSendNotice_" + widgetInstanceId).click(function (e) {

        if (!noticesModule.pushPacketSizeValid( CKEDITOR.instances["modalNoticesContent-" + widgetInstanceId].getData())) {

            bootbox.confirm({
                message: "This message is too large to be transmitted as a push notification, so will only be sent as an email to your email subscribers.",
                buttons: {
                    confirm: {
                        label: 'Proceed',
                        className: 'btn-success'
                    },
                    cancel: {
                        label: 'Cancel',
                        className: 'btn-danger'
                    }
                },
                callback: function (result) {
                   
                    if (result)
                        noticesModule.saveAndSendNotice(widgetInstanceId);
                }
            });

            return false;
        }

        $(this).find('.fa').addClass('fa-spinner');
        $(this).attr('disabled', 'disabled');

        noticesModule.saveAndSendNotice(widgetInstanceId);
        e.stopImmediatePropagation();

        return false;
    });

    $(document).on('click', '.delete-notice', function (e) {
        var row = $(this).parent('td').parent('tr');
        var noticeId = row.data('id');

        bootbox.dialog({
            message: '<div class="alert alert-warning">Are you sure you wish to delete this notice? Please type "DELETE" to confirm deletion.</div><div class="form-group"><input class="form-control" id="noticeDeleteText" type="text" autofocus/></div>',
            title: "Confirm Delete",
            buttons: {
                cancel: {
                    label: "Cancel"
                },
                delete: {
                    label: "Delete",
                    className: "btn-danger",
                    callback: function () {
                        var check = $("#noticeDeleteText").val();
                        if (check.toLowerCase() === "delete") {
                            noticesModule.deleteNotice(noticeId, row);
                            e.stopImmediatePropagation();
                        }
                        else {
                            bootbox.dialog({
                                message: "Please type DELETE.",
                                title: "Warning",
                                buttons: {
                                    main: {
                                        label: "Ok",
                                        className: "btn-info"
                                    }
                                }
                            });
                            return false;
                        }
                    }
                }
            }
        }).on("shown.bs.modal", function () {
            $(this).find('[autofocus]').focus();
        });
        e.stopImmediatePropagation();
        return false;
    });

    $("#btnManageNotice_" + widgetInstanceId).on('click', function (event) {
        noticesModule.maxPages = 1;
        noticesModule.page = 0;
        $("#noticesModal_" + widgetInstanceId).modal('show');
        event.stopImmediatePropagation();
    });

    noticesModule.attachClickHandlers(widgetInstanceId);
    $("#custom-page-cover").width($(window).width());
    $("#custom-page-cover").height($(window).height());
};

noticesModule.attachClickHandlers = function (widgetInstanceId) {
    $("#taNoticesContent-" + widgetInstanceId + ".cke_editable").on('click.click-richtext-' + widgetInstanceId, function () {
        var widget = $(this);
        // Remove this handler attached to clicking within richtext area
        $("#taNoticesContent-" + widgetInstanceId).off('click.click-richtext-' + widgetInstanceId);
        // Hide the toolbar so a user cannot click on move/delete while editting text
        var toolbar = $("#widget_" + widgetInstanceId).find(".btn-toolbar");
        toolbar.hide();
        // Adjust CSS setttings so widget is above cover
        $(widget).css("z-index", "1010");
        $("#custom-page-cover").show();

        $("#custom-page-cover").on('click.confirm-richtext-' + widgetInstanceId, function (e) {
            // if the content has been updated then display confirmation
           
            if (widget.html().trim() != $("#notices-prevContent-" + widgetInstanceId).html().trim()) {
                // Popup bootbox confirmation
                noticesModule.showSaveCancelConfirmation(widgetInstanceId, false);
            }
            else {
                noticesModule.setupWidget(widgetInstanceId, false, true);
            }
            // Stop cover click propagating to lower z-index ranked elements
            e.stopPropagation();
            return false;
        });

        return false;
    });

    if ($("#isWebmaster").val() == "False") {
        $(".notice-confirm-email").remove();
    }

   
    
};

noticesModule.pushPacketSizeValid = function ( text ) {
    var isSizeValid = false;

    $.ajax(
        {
            data: {text:text},
            url: '/cms/site/' + $('#SiteId').val() + '/notices/sizevalid',
            async: false,
            method:'POST',
            success: function(result) {
                isSizeValid = result.isSizeValid;
            }
        });
    
    return isSizeValid;
};

noticesModule.sendEmail = function (widgetInstanceId, successCallback) {
    $.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/notices/send',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        data: JSON.stringify({ 'text': CKEDITOR.instances["taNoticesContent-" + widgetInstanceId].getData() }),
        success: function (data) {
            if (data) {
                $("#btnSentNotice").find('.fa').removeClass('fa-spinner');
                $("#btnSentNotice").attr('disabled', false);
                successCallback();
            }
        }
    });
};

noticesModule.maxPages = 1;
noticesModule.page = 0;

noticesModule.getNoticeHistory = function (page, widgetInstaceId) {
    $.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/notices/gethistory?page=' + page,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data != null && data.length > 0) {
                var html = '';
                for (var i = 0; i < data.length; i++) {
                    html += '<tr data-id="' + data[i].Id + '" data-widgetinstanceid="' + widgetInstaceId + '">';
                    html += '<td class="notice-time">' + data[i].SentOn + '</td>';
                    html += '<td class="notice-txt">' + data[i].Message + '</td>';
                    html += '<td class="notice-action"><a class="btn btn-warning btn-sm pull-left cursor-pointer delete-notice"><i class="glyphicon glyphicon-trash"></i></a></td>';
                    html += '</tr>';
                }
                noticesModule.page = noticesModule.page + 1;
                noticesModule.maxPages = data[0].MaxPages;
                if (page = 0) {
                    $("#notice-history_" + widgetInstaceId).html('');
                    $("#notice-history_" + widgetInstaceId).html(html);
                }
                else {
                    $("#notice-history_" + widgetInstaceId).append(html);
                }
                return false;
            }
        }
    });
};

noticesModule.deleteNotice = function (noticeId, row) {
    var widgetInstanceId = row.data('widgetinstanceid');
    $.ajax({
        url: '/cms/site/notices/deletenotice?id=' + noticeId,
        type: 'DELETE',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data) {
                $(row).remove();
                if ($('#notice-history')[0].scrollHeight < 300 && noticesModule.page < noticesModule.maxPages) {
                    noticesModule.getNoticeHistory(noticesModule.page, widgetInstanceId);
                    return false;
                }
                return false;
            }
            else {
                bootbox.alert('Something went wrong.');
            }
        }
    });
}

noticesModule.detachClickConfirmHandlers = function (widgetInstanceId) {
    // detach this handler regardless of whether save/cancel is clicked
    $("#custom-page-cover").off('click.confirm-richtext-' + widgetInstanceId);
    // display toolbar once again
    $("#widget_" + widgetInstanceId).find(".btn-toolbar").show();
    // Remove cover and set z-index to normal
    $("#taNoticesContent-" + widgetInstanceId).css("z-index", "0");
    $("#custom-page-cover").hide();
};

noticesModule.showSaveCancelConfirmation = function (widgetInstanceId, isDiscardChanges) {
    var str = "";
    if (isDiscardChanges) {
        str = "<p>Discard any changes you have made to this content?</p>";
    } else {
        str = "<p>This text is not saved. Press OK to save changes or press CANCEL to continue editing text.</p>";
    }

    $("#cke_richtext-" + widgetInstanceId).hide();
    bootbox.confirm(str, function (result) {
        if (result) {
            noticesModule.setupWidget(widgetInstanceId, true, isDiscardChanges);
        } else {
            $("#cke_richtext-" + widgetInstanceId).show();
        }
    });
}

noticesModule.setupWidget = function (widgetInstanceId, commitChanges, isDiscardChanges) {
    // Detach this handler for confirmation box and show toolbar

    noticesModule.detachClickConfirmHandlers(widgetInstanceId);
    if (isDiscardChanges) {
        // User has asked to cancel changes so swap the previous content into content area
        $("#taNoticesContent-" + widgetInstanceId).html($("#notices-prevContent-" + widgetInstanceId).html());
    }
    if (commitChanges) {
        noticesModule.commitChanges(widgetInstanceId);
    }

    // Attach handler and hide transparent cover
    noticesModule.attachClickHandlers(widgetInstanceId);

}


/* -------- Inclusions ---------- */
noticesModule.loadInclusions = function () {
    $("#notice-subscribers-wrapper").load("/" + $("#SiteId").val() + "/notices/subscribers", function () {
        noticesModule.attachInclusionModalHandlers();
        noticesModule.hasSubscribers();
    });
};

noticesModule.attachInclusionModalHandlers = function () {
    $(".btnAddSubscriber").unbind("click");
    $(".btnAddSubscriber").on("click", function () {
        // Disable modal actions
        $("#myModal .modal-body").animate({ scrollTop: $("#myModal").height() + 150 }, 'slow');
        $(".btnAddSubscriber").hide();
        // Remove info text
        $("#alertNoSubscribers").hide();
        // Add Empty Row
        var template = Handlebars.compile($('#hbtNewInclusion').html());
        $(".tblEmailInclusions").append(template);
        // Attach Save/Cancel Handlers
        $(".btnAddNewIncludedEmail").on('click', function () {
            var tableRow = $(this).closest("tr");
            var emailAddress = tableRow.find('.edit-email').val();
            if (!sportsground.utils.validateEmailAddress(emailAddress)) {
                tableRow.find(".form-group").addClass("has-error");
                return false;
            } else {
                tableRow.find(".form-group").removeClass("has-error");
            }
            var model = {
                email: emailAddress
            };
            $.ajax({
                url: '/cms/site/' + $('#SiteId').val() + '/notices/optin',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(model),
                success: function (data, textStatus, xhr) {
                    // Hide 'add-new' row & show add button
                    $(".addIncludedEmailRow").remove();
                    $('.btnAddSubscriber').show();
                    $(".inclusion-action-buttons").show();
                    // Check the inclusion was successfully added
                    if (data.length > 0)
                        return false;
                    if (data.Id == 0)
                        return false;
                    $("#myModal .modal-body").animate({ scrollTop: $("#myModal").height() + 150 }, 'slow');
                    noticesModule.loadInclusions();
                }
            });
        });
        $(".btnCancelNewIncludedEmail").unbind("click");
        $(".btnCancelNewIncludedEmail").on('click', function () {
            $(".addIncludedEmailRow").remove();
            $('.btnAddSubscriber').show();
            $(".inclusion-action-buttons").show();
        });
    });

   // $(".tblEmailInclusions").unbind("click");
    $(".tblEmailInclusions").on('click', ".btnEditIncludedEmail", function () {
        var tableRow = $(this).closest("tr");
        // hide edit/remove buttons and display save
        $(this).hide();
        tableRow.find(".btnDeleteNewsletterAdvert").hide();
        tableRow.find(".btnSaveIncludedEmail").show();
        $('.btnAddSubscriber').hide();
        // switch edit input for display
        tableRow.find(".display-email").parent().hide();
        tableRow.find(".edit-email").show();
    });

    $(".tblEmailInclusions").on("click", ".btnSaveIncludedEmail", function () {
        var tableRow = $(this).closest("tr");
        var emailDisplay = tableRow.find(".display-email");
        var emailInput = tableRow.find(".edit-email");
        // Validate email address before saving
        if (!sportsground.utils.validateEmailAddress(emailInput.val())) {
            emailInput.closest(".form-group").addClass("has-error");
            return false;
        } else {
            emailInput.closest(".form-group").removeClass("has-error");
        }

        var model = {
            subId: tableRow.data("id"),
            email: emailInput.val()
        };
        $.ajax({
            url: '/cms/site/' + $('#SiteId').val() + '/notices/updatesubscriber',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data) {
                // Switch edit input to display
                emailDisplay.html(emailInput.val());
                emailInput.hide();
                emailDisplay.parent().show();
                // Change buttons
                tableRow.find('.btnEditIncludedEmail').show();
                tableRow.find('.btnSaveIncludedEmail').hide();
                tableRow.find(".btnDeleteNoticesAdvert").show();
                $('.btnAddSubscriber').show();
            }
        });
    });

    $(".tblEmailInclusions").on("click", ".btnDeleteNoticesAdvert", function () {
        var tableRow = $(this).closest("tr");
        noticesModule.removeInclusion(tableRow.data("id"));
        
    });
};

noticesModule.detachInclusionModalHandlers = function () {
    $(".tblEmailInclusions").off('click', ".btnEditIncludedEmail");

    $(".tblEmailInclusions").off("click", ".btnSaveIncludedEmail");

    $(".tblEmailInclusions").off("click", ".btnDeleteNoticesAdvert");
};

noticesModule.removeInclusion = function (id) {
    var model = {
        subId: id
    };
    $.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/notices/removesubscriber',
        type: 'DELETE',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            noticesModule.loadInclusions();
        }
    });
}
;
var richTextModule = extend(sportsground, 'sportsground.cms.widgets.richText');


richTextModule.create = function (widgetInstanceId) {
    if (!$('body').hasClass('edit'))
        return false;

    var widget = $('#richtext-' + widgetInstanceId);
 
    $("#richtext-prevContent-" + widgetInstanceId).html(widget.html());
    if (!CKEDITOR.instances["richtext-" + widgetInstanceId] && $("#richtext-" + widgetInstanceId).attr("contenteditable") == "true") {
        // This richtext has been asyncronously loaded and we must bind ckeditor to new dom element
        var editor = CKEDITOR.inline("richtext-" + widgetInstanceId);
        var googleFonts = ['Amatic SC', 'Montserrat', 'Raleway', 'Playfair Display', 'Nunito', 'Nunito Sans', 'Arvo', 'Open Sans', 'Roboto Slab', 'Quicksand', 'Lato', 'Oswald'];

        for (var i = 0; i < googleFonts.length; i++) {
            var fontName = googleFonts[i].replace(' ', '+');

            if (googleFonts[i] === "Amatic SC") {
                fontName = "Amatic+SC:700&display=swap";
            }
            else if (googleFonts[i] === "Nunito Sans") {
                fontName = "Nunito+Sans&display=swap";
            }
            googleFonts[i] = '//fonts.googleapis.com/css?family=' + fontName;
            $("head").append("<link href='" + googleFonts[i] + "' rel='stylesheet' type='text/css'>");
        }

        editor.config.contentsCss = ['/Content/ckeditor/contents.css'].concat(googleFonts);
    }


    richTextModule.attachClickHandlers(widgetInstanceId);
    $("#custom-page-cover").width($(window).width());
    $("#custom-page-cover").height($(window).height());
};

richTextModule.commitChanges = function (widgetInstanceId) {
    var widget = $("#richtext-" + widgetInstanceId);

    // if no changes have been made then do not save
    if (widget.html() === $("#richtext-prevContent-" + widgetInstanceId).val())
        return false;

    var html = widget.html();

    var editorElem = $('<p>').append(html);

    if ( editorElem.length === 1 && editorElem.find('a').length > 0 ) { //set the anchors to inherit child element color
        html = sportsground.cms.common.setAnchorToHaveChildColor(editorElem, html);
    }

    text = sportsground.cms.common.removeEditModeLinkParam(html);

    widget.html(html);
    $("#richtext-prevContent-" + widgetInstanceId).html(html);

    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'RichText',
        Settings: {
            Html: html
        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202) {
                $("#modal-dialog").modal('show');
            }
        }
    });
};

richTextModule.styleCkEditorSaveAndCancelButtons = function () {
    CKEDITOR.on("instanceReady", function (event) {
        //$('.cke_toolbar_break').replaceWith('<br/>');
        $('.cke_button__save_icon').replaceWith('<i class="glyphicon glyphicon-floppy-disk"></i>');
        $('.cke_button__cancel_icon').replaceWith('<i class="glyphicon glyphicon-remove"></i>');
    });
};

richTextModule.attachClickHandlers = function (widgetInstanceId) {
    $("#richtext-" + widgetInstanceId + ".cke_editable").on('click.click-richtext-' + widgetInstanceId, function () {
        var widget = $(this);
        // Remove this handler attached to clicking within richtext area
        $("#richtext-" + widgetInstanceId).off('click.click-richtext-' + widgetInstanceId);
        // Hide the toolbar so a user cannot click on move/delete while editting text
        var toolbar = $("#widget_" + widgetInstanceId).find(".btn-toolbar");
        toolbar.hide();
        // Adjust CSS setttings so widget is above cover
        $(widget).css("z-index", "1010");
        $("#custom-page-cover").show();

        $("#custom-page-cover").on('click.confirm-richtext-' + widgetInstanceId, function (e) {
            // if the content has been updated then display confirmation		  
            if (widget.html().trim() != $("#richtext-prevContent-" + widgetInstanceId).html().trim()) {
                // Popup bootbox confirmation
                richTextModule.showSaveCancelConfirmation(widgetInstanceId, false);
            }
            else {
                richTextModule.setupWidget(widgetInstanceId, false, true);
            }
            // Stop cover click propagating to lower z-index ranked elements
            e.stopPropagation();
            return false;
        });

        return false;
    });


};

richTextModule.detachClickConfirmHandlers = function (widgetInstanceId) {
    // detach this handler regardless of whether save/cancel is clicked
    $("#custom-page-cover").off('click.confirm-richtext-' + widgetInstanceId);
    // display toolbar once again
    $("#widget_" + widgetInstanceId).find(".btn-toolbar").show();
    // Remove cover and set z-index to normal
    $("#richtext-" + widgetInstanceId).css("z-index", "0");
    $("#custom-page-cover").hide();
};

richTextModule.showSaveCancelConfirmation = function (widgetInstanceId, isDiscardChanges) {
    var str = "";
    if (isDiscardChanges) {
        str = "<p>Discard any changes you have made to this content?</p>";
    } else {
        str = "<p>This text is not saved. Press OK to save changes or press CANCEL to continue editing text.</p>";
    }

    $("#cke_richtext-" + widgetInstanceId).hide();
    bootbox.confirm(str, function (result) {
        if (result) {
            richTextModule.setupWidget(widgetInstanceId, true, isDiscardChanges);
        } else {
            $("#cke_richtext-" + widgetInstanceId).show();
        }
    });
}

richTextModule.setupWidget = function (widgetInstanceId, commitChanges, isDiscardChanges) {
    // Detach this handler for confirmation box and show toolbar
    richTextModule.detachClickConfirmHandlers(widgetInstanceId);
    if (isDiscardChanges) {
        // User has asked to cancel changes so swap the previous content into content area
        $("#richtext-" + widgetInstanceId).html($("#richtext-prevContent-" + widgetInstanceId).html());
    }
    if (commitChanges) {
        richTextModule.commitChanges(widgetInstanceId);
    }

    // Attach handler and hide transparent cover
    richTextModule.attachClickHandlers(widgetInstanceId);
};
var rssFeedModule = extend(sportsground, 'sportsground.cms.widgets.rssFeed');

rssFeedModule.create = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);

    rssFeedModule.attachPaginationHandlers(widgetInstanceId);

    rssFeedModule.rssFeedList = [];

    var rssFeedUrls = widget.find('.hdnRssFeedUrl').val();

    if (rssFeedUrls != "" && rssFeedUrls != undefined) {
        var pageNumber = widget.find('.hdnPageNumber').val();
        var take = widget.find('.rssFeed-list').attr('data-take');
        rssFeedModule.getRssFeed(widgetInstanceId, rssFeedUrls, pageNumber, take);
    }
};

rssFeedModule.getRssFeed = function (widgetInstanceId, rssFeedUrls, pageNumber, take) {
    var widget = $('#widget_' + widgetInstanceId);

    var model = {
        urls: rssFeedUrls,
        pageNumber: pageNumber,
        take: take
    }
    $.ajax({
        url: '/cms/site/news/rssfeed',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            if (data != null) {
                if (data.Result == false) {
                    rssFeedModule.rssFeedList = [];
                }
                else {
                    if (data.FeedItems.length > 0) {
                        rssFeedModule.rssFeedList = data.FeedItems;
                        widget.find('.hdnPageCount').val(data.PageCount);
                        rssFeedModule.loadRssFeed(widgetInstanceId);
                    }
                    else {
                        var html = '<p>News feed not available.</p>';
                        widget.find('.rssFeed-list').html(html);
                        widget.find('.rssFeed-list-pager').addClass('hidden');
                    }
                }
            }
        }
    });
};

rssFeedModule.loadRssFeed = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);
    var rssFeedPerPage = widget.find('.rssFeed-list').data('take');

    var container = widget.find('.rssFeed-list');

    container.html('');

    var hasTextSnippet = true;
    var hdnHasTextSnippet = widget.find('.hdnHasTextSnippet').val();
    var hasShowThumbnails = true;
    var hdnHasShowThumbnails = widget.find('.hdnHasShowThumbnails').val();
    if (hdnHasTextSnippet != undefined && hdnHasTextSnippet != null && hdnHasTextSnippet.toLowerCase() == "false")
        hasTextSnippet = false;
    if (hdnHasShowThumbnails != undefined && hdnHasShowThumbnails != null && hdnHasShowThumbnails.toLowerCase() == "false")
        hasShowThumbnails = false;

    var rawHtml = $('#hbtRssFeed-List-Item').html();
    var template = Handlebars.compile(rawHtml);

    var data = rssFeedModule.rssFeedList;

    for (var i = 0; i < data.length; i++) {
        if (!hasTextSnippet) {
            data[i].Summary = "";
        }
        data[i].ShowThumbnail = hasShowThumbnails;
        container.append(template(data[i]));
    }

    var pageCount = widget.find(".hdnPageCount").val();
    var pageNumber = widget.find(".hdnPageNumber").val();
    // Hide next/prev buttons if we are at the end/start of the articles list
    var nextButton = widget.find(".news-list-next");
    var prevButton = widget.find(".news-list-prev");
    if (parseInt(pageNumber) + 1 >= pageCount) {
        nextButton.addClass('hidden');
    } else {
        nextButton.removeClass('hidden');
    }

    if (parseInt(pageNumber) > 0) {
        prevButton.removeClass('hidden');
    } else {
        prevButton.addClass('hidden');
    }
}

rssFeedModule.commitChanges = function (widgetInstanceId) {
    var widget = $("#widget_" + widgetInstanceId);
    var take = $('#uxNewsTakeDropdown').val();
    var url = $('#RssFeedUrl').val();

    var isvalidUrls = true;

    if (url != "") {
        var urls = url.split(',');
        if (urls.length > 0) {
            for (var i = 0; i < urls.length; i++) {
                var isvalid = is_valid_url(url);
                if (!isvalid) {
                    isvalidUrls = false;
                    break;
                }
            }
        }
    }

    if (!isvalidUrls || url == "") {
        $('#RssFeedUrl').parent('.form-group').removeClass('has-success');
        $('#RssFeedUrl').parent('.form-group').addClass('has-error');
        return false;
    }
    else {
        $('#RssFeedUrl').parent('.form-group').removeClass('has-error');
        $('#RssFeedUrl').parent('.form-group').addClass('has-success');
    }
   
    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'RssFeed',
        Settings: {
            Take: take,
            RssFeedUrl: url,
            HasTextSnippet: $("#chkTextSnippet").is(':checked'),
            HasShowThumbnails: $("#chkShowThumbnails").is(':checked'),
            HasHeader: $("#chkShowHeader").is(':checked'),
            HeaderText: $("#HeaderText").val()
        }
    };

    rssFeedModule.updateWidgetSettings(widgetSettings);

    widget.find('.hdnRssFeedUrl').val(url);
    widget.find('.rssFeed-list').attr('data-take', take);
    widget.find('.hdnHasTextSnippet').val(widgetSettings.Settings.HasTextSnippet);
    widget.find('.hdnHasShowThumbnails').val(widgetSettings.Settings.HasShowThumbnails);
    if (widgetSettings.Settings.HasHeader) {
        widget.find("#hasHeader").removeClass('hidden');
    }
    else {
        widget.find("#hasHeader").addClass('hidden');
    }
    widget.find(".rssFeed-list-heading").html(widgetSettings.Settings.HeaderText);

    rssFeedModule.create(widgetInstanceId);
    $("#myModal").modal('hide');
};

rssFeedModule.updateWidgetSettings = function (widgetSettings) {
    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202) {
                $("#modal-dialog").modal('show');
            }
        }
    });
};

rssFeedModule.modalCreated = function (widgetInstanceId) {
};

rssFeedModule.attachPaginationHandlers = function (widgetInstanceId) {
    var widget = $('#widget_' + widgetInstanceId);
    var pageNumberDomObject = $("#widget_" + widgetInstanceId).find(".hdnPageNumber");

    $("#widget_" + widgetInstanceId).on("click", ".news-list-next", function () {
        var pageNumber = parseInt(pageNumberDomObject.val());
        var feedUrls = widget.find('.hdnRssFeedUrl').val();
        var take = widget.find('.rssFeed-list').data('take');
        rssFeedModule.getRssFeed(widgetInstanceId, feedUrls, pageNumber + 1, take);
        pageNumberDomObject.val(pageNumber + 1);
    });

    $("#widget_" + widgetInstanceId).on("click", ".news-list-prev", function () {
        var pageNumber = parseInt(pageNumberDomObject.val());
        var feedUrls = widget.find('.hdnRssFeedUrl').val();
        var take = widget.find('.rssFeed-list').data('take');
        rssFeedModule.getRssFeed(widgetInstanceId, feedUrls, pageNumber - 1, take);
        pageNumberDomObject.val(pageNumber - 1);
    });
};

function is_valid_url(url) {
    return /^http(s)?:\/\/?(www\.)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/.test(url);
};
var searchModule = extend(sportsground, 'sportsground.cms.widgets.search');

searchModule.commitChanges = function (widgetInstanceId) {

};

searchModule.modalCreated = function () {

};

;

//Copyright Sportsground Limited 2016

var compWidgetApiVersion = "1.0";
var sifCompWidgetBaseUrl = "/api/" + compWidgetApiVersion + "/competition/sifwidget/";

var sifDrawsModule = extend(sportsground, 'sportsground.cms.widgets.sIFCompetition');

sifDrawsModule.isSIF = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);
    var sportId = $(compWidget).find('.hdnSelectedSportId').val();
    var seasonId = $(compWidget).find('.hdnSelectedSeasonId').val();

    if (isNaN($('#comp-sports').val()) && isNaN($('#comp-seasons').val())) {

        $($(compWidget).find('.draws-export')[0]).hide();
        $($(compWidget).find('.results-export')[0]).hide();

        return true;
    }
    else {

        $($(compWidget).find('.draws-export')[0]).show();
        $($(compWidget).find('.results-export')[0]).hide();

        return false;
    }
}

//front end client side create
sifDrawsModule.create = function (widgetInstanceId) {
    sifDrawsModule.setUpDataToggle();

    var competitionWidget = $('#widget_' + widgetInstanceId);
    var now = new Date();
    var weekAfter = new Date();
    weekAfter.setDate(weekAfter.getDate() + 7);

    //create from and to datepickers
    $(competitionWidget).find('input.comp-widget-from').sportsgroundMobiscroll().datePicker(now, competitionWidget, 'competition');
    $(competitionWidget).find('input.comp-widget-to').sportsgroundMobiscroll().datePicker(weekAfter, competitionWidget, 'competition');

    var drawsTabExist = $(competitionWidget).find('.draws-tab').length;
    var resultsTabExist = $(competitionWidget).find('.results-tab').length;
    var standingsTabExist = $(competitionWidget).find('.standings-tab').length;

    if (!drawsTabExist && resultsTabExist) {
        $('.results-tab').trigger('click');
    }
    else if (!drawsTabExist && !resultsTabExist && standingsTabExist) {
        $('.standings-tab').trigger('click');
    }

    //populate front end competition dropdown list 
    $(competitionWidget).find('select.fe-comp-comps').each(function (i) {
        var compIds = $(this).data("compids");
        var compWidget = $(this).parents('.wSIFCompetition');
        var dropdownList = $(this);

        var model = {
            compIds: compIds
        };

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: sifCompWidgetBaseUrl + 'competitionsfromids',
            data: JSON.stringify(model),
            cache: false,
            success: function (data) {

                for (var index = 0; index < data.length; index++) {
                    $(dropdownList).append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                }

                var widgetInstanceId = compWidget.data("id");
                var compId = compWidget.find('select.fe-comp-comps').val();

                sifDrawsModule.getFEPhases(widgetInstanceId, compId, true);

            }
        });

    });

    $(competitionWidget).find('select.fe-comp-comps').change(function (e) {

        var widgetId = $($(this).parents('.wSIFCompetition')[0]).data("id");
        var compId = $(this).val();

        sifDrawsModule.getFEPhases(widgetId, compId, true);

    });

    $(competitionWidget).find('select.fe-comp-orgs').change(function (e) {

        var widgetId = $($(this).parents('.wSIFCompetition')[0]).data("id");

        sifDrawsModule.getFEGrades(widgetId);

    });

    $(competitionWidget).find('select.fe-comp-grades').change(function (e) {

        var widgetId = $($(this).parents('.wSIFCompetition')[0]).data("id");

        if (sifDrawsModule.isSIF(widgetId))
            sifDrawsModule.getFEComps(widgetId);

    });

    $(competitionWidget).find('.apply-comp-filters').click(function (e) {

        var widgetId = $($(this).parents('.wSIFCompetition')[0]).data("id");
        sifDrawsModule.getDraws(widgetId);

    });

    if ($('#OrganisationId').val() == "10047") { //hack/hard code so ad doesnt show for canterbury rugby crfu

        $(".competition-desktop-ad").remove();
        $(".competition-mobile-ad").remove();

    }



    $(".calendar-icon").click(function (e) {
        try {
            $($(e)[0].currentTarget).prev().data("DateTimePicker").show();
        }
        catch (e) {
            $(".comp-widget-from").click();
        }

    });

    $(".calendar-icon-from").click(function (e) {
        try {
            $(".comp-widget-from").click();
        }
        catch (e) {

        }

    });

    $(".calendar-icon-to").click(function (e) {
        try {
            $(".comp-widget-to").click();
        }
        catch (e) {

        }

    });

    $(".toggle-widget-filters").click(function (e) {

        $(".comp-widget-filters-wrapper").toggle();
        $(".toggle-widget-filters .fa-chevron-up").toggle();
        $(".toggle-widget-filters .fa-chevron-down").toggle();

        if ($(".toggle-filter-text").html() == "Hide Filters") {
            $(".toggle-filter-text").html("Show Filters");
        }
        else {
            $(".toggle-filter-text").html("Hide Filters");
        }

    });

};

sifDrawsModule.setUpExportEvent = function () {

    $('.draws-export span').unbind('click');
    $(".draws-export span").click(function (e) {

        var widgetId = $($(this).parents('.wSIFCompetition')[0]).data("id");
        sifDrawsModule.exportDraw(widgetId);

    });

    $('.results-export span').unbind('click');
    $(".results-export span").click(function (e) {

        var widgetId = $($(this).parents('.wSIFCompetition')[0]).data("id");
        sifDrawsModule.exportResults(widgetId);

    });

}

sifDrawsModule.getFEPhases = function (widgetId, selectedCompId, loadGrades) {


    sifDrawsModule.getFEOrgs(widgetId, selectedCompId, loadGrades);



}

sifDrawsModule.getFEOrgs = function (widgetId, selectedCompId, loadGrades) {


    $.get(sifCompWidgetBaseUrl + 'organisations?ids=' + selectedCompId)
        .done(function (data) {

            var compWidget = $("#widget_" + widgetId);
            var allowedOrgIds = $(compWidget).find('select.fe-comp-orgs').data("orgids");
            var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');

            orgsDropdown.multiselect('destroy');
            orgsDropdown.removeAttr("multiple");
            orgsDropdown.find('option').remove();

            var allOrgIds = [];
            for (var index = 0; index < data.length; index++) {

                if (allowedOrgIds.toString().indexOf(data[index].Id) != -1) {
                    orgsDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                }

                allOrgIds.push(data[index].Id);

            }

            if (data.length > 0) {
                orgsDropdown.attr("multiple", "multiple");
                orgsDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Organisations Selected",
                    nonSelectedText: "Select an Organisation...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {

                    }
                });
            }

            orgsDropdown.multiselect('deselectall', false);
            orgsDropdown.multiselect('select', allOrgIds);

            $($(compWidget).find('.comp-widget-org-wrapper')[0]).find('.multiselect-item.multiselect-all').each(function (index) {
                $(this).addClass('active');
            });

            $($(compWidget).find('.comp-widget-org-wrapper')[0]).find('.multiselect-all input').each(function (index) {
                $(this).prop('checked', true);
            });

            if (loadGrades)
                sifDrawsModule.getFEGrades(widgetId);

        });

}

sifDrawsModule.getFEComps = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);
    var selectedGrades = $(compWidget).find('select.fe-comp-grades').val();
    var seasonId = $(compWidget).find('.hdnSelectedSeasonId').val();
    var sportId = $(compWidget).find('.hdnSelectedSportId').val();

    var gradeIds = selectedGrades != null && selectedGrades != "" ? selectedGrades.join(",") : ["0"];

    $.get(sifCompWidgetBaseUrl + 'competitionsbygrades?ids=' + gradeIds + "&seasonId=" + seasonId + "&sportId=" + sportId)
        .done(function (data) {

            var compWidget = $("#widget_" + widgetId);

            var dropdown = $(compWidget).find('select.fe-comp-comps');
            dropdown.find('option').remove();

            for (var index = 0; index < data.length; index++) {
                $(dropdown).append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
            }

            var compWidget = $("#widget_" + widgetId);
            var compId = $(compWidget).find('select.fe-comp-comps').val();

            sifDrawsModule.getFEPhases(widgetId, compId, false);

        });
}

sifDrawsModule.getFEGrades = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);
    var phaseIds = $(compWidget).find('select.fe-comp-phases').val();

    $.get(sifCompWidgetBaseUrl + 'Grades?orgId=' + $('#OrganisationId').val())
        .done(function (data) {

            var compWidget = $("#widget_" + widgetId);
            var allowedGradeIds = $(compWidget).find('select.fe-comp-grades').data("gradeids");
            var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

            gradesDropdown.multiselect('destroy');
            gradesDropdown.removeAttr("multiple");
            gradesDropdown.find('option').remove();

            //check an org has been selected
            var orgIds = true;//$('#comp-admin-orgs').val();
            var allGradeIds = [];
            if (orgIds) {

                for (var index = 0; index < data.length; index++) {
                    if (allowedGradeIds.toString().indexOf(data[index].Id) != -1) {
                        gradesDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    }
                    allGradeIds.push(data[index].Id);
                }

            }

            if (data.length > 0) {

                gradesDropdown.attr("multiple", "multiple");
                gradesDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Grades Selected",
                    nonSelectedText: "Select a Grade...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {

                    }
                });

            }

            gradesDropdown.multiselect('deselectall', false);
            gradesDropdown.multiselect('select', allGradeIds);

            $($(compWidget).find('.comp-widget-grade-wrapper')[0]).find('.multiselect-item.multiselect-all').each(function (index) {
                $(this).addClass('active');
            });

            $($(compWidget).find('.comp-widget-grade-wrapper')[0]).find('.multiselect-all input').each(function (index) {
                $(this).prop('checked', true);
            });

            // sifDrawsModule.getFETeams(widgetId);

            if (!$(compWidget).data("justloaded")) {
                sifDrawsModule.getDraws(widgetId);
                $(compWidget).data("justloaded", true);
            }
        });
}

sifDrawsModule.getSelectedSportId = function () {
    return $('#comp-sports').val();
}

sifDrawsModule.getSelectedSeasonId = function () {
    return $('#comp-seasons').val();
}

sifDrawsModule.loadFilters = function () {

    var phaseDropdown = $('#comp-admin-phases');

    $(phaseDropdown).parent().parent().hide();//get phase wrapper
    $(".grades-wrapper").prependTo(".comp-edit-second-row");
    sifDrawsModule.getGrades(true);

}

sifDrawsModule.getComps = function (isSif) {
    var organisationId = $('#OrganisationId').val();
    var sportId = sifDrawsModule.getSelectedSportId();
    var seasonId = sifDrawsModule.getSelectedSeasonId();

    if (sportId == "0" || seasonId == "0") {
        return;
    }

    var gradeIds = $('#comp-admin-grades').val();
    if (gradeIds) {
        gradeIds = gradeIds.join(",")
    }

    var model = {
        organisationId: organisationId,
        gradeIds: gradeIds,
        sportId: sportId,
        seasonId: seasonId
    };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: sifCompWidgetBaseUrl + 'Competitions',
        data: JSON.stringify(model),
        cache: false,
        success: function (data) {

            var compsDropdown = $('#comp-admin-comps');

            sifDrawsModule.clearAllDropdowns(isSif);

            var allCompIds = [];

            for (var index = 0; index < data.length; index++) {
                compsDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                allCompIds.push(data[index].Id);
            }

            if (data.length > 0) {
                compsDropdown.attr("multiple", "multiple");
                compsDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Competitions Selected",
                    nonSelectedText: "Select a Competition...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {

                        $("#hdnSelectedCompIds").val($('#comp-admin-comps').val());
                        sifDrawsModule.getPhases(isSif);

                    }
                });
            }

            compsDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedCompIds").val() != "") {
                compsDropdown.multiselect('select', $("#hdnSelectedCompIds").val().split(","));

                if ($("#hdnSelectedCompIds").val().split(",").length == allCompIds.length) {

                    $(".admin-comps-wrapper").find('.multiselect-item.multiselect-all').each(function (index) {
                        $(this).addClass('active');
                    });

                    $(".admin-comps-wrapper").find('.multiselect-all input').each(function (index) {
                        $(this).prop('checked', true);
                    });

                }

            }
            else {
                compsDropdown.multiselect('select', allCompIds);
            }

            if ($("#hdnSelectedCompIds").val().split(",").length > 0) {
                sifDrawsModule.getPhases(isSif);
            }

        }
    });
}

sifDrawsModule.clearAllDropdowns = function (isSif) {

    try {

        var compsDropdown = $('#comp-admin-comps');
        var orgsDropdown = $('#comp-admin-orgs');
        var phaseDropdown = $('#comp-admin-phases');
        var gradesDropdown = $('#comp-admin-grades');
        var teamsDropdown = $('#comp-admin-teams');

        compsDropdown.multiselect('destroy');
        compsDropdown.removeAttr("multiple");
        orgsDropdown.multiselect('destroy');
        orgsDropdown.removeAttr("multiple");
        phaseDropdown.multiselect('destroy');
        phaseDropdown.removeAttr("multiple");

        if (!isSif) {
            gradesDropdown.multiselect('destroy');
            gradesDropdown.removeAttr("multiple");
        }

        teamsDropdown.multiselect('destroy');
        teamsDropdown.removeAttr("multiple");

        compsDropdown.find('option').remove();
        orgsDropdown.find('option').remove();
        phaseDropdown.find('option').remove();

        if (!isSif) {
            gradesDropdown.find('option').remove();
        }

        teamsDropdown.find('option').remove();

    }
    catch (e) {
        //first time
    }

}


sifDrawsModule.getOrgs = function (isSif) {

    var compIds = $('#comp-admin-comps').val();

    if (!compIds || compIds == "Select a Competition...") {
        compIds = ["0"];
    }

    var model = {
        ids: compIds.join(",")
    };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: sifCompWidgetBaseUrl + 'organisationslist',
        data: JSON.stringify(model),
        cache: false,
        success: function (data) {

            var orgDropdown = $('#comp-admin-orgs');

            try {
                orgDropdown.multiselect('destroy');
                orgDropdown.removeAttr("multiple");
            }
            catch (e) {
                //first time
            }

            orgDropdown.find('option').remove();

            var allOrgIds = [];
            for (var index = 0; index < data.length; index++) {
                orgDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                allOrgIds.push(data[index].Id);
            }

            if (data.length > 0) {
                orgDropdown.attr("multiple", "multiple");
                orgDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Organisations Selected",
                    nonSelectedText: "Select an Organisation...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {

                        $("#hdnSelectedOrgIds").val($('#comp-admin-orgs').val());

                        if (!isSif)
                            sifDrawsModule.getGrades(isSif);
                    }
                });
            }

            orgDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedOrgIds").val() != "") {
                orgDropdown.multiselect('select', $("#hdnSelectedOrgIds").val().split(","));

                if ($("#hdnSelectedOrgIds").val().split(",").length == allOrgIds.length) {

                    $(".admin-orgs-wrapper").find('.multiselect-item.multiselect-all').each(function (index) {
                        $(this).addClass('active');
                    });

                    $(".admin-orgs-wrapper").find('.multiselect-all input').each(function (index) {
                        $(this).prop('checked', true);
                    });

                }

            }
            else {
                orgDropdown.multiselect('select', allOrgIds);
            }

            if (!isSif)
                sifDrawsModule.getGrades(isSif);

        }
    });

}


sifDrawsModule.getPhases = function (isSif) {

    var compIds = $('#comp-admin-comps').val();

    if (!compIds || compIds == "Select a Competition...") {
        compIds = ["0"];
    }

    var model = {
        compIds: compIds
    };

    sifDrawsModule.getOrgs(isSif);


}

sifDrawsModule.getGrades = function (isSif) {

    var phaseIds = $('#comp-admin-phases').val();
    $.get(sifCompWidgetBaseUrl + 'Grades?orgId=' + $('#OrganisationId').val())
        .done(function (data) {

            var gradesDropdown = $('#comp-admin-grades');

            try {
                gradesDropdown.multiselect('destroy');
                gradesDropdown.removeAttr("multiple");
            }
            catch (e) {
                //first time
            }

            gradesDropdown.find('option').remove();

            //check an org has been selected
            var orgIds = $('#comp-admin-orgs').val();
            var allGradeIds = [];
            if (orgIds || isSif) {

                for (var index = 0; index < data.length; index++) {
                    gradesDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    allGradeIds.push(data[index].Id);
                }

            }

            if (data.length > 0) {

                gradesDropdown.attr("multiple", "multiple");
                gradesDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Grades Selected",
                    nonSelectedText: "Select a Grade...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {

                        $("#hdnSelectedGradeIds").val($('#comp-admin-grades').val());

                        if (isSif) {
                            setTimeout(function () { sifDrawsModule.getComps(isSif) }, 500);
                        }
                    }
                });

            }

            if (isSif) {
                setTimeout(function () { sifDrawsModule.getComps(isSif) }, 500);
            }

            gradesDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedGradeIds").val() != "") {
                gradesDropdown.multiselect('select', $("#hdnSelectedGradeIds").val().split(","));

                if ($("#hdnSelectedGradeIds").val().split(",").length == allGradeIds.length) {

                    $(".grades-wrapper").find('.multiselect-item.multiselect-all').each(function (index) {
                        $(this).addClass('active');
                    });

                    $(".grades-wrapper").find('.multiselect-all input').each(function (index) {
                        $(this).prop('checked', true);
                    });

                }
            }
            else {
                gradesDropdown.multiselect('select', allGradeIds);
            }

        });
}

sifDrawsModule.setUpDataToggle = function () {

    $('.results-tab[data-toggle=tab]').click(function () {

        var widgetId = $(this).parents('.wSIFCompetition').data("id");
        var compWidget = $("#widget_" + widgetId);

        var now = new Date();
        var weekAgo = new Date();
        weekAgo.setDate(weekAgo.getDate() - 7);

        $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(weekAgo);
        $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(now);

        $(compWidget).find(".apply-comp-filters").click();

        // getDraws does not get triggered on mobile when javascript set the date on change tab, trigger manually
        if (sportsground.ui.isMobile()) {
            sifDrawsModule.getDraws(widgetId);
        }
    });

    $('.draws-tab[data-toggle=tab]').click(function () {

        var widgetId = $(this).parents('.wSIFCompetition').data("id");
        var compWidget = $("#widget_" + widgetId);

        var now = new Date();
        var weekAfter = new Date();
        weekAfter.setDate(weekAfter.getDate() + 7);

        $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(now);
        $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(weekAfter);

        $(compWidget).find(".apply-comp-filters").click();

        // getDraws does not get triggered on mobile when javascript set the date on change tab, trigger manually
        if (sportsground.ui.isMobile()) {
            sifDrawsModule.getDraws(widgetId);
        }
    });
}

sifDrawsModule.checkDisplayBoxes = function () {

    var draws = $("#hdnSelectedDraws").val();
    var results = $("#hdnSelectedResults").val();
    var standings = $("#hdnSelectedStandings").val();

    if (draws === 'True') {
        $("#display-draw").prop("checked", true);
    }
    else {
        $("#display-draw").prop("checked", false);
    }

    if (results === 'True') {
        $("#display-results").prop("checked", true);
    }
    else {
        $("#display-results").prop("checked", false);
    }

    if (standings === 'True') {
        $("#display-standings").prop("checked", true);
    }
    else {
        $("#display-standings").prop("checked", false);
    }

}

sifDrawsModule.getDraws = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);

    var compDropdown = $(compWidget).find('select.fe-comp-comps');
    var phaseDropdown = $(compWidget).find('select.fe-comp-phases');
    var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

    var compId = compDropdown.val();
    var phaseId = phaseDropdown.val();
    var orgIds = orgsDropdown.val();
    var gradeIds = gradesDropdown.val();
    var from = $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().getDate().toLocalISOString();
    var to = $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().getDate().toLocalISOString();

    var sportId = $(compWidget).find('.hdnSelectedSportId').val();
    var seasonId = $(compWidget).find('.hdnSelectedSeasonId').val();

    var model = {
        competitionId: compId,
        phaseId: phaseId,
        orgIds: orgIds != null && orgIds != "" ? orgIds.join(",") : "",
        from: from,
        to: to,
        sportId: sportId,
        seasonId: seasonId,
        gradeIds: gradeIds != null && gradeIds != "" ? gradeIds.join(",") : "",
        gradeId: "",
        organisationId: ""
    };


    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: sifCompWidgetBaseUrl + 'filteredfixtures',
        data: JSON.stringify(model),
        cache: false,
        success: function (data) {

            var gradeIds = [];
            var grades = [];

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

                //sif hack for no gradeid returned
                if (data[i].GradeId == null || data[i].GradeId == undefined || !data[i].GradeId) {
                    data[i].GradeId = data[i].GradeName;
                }
                //sif hack for no sections
                if (data[i].SectionId == null || data[i].SectionId == undefined || !data[i].SectionId) {
                    data[i].SectionId = data[i].Round;
                    data[i].SectionName = data[i].RoundName;
                }
            }
            for (var i = 0; i < data.length; i++) {
                if ($.inArray(data[i].GradeId.toString() + data[i].SectionId.toString(), gradeIds) == -1) {
                    gradeIds.push(data[i].GradeId.toString() + data[i].SectionId.toString());
                    grades.push({ "GradeId": data[i].GradeId, "GradeName": data[i].GradeName, "Fixtures": [], "SectionId": data[i].SectionId, "SectionName": data[i].SectionName });
                }

                var grade = jQuery.grep(grades, function (g) {
                    return g.GradeId == data[i].GradeId && g.SectionId == data[i].SectionId;
                })[0];

                grade.Fixtures.push(data[i]);

            }

            var drawDiv = $($(compWidget).find('.fe-draws-list')[0]);
            drawDiv.html("<div class='draws-export'><span></span></div><table></table>");

            var resultsDiv = $($(compWidget).find('.fe-results-list')[0]);
            resultsDiv.html("<div class='results-export'></div><table></table>");

            sifDrawsModule.isSIF(widgetId);

            for (var i = 0; i < grades.length; i++) {
                $($(compWidget).find('.fe-draws-list table')[0]).append("<tr class='grade-header'><td colspan='6'>" + grades[i].GradeName + " (" + grades[i].SectionName + ")</td></tr>");
                $($(compWidget).find('.fe-results-list table')[0]).append("<tr class='grade-header'><td colspan='5'>" + grades[i].GradeName + " (" + grades[i].SectionName + ")</td></tr>");

                for (var f = 0; f < grades[i].Fixtures.length; f++) {
                    var oddEven = f % 2 == 0 ? 'fixture-row-even' : 'fixture-row-odd';

                    var fixture = grades[i].Fixtures[f];
                    var date = new Date(fixture.Date.replace("Z", "") + "Z");
                    date.setMinutes(date.getMinutes() + date.getTimezoneOffset());

                    var officialA = "";
                    if (fixture.OfficialA) {
                        officialA = fixture.OfficialA;
                    }

                    var officialB = "";
                    if (fixture.OfficialB) {
                        officialB = fixture.OfficialB;
                    }

                    var drawsRow = "<tr class='" + oddEven + "'>"
                        + "<td>" + date.getDate() + "/" + (date.getMonth() + 1).toString() + "/" + date.getFullYear() + " " + date.toTimeFormatAMPM() + "</td>"
                        + "<td class='full-name-comp home-team'>" + fixture.HomeTeamName + "</td><td class='abbr-name-comp home-team'>" + fixture.HomeTeamName + "</td>"
                        + "<td>vs</td>"
                        + "<td class='full-name-comp away-team'>" + fixture.AwayTeamName + "</td><td class='abbr-name-comp away-team'>" + fixture.AwayTeamName + "</td>";

                    var defaultCss = "default-" + fixture.CssName;
                    var statusCss = "status-" + fixture.CssName;
                    drawsRow += "<td class='full-name-venue draw-" + defaultCss + "'>" + fixture.VenueName + "</td>"
                        + "<td class='abbr-name-venue draw-" + defaultCss + "'>" + fixture.VenueName + "</td>";
                    drawsRow += "<td class='full-name-comp draw-" + statusCss + "'>" + fixture.StatusName + "</td>"
                        + "<td class='abbr-name-comp draw-" + statusCss + "'>" + fixture.StatusName + "</td>";

                    drawsRow += "<td class='full-name-comp'>" + officialA + "<br/>" + officialB + "</td></tr>";
                    $($(compWidget).find('.fe-draws-list table')[0]).append(drawsRow);

                    if (fixture.PublicNotes) {
                        $($(compWidget).find('.fe-draws-list table')[0]).append("<tr class='" + oddEven + "'><td class='comp-widget-publicnotes' colspan='5'>" + fixture.PublicNotes + "</td></tr>");
                    }

                    var now = new Date();
                    if (now > date) {
                        var resultsRow = "<tr class='" + oddEven + "'>"
                            + "<td>" + date.getDate() + "/" + (date.getMonth() + 1).toString() + "/" + date.getFullYear() + " " + date.toTimeFormatAMPM() + "</td>"
                            + "<td class='full-name-comp home-team'>" + fixture.HomeTeamName + "</td><td class='abbr-name-comp home-team'>" + fixture.HomeTeamName + "</td>";

                        resultsRow += "<td class='result-" + defaultCss + "'>" + fixture.HomeScore + " vs " + fixture.AwayScore + "</td>";
                        resultsRow += "<td class='result-" + statusCss + "'>" + fixture.StatusName + "</td>";

                        resultsRow += "<td class='full-name-comp away-team'>" + fixture.AwayTeamName + "</td><td class='abbr-name-comp away-team'>" + fixture.AwayTeamName + "</td></tr>";
                        $($(compWidget).find('.fe-results-list table')[0]).append(resultsRow);
                        if (fixture.PublicNotes) {
                            $($(compWidget).find('.fe-results-list table')[0]).append("<tr class='" + oddEven + "'><td class='comp-widget-publicnotes' colspan='5'>" + fixture.PublicNotes + "</td></tr>");
                        }
                    }

                }
            }

            if (data.length == 0) {
                drawDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
                resultsDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
            }

            sifDrawsModule.setUpExportEvent();

        }
    });

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: sifCompWidgetBaseUrl + 'filteredstandings',
        data: JSON.stringify(model),
        cache: false,
        success: function (data) {

            var standingsDiv = $($(compWidget).find('.fe-standings-list')[0]);
            //standingsDiv.html("<div class='standings-export'><span><i class='fa fa-file-pdf-o' aria-hidden='true'></i></span></div><table></table>");
            standingsDiv.html("<table></table>");
            $($(compWidget).find('.fe-standings-list table')[0]).append("<tr><th class='team-column'></th><th class='played-column played-column-desktop'>Played</th><th class='played-column played-column-mobile'>P</th><th class='wins-column wins-column-desktop'>Win</th><th class='wins-column wins-column-mobile'>W</th><th class='losses-column losses-column-desktop'>Loss</th><th class='losses-column losses-column-mobile'>L</th><th class='draw-column draw-column-desktop'>Draw</th><th class='draw-column draw-column-mobile'>D</th><th class='bonus-column'>Bonus/Penalty</th><th class='for-column'>For</th><th class='against-column'>Against</th><th class='dif-column'>Differential</th><th class='total-column total-column-desktop'>Total</th><th class='total-column total-column-mobile'>Pts</th></tr>");


            var emptyStandingsTable = true;

            for (var i = 0; i < data.length; i++) {
                var grade = data[i];

                for (var g = 0; g < grade.Sections.length; g++) {

                    var section = grade.Sections[g];

                    var groupingTitle = "<tr class='grade-header'><td colspan='10'>" + grade.Name;
                    if (section.Name != "") {
                        groupingTitle += " (" + section.Name + ")";
                    }
                    groupingTitle += "</td></tr>";

                    $($(compWidget).find('.fe-standings-list table')[0]).append(groupingTitle);
                    emptyStandingsTable = false;
                    for (var s = 0; s < section.Standings.length; s++) {
                        var oddEven = s % 2 == 0 ? 'fixture-row-even' : 'fixture-row-odd';

                        var standing = section.Standings[s];
                        var standingLine = "<tr class='" + oddEven + "'>";
                        standingLine += "<td class='full-name-comp team-column'>" + standing.TeamName + "</td>";
                        standingLine += "<td class='abbr-name-comp team-column'>" + (standing.TeamNameAbbr != null ? standing.TeamNameAbbr : standing.TeamName) + "</td>";
                        standingLine += "<td class='played-column'>" + standing.Played + "</td>";
                        standingLine += "<td class='wins-column'>" + standing.Wins + "</td>";
                        standingLine += "<td class='losses-column'>" + standing.Losses + "</td>";
                        standingLine += "<td class='draw-column'>" + standing.Draws + "</td>";
                        standingLine += "<td class='bonus-column'>" + standing.BonusPoints + "</td>";
                        standingLine += "<td class='for-column'>" + standing.ForPoints + "</td>";
                        standingLine += "<td class='against-column'>" + standing.AgainstPoints + "</td>";
                        standingLine += "<td class='dif-column'>" + standing.Differential + "</td>";
                        standingLine += "<td class='total-column'>" + standing.StandingPoints + "</td>";
                        standingLine += "</tr>";

                        $($(compWidget).find('.fe-standings-list table')[0]).append(standingLine);

                    }
                }
            }

            if (emptyStandingsTable) {

                var standingsDiv = $($(compWidget).find('.fe-standings-list')[0]);
                standingsDiv.html("<div class='no-fixtures'>No standings using the current filters.</div>");

            }

            sifDrawsModule.setUpExportEvent();

        }
    });

}

sifDrawsModule.exportDraw = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);

    var compDropdown = $(compWidget).find('select.fe-comp-comps');
    var phaseDropdown = $(compWidget).find('select.fe-comp-phases');
    var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

    var compId = compDropdown.val();
    var compText = compDropdown.find("option:selected").text();
    var phaseName = phaseDropdown.text();
    var orgIds = orgsDropdown.val().map(Number);
    var gradeIds = gradesDropdown.val().map(Number);
    var gradeNames = null;
    var from = $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().getDate().toLocalISOString();
    var to = $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().getDate().toLocalISOString();

    var published = 2;
    var groupBy = "grade";
    var includeResults = false;
    var includeOfficials = true;
    var status = null;

    window.open("/Competition/ExportFixturesWidget?competitionId=" + compId +
        "&competitionName=" + compText +
        "&from=" + from +
        "&to=" + to +
        "&phaseName=" + phaseName +
        "&gradeIds=" + gradeIds +
        "&gradeNames=" + gradeNames +
        "&published=" + published +
        "&groupBy=" + groupBy +
        "&includeResults=" + includeResults +
        "&includeOfficials=" + includeOfficials +
        "&status=" + status +
        "&orgIds=" + orgIds
        , '_blank');

}

sifDrawsModule.exportResults = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);

    var compDropdown = $(compWidget).find('select.fe-comp-comps');
    var phaseDropdown = $(compWidget).find('select.fe-comp-phases');
    var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

    var compId = compDropdown.val();
    var compText = compDropdown.find("option:selected").text();
    var phaseName = phaseDropdown.text();
    var orgIds = orgsDropdown.val();
    var gradeIds = gradesDropdown.val();
    var gradeNames = null;
    var from = $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().getDate().toLocalISOString();
    var to = $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().getDate().toLocalISOString();

    var published = 2;
    var groupBy = "time";
    var includeResults = true;
    var includeOfficials = true;
    var status = null;

    window.open("/Competition/ExportFixturesWidget?competitionId=" + compId +
        "&competitionName=" + compText +
        "&from=" + from +
        "&to=" + to +
        "&phaseName=" + phaseName +
        "&gradeIds=" + gradeIds +
        "&gradeNames=" + gradeNames +
        "&published=" + published +
        "&groupBy=" + groupBy +
        "&includeResults=" + includeResults +
        "&includeOfficials=" + includeOfficials +
        "&status=" + status +
        "&orgIds=" + orgIds
        , '_blank');

}

sifDrawsModule.exportStandings = function (widgetId) {

    alert(widgetId);

}

sifDrawsModule.clearSavedHidden = function () {
    $("#hdnSelectedCompIds").val("");
    $("#hdnSelectedPhaseIds").val("");
    $("#hdnSelectedOrgIds").val("");
    $("#hdnSelectedGradeIds").val("");
    $("#hdnSelectedTeamIds").val("");
    $("#hdnSelectedDraws").val("");
    $("#hdnSelectedResults").val("");
    $("#hdnSelectedStandings").val("");
}

//admin edit modal create
sifDrawsModule.modalCreated = function (widgetInstanceId) {

    sifDrawsModule.checkDisplayBoxes();

    $.get(sifCompWidgetBaseUrl + 'Sports')
        .done(function (data) {
            for (var index = 0; index < data.length; index++) {
                $('#comp-sports').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
            }

            var selectedSportId = $("#comp-sports").data("sportid") == "" ? 0 : $("#comp-sports").data("sportid");

            $("#comp-sports").val(selectedSportId);

            $.get(sifCompWidgetBaseUrl + 'Seasons')
                .done(function (data) {
                    for (var index = 0; index < data.length; index++) {
                        $('#comp-seasons').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    }

                    var selectedSeasonId = $("#comp-seasons").data("seasonid") == "" ? 0 : $("#comp-seasons").data("seasonid");

                    $("#comp-seasons").val(selectedSeasonId);
                    sifDrawsModule.loadFilters();

                });

        });


    $('#comp-sports').change(function (e) {
        sifDrawsModule.clearSavedHidden();
        sifDrawsModule.loadFilters();

    });


    $('#comp-seasons').change(function (e) {
        sifDrawsModule.clearSavedHidden();
        sifDrawsModule.loadFilters();
    });


};

sifDrawsModule.handlers = {
    init: function () {


    }
}

sifDrawsModule.commitChanges = function (widgetInstanceId) {

    //serialize comp widget settings
    var sportId = sifDrawsModule.getSelectedSportId();
    var seasonId = sifDrawsModule.getSelectedSeasonId();
    var competitionIds = $('#comp-admin-comps').val().join(",");
    var orgIds = $('#comp-admin-orgs').val().join(",");
    var gradeIds = $('#comp-admin-grades').val().join(",");
    //  var teamIds = $('#comp-admin-teams').val().join(",");
    var draws = $("#display-draw").is(":checked");
    var results = $("#display-results").is(":checked");
    var standings = $("#display-standings").is(":checked");

    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'SIFCompetition',
        Settings: {
            SportId: sportId,
            SeasonId: seasonId,
            CompetitionIds: competitionIds,
            OrgIds: orgIds,
            PhaseIds: [],
            GradeIds: gradeIds,
            //  TeamIds: teamIds,
            Draws: draws,
            Results: results,
            Standings: standings
        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202)
                $("#modal-dialog").modal('show');

            sifDrawsModule.rebuildWidget(widgetInstanceId);

        }
    });

    $("#myModal").modal('hide');
};


sifDrawsModule.rebuildWidget = function (widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function (html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            sifDrawsModule.create(widgetInstanceId);
        }
    });
};;
var socialMediaModule = extend(sportsground, 'sportsground.cms.widgets.socialMedia');

socialMediaModule.create = function (widgetInstanceId) {
	socialMediaModule.loadFacebook();
	socialMediaModule.loadGooglePlus();
	socialMediaModule.loadTwitter(widgetInstanceId);
};

socialMediaModule.loadFacebook = function () {
	if (!window.fbLoaded) {
		$.getScript(document.location.protocol + '//connect.facebook.net/en_US/all.js#xfbml=1', function (data, textStatus, jqxhr) {
			socialMediaModule.fbAsyncInit();
			window.fbLoaded = true;
		});
	}
	else {
		FB._initialized = false;
		socialMediaModule.fbAsyncInit();
	}
};

socialMediaModule.fbAsyncInit = function () {
	var appId = $('.fb-appid:first').val();
	FB.init({ appId: appId, status: true, cookie: true, xfbml: true });
};

socialMediaModule.loadGooglePlus = function () {
	(function () {
		var po = document.createElement('script');
		po.type = 'text/javascript';
		po.async = true;
		po.src = 'https://apis.google.com/js/platform.js';
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(po, s);
	})();
}

socialMediaModule.loadTwitter = function (widgetInstanceId) {
	if (!window.twLoaded) {
		$.getScript('https://platform.twitter.com/widgets.js', function (data, textStatus, jqxhr) {
			twttr.widgets.load();
			window.twLoaded = true;
		});
	}
	else {
		twttr.widgets.load();
	}
}

socialMediaModule.modalCreated = function (widgetInstanceId) {
	// for each of the socialmedia sources 
	var widget = $('#widget_' + widgetInstanceId);
	$('.socialMedia:visible', widget).each(function() {
		var type = $(this).data('type');
		$('#chk' + type).prop('checked', true);
	});
};

socialMediaModule.commitChanges = function (widgetInstanceId) {
	// Validate that one option is selected
	var noneSelected = true;
	$(".SocialMediaCheckBoxList").each(function () {
		if (this.checked)
			noneSelected = false;
	});
	if (noneSelected)
		return;
	
	$(".SocialMediaCheckBoxList").each(function () {
		var type = $(this).data('type');
		$('#socialMedia' + type + widgetInstanceId).toggle(this.checked);
	});

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'SocialMedia',
		Settings: {
			HasFacebook: $('#socialMediaFacebook' + widgetInstanceId).is(":visible"),
			HasGooglePlus: $('#socialMediaGooglePlus' + widgetInstanceId).is(":visible"),
			HasTwitter: $('#socialMediaTwitter' + widgetInstanceId).is(":visible")
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function(data, textStatus, xhr) {
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');
			}
		}
	});

	// Hide popup modal
	$("#myModal").modal('hide');
};;
var spliterModule = extend(sportsground, 'sportsground.cms.widgets.splitter');

spliterModule.create = function (widgetInstanceId) {
	//load nested widgets
	$('#widget_' + widgetInstanceId + ' .splitter-column-sortable').each(function () {
		var placeholder = $(this).data('key');
		var splitterId = $(this).closest('.splitter').data('id');
		var container = $(this);
		var editMode = sportsground.utils.getQueryStringParameterByName('em');
		$.getJSON('/cms/widgets/list?id=' + splitterId + '&p=' + placeholder + '&t=Child', function (result) {
            for (var i = 0; i < result.length; i++) {
                sportsground.cms.widgets.createPlaceholder(container, result[i]);
                $.get("/cms/widgets/" + result[i] + '?em=' + editMode, function (html) {                  
					sportsground.cms.widgets.load(container, html);
				});
			}
		});
	});

	var addContentButton = $("#widget_" + widgetInstanceId).find("div.splitter");

	$.each(addContentButton.children(), function (index, column) {
		var button = $(column).find("button.add-content-btn");
		if (button.width() < 140) {
			button.find("span.add-content-span").hide();
		}
	});

	sportsground.cms.sortable.widgetPlaceholdersInit();
};

spliterModule.modalCreated = function (widgetInstanceId) {

    $('#myModal .modal-header').append('<div class="pull-right hideWidgetDiv"><input type="checkbox" id="hideWidget"/><label for="hideWidget" class="hideWidget control-label">Hide on Mobile</label></div>');
    var isHiddenOnMobile = $("#hdnHideOnMobile").val();
    if (isHiddenOnMobile === "True") {
        $("#hideWidget").prop('checked', 'checekd');
    }
    else
        $("#hideWidget").prop('checked', false);

    // select current option
    var splitter = $('#widget_' + widgetInstanceId + ' .splitter');
    var columnOption = splitter.data('key');
    $(".childsplitter-selectable-layout").each(function () {
        if ($(this).data('val') == columnOption)
            $(this).addClass('selected');
    });

    var stackContent = splitter.data('stack-content');
    $('#cbStackContent').prop('checked', stackContent.toBool());
	
	// disable some columns
	var columnContainers = $('#widget_' + widgetInstanceId + ' .splitter-column-sortable');
	var numColumnsUsed = 0;
	$.each(columnContainers, function(index, columnContainer) {
		if ($(columnContainer).find('.widget').length > 0)
			numColumnsUsed++;
	});

	for (var numColumns = 1; numColumns <= 4; numColumns++) {
		if (numColumns >= numColumnsUsed)
			break;
		$(".childsplitter-selectable-layout.col" + numColumns).addClass('disabled');
	}

	// Set selected handler
	$(".childsplitter-selectable-layout:not(.disabled)").click(function () {
		$(".childsplitter-selectable-layout").removeClass('selected');
		$(this).addClass('selected');
		return false;
	});

	// Set selected handler
	$(".childsplitter-selectable-layout:not(.disabled)").on('dblclick', function () {
		$(".childsplitter-selectable-layout").removeClass('selected');
		$(this).addClass('selected');
		$('.widget-settings-update').click();
		return false;
	});

	// Attach help popup to disabled layouts
	$('.childsplitter-selectable-layout.disabled').each(function () {
		$(this).popover({
			trigger: 'hover',
			placement: 'right',
			title: 'Option Unavailable',
			content: "Some column options have been disabled as more columns are actually being used. Please delete or move some widgets into other columns if you wish to use this layout."
		}).on("show.bs.popover", function() {
			$(this).data("bs.popover").tip().css("min-width", "300px");
		});
    });

    $("#rbUseSectionPdding").on('click', function () {
        $(".customPadding").addClass('hidden');
        $(".customWidgetsPadding").removeClass('hidden');
    });

    $("#rbUseSplitterPadding").on('click', function () {
        $(".customWidgetsPadding").addClass('hidden');
        $(".customPadding").removeClass('hidden');
    });

    spliterModule.initBackgroundColorSettings(widgetInstanceId);
};

spliterModule.commitChanges = function (widgetInstanceId) {
    var newColumnOption = $('.childsplitter-selectable-layout.selected').data('val');

    var transparency = $('#splitterTransparencySliderInput').val().replace('%', '');
    transparency = parseInt(transparency) / 100;

	var relocateSettings = {
        columnOption: newColumnOption,
        BackgroundColor: $('#splitterBackgroundColor').val(),
        BackgroundTransparency: transparency
    };

    var padding = $("#txtSplitterPadding").val();
    if ( padding === "" || padding === undefined )
        padding = 0;

    var widgetPadding = $("#txtWidgetsPadding").val();
    if (widgetPadding === "" || widgetPadding === undefined)
        widgetPadding = 0;

	$.ajax({
		url: '/cms/childsplitter/' + widgetInstanceId,
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(relocateSettings),
		success: function (data, textStatus, xhr) {
			// Update the widget settings if we successfully relocated widgets
			var widgetSettings = {
				WidgetId: widgetInstanceId,
				WidgetType: 'Splitter',
				Settings: {
                    ColumnOption: newColumnOption,
                    InlineContentOnMobileView: !$('#cbStackContent').is(':checked'),
                    BackgroundColor: $('#splitterBackgroundColor').val(),
                    BackgroundTransparency: transparency,
                    Padding: padding,
                    ApplyShadow: $("#rbApplyShadow").is(':checked'),
                    UseSplitterPadding: $("#rbUseSplitterPadding").is(':checked'),
                    WidgetsPadding: widgetPadding,
                    HideOnMobile: $("#hideWidget").is(':checked')
				}
			};
			$.ajax({
				url: '/cms/widgets/settings',
				type: 'PUT',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(widgetSettings),
				success: function (data, textStatus, xhr) {
					$("#myModal").modal('hide');
					sportsground.cms.widgets.splitter.rebuildSplitter(widgetInstanceId);
				}
			});
		}
	});
};

spliterModule.rebuildSplitter = function (widgetInstanceId) {
	$.ajax({
		url: '/cms/widgets/' + widgetInstanceId + '?em=1',
		type: 'GET',
		success: function (html, textStatus, xhr) {
			var splitterContainer = $('#widget_' + widgetInstanceId);
			splitterContainer.replaceWith(html);
            spliterModule.create(widgetInstanceId);
		}
	});
};

spliterModule.initBackgroundColorSettings = function (widgetInstanceId) {
    var splitter = $("#childSplitter_" + widgetInstanceId);

    var backgroundColor = splitter.data('bgcolor');
    var transparency = splitter.data('transparency');

    if (backgroundColor == undefined)
        backgroundColor = "";

    if (transparency == undefined || transparency == null) 
        transparency = 0;

    $('#splitterBackgroundColor').val(backgroundColor);
    $('#splitterBackgroundColor').simplecolorpicker({ trigger: 'splitterBackgroundColorTrigger', selectedColor: backgroundColor });

    if (backgroundColor == null || backgroundColor == '') {
        $('span.simplecolorpicker.input-group-addon').text('No colour selected');
    }

    $('#splitterTransparencySlider').slider({
        isRTL: true,
        range: 'false',
        value: -transparency,
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $('#splitterTransparencySliderInput').val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });

    $('#splitterTransparencySliderInput').val(Math.abs(Math.round(transparency * 100)) + '%');

    $('.color').on('click', function () {
        $('span.simplecolorpicker.input-group-addon').text('');
    });
};;
var sponsorsModule = extend(sportsground, 'sportsground.cms.widgets.sponsors');

sponsorsModule.create = function(widgetInstanceId) {
	// Load in sponsors from CSV list of ID's
	var organisationId = $("#OrganisationId").val();
	var url = "/cms/site/" + organisationId + "/sponsors";
	$.ajax({
		url: url,
		contentType: 'application/json; charset=utf-8',
		success: function (data, textStatus, xhr) {
			var selectedSponsorIds = $("#hdnSponsorIds-" + widgetInstanceId).val().split(",");

			$("#sponsors-list-widget-" + widgetInstanceId).html("");
			$.each(data, function (key) {
				// A list of organisation sponsors is data
				var found = $.inArray(data[key].Id.toString(), selectedSponsorIds) > -1;

				if (found) {
					var template = Handlebars.compile($("#hbtSponsor-" + widgetInstanceId).html());
					var html = template(data[key]);

					$("#sponsors-list-widget-" + widgetInstanceId).append(html);
				}
			});
		}
	});
}

sponsorsModule.modalCreated = function (widgetInstanceId) {
	// post ID's and receive markup back to use
	var organisationId = $("#OrganisationId").val();
	var url = "/cms/site/" + organisationId + "/sponsors";
	$.ajax({
		url: url,
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			$("#sponsors-widget-list-group").html("");

			// foreach sponsor render hb template with checkbox
			var template = Handlebars.compile($("#hbtSponsor").html());
			$.each(data, function(key) {
				$("#sponsors-widget-list-group").append(template(data[key]));
			});

			var sponsorsArray = $("#hdnSponsorIds").val().split(",");
			if (sponsorsArray != null) {
				$.each(sponsorsArray, function(key, value) {
					$("#chkSponsor-" + value).attr("checked", "checked");
				});
			}
		}
	});
}

sponsorsModule.commitChanges = function (widgetInstanceId) {
	var sponsorIds = [];
	$("[name='sponsor-widget']:checked").each(function () {
		sponsorIds.push($(this).val());
	});

	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'Sponsors',
		Settings: {
			SponsorIds: JSON.stringify(sponsorIds)
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');			
			}
			$("#hdnSponsorIds-" + widgetInstanceId).val(sponsorIds.join(","));

			sportsground.cms.widgets.sponsors.create(widgetInstanceId);
		}
	});

	$("#myModal").modal('hide');
};
var sponsorsSlideshowModule = extend(sportsground, 'sportsground.cms.widgets.sponsorsSlideshow');


sponsorsSlideshowModule.convertImageSrc = function (src, outputType, imageWidth, withUnderscore) {
    // strip all and any suffix's
    src = src.replace('_wo', '').replace('_t', '').replace('_ht', '').replace('####', '');

    // strip the query
    var pos = src.lastIndexOf('?');
    if (pos > -1) {
        src = src.substring(0, pos);
    }

    // get the extension
    var lastIndexOfDot = src.lastIndexOf('.');
    var extension = src.substring(lastIndexOfDot + 1);

    var suffix = '';
    if (outputType === 'THUMB') {
        suffix = '_t';
    }
    else if (outputType === 'WEBOPTIMIZED') {
        if (imageWidth > 0) {

            if (withUnderscore) {
                suffix = "_" + imageWidth;
            }
            else {
                suffix = imageWidth;
            }
        }
        else {
            suffix = '_wo';
        }
    }
    else if (outputType === 'HEADERTHUMB') {
        suffix = '_ht';
    }

    return src.substring(0, lastIndexOfDot) + suffix + '.' + extension;
};

sponsorsSlideshowModule.create = function (widgetInstanceId) {
	var widget = $('#widget_' + widgetInstanceId);
	var slippryContainer = widget.find('.sy-box');
	slippryContainer.html('');

	var sponsors = [];
    var sponsorsJson = $('#hdnSponsors_' + widgetInstanceId).val();
    if (sponsorsJson != null && sponsorsJson != "")
		sponsors = $.parseJSON(sponsorsJson);

	sponsorsSlideshowModule.layout = $('#hdnLayout_' + widgetInstanceId).val();
	if (sponsorsSlideshowModule.layout === '')
	    sponsorsSlideshowModule.layout = 'portrait';

	sponsorsSlideshowModule.crop = $('#hdnCrop_' + widgetInstanceId).val();
	if (sponsorsSlideshowModule.crop === '')
		sponsorsSlideshowModule.crop = 'False';

	sponsorsSlideshowModule.scale = $('#hdnScale_' + widgetInstanceId).val();
	if (sponsorsSlideshowModule.scale === '')
	    sponsorsSlideshowModule.scale = 'False';

	sponsorsSlideshowModule.randomize = $('#hdnRandomize_' + widgetInstanceId).val();
	if (sponsorsSlideshowModule.randomize === '')
		sponsorsSlideshowModule.randomize = 'False';

	if (sponsorsSlideshowModule.randomize === 'True')
		shuffle(sponsors);

	var width = slippryContainer.outerWidth();

	var imageWidth = 1122;
	if (width <= 539) {
	    imageWidth = 539;
	}
	if (width <= 248) {
	    imageWidth = 248;
	}
    
	var height;
	switch (sponsorsSlideshowModule.layout) {
	    case 'panorama':
	        height = Math.round(0.35 * width);
	        break;
	    case 'landscape':
	        height = Math.round(0.71 * width);
	        break;
	    case 'portrait':
	        height = Math.round(1.4 * width);
	        break;
	    case 'square':
	    default:
	        height = width;
	        break;
    }

    var maxAllowedImages = sponsors.length > 20 ? 20 : sponsors.length;
    for (var i = 0; i < maxAllowedImages; i++) {
		var html = '<li>';
		if (sponsors[i].linkType !== 'none') {
			html += '<a href="';
			if (sponsors[i].linkType === 'url') {
				html += sponsors[i].linkData + '" ';
				if (sponsors[i].linkNewTab)
					html += 'target="_blank" ';
				html += '>';
			}
			else if (sponsors[i].linkType === 'page') {
				$.ajax({
					url: '/cms/page/' + sponsors[i].linkData + '/geturl',
					async: false,
					type: 'GET',
					contentType: 'application/json; charset=utf-8',
					success: function(data) {
						html += data + '">';
					}
				});
			}
			else if (sponsors[i].linkType === 'document') {
				html += '/asset/downloadasset?id=' + sponsors[i].linkData + '">';
			}
			else if (sponsors[i].linkType === 'onlineForm') {
			    html += '/viewform/' + sponsors[i].linkData + '">';
			}
			else if (sponsors[i].linkType === 'email') {
				html += 'mailto:' + sponsors[i].linkData + '">';
			}
		}

		var fullImageUrl = sponsors[i].src.replace('_t', '');
		var woSizedSrc = sponsorsSlideshowModule.convertImageSrc(fullImageUrl, 'WEBOPTIMIZED', imageWidth, true);

        html += '<img id="sponsorSlideImg_' + sponsors[i].id + '" title="' + sponsors[i].caption + '" src="' + woSizedSrc + '" alt="sportsground">';
		if (sponsors[i].linkType !== 'none') {
			html += '</a>';
		}
		html += '</li>';
		slippryContainer.append(html);
		//slippryContainer.append('<li><img title="' + sponsors[i].caption + '" src="/asset/getscaledsponsor?sponsorid=' + sponsors[i].id + '&width=' + width + '&height=' + height + '&crop=' + sponsorsSlideshowModule.crop + '" alt="sportsground"></li>');
	}

	slippryContainer.slippry({
		// options
		adaptiveHeight: false, // height of the sliders adapts to current slide
		captions: 'overlay', // Position: overlay, below, custom, false

		responsive: false, // setting this to false stops the overlay going over elements below, preventing button clicks

		// pager
		pager: false,

		// controls
		controls: false,
		autoHover: false,

		// transitions
		transition: 'fade', // fade, horizontal, kenburns, false
		speed: 2000, // time the transition takes (ms)
        onSlideBefore: function (slide, old_index, new_index) {            

            var slideShowId = $( slide ).closest( '.wSponsorsSlideshow' ).data( 'id' );
            var slideShowItem = {
                "layout": $( '#hdnLayout_' + slideShowId ).val(),
                "crop": $( '#hdnCrop_' + slideShowId ).val(),
                "scale": $( '#hdnScale_' + slideShowId ).val()
            };

            var slideShowHeight;
            switch ( slideShowItem.layout ) {
                case 'panorama':
                    slideShowHeight = Math.round( 0.35 * width );
                    break;
                case 'landscape':
                    slideShowHeight = Math.round( 0.71 * width );
                    break;
                case 'portrait':
                    slideShowHeight = Math.round( 1.4 * width );
                    break;
                case 'square':
                default:
                    slideShowHeight = width;
                    break;
            }

		    var sponsor = slide.find('img');

		    // calculate aspect ratios
            var sliderAspect = width / slideShowHeight;
		    var imageAspect = sponsor.width() / sponsor.height();
            
            if (slideShowItem.crop && slideShowItem.crop && slideShowItem.crop.toLowerCase() === 'true') {
				
                if (sliderAspect > imageAspect) {
                    // crop vertically
                    sponsor.css('width', width);
                    var margin = (slideShowHeight - sponsor.height()) / 2;
                    sponsor.css('margin-top', margin);
                }
                else {
	                // crop horizontally
	                sponsor.css('height', slideShowHeight);
	                var margin = (width - sponsor.width()) / 2;
	                sponsor.css('margin-left', margin);
                }

            }
            else if ((slideShowItem.scale && slideShowItem.scale && slideShowItem.scale.toLowerCase() === 'true') || maxAllowedImages == 1)//scale
            {
                var spheight = sponsor.height();
                var orgheight = sponsor.height();
                var spwidth = sponsor.width();
                var orgwidth = sponsor.width();
                var attrheight = slide.find('img').attr('height');
                var attrwidth = slide.find('img').attr('width');
                if ((attrheight != undefined) && (attrwidth != undefined)) {
                    var spheight = attrheight;
                    var orgheight = attrheight;
                    var spwidth = attrwidth;
                    var orgwidth = attrwidth;
                }
                
                var ratio = 0;
                sponsor.css('height', '100%');
                sponsor.css('width', 'auto'); // IE does not support initial, so auto will be applied to width
                sponsor.css('width', 'initial'); // Chrome, Edge, FireFox will replace auto to initial
                sponsor.css('margin', 'auto');

                var sponsorAnchor = slide.find('a');
                sponsorAnchor.css('height', '100%');

                slide.css('height', '100%');


                if ((spwidth > width) || (spwidth < width)) {
                    slide.css('display', 'table');
                    sponsorAnchor.css('display', 'table-cell');
                    sponsorAnchor.css('vertical-align', 'middle');

                    ratio = width / spwidth;
                    spwidth = spwidth * ratio;
                    spheight = spheight * ratio;

                    if (spheight > slideShowHeight) {
                        ratio = slideShowHeight / spheight;
                        spwidth = spwidth * ratio;
                        spheight = spheight * ratio;
                    }

                    sponsor.css('width', spwidth);
                    sponsor.css('height', spheight);
                    sponsor.css('height', spheight);
                }
                else if (spheight > slideShowHeight) {
                    slide.css('display', 'table');
                    sponsorAnchor.css('display', 'table-cell');
                    sponsorAnchor.css('vertical-align', 'middle');

                    ratio = slideShowHeight / spheight;

                    spwidth = spwidth * ratio;
                    spheight = spheight * ratio;

                    sponsor.css('width', spwidth);
                    sponsor.css('height', spheight);
                    sponsor.css('height', spheight);
                }
                //vertically center
                else if (sponsor.width() > sponsor.height()) {
                    slide.css('display', 'table');
                    sponsorAnchor.css('display', 'table-cell');
                    sponsorAnchor.css('vertical-align', 'middle');

                    ratio = sponsor.height() / sponsor.width(); 
                    spwidth = spwidth * ratio;    
                    spheight = height * ratio;        

                    sponsor.css('width', '100%');
                    sponsor.css('height', 'auto'); // IE does not support initial, so auto will be applied to height
                    sponsor.css('height', 'initial'); // Chrome, Edge, FireFox will replace auto to initial
                }
                slide.find('img').attr('width', orgwidth);
                slide.find('img').attr('height', orgheight);
            }
			else
            {
                 if (sliderAspect > imageAspect) {
                     // scroll vertically
                     sponsor.css('width', width);
                     var margin = slideShowHeight - sponsor.height();
                     // only scroll if there's enough to scroll, otherwise crop
                     if (margin < -slideShowHeight / 10) {
                         $(sponsor[0]).css({ 'margin-top': '0px' });
                         sponsor.animate({ 'margin-top': margin + 'px' }, 2000);
                     }
                     else {
                         $(sponsor[0]).css({ 'margin-top': '0px' });
                         sponsor.animate({ 'margin-top': margin / 2 + 'px' }, 2000);
                     }
                 }
                 else {
                     // scroll horizontally
                     sponsor.css('height', slideShowHeight);
                     var margin = width - sponsor.width();
                     // only scroll if there's enough to scroll, otherwise crop
                     if (margin < -width / 10) {
                         $(sponsor[0]).css({ 'margin-left': '0px' });
                         sponsor.animate({ 'margin-left': margin + 'px' }, 2000);
                     }
                     else {
                         $(sponsor[0]).css({ 'margin-left': '0px' });
                         sponsor.animate({ 'margin-left': margin / 2 + 'px' }, 2000);
                     }

                 }
			}
			
		}
	});
    widget.find('.sy-box').css('height', height + 'px');
    widget.find('.sy-box').data('height', height + 'px');
};

sponsorsSlideshowModule.modalCreated = function (widgetInstanceId) {
	// ----- Load selected sponsors
	sponsorsSlideshowModule.sponsors = [];
	var sponsorJson = $('#hdnSponsors_' + widgetInstanceId).val();
	if (sponsorJson.length > 0) {
		sponsorsSlideshowModule.sponsors = $.parseJSON(sponsorJson);
		sponsorsSlideshowModule.loadSelectedSponsors();
    }

    $('#lblExceededMaxImages').hide();
    $('#widget-edit-modal-SponsorsSlideshow').find('.widget-settings-update').removeAttr("disabled");
    if (sponsorsSlideshowModule.sponsors.length > 20) {
        $('#lblExceededMaxImages').show();
        $('#widget-edit-modal-SponsorsSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
    }

	$('#btnChooseSponsors').on('click', function () {
		$('#tabsponsors_sponsorReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function() {
			$('#tabsponsors_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
		});
        
		// ----- Load entire list of sponsors to choose from
		sponsorsSlideshowModule.loadAllSponsors();

		if ($('#btnDoneSelectingsponsors').length === 0) {
			$('.widget-settings-update').after('<button id="btnDoneSelectingsponsors" class="btn btn-primary">Done Selecting Sponsors</button>');
			$('#btnDoneSelectingsponsors').on('click', function() {
				$('#tabsponsors_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function() {
					$('#tabsponsors_sponsorReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
				});
				$('#btnDoneSelectingsponsors').hide();
				$('#btnUploadMoreSponsors').hide();
				$('.widget-settings-cancel-update').show();
				$('.widget-settings-update').show();
                
                $('[name="chkSlideshowSponsor"]').each(function () {
                    var caption = null;
                    for (var index = 0; index < sponsorsSlideshowModule.sponsors.length; index++) {
                        if (sponsorsSlideshowModule.sponsors[index].id === $(this).val()) {
                            caption = sponsorsSlideshowModule.sponsors[index].caption;
                            sponsorsSlideshowModule.sponsors.splice(index, 1);
                            break;
                        }
                    }
					if (this.checked) {
                        var sponsorId = $(this).val();
						sponsorsSlideshowModule.sponsors.push({
                            id: sponsorId,
                            name: $('#hdnSponsorName-' + sponsorId).val(),
                            caption: caption ? caption : $('#hdnSponsorCaption-' + sponsorId).val(),
							linkType: 'url',
							src: $('#imgSponsorSelect-' + sponsorId).attr('src'),
							linkData: $('#hdnSponsorUrl-' + sponsorId).val(),
							linkNewTab: true
						});
					}
				});

                sponsorsSlideshowModule.loadSelectedSponsors();

                if (sponsorsSlideshowModule.sponsors.length > 20) {
                    $('#lblExceededMaxImages').show();
                    $('#widget-edit-modal-SponsorsSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
                }
                else {
                    $('#lblExceededMaxImages').hide();
                    $('#widget-edit-modal-SponsorsSlideshow').find('.widget-settings-update').removeAttr("disabled");
                }
			});

            if ($("#isWebmaster").val() == "True") {
                $('.widget-settings-update').after('<button id="btnUploadMoreSponsors" class="btn btn-default">Manage Sponsors</button>');
                $('#btnUploadMoreSponsors').on('click', function() {
                    $('#myModal').one('hidden.bs.modal', function () {
                        $('#myModal').one('hidden.bs.modal', function () {
                            $('#widget_' + widgetInstanceId + ' .widget-settings-edit').click();
                        });
                        $('#btnSponsorsManager').click();
                    });
                    $('#myModal').modal('hide');
                });
            }
		}
		else {
			$('#btnDoneSelectingsponsors').show();
			$('#btnUploadMoreSponsors').show();
		}

		$('.widget-settings-cancel-update').hide();
		$('.widget-settings-update').hide();
		return false;
	});


	$('input[type="radio"][name="rbLayout"]').on('change', function () {
		sponsorsSlideshowModule.layout = $(this).val();
	});

	$('input[type="radio"][name="rbDisplay"]').on('change', function () {

	    if ($(this).prop("id") == "rbDisplayScroll") {
	        sponsorsSlideshowModule.scroll = $(this).val();
	        sponsorsSlideshowModule.crop = 'False';
	        sponsorsSlideshowModule.scale = 'False';
	    }

	    if ($(this).prop("id") == "rbDisplayCrop") {
	        sponsorsSlideshowModule.crop = $(this).val();
	        sponsorsSlideshowModule.scroll = 'False';
	        sponsorsSlideshowModule.scale = 'False';
	    }

	    if ($(this).prop("id") == "rbDisplayScale") {
	        sponsorsSlideshowModule.scale = $(this).val();
	        sponsorsSlideshowModule.scroll = 'False';
	        sponsorsSlideshowModule.crop = 'False';
	    }
	});

	sponsorsSlideshowModule.layout = $('#hdnLayout').val();
	if (sponsorsSlideshowModule.layout === '')
		sponsorsSlideshowModule.layout = 'portrait';
	$('input[type="radio"][value="' + sponsorsSlideshowModule.layout + '"]').prop('checked', true);

	sponsorsSlideshowModule.crop = $('#hdnCrop').val();
	sponsorsSlideshowModule.scale = $('#hdnScale').val();

	if (sponsorsSlideshowModule.crop === '')
	    sponsorsSlideshowModule.crop = 'False';

	if (sponsorsSlideshowModule.scale === '')
	    sponsorsSlideshowModule.scale = 'False';

    if ( sponsorsSlideshowModule.sponsors.length > 0 ) {
        if (sponsorsSlideshowModule.crop === 'True')
            $('#rbDisplayCrop').prop('checked', true);
        else if (sponsorsSlideshowModule.scale === 'True')
            $('#rbDisplayScale').prop('checked', true);
        else
            $('#rbDisplayScroll').prop('checked', true);
    } else {
        // when there is no sponsor, default is scale
        $('#rbDisplayScale').attr('checked', true);
        sponsorsSlideshowModule.scale = 'True';
    }

	if ($('#hdnRandomize').val() === 'True') {
		$('#cbDisplayRandom').prop('checked', true);
		sponsorsSlideshowModule.randomize = 'True';
	}

	$('#tasponsorCaption').on('blur', function () {
		sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].caption = $(this).val();
	});

	$('#sponsorSettings_Prev').on('click', function () {
		sponsorsSlideshowModule.currentsponsorIndex--;
		if (sponsorsSlideshowModule.currentsponsorIndex < 0)
			sponsorsSlideshowModule.currentsponsorIndex = sponsorsSlideshowModule.sponsors.length - 1;

		var sponsor = sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex];
		$('#imgPreview').attr('src', sponsor.src);

		$('#tasponsorCaption').val(sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].caption);
		sponsorsSlideshowModule.setLinkHtmlValuesFromJson();
		return false;
	});

	$('#sponsorSettings_Next').on('click', function () {
		sponsorsSlideshowModule.currentsponsorIndex++;
		if (sponsorsSlideshowModule.currentsponsorIndex >= sponsorsSlideshowModule.sponsors.length)
			sponsorsSlideshowModule.currentsponsorIndex = 0;

		var sponsor = sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex];
		$('#imgPreview').attr('src', sponsor.src);

		$('#tasponsorCaption').val(sponsor.caption);
		sponsorsSlideshowModule.setLinkHtmlValuesFromJson();
		return false;
	});

	$('#btnsponsorSettingsBack').on('click', function () {
		$('#tabsponsors_sponsorSettings').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$('#tabsponsors_sponsorReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
		});
		return false;
	});


	$('#tabsponsors_gallerySelect').on('click', '.chkSlideshowSponsor', function (event) {
		event.stopPropagation();
	});
	$('#tabsponsors_gallerySelect').on('click', '.sponsorThumbnailContainer', function() {
		var cb = $(this).find('.chkSlideshowSponsor');

		if (cb.is(':checked')) {
			cb.prop('checked', false);
		} else {
			cb.prop('checked', true);
		}

		return false;
	});

	$('input[type="radio"][name="rbLinkType"]').on('change', function() {
		$('.link-settings').hide();
		$('#linkSettings_' + $(this).val()).show();
		sponsorsSlideshowModule.setLinkJsonValuesFromHtml();

		// TODO: Set the value of linkData based on selection
		//sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = '';
	});

    $('#tbLinkUrlLocation').on('blur', function() {
        sportsground.ui.attachHandlerPrependHttpOnWwwLinks(this);
        sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = url;
    });


	sportsground.cms.common.bindRemoveEditModeOnPaste();

	$('#tbLinkEmail').on('blur', function () {
		sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $(this).val();
	});

	$('#slLinkPageOptions').on('change', function() {
		sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $(this).val();
	});

	$('#slLinkDocumentOptions').on('change', function () {
		sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $(this).val();
	});

	$('#slLinkFormOptions').on('change', function () {
	    sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $(this).val();
	});

	$('#cbLinkUrlNewTab').on('change', function() {
		sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkNewTab = $(this).is(':checked');
	});

	$.ajax({
        url: '/cms/site/' + $('#SiteId').val() + '/getsitepages?showHiddenPages=false',
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
		success: function(data) {
			for (var indexRoot = 0; indexRoot < data.length; indexRoot++) {
				if (data[indexRoot].Type == 'section') {
					var html = '<optgroup label="' + data[indexRoot].Title + '">';
					for (var indexSub = 0; indexSub < data[indexRoot].Children.length; indexSub++) {
						html += '<option value="' + data[indexRoot].Children[indexSub].Id + '">' + data[indexRoot].Children[indexSub].Title + '</option>';
					}
					html += '</optgroup>';
					$('#slLinkPageOptions').append(html);
				}
				else {
					$('#slLinkPageOptions').append('<option value="' + data[indexRoot].Id + '">' + data[indexRoot].Title + '</option>');
				}
			}
		}
	});
};

sponsorsSlideshowModule.setLinkHtmlValuesFromJson = function () {
	$('.link-settings').hide();
	$('#linkSettings_' + sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkType).show();

	var currentsponsor = sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex];
	$('input[type="radio"][value="' + currentsponsor.linkType + '"]').prop('checked', true);
	$('#tbLinkUrlLocation').val('');
	$('#cbLinkUrlNewTab').prop('checked', false);
	$('#tbLinkEmail').val('');
	$('#slLinkPageOptions')[0].selectedIndex = 0;
	$('#slLinkDocumentOptions')[0].selectedIndex = 0;
	$('#slLinkFormOptions')[0].selectedIndex = 0;

	switch (currentsponsor.linkType) {
		case 'url':
			$('#tbLinkUrlLocation').val(sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData);
			$('#cbLinkUrlNewTab').prop('checked', currentsponsor.linkNewTab === true);
			break;
		case 'page':
			$('#slLinkPageOptions').val(sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData);
			break;
		case 'document':
			$('#slLinkDocumentOptions').val(sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData);
			break;
	    case 'onlineForm':
	        $('#slLinkFormOptions').val(sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData);
	        break;
		case 'email':
			$('#tbLinkEmail').val(sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData);
			break;
		default:
	}
};

sponsorsSlideshowModule.setLinkJsonValuesFromHtml = function() {
	sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkType = $('input[name=rbLinkType]:checked').val();
	switch (sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkType) {
		case 'url':
			sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $('#tbLinkUrlLocation').val();
			sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkNewTab = $('#cbLinkUrlNewTab').prop('checked');
			break;
		case 'page':
			sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $('#slLinkPageOptions').val();
			break;
		case 'document':
			sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $('#slLinkDocumentOptions').val();
			break;
	    case 'onlineForm':
	        sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $('#slLinkFormOptions').val();
	        break;
		case 'email':
			sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].linkData = $('#tbLinkEmail').val();
			break;
		default:
	}
};

sponsorsSlideshowModule.commitChanges = function (widgetInstanceId) {
	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'SponsorsSlideshow',
		Settings: {
			SponsorsJson: JSON.stringify(sponsorsSlideshowModule.sponsors),
			Layout: sponsorsSlideshowModule.layout,
			Crop: sponsorsSlideshowModule.crop,
			Scale: sponsorsSlideshowModule.scale,
			Randomize: $('#cbDisplayRandom').is(':checked')
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202) {
				$('#modal-dialog').modal('show');
			}
		}
	});

	$('#myModal').modal('hide');

	$('#hdnSponsors_' + widgetInstanceId).val(JSON.stringify(sponsorsSlideshowModule.sponsors));
	$('#hdnLayout_' + widgetInstanceId).val(sponsorsSlideshowModule.layout);
	$('#hdnCrop_' + widgetInstanceId).val(sponsorsSlideshowModule.crop);
	$('#hdnScale_' + widgetInstanceId).val(sponsorsSlideshowModule.scale);
	sponsorsSlideshowModule.create(widgetInstanceId);
};

sponsorsSlideshowModule.loadSelectedSponsors = function () {
	$('.selected-sponsor-thumb').remove();

	var rawHtml = $('#hbtSelectedThumb').html();
	var template = Handlebars.compile(rawHtml);
	if (sponsorsSlideshowModule.sponsors.length > 0) {
		$.each(sponsorsSlideshowModule.sponsors, function (index) {
			//var indexOfExtension = sponsorsSlideshowModule.sponsors[index].src.lastIndexOf('.');
			//sponsorsSlideshowModule.sponsors[index].src = sponsorsSlideshowModule.sponsors[index].src.substr(0, indexOfExtension) + '_t.' + sponsorsSlideshowModule.sponsors[index].src.substr(indexOfExtension + 1);

            sponsorsSlideshowModule.sponsors[index].tn = sportsground.utils.convertImageSrc(sponsorsSlideshowModule.sponsors[index].src, 'THUMB');
            sponsorsSlideshowModule.sponsors[index].tn = sponsorsSlideshowModule.sponsors[index].tn + "?ts"+ new Date().getTime();
		    $('#selectedsponsorsContainer').append(template(sponsorsSlideshowModule.sponsors[index]));
		});
	}


	$('#selectedsponsorsContainer').sortable({
		cancel: 'input',
		cursor: 'move',
		items: '> .selected-sponsor-thumb',
		handle: '.draghandle',
		update: function () {
			var sortedIds = $('#selectedsponsorsContainer').sortable('toArray');
			var sortedsponsors = [];
			for (var si = 0; si < sortedIds.length; si++) {
				for (var ui = 0; ui < sponsorsSlideshowModule.sponsors.length; ui++) {
					if (sortedIds[si] === sponsorsSlideshowModule.sponsors[ui].id) {
						sortedsponsors[si] = sponsorsSlideshowModule.sponsors[ui];
						break;
					}
				}
			}
			sponsorsSlideshowModule.sponsors = sortedsponsors;
		}
	});

	$('.selected-sponsor-settings').on('click', function () {
		var sponsorId = $(this).closest('.selected-sponsor-thumb').attr('id');

		for (var index = 0; index < sponsorsSlideshowModule.sponsors.length; index++) {
			if (sponsorsSlideshowModule.sponsors[index].id === sponsorId) {
				sponsorsSlideshowModule.currentsponsorIndex = index;

				$('#imgPreview').attr('src', sponsorsSlideshowModule.sponsors[index].src);
				break;
			}
		}

		$('#tasponsorCaption').val(sponsorsSlideshowModule.sponsors[sponsorsSlideshowModule.currentsponsorIndex].caption);

		sponsorsSlideshowModule.setLinkHtmlValuesFromJson();

		$('#tabsponsors_sponsorReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$('#tabsponsors_sponsorSettings').effect('slide', { direction: 'right', mode: 'show' }, 500);
		});
	});

	$('.selected-sponsor-delete').on('click', function () {
		var sponsorId = $(this).closest('.selected-sponsor-thumb').attr('id');
		bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected sponsor from the slider?</p>', function (result) {
			if (!result)
				return;

			$('#' + sponsorId).remove();
			for (var index = 0; index < sponsorsSlideshowModule.sponsors.length; index++) {
				if (sponsorsSlideshowModule.sponsors[index].id === sponsorId) {
					sponsorsSlideshowModule.sponsors.splice(index, 1);
					break;
				}
            }

            if (sponsorsSlideshowModule.sponsors.length > 20) {
                $('#lblExceededMaxImages').show();
                $('#widget-edit-modal-SponsorsSlideshow').find('.widget-settings-update').attr("disabled", "disabled");
            }
            else {
                $('#lblExceededMaxImages').hide();
                $('#widget-edit-modal-SponsorsSlideshow').find('.widget-settings-update').removeAttr("disabled");
            }

		});
		return false;
	});

};

sponsorsSlideshowModule.loadAllSponsors = function() {
	// post ID's and receive markup back to use
	var organisationId = $('#OrganisationId').val();
	var url = '/cms/site/' + organisationId + '/sponsors';
	$.ajax({
		url: url,
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			var selectSponsorsContainer = $('#cntSponsors');
			selectSponsorsContainer.html('');

			// foreach sponsor render hb template with checkbox
			var template = Handlebars.compile($('#hbtSponsor').html());
			$.each(data, function (key) {

			    data[key].tn = sportsground.utils.convertImageSrc(data[key].ImageUrl, 'THUMB');
			    selectSponsorsContainer.append(template(data[key]));

			});

			// Loop through current sponsors to check those sponsors which have already been added
			$.each(sponsorsSlideshowModule.sponsors, function (key, value) {

			    $('#chkSponsor-' + sponsorsSlideshowModule.sponsors[key].id).attr('checked', 'checked');

			});
		}
	});
};;
var stackerModule = extend(sportsground, 'sportsground.cms.widgets.stacker');

stackerModule.create = function(widgetInstanceId) {
	var widget = $('#widget_' + widgetInstanceId);
	var container = widget.find(".stacker-content");
	$.ajax({
		url: '/cms/site/' + $('#SiteId').val() + '/getstackercontent',
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
		cache: false,
		success: function (data) {
			if (data.length == 0) {
				widget.find('.stacker-no-content').show();
				return;
			}

			var template = Handlebars.compile(widget.find('.hbt-stacker-item').html());
			for (var i = 0; i < data.length; i++) {
				data[i].linkNewTab = (data[i].linkNewTab == "true");
				container.append(template(data[i]));
			}
		}
	});

	// HACK WARNING! this is to overwrite the default edit stacker widget settings and open global stacker modal instead.. Ew
	widget.on("click.trigger-stacker-settings", '.widget-settings-edit', function () {
		$("#btnChangeStackerContent").trigger("click");
		return false;
	});
};

stackerModule.modalCreated = function (widgetInstanceId) {
	
};;
var subscribeModule = extend(sportsground, 'sportsground.cms.widgets.subscribe');

subscribeModule.create = function (widgetInstanceId) {

    $("#btnSubscribeInput_" + widgetInstanceId).on('click', function () {
        var email = $("#txtSubscribeInput_" + widgetInstanceId).val();
        $("#spanSubscribeAlert_" + widgetInstanceId).html('');

        if (!sportsground.utils.validateEmailAddress(email)) {
            $("#spanSubscribeAlert_" + widgetInstanceId).html('Please enter a valid email address.');
            $("#spanSubscribeAlert_" + widgetInstanceId).removeClass('hidden');
            return false;
        }
        else {
            $("#spanSubscribeAlert_" + widgetInstanceId).html('');
            $("#spanSubscribeAlert_" + widgetInstanceId).addClass('hidden');
        }

        var model = {
            email: email
        };
        $.ajax({
            url: '/cms/site/' + $('#SiteId').val() + '/notices/optin',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data) {
                $("#txtSubscribeInput_" + widgetInstanceId).val('');
                $("#spanSubscribeAlert_" + widgetInstanceId).html('You have successfully subscribed.');
                $("#spanSubscribeAlert_" + widgetInstanceId).removeClass('hidden');
                setTimeout(function () {
                    $("#spanSubscribeAlert_" + widgetInstanceId).html('');
                    $("#spanSubscribeAlert_" + widgetInstanceId).addClass('hidden');
                }, 5000);
            }
        });
        return false;
    });

};

subscribeModule.modalCreated = function (widgetInstanceId) {

    $('#myModal .modal-header').append('<div class="pull-right hideWidgetDiv"><input type="checkbox" id="hideWidget"/><label for="hideWidget" class="hideWidget control-label">Hide on Mobile</label></div>');
    var isHiddenOnMobile = $("#hdnHideOnMobile").val();
    if ( sportsground.cms.utils.isTrue(isHiddenOnMobile) ) {
        $("#hideWidget").prop('checked', 'checekd');
    }
    else
        $("#hideWidget").prop('checked', false);

    subscribeModule.InitTransparencies();
    subscribeModule.InitFonts();
    subscribeModule.InitColors();
    subscribeModule.InitBorders(widgetInstanceId);


    $("#inputHeightDropDownList").on('change', function () {
        if ($(this).val() === "Custom") {
            $(".inputCustomHeight").removeClass('hidden');
        }
        else {
            $(".inputCustomHeight").addClass('hidden');
        }
        return false;
    });

    $("#buttonHeightDropDownList").on('change', function () {
        if ($(this).val() === "Custom") {
            $(".buttonCustomHeight").removeClass('hidden');
        }
        else {
            $(".buttonCustomHeight").addClass('hidden');
        }
        return false;
    });

    $("#buttonWidthDropDownList").on('change', function () {
        if ($(this).val() === "Automatic") {
            $(".buttonCustomWidth").addClass('hidden');
        }
        else {
            $(".buttonCustomWidth").removeClass('hidden');
        }
        return false;
    });

};

subscribeModule.InitTransparencies = function () {
    $("#uxInputColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxInputColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxInputColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxInputColorTransparencyInput").val(Math.abs(Math.round($("#uxInputColorTransparencyInput").val() * 100)) + '%');

    $("#uxInputStrokeTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxInputStrokeTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxInputStrokeTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxInputStrokeTransparencyInput").val(Math.abs(Math.round($("#uxInputStrokeTransparencyInput").val() * 100)) + '%');

    $("#uxButtonColorTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonColorTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonColorTransparencyInput").val(Math.abs(Math.round($("#uxButtonColorTransparencyInput").val() * 100)) + '%');

    $("#uxButtonStrokeTransparencySlider").slider({
        isRTL: true,
        range: 'false',
        value: -$("#uxButtonStrokeTransparencyInput").val(),
        min: -1,
        max: 0,
        step: 0.01,
        slide: function (event, ui) {
            $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round(ui.value * 100)) + '%');
        }
    });
    $("#uxButtonStrokeTransparencyInput").val(Math.abs(Math.round($("#uxButtonStrokeTransparencyInput").val() * 100)) + '%');
};

subscribeModule.InitFonts = function () {
    var selectedInputFont = $('#uxInputFontHidden').val();
    if (selectedInputFont === "")
        selectedInputFont = $("#hdnFontFamily").val();

    $('#inputfontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedInputFont,
        'selected': function (style) {
            $('#uxInputFontHidden').val(style);
        }
    });
    $('#uxInputFontSelectTrigger').on('click', function () {
        $('#inputfontSelect').click();
        return false;
    });

    var selectedButtonFont = $('#uxButtonFontHidden').val();
    if (selectedButtonFont === "")
        selectedButtonFont = $("#hdnFontFamily").val();

    $('#buttonFontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedButtonFont,
        'selected': function (style) {
            $('#uxButtonFontHidden').val(style);
        }
    });
    $('#uxButtonFontSelectTrigger').on('click', function () {
        $('#buttonFontSelect').click();
        return false;
    });


};

subscribeModule.InitColors = function () {

    var siteFontColor = $("#hdnFontFamilyColor").val();
    if ( $("#inputFontColor").val() === "" ) {
        $("#inputFontColor").val(siteFontColor);
    }

    if ( $("#buttonColor").val() === "" ) {
        $("#buttonColor").val(siteFontColor);
    }

    $("#inputColor").simplecolorpicker({ trigger: 'uxInputColorTrigger' });
    $("#inputStrokeColor").simplecolorpicker({ trigger: 'inputStrokeColorTrigger' });
    $("#inputFontColor").simplecolorpicker({ trigger: 'inputFontColorTrigger' });

    $("#buttonColor").simplecolorpicker({ trigger: 'buttonColorTrigger' });
    $("#buttonStrokeColor").simplecolorpicker({ trigger: 'buttonStrokeColorTrigger' });
    $("#buttonFontColor").simplecolorpicker({ trigger: 'buttonFontColorTrigger' });
};

subscribeModule.InitBorders = function (widgetInstanceId) {

    //For Input Field Border
    var simpleColorInputSpan = $("#dvInputStrokeColor_" + widgetInstanceId).find('.icon');
    simpleColorInputSpan.css('background-color', '#eeeeee');

    var inputStrokeIndicator = "<span class='input-stroke btn-widget-stroke-indicator'></span>";
    $(simpleColorInputSpan).html(inputStrokeIndicator);

    var inputStrokeColor = $("#inputStrokeColor").val();
    $(".input-stroke").css('border-color', inputStrokeColor);

    var inputIsSquare = $("#inputUsingSquareCorners").val() === "True";
    if (inputIsSquare) {
        $('.input-stroke').css('border-radius', 0 + "px");
    }
    else {
        var inputRadius = $("#txtInputRadius").val();
        $('.input-stroke').css('border-radius', inputRadius + "px");
    }

    $("#inputStrokeColor").on('change', function () {
        simpleColorInputSpan.css('background-color', '#eeeeee');
        var selectedInputStrokeColor = $("#dvInputStrokeColor_" + widgetInstanceId).find('.picker span[data-selected]');
        $('.input-stroke').css('border-color', selectedInputStrokeColor.data('color'));
        return false;
    });

    $("#rbInputSquareCorner").on('change', function () {
        $(".inputRadius").addClass('hidden');
        $('.input-stroke').css('border-radius', 0 + "px");
        return false;
    });

    $("#rbInputRoundCorner").on('change', function () {
        $(".inputRadius").removeClass('hidden');
        $('.input-stroke').css('border-radius', 4 + "px");
        return false;
    });

    //For Button Border
    var simpleColorButtonSpan = $("#dvButtonStrokeColor_" + widgetInstanceId).find('.icon');
    simpleColorButtonSpan.css('background-color', '#eeeeee');

    var buttonStrokeIndicator = "<span class='btn-stroke btn-widget-stroke-indicator'></span>";
    $(simpleColorButtonSpan).html(buttonStrokeIndicator);

    var buttonStrokeColor = $("#buttonStrokeColor").val();
    $(".btn-stroke").css('border-color', buttonStrokeColor);

    var buttonIsSquare = $("#buttonUsingSquareCorners").val() === "True";
    if (buttonIsSquare) {
        $('.btn-stroke').css('border-radius', 0 + "px");
    }
    else {
        var buttonRadius = $("#txtButtonRadius").val();
        $('.btn-stroke').css('border-radius', buttonRadius + "px");
    }

    $("#buttonStrokeColor").on('change', function () {
        simpleColorButtonSpan.css('background-color', '#eeeeee');
        var selectedButtonStrokeColor = $("#dvButtonStrokeColor_" + widgetInstanceId).find('.picker span[data-selected]');
        $('.btn-stroke').css('border-color', selectedButtonStrokeColor.data('color'));
        return false;
    });

    $("#rbButtonSquareCorner").on('change', function () {
        $(".buttonRadius").addClass('hidden');
        $('.btn-stroke').css('border-radius', 0 + "px");
        return false;
    });

    $("#rbButtonRoundCorner").on('change', function () {
        $(".buttonRadius").removeClass('hidden');
        $('.btn-stroke').css('border-radius', 4 + "px");
        return false;
    });
};

subscribeModule.commitChanges = function (widgetInstanceId) {
    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'Subscribe',
        Settings: {
            InputPlaceholder: $("#txtInputPlaceholder").val(),
            InputColor: $("#inputColor").val(),
            InputColorTransparency: Math.abs($('#uxInputColorTransparencySlider').slider("option", "value")),
            InputBorderColor: $("#inputStrokeColor").val(),
            InputBorderColorTransparency: Math.abs($('#uxInputStrokeTransparencySlider').slider("option", "value")),
            InputFontFamily: $("#uxInputFontHidden").val(),
            InputFontSize: $("#txtInputFontSize").val(),
            InputFontColor: $("#inputFontColor").val(),
            InputHeight: $("#inputHeightDropDownList").val(),
            InputCustomHeight: $("#txtInputCustomHeight").val(),
            InputUsingRoundCorners: $("#rbInputRoundCorner").is(":checked"),
            InputCustomRadius: $("#txtInputRadius").val(),
            ButtonText: $("#buttonText").val(),
            ButtonColor: $("#buttonColor").val(),
            ButtonColorTransparency: Math.abs($('#uxButtonColorTransparencySlider').slider("option", "value")),
            ButtonBorderColor: $("#buttonStrokeColor").val(),
            ButtonBorderColorTransparency: Math.abs($('#uxButtonStrokeTransparencySlider').slider("option", "value")),
            ButtonFontFamily: $("#uxButtonFontHidden").val(),
            ButtonFontSize: $("#txtButtonFontSize").val(),
            ButtonFontColor: $("#buttonFontColor").val(),
            ButtonHeight: $("#buttonHeightDropDownList").val(),
            ButtonCustomHeight: $("#txtButtonCustomHeight").val(),
            ButtonWidth: $("#buttonWidthDropDownList").val(),
            ButtonCustomWidth: $("#txtButtonCustomWidth").val(),
            ButtonUsingRoundCorners: $("#rbButtonRoundCorner").is(":checked"),
            ButtonCustomRadius: $("#txtButtonRadius").val(),
            HideOnMobile: $("#hideWidget").is(':checked')
        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202) {
                $("#modal-dialog").modal('show');
            }
            else {
                subscribeModule.rebuildWidget(widgetInstanceId);
            }
        }
    });

    $("#myModal").modal('hide');
};

subscribeModule.rebuildWidget = function (widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function (html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            subscribeModule.create(widgetInstanceId);
        }
    });
};;
var thumbnailSliderModule = extend(sportsground, 'sportsground.cms.widgets.thumbnailSlider');


thumbnailSliderModule.create = function (widgetInstanceId) {
	var widget = $('#widget_' + widgetInstanceId);
	var widgetWidth = widget.outerWidth();
	var colClass, numCols;
	if (widgetWidth > 1100) {
		colClass = 'col-md-1';
		numCols = 12;
	}
	else if (widgetWidth > 700) {
		colClass = 'col-md-2 col-sm-2 col-xs-2';
		numCols = 6;
	}
	else if (widgetWidth > 500) {
		colClass = 'col-md-3 col-sm-3 col-xs-3';
		numCols = 4;
	}
	else {
		colClass = 'col-md-6 col-sm-6 col-xs-6';
		numCols = 2;
	}

	var carouselContainer = widget.find('.carousel-inner');
	carouselContainer.html('');

	var images = [];
	var imagesJson = $('#hdnImages_' + widgetInstanceId).val();
	if (imagesJson.length > 0)
		images = $.parseJSON(imagesJson);

	var imageIds = $.map(images, function (val) { return val.id; });
	$.ajax({
        url: '/asset/GetImageAssetUrls',
        type: 'POST',
        data: JSON.stringify(imageIds),
		contentType: 'application/json; charset=utf-8',
		success: function(data) {
			var html = '<div class="item active"><div class="row">';
			for (var i = 0; i < data.length; i++) {
				if (i > 0 && i % numCols == 0) {
					html += '</div></div><div class="item"><div class="row">';
				}
				html += '<div class="' + colClass + ' col-centered"><a class="fancybox" rel="gallery1" href="'
                    + data[i].WebOptSrc + '"><img src="' +
                    data[i].Src + "?v=" + data[i].Modified + '" class="img-responsive imgThumbnail" /></a></div>';
			}
			html += '</div></div>';
			carouselContainer.append(html);

			$(".fancybox").fancybox({
				openEffect: 'none',
				closeEffect: 'none'
            });
            sportsground.cms.common.changeThumbnailsForIE('fancybox');
		}
	});
};

thumbnailSliderModule.hideImageModal = function () {
    $('#tabImages_gallerySelect').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
        $('#tabImages_imageReorder').effect('slide', { direction: 'right', mode: 'show' }, 500);
    });
    $('#btnDoneSelectingImages').hide();
    $('#btnCancelSelectingImages').hide();
    $('.widget-settings-cancel-update').show();
    $('.widget-settings-update').show();
    thumbnailSliderModule.loadSelectedImages();
    $(".gallery-action-buttons").hide();
};

thumbnailSliderModule.modalCreated = function (widgetInstanceId) {
	thumbnailSliderModule.imageGalleryInitialised = false;
    thumbnailSliderModule.images = [];
    thumbnailSliderModule.tempImages = [];
	var imageJson = $('#hdnImages').val();
	if (imageJson.length > 0) {
        thumbnailSliderModule.images = $.parseJSON(imageJson);
        thumbnailSliderModule.tempImages = $.parseJSON(imageJson);
		thumbnailSliderModule.loadSelectedImages();
	}

	$('#myModal .modal-footer').append('<div class="pull-left gallery-action-buttons" style="display:none;"><a id="btnUploadImages" href="#"><i class="glyphicon glyphicon-cloud-upload" />&nbsp;&nbsp;Upload an Image</a></div>');
	$('#modalOrganisationId').val($('#OrganisationId').val());

	$('#btnChooseImages').on('click', function () {
		$('#tabImages_imageReorder').effect('slide', { direction: 'left', mode: 'hide' }, 500, function () {
			$('#tabImages_gallerySelect').effect('slide', { direction: 'right', mode: 'show' }, 500);
		});

        if ($('#btnDoneSelectingImages').length == 0) {
            $('.widget-settings-update').after('<button id="btnCancelSelectingImages" class="btn btn-info">Cancel</button><button id="btnDoneSelectingImages" class="btn btn-primary">Save</button>');
            $('#btnDoneSelectingImages').on('click', function () {
                thumbnailSliderModule.images = thumbnailSliderModule.tempImages.slice();
                thumbnailSliderModule.hideImageModal();
            });
            $('#btnCancelSelectingImages').on('click', function () {
                thumbnailSliderModule.tempImages = thumbnailSliderModule.images.slice();
                thumbnailSliderModule.hideImageModal();
            });
        }
        else {
            $('#btnDoneSelectingImages').show();
            $('#btnCancelSelectingImages').show();
        }

		$('.widget-settings-cancel-update').hide();
		$('.widget-settings-update').hide();

		var imageGallerySettings = {
            allowEditing: false,
            container: $('#tabImages_gallerySelect'),
			loadThumbsCallback: function () {
				$('.cbImageSelect').off('change.thumbnailsliderselectimage');
				$('.cbImageSelect').on('change.thumbnailsliderselectimage', function () {
					var id = $(this).parent().parent().data('id');
					if (this.checked)
                        thumbnailSliderModule.tempImages.push({ id: id, caption: '', linkType: 'none' });
					else if (!this.checked)
                        for (var index = 0; index < thumbnailSliderModule.tempImages.length; index++) {
                            if (thumbnailSliderModule.tempImages[index].id == id) {
                                thumbnailSliderModule.tempImages.splice(index, 1);
								break;
							}
						}
				});
				$(".imgImageSelect").off('click.triggerCheckboxChange');
				$(".imgImageSelect").on('click.triggerCheckboxChange', function () {
					var siblingCheckbox = $(this).closest(".gallery-thumb-image").find(".cbImageSelect");
					siblingCheckbox.trigger("click");
				});
				for (var i = 0; i < thumbnailSliderModule.images.length; i++) {
					$('#item_' + thumbnailSliderModule.images[i].id).find('input').attr('checked', 'checked');
				}
			}
		};
        sportsground.cms.imageGallery.init(imageGallerySettings);
        if (!thumbnailSliderModule.imageGalleryInitialised) {
			sportsground.cms.imageGallery.fileupload.init();
			thumbnailSliderModule.imageGalleryInitialised = true;
		}
		$(".gallery-action-buttons").show();

		return false;
	});
};

thumbnailSliderModule.commitChanges = function (widgetInstanceId) {
	var widgetSettings = {
		WidgetId: widgetInstanceId,
		WidgetType: 'ThumbnailSlider',
		Settings: {
			ImagesJson: JSON.stringify(thumbnailSliderModule.images)
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');
			}
		}
	});

	$("#myModal").modal('hide');

	$('#hdnImages_' + widgetInstanceId).val(JSON.stringify(thumbnailSliderModule.images));
	thumbnailSliderModule.create(widgetInstanceId);
};

thumbnailSliderModule.loadSelectedImages = function () {
	$('.selected-image-thumb').remove();
	var imageIds = $.map(thumbnailSliderModule.images, function (val) { return val.id; });
	$.ajax({
        url: '/asset/GetImageAssetUrls',
        type: 'POST',
        data: JSON.stringify(imageIds),
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			var rawHtml = $('#hbtSelectedThumb').html();
			var template = Handlebars.compile(rawHtml);
			for (var i = 0; i < data.length; i++) {
				$('#selectedImagesContainer').append(template(data[i]));
			}

			$('#selectedImagesContainer').sortable({
				cancel: 'input',
				cursor: 'move',
				items: '> .selected-image-thumb',
				handle: '.draghandle',
				update: function () {
					var sortedIds = $('#selectedImagesContainer').sortable('toArray');
					var sortedImages = [];
					for (var si = 0; si < sortedIds.length; si++) {
						for (var ui = 0; ui < thumbnailSliderModule.images.length; ui++) {
							if (sortedIds[si] == thumbnailSliderModule.images[ui].id) {
								sortedImages[si] = thumbnailSliderModule.images[ui];
								break;
							}
						}
					}
					thumbnailSliderModule.images = sortedImages;
				}
			});

			$('.selected-image-delete').on('click', function () {
				var imageId = $(this).closest('.selected-image-thumb').attr('id');
				bootbox.confirm('<h3>Are you sure?</h3><p>Are you sure you would like to remove the selected image from the slider?</p>', function (result) {
					if (!result)
						return;

					$('#' + imageId).remove();
					for (var index = 0; index < thumbnailSliderModule.images.length; index++) {
						if (thumbnailSliderModule.images[index].id == imageId) {
							thumbnailSliderModule.images.splice(index, 1);
							break;
						}
					}

				});
				return false;
			});
		}
	});
};;
var twitterFeedModule = extend(sportsground, 'sportsground.cms.widgets.twitterFeed');


twitterFeedModule.create = function (widgetId) {
};

twitterFeedModule.modalCreated = function (widgetId) {
    var twitterUrl = $("#widget_" + widgetId).find(".twitter-container").data('url');

    $("#TwitterFeedUrl").val(twitterUrl);

    $("#TwitterFeedUrl").on('blur', sportsground.ui.attachHandlerPrependHttpOnWwwLinks);
};

twitterFeedModule.commitChanges = function (widgetId) {
    var url = $("#TwitterFeedUrl").val();

    // Save New Settings
    var widgetSettings = {
        WidgetId: widgetId,
        WidgetType: 'TwitterFeed',
        Settings: {
            TwitterUrl: url
        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            // Find the widget element based on the ID
            var twitterFeedContainer = $("#widget_" + widgetId);

            // remove the iframe
            $(twitterFeedContainer).find("iframe").remove();

            // update the data-url of the container
            $(twitterFeedContainer).find(".twitter-container").data("url", url);

            // regenerate the anchor (this will regenerate the twitter iframe)
            $(twitterFeedContainer).find(".twitter-container").html(
                '<a class="twitter-timeline" href="' + url + '" data-height="500" data-width="500"></a>' +
                '<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>'
            );
        }
    });

    // Hide popup modal
    $("#myModal").modal('hide');
};;
var widgetModule = extend(sportsground, 'sportsground.cms.widgets');

widgetModule.create = function (options) {
	$.post('/cms/widgets/create',
		{
			w: options.widgetType,
			p: options.splitterPlaceholder,
			sid: options.splitterId,
			st: options.splitterType
		},
		function (data) {
			widgetModule.load($('#' + options.containerId), data);
			$('#widgetToolboxModal').modal('hide');

			var widgetId = $($.trim(data)).data('id');
			var $widget = $("#widget_" + widgetId);

			// Show Modal with widget settings	
			if ($widget.data("modal") == "True")
				$widget.find('.widget-settings-edit').click();

			if (options.widgetType == 'RichText') {
				CKEDITOR.on('instanceReady', function(evt) {
                    $("#richtext-" + widgetId + ".cke_editable").focus();
                });
			}

			sportsground.cms.widgets.addingState = false;
		}
	);
};

widgetModule.load = function(container, html, hideAddRemoveButtons) {
    var widget = $($.trim(html));
    var placeholder = container.find('#temp_' + widget.data('id'));
    if (placeholder.length > 0)
        placeholder.replaceWith(html);
    else
        container.append(html);
   
	// HTML has been loaded. Find modal form and validate with jquery-validator
	var requireJsOnLoad = widget.data('load');
	var newElementId = widget.data('id');
	if (requireJsOnLoad == 'True') {
		var widgettype = widget.data('widgettype');
		var jsClassName = widgettype.charAt(0).toLowerCase() + widgettype.slice(1);
		sportsground.cms.widgets[jsClassName].create(newElementId);
	}
	if (hideAddRemoveButtons) {
		var widgetDomElement = container.find('#widget_' + newElementId);
		$('.widget-drag', widgetDomElement).hide();
		$('.widget-settings-delete', widgetDomElement).hide();
    }    
    if ($("#hdnIsHomePage").val() == "True" && $("#hdnIsHomePageLocked").val() == "True" && $("#hdnIsSubSite").val() == "False") {
        sportsground.cms.common.disablewidgetsAndSplitters();
    }
};

// Widgets are loaded via ajax, as we have no control over the timing/order that the ajax calls return
// we add a placeholder in the container that is replaced when the widget loads.
widgetModule.createPlaceholder = function(container, widgetId) {
    container.append('<div id="temp_' + widgetId + '" ></div>');
};

widgetModule.remove = function (widgetInstanceId) {
	$.ajax({
		url: '/cms/widgets/' + widgetInstanceId,
		type: 'DELETE',
		contentType: 'application/json; charset=utf-8',
		success: function () {
			$("#widget_" + widgetInstanceId).remove();
		}
	});
};

widgetModule.initializeWidgetsHandlers = function () {
	$(document).on('click', '.widget-settings-edit', function() {
		var container = $(this).closest('.widget');
		var requiredJsOnModal = container.data('modal');
		var widgettype = container.data('widgettype');
		var widgetInstanceId = container.attr('id').substr(7);
		
		// Callback once DOM in modal is loaded from remote attribute
		$("#myModal").load("/cms/widgets/" + widgetInstanceId + "/settings", function() {
			// Attach some unobtrusive validation to this modal form		
			var form = $("#modal-body").find('form');
			$.validator.unobtrusive.parse(form);
			// Form is loaded dynamically so these defaults are not set for it on page load
			overrideUnobtrusiveDefaults();

			// Natural <form> behaviour is for an  enter key to post form. We don't want this! press the submit button please.
			$(form).find("input").keypress(function (e) {
				if (e.which == 13) {
					e.preventDefault();
					$(".widget-settings-update").click();
				}
			});
			
			var isInCreate = $("#hdnIsInCreate").val();

			if ($("#widget-edit-modal-Notices").length && isInCreate == "True") {
			    $.ajax("/cms/widgets/updateIsInCreate/" + widgetInstanceId);
			    var noticeTextWidget = $('#widget_' + widgetInstanceId + ' .richtext-editor');
			    noticeTextWidget.focus();
			    return;
			}

			$('#myModal').one('shown.bs.modal', function (e) {
                $('body').addClass('modal-open');
                if (requiredJsOnModal == 'True') {
                    var jsClassName = widgettype.charAt(0).toLowerCase() + widgettype.slice(1);
                    sportsground.cms.widgets[jsClassName].modalCreated(widgetInstanceId);
                    // Place focus in first input field
                    var form = $("#modal-body").find('form');
                    form.find(".form-control").first().focus(); // jQuery seems to be okay with this possible null reference
                }
			});

			$("#myModal").modal({
			    backdrop: 'static',
			    keyboard: false  // to prevent closing with Esc button (if you want this too)
			}, 'show');
		});
	});

	$(document).on('click', '.widget-settings-delete', function () {
		// Hide widget div without deleting
		// store widget id in hidden field, comma seperated
		var container = $(this).closest('.widget');
		var widgetInstanceId = container.data('id');

		var htmlNotification = "<div class='text-center'><h1><i class='glyphicon glyphicon-warning-sign'  style='color:#cc002e;'></i></h1><h4 style='color:#cc002e;'>Are you sure you want to permanently delete this content?</h4>";
		if ($(container).data("widgettype") == "Splitter" && $(container).find('.widget').length > 0) {
			// This is a splitter, different message required
			htmlNotification += widgetModule.buildSplitterDeleteConfirmation($(container).find('.widget'));
		}
		htmlNotification += "</div>";

		bootbox.dialog({
			message: htmlNotification,
				buttons: {
				success: {
					label: "No, Keep",
					className: "btn-info",
					callback: function () {
						bootbox.hideAll();
					}
				},
				danger: {
					label: "Yes, Delete",
					className: "btn-danger",
					callback: function (result) {
						if (result) {
							// Delete widget
							sportsground.cms.widgets.remove(widgetInstanceId);
						}
					}
				}
			}
		});
	});

	$(document).on('click', '.widget-settings-cancel-update', function() {
		// check
		var isInCreate = $("#hdnIsInCreate").val();
		if (isInCreate == "True") {
			// call delete functionality
			var modalHead = $("#widget-modal-header");
			var widgetInstanceId = modalHead.data('pagewidgetid');
			sportsground.cms.widgets.remove(widgetInstanceId);
		}
	});

	$(document).on('click', '.widget-settings-update', function () {
		var modalHead = $("#widget-modal-header");
		var widgetInstanceId = modalHead.data('pagewidgetid');
		var widgetType = modalHead.data('widgettype');

		// Check the form is valid before saving!
		var $form = $("#modal-body").find('form');

        if ($form.length > 0) {//some modals dont have form
            if (!$form.valid()) return;
        }

		var isInCreate = $("#hdnIsInCreate").val();
		if (isInCreate == "True") {
			// Make call to set isInCreate to false
			$.ajax("/cms/widgets/updateIsInCreate/" + widgetInstanceId);
		}	

		var jsClassName = widgetType.charAt(0).toLowerCase() + widgetType.slice(1);
		sportsground.cms.widgets[jsClassName].commitChanges(widgetInstanceId);
	});

	$(document).on('mouseenter', '.widget', function (event) {
		$(this).addClass('widgetHighlight');
	}).on('mouseleave', '.widget', function (event) {
		$(this).removeClass('widgetHighlight');
	});
};

widgetModule.saveAll = function () {
	//for each widget hidden on this page pending delete, call its remove method
	var removeCsv = $("#removeWidgetsCsv").val();
	if (removeCsv != "") {
		widget.remove(removeCsv);
	}

	//for each widget on this page call its save method
	$(".widget").each(function() {
		var type = $(this).data('widgettype');
		var widget = $(this).attr("id");

		if (type != null && widget != null) {
			var widgetId = widget.split("_")[1];

			var jsClassName = type.charAt(0).toLowerCase() + type.slice(1);
			sportsground.cms.widgets[jsClassName].commitChanges(widgetId);
		}
	});
};

widgetModule.buildSplitterDeleteConfirmation = function (widgets) {
	// Group By widget type to find how many widgets of each type there are
	var widgetCount = {};
	$(widgets).each(function(key) {
		var name = $(this).data("widgettitle");

        if (name != undefined) {
            if (widgetCount[name] != 1) {
                // It's NOT in here. Add it to the unique array
                widgetCount[name] = 1;
            } else {
                // Already a widget of this type. Increment the count++
                widgetCount[name]++;
            }
        }
	});
	// bootbox confirm window
	var htmlNotification = "<ul class='deleteWidgetsConfirmation text-left'>";
	for (var widget in widgetCount) {
		var widgetName = widget.replace(/([a-z])([A-Z])/g, '$1 $2');
		htmlNotification += "<li>" + widgetName + " (" + widgetCount[widget] + ")</li>";
	}
	htmlNotification += "</ul>";

	return htmlNotification;
};;
var youtubeModule = extend(sportsground, 'sportsground.cms.widgets.youtube');


youtubeModule.create = function (widgetId) {
	$("#widget_" + widgetId).css('height', '100%');
};

youtubeModule.modalCreated = function (widgetId) {

	var pageIframe = $("#widget_" + widgetId).find("iframe");
	var pageVideoUrl = $(pageIframe).attr('src');
	var pageVideoSize = $(pageIframe).attr('class');

	$("#YouTubeUrl").val(pageVideoUrl);
	$('select[name^="settings.VideoHeight"]').val(pageVideoSize);

    $("#YouTubeUrl").on('blur', sportsground.ui.attachHandlerPrependHttpOnWwwLinks);
};

youtubeModule.commitChanges = function (widgetId) {
	// Get new youtube URL
	var url = $("#YouTubeUrl").val();

	// Find the widget element based on the ID
	var youtubeContainer = $("#widget_" + widgetId).find("iframe");

	var video_id = "";
	var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
	if (url.match(p)) {
		video_id = RegExp.$1;
	}

	// Set the src to the new URL
    var newUrl = "https://www.youtube.com/embed/" + video_id + "?h1=en&autoplay=0&showsearch=0&showinfo=0&rel=0";
	$(youtubeContainer).attr('src', newUrl);

	// Set Iframe to selected video player size
	var size = $("#settings_VideoHeight :selected").text();
	$(youtubeContainer).removeClass().addClass(size);

	// Save New Settings
	var widgetSettings = {
		WidgetId: widgetId,
		WidgetType: 'Youtube',
		Settings: {
			VideoUrl: newUrl,
			VideoHeight: size
		}
	};

	$.ajax({
		url: '/cms/widgets/settings',
		type: 'PUT',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(widgetSettings),
		success: function (data, textStatus, xhr) {
			if (xhr.status === 202) {
				$("#modal-dialog").modal('show');
			}
		}
	});

	// Hide popup modal
	$("#myModal").modal('hide');
};;
var compCacheModule = extend(sportsground, 'sportsground.cms.widgets.competitioncaching');

$.localStorage.settings = {
    cookiePrefix: 'html5fallback:localStorage:', // Prefix for the Local Storage substitution cookies
    cookieOptions: {
        path: '/', // Path for the cookie
        domain: document.domain, // Domain for the cookie
        expires: 365 // Days left for cookie expiring
    }
};

compCacheModule.get = function (widget, responseCallback) {
    var widgetId = $(widget).data('id');
    var filterSettings = {};

    var name = 'SKED' + widgetId;
    
    var compIds = $.localStorage.getItem(name + '_compIds');
    var orgIds = $.localStorage.getItem(name + '_orgIds');
    var gradeIds = $.localStorage.getItem(name + '_gradeIds');
    var phaseIds = $.localStorage.getItem(name + '_phaseIds');
    
    if (compIds != null && orgIds != null && gradeIds != null && phaseIds != null) {
        filterSettings = {
            compIds: compIds.trim(),
            orgIds: orgIds.trim(),
            gradeIds: gradeIds.trim(),
            phaseIds: phaseIds.trim()
        };
    }

    responseCallback(widget, filterSettings);
}

compCacheModule.save = function (widgetId) {

    var widget = $("#widget_" + widgetId);

    var compDropdown = $(widget).find('select.fe-comp-comps');
    var orgsDropdown = $(widget).find('select.fe-comp-orgs');
    var gradesDropdown = $(widget).find('select.fe-comp-grades');
    var phaseDropdown = $(widget).find('select.fe-comp-phases');

    var compIds = compDropdown.val();
    var orgIds = sportsground.cms.utils.getSelectedValuesFromMultiSelectList(orgsDropdown);
    var gradeIds = sportsground.cms.utils.getSelectedValuesFromMultiSelectList(gradesDropdown);
    var phaseIds = phaseDropdown.val();

    var name = 'SKED' + widgetId;
  
    $.localStorage.setItem(name + '_compIds', compIds);
    $.localStorage.setItem(name + '_orgIds', orgIds);
    $.localStorage.setItem(name + '_gradeIds', gradeIds);
    $.localStorage.setItem(name + '_phaseIds', phaseIds);
}

compCacheModule.clear = function (widgetId) {

    var name = 'SKED' + widgetId;
    $.localStorage.removeItem(name);
    $.localStorage.removeItem(name + '_compIds');
    $.localStorage.removeItem(name + '_orgIds');
    $.localStorage.removeItem(name + '_gradeIds');
    $.localStorage.removeItem(name + '_phaseIds');
};
var crmPersonDetails = {
	setupRowClickEvents: function () {

		var self = this;

		$('.person-row').click(function () {
			$('#loading-indicator').show();
			$.ajax({
				url: "/crm/GetPerson",
				dataType: "json",
				async: true,
				data: { "personId": $(this).data("id") },
				success: function (data) {
					self._setupValues(data);

					$("#crm-person-details-modal").modal({
						backdrop: 'static',
						keyboard: false // to prevent closing with Esc button (if you want this too)
					}).modal('show');
				},
				complete: function() {
					$('#loading-indicator').hide();
				}
			});
		});
	},

	UpdateTitle: function () {
		var firstName = $('#crm-person-details-modal .crm-person-first-name').val();
		var lastName = $('#crm-person-details-modal .crm-person-last-name').val();
		var id = $('#crm-person-details-modal .crm-person-id').val();
		$('#crm-person-details-modal .title').html(firstName + ' ' + lastName + ' (' + id + ')');
	},

	_setupValues: function(data) {
		$('#crm-person-details-modal .crm-person-id').val(data.Id);
		$('#crm-person-details-modal .crm-person-first-name').val(data.FirstName);
		$('#crm-person-details-modal .crm-person-last-name').val(data.LastName);
		$('#crm-person-details-modal .crm-person-email').val(data.Email);
		$('#crm-person-details-modal .crm-person-dob').val(data.DateOfBirth);
		if (data.Address != null) {
			$('#crm-person-details-modal .crm-person-address-street').val(data.Address.StreetAddress);
			$('#crm-person-details-modal .crm-person-address-suburb').val(data.Address.Suburb);
			$('#crm-person-details-modal .crm-person-address-city').val(data.Address.City);
			$('#crm-person-details-modal .crm-person-address-postcode').val(data.Address.PostCode);
			$('#crm-person-details-modal .crm-person-address-country').val(data.Address.Country);
		}
		$('#crm-person-details-modal .crm-person-donotemail').val(data.DoNotEmail);
		if (data.Phone1 != null) {
			$('#crm-person-details-modal .crm-person-phone1').val(data.Phone1);
		}
		if (data.Phone2 != null) {
			$('#crm-person-details-modal .crm-person-phone2').val(data.Phone2);
		}
		if (data.Gender != null) {
			$('#crm-person-details-modal .crm-person-gender').val(data.Gender);
		}
		if (data.Ethnicity != null) {
			$('#crm-person-details-modal .crm-person-ethnicity').val(data.Ethnicity);
		}

		$('#crm-person-details-modal .crm-person-photo').attr("src", data.PhotoUrl);

		this.UpdateTitle();
	}
};

$('#crm-person-details-modal .update-title').on('input', function () {
	crmPersonDetails.UpdateTitle();
});

$('#btn-save-crm-person-details').click(function () {
	var address = {
		StreetAddress: $('#crm-person-details-modal .crm-person-address-street').val(),
		Suburb: $('#crm-person-details-modal .crm-person-address-suburb').val(),
		City: $('#crm-person-details-modal .crm-person-address-city').val(),
		PostCode: $('#crm-person-details-modal .crm-person-address-postcode').val(),
		Country: $('#crm-person-details-modal .crm-person-address-country').val(),
	};

	var model = {
		Id: $('#crm-person-details-modal .crm-person-id').val(),
		FirstName: $('#crm-person-details-modal .crm-person-first-name').val(),
		LastName: $('#crm-person-details-modal .crm-person-last-name').val(),
		Email: $('#crm-person-details-modal .crm-person-email').val(),
		DateOfBirth: $('#crm-person-details-modal .crm-person-dob').val(),
		Address: address,
		DoNotEmail: $('#crm-person-details-modal .crm-person-donotemail').val(),
		Phone1: $('#crm-person-details-modal .crm-person-phone1').val(),
		Phone2: $('#crm-person-details-modal .crm-person-phone2').val(),
		Gender: $('#crm-person-details-modal .crm-person-gender').val(),
		Ethnicity: $('#crm-person-details-modal .crm-person-ethnicity').val()
	};

	$.ajax({
		url: '/crm/UpdatePerson',
		type: 'POST',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model),
		async: false,
		success: function (data) {
			if (data.success) {
				$("#crm-person-details-modal").modal().modal('hide');
				crmPersonGrid.populateRows();
			}
		}
	});
});

;
var crmPersonGrid = {
	_people: Array(),
	_totalPersonCount: 0,
	_columnDataTypes: Array(),
	_peoplePerPage: 100,
	_currentPage: 0,
	_lastPage: 0,
	_searchString: '',
	_rowDataLoaded :false,

	init: function() {
		var self = this;
		this._rowDataLoaded = false;

		$('.CrmPeopleOptionalHeading').change(function() {
			self._renderTable();
		});

		this._populateColumnValues();
		this.populateRows();
	},

	populateRows: function () {
		this._rowDataLoaded = false;
		$('#loading-indicator').show();
		var self = this;
		$.ajax({
			url: "/crm/GetRowData", //TFSCRMBAD needs to be per-org
			dataType: "json",
			async: true,
			data: { "offset": this._currentPage * this._peoplePerPage, "rowCount": this._peoplePerPage, "searchString": this._searchString },
			success: function (crmPersonRowDataViewModel) {
				self._setRowData(crmPersonRowDataViewModel);
			},
			complete: function() {
				$('#loading-indicator').hide();
			}
		});
	},

	setSearchString: function(searchString) {
		this._searchString = searchString;
		this._currentPage = 0;
		this.populateRows();
	},

	moveToFirstPage: function() {
		if (this._currentPage !== 0) {
			this._moveToPage(0);
		}
	},

	moveToPreviousPage: function() {
		if (this._currentPage > 0) {
			this._moveToPage(this._currentPage - 1);
		}
	},

	moveToNextPage: function() {
		if (this._currentPage < this._lastPage) {
			this._moveToPage(this._currentPage + 1);
		}
	},

	moveToLastPage: function() {
		if (this._currentPage !== this._lastPage) {
			this._moveToPage(this._lastPage);
		}
	},

	_populateColumnValues: function() {
		var self = this;
		$.ajax({
			url: "/crm/GetAvailableColumns", //TFSCRMBAD needs to be per-org
			dataType: "json",
			async: true,
			success: function(items) {
				$('.CrmPeopleOptionalHeading').empty();
				$.each(items, function(i, item) {
					self._columnDataTypes[i] = item.DataType;
					$('.CrmPeopleOptionalHeading').append($('<option>', {
						value: item.Value,
						text: item.Text
					}));
				});
				$('#CrmPeopleOptionalHeading1').val(0);
				$('#CrmPeopleOptionalHeading2').val(1);
				$('#CrmPeopleOptionalHeading3').val(2);
				self._renderTable();
			}
		});
	},

	_setRowData: function(crmPersonRowDataViewModel) {
		this._people = crmPersonRowDataViewModel.People;
		this._rowDataLoaded = true;
		this._totalPersonCount = crmPersonRowDataViewModel.TotalCount;
		this._lastPage = Math.floor(this._totalPersonCount / this._peoplePerPage);
		this._renderTable();
	},

	_renderTable: function() {
		$('#crmPersonTable').empty();
		this._renderTableRows();
		this._renderRowInformation();
		crmPersonDetails.setupRowClickEvents();
	},

	_renderTableRows: function() {
		var newTableContents;

		if (this._people.length === 0 && this._rowDataLoaded) {
			newTableContents = '<tr><td colspan="4">No people found</td></tr>';
		} else {
			var self = this;
			$.each(this._people, function(i, person) {
				newTableContents += self._getRowHtml(person);
			});
		}
		$('#crmPersonTable').html(newTableContents);
	},

	_getRowHtml: function(person) {
		var rowHtml = '<tr class="person-row" data-id="' + person.Id + '">';
		rowHtml += '<td>' + person.FirstName + '</td>';
		rowHtml += '<td>' + person.LastName + '</td>';
		rowHtml += '<td>' + person.Email + '</td>';
		rowHtml += '<td>' + person.DateOfBirth + '</td>';
		rowHtml += this._getOptionalColumnHtml(person, $('#CrmPeopleOptionalHeading1').val());
		rowHtml += this._getOptionalColumnHtml(person, $('#CrmPeopleOptionalHeading2').val());
		rowHtml += this._getOptionalColumnHtml(person, $('#CrmPeopleOptionalHeading3').val());
		rowHtml += '</tr>';
		return rowHtml;
	},
	
	_getOptionalColumnHtml: function(person, optionColumnId) {
		var colDataType = this._columnDataTypes[optionColumnId];
		var colValue = person.OptionalColumnValues[optionColumnId];

		if (colValue == null)
			return '<td></td>';

		if (colDataType === "Text") {
			return '<td>' + colValue + '</td>';
		} else if (colDataType === "URL") {
			return '<td><img src="' + colValue + '"></td>';
		} else if (colDataType === "Bool") {
			var rowHtml = '<td><input type="checkbox" readonly disabled class="old" ';
			if (colValue === "True") rowHtml += ' checked ';
			rowHtml += '/></td>';
			return rowHtml;
		} else {
			return '<td>' + colValue + '</td>';
		}
	},

	_renderRowInformation: function() {
		var fromCount = (this._currentPage * this._peoplePerPage) + 1;
		var toCount = fromCount + this._people.length - 1;
		if (this._people.length === 0) {
			fromCount = 0;
			toCount = 0;
		}
		$('#crmPeoplePageInfo').html(fromCount + ' to ' + toCount + ' of ' + this._totalPersonCount + ' results');
	},

	_moveToPage: function(pageNumber) {
		this._currentPage = pageNumber;
		this.populateRows();
	}

};


if ($("#CrmPeopleOptionalHeading1").val() != undefined) {
	crmPersonGrid.init();
}

$('#crmPeopleFirstPage').click(function () {
	crmPersonGrid.moveToFirstPage();
});

$('#crmPeoplePreviousPage').click(function () {
	crmPersonGrid.moveToPreviousPage();
});

$('#crmPeopleNextPage').click(function () {
	crmPersonGrid.moveToNextPage();
});

$('#crmPeopleLastPage').click(function () {
	crmPersonGrid.moveToLastPage();
});

$('#crmPeopleSearchGo').click(function () {
	crmPersonGrid.setSearchString($('#crmPeopleSearchString').val());
});

$('#crmPeopleSearchString').keypress(function (e) {
	if (e.which === 13) {
		crmPersonGrid.setSearchString($('#crmPeopleSearchString').val());
	}
});;
var dashboard = extend(sportsground, 'sportsground.dashboard');

$(function () {
    sportsground.utils.loadHandlebarsHelpers();

	// Hides loading indicator once the modal has loaded
	$("#myModal").on('shown.bs.modal', function() {
		$('#loading-indicator').hide();
	});

	$("#btnImageGallery").unbind("click");
	$("#btnImageGallery").on('click', function() {
	    $('#loading-indicator').show();
	    $("#myModal").load("/Asset/ImageGallery?organisationid=" + $("#OrganisationId").val(), function () {
	        $("#myModal").modal({
	            backdrop: 'static',
	            keyboard: false  // to prevent closing with Esc button (if you want this too)
	        }).modal('show');
	        sportsground.cms.imageGallery.init({
	            allowEditing: true
	        });
	        sportsground.cms.imageGallery.fileupload.init();
	    });
	    return false;
	});

	$('#btnDocumentManager').unbind("click");
	$('#btnDocumentManager').on('click', function () {
	    $('#loading-indicator').show();
        $("#myModal").load("/Asset/DocumentManager?organisationId=" + $("#OrganisationId").val() + "&isKnowledgeLibrary=false", function () {
	        $("#myModal").modal({
	            backdrop: 'static',
	            keyboard: false  // to prevent closing with Esc button (if you want this too)
	        }).modal('show');
	        sportsground.cms.documentManager.init({
	            allowEditing: true
	        });
	    });
	    return false;
    });

    $('#btnCloudManager').unbind("click");
    $('#btnCloudManager').on('click', function () {
        
        var hasLibraries = $('#btnCloudManager').data("haslibraries");
        if (sportsground.cms.utils.isTrue(hasLibraries)){

            $('#loading-indicator').show();
            $("#myModal").load("/Asset/DocumentManager?organisationId=" + $("#OrganisationId").val() + "&isKnowledgeLibrary=true", function () {
                $("#myModal").modal({
                    backdrop: 'static',
                    keyboard: false  // to prevent closing with Esc button (if you want this too)
                }).modal('show');

                if (gallery.settings) {
                    gallery.settings.isSuperSplitterBG = false;
                }
                sportsground.cms.documentManager.init({
                    allowEditing: true,
                    knowledgeLibrary: true,
                    isMedia: false
                });
            });
            return false;

        }
        else {

            var message = "<p>The Knowledge Library is an area where governing organisations can store and share folders of document templates and resources with affiliated clubs and schools. Examples include policies, procedures, management templates, health & safety resources, position descriptions and much more.</p>";
            message += "<p>Affiliated schools and sports organisations can view, download and customise the document templates, then save them to your own document storage area on the Sporty platform for your own use. </p>";
            message += "<p>If you are a regional or national governing body and wish to make resources available to your affiliated clubs or schools, contact <a href='mailto:sales@sporty.co.nz'>sales@sporty.co.nz</a> </p>";


            var dialog = bootbox.dialog({
                title: 'Knowledge Library',
                message: message
            });

        }
    });
});

dashboard.initialize = function (selectedOrganisationNames) {
    $('.organisation-name span').html(selectedOrganisationNames);

    var caretPosition = $('#ddOrgChangeCaret').offset();
    var ddOffsetTop = caretPosition.top + $('#ddOrgChangeCaret').height();
    $('#orgChangeDropdown .inner').css('top', ddOffsetTop + 'px');
    $('#orgChangeDropdown .inner').css('left', caretPosition.left + 'px');

    $('#orgChangeDropdown').on('click', function () {
        $('#ddOrgChangeCaret').click();
    });
    $(".tile-link.disabled").click(function () {
        bootbox.dialog({
            title: "Access restricted",
            message: "Sorry you don't have access to this area.",
            buttons: {
                success: { label: "OK", className: "btn-success" }
            }
        });
    });

    UserSettings.initialize();
}

dashboard.initIntranetMembers = function() {
	$(".btnChangeSitePassword").on('click', function () {
		// Open modal prompting for password
		$('#loading-indicator').show();

		var siteId = $(this).parent().data("siteid");

		$("#myModal").load('/Dashboard/ChangeMembersPassword/site/' + siteId, function () {
			$("#myModal").modal({
				backdrop: 'static',
				keyboard: false // to prevent closing with Esc button (if you want this too)
			}).modal('show');
			// do any members stuff you need to
			// do any members stuff you need to
			$.validator.unobtrusive.parse($('#changeSiteMembersPassword'));
			// Form is loaded dynamically so these defaults are not set for it on page load
			overrideUnobtrusiveDefaults();
			$("#btnMembersLoginSubmit").on("click", function () {
				if (!$("#changeSiteMembersPassword").valid())
					return false;
				$.ajax({
					url: '/Dashboard/ChangeMembersPassword/',
					type: 'POST',
					contentType: 'application/json; charset=utf-8',
					data: JSON.stringify({
						SiteId: siteId,
						Password: $("#txtMembersPassword").val()
					}),
					success: function (data, textStatus, xhr) {
						//close modal
						$("#myModal").modal('hide');
					}
				});
			});
		});
		return false;
	});
}

dashboard.htmlDecode = function(input) {
	var e = document.createElement('div');
	e.innerHTML = input;
	return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
};
;
var newsletter = extend(sportsground, 'sportsground.dashboard.newsletter');

newsletter.init = function () {

	newsletter.initSettingsManager();

	// Attach categories to multi-select box
	$('.multiselect').multiselect({
		buttonTitle: function () {
			return "News Article Categories";
		},
		buttonWidth: "100%",
		numberDisplayed: 3,
		templates: {
			button: '<button type="button" class="btn-block btn btn-primary multiselect dropdown-toggle" data-toggle="dropdown"></button>',
			li: '<li><a href="javascript:void(0);"><label class="old"></label></a></li>'
		}
	});
    var cachebuster = Math.round(new Date().getTime() / 1000);
	// Init CKEditor for Content
	CKEDITOR.replace('txtNewsletterContent', {
        customConfig: '/Content/ckeditor/noncms_config.js?cb=' + cachebuster,
        autoGrow_minHeight: 250
	});

    CKEDITOR.instances['txtNewsletterContent'].on('key', function (event) { newsletter.changesMade = true; });
    CKEDITOR.instances['txtNewsletterContent'].on('blur', function (event) { newsletter.saveChanges(); });
	$("#ReplyToAddress, #txtSubject, #ddlNumOfArticles, #chkListCategories").on("change", function (event) { newsletter.changesMade = true; })

    newsletter.attachModalHandlers();
};

newsletter.saveChangesClick = function () {

    $(".btnSaveNewsSettingsSubmit").on('click', function () {
        $(".btnSaveNewsSettingsSubmit").prop("disabled", true);
        $(".btnSaveNewsSettingsSubmit i").addClass("fa-spinner");
        setTimeout(function () {
            newsletter.saveChanges();
            $(".btnSaveNewsSettingsSubmit").prop("disabled", false);
            $(".btnSaveNewsSettingsSubmit i").removeClass("fa-spinner");
        }, 500);
    });

};

newsletter.saveChanges = function () {

    var html = CKEDITOR.instances['txtNewsletterContent'].getData();
    var editorElem = $('<p>').append(html);
    if ( editorElem.length === 1 && editorElem.find('a').length > 0 ) { //set the anchors to inherit child element color
        html = sportsground.cms.common.setAnchorToHaveChildColor(editorElem, html);
        CKEDITOR.instances['txtNewsletterContent'].setData(html);
    }

    // Save Newsletter Markup
    $("#txtNewsletterContent").val(html);
    // Retrieve News Categories included to save
    $("#hdnSelectedNewsCategoryIds").val($("#chkListCategories").val());

    var model = {
        ReplyToAddress: $("#ReplyToAddress").val(),
        Subject: $("#txtSubject").val(),
        NumberOfArticles: $("#ddlNumOfArticles").val(),
        Content: $("#txtNewsletterContent").val(),
        SelectedNewsCategoryIds: $("#hdnSelectedNewsCategoryIds").val()
    };

    $.ajax({
        url: '/dashboard/newsletter/' + $("#OrganisationId").val() + '/savesettings',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            newsletter.changesMade = false;
            newsletter.sportyUnload = false;
        }
    });
}

newsletter.attachModalHandlers = function () {
    $(".btnStepOneSubmit").on('click', newsletter.stepOneSubmit);
    $(".btnStepTwoSubmit").on("click", newsletter.stepTwoSubmit);
    $(".btnStepTwoBack").on("click", newsletter.showStepOne);     
    $("#btnManageGifsSponsors").on("click", function () {
        newsletter.loadSelectSponsorsModal(newsletter.Sponsors);
    });
    
    //load step 2 if refreshing on step 2 or coming in on step 2 url
    var step = window.location.hash.substr(1);
    if (step == "step2") {
        newsletter.stepOneSubmit();
    }

};

newsletter.stepOneSubmit = function () {
    // Validate form fields
    if (!$("#createNewsletterForm").valid())
        return false;

    newsletter.saveChanges();
    
    // Update content field by getting CKEDITOR data
    $("#txtNewsletterContent").val(CKEDITOR.instances['txtNewsletterContent'].getData());

    // Display subject below page-header
    $("#txtSubjectHeader").text("").append($("#txtSubject").val()); 
    $("#txtSubjectHeader").show();

    newsletter.loadAddRecipientsModal();

    $("#newsletter-options").hide();
    $("#newsletter-preview").show();

    // show step two
    location.hash = '#step2';    
};

newsletter.loadPreviewModal = function () {

    $(".preview-newsletter-modal").unbind("click");
    $(".preview-newsletter-modal").click(function () {
        newsletter.getPreviewModal(true, false);
    });
};

newsletter.getPreviewModal = function (show, submitform) {
   
    var categories = "";
    if ($("#chkListCategories").val() != null)
        categories = $("#chkListCategories").val().join(",");

    var model = {
        OrganisationId: $("#OrganisationId").val(),
        take: $("#ddlNumOfArticles").val(),
        categories: categories,
        pageNumber: 0,
        excludeHidden: true
    };
    
    $.ajax({
        url: '/dashboard/newsletter/' + $("#OrganisationId").val() + '/preview',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            $("#myModal").html(data);

            $.ajax({
                url: '/cms/site/' + $("#OrganisationId").val() + '/news/list',
                type: 'POST',
                data: JSON.stringify(model),
                contentType: 'application/json; charset=utf-8',
                success: function (data, textStatus, xhr) {
                    $(".newsletter-news-articles").html('');
                    // Append News Articles
                    Handlebars.registerHelper({
                        or: function () {
                            return Array.prototype.slice.call(arguments, 0, -1).some(Boolean);
                        }
                    });
                    var template = Handlebars.compile($('#hbtNewsArticle').html());
                    var ewa = $("#hdnEasyWebAddress").val();

                    $(".newsletter-news-articles").html("");
                    for (var i = 0; i < data.length; i++) {
                        var article = data[i];
                        article.Summary = sportsground.dashboard.htmlDecode(article.Summary);
                        article.ThumbnailPath = sportsground.utils.prependHttpForWwwLinks(article.ThumbnailPath);

                        if (!article.HasScaledThumbnail) {
                            article.ThumbnailPath = sportsground.utils.convertImageSrc(article.ThumbnailPath, 'SQUARE');
                        }

                        var html = template(article);

                        // Compile handlebars template for each and append to page markup                      
                        $(".newsletter-news-articles").append(html);
                    }

                    // Append Content to Template
                    $("#txtNewsletterContent").val(CKEDITOR.instances['txtNewsletterContent'].getData());
                    $(".newsletter-content").html("");
                    if ($("#txtNewsletterContent").val() != "") {
                        $(".newsletter-content-container").show();
                        $(".newsletter-content").append($("#txtNewsletterContent").val());
                        $(".newsletter-content").find('ul').css("padding-left", "30px");
                        $(".newsletter-content").find('ol').css("padding-left", "30px");
                        $("#dvNewletterContent").css("width", "400px");
                        $("#dvNewletterContent").css("word-wrap", "break-word");
                    } else {
                        $(".newsletter-content-container").hide();
                    }

                    //// Load sponsors if the organisation is paying
                    if ($("#hdnIsPayingOrganisation").val() == "True") {
                        newsletter.renderSponsors(newsletter.Sponsors);
                    }

                    if (show)
                    {
                        $("#myModal").modal({
                            backdrop: 'static',
                            keyboard: false  // to prevent closing with Esc button (if you want this too)
                        }).modal('show');
                    }    

                    if (submitform) {
                        // Save Newsletter Markup
                        $("#hdnNewsLetterMarkup").val($("#newsletterMarkup").html());
                        $("#createNewsletterForm").submit();
                    }
                }
            });
        }
    });
}

newsletter.showStepOne = function () {
    $("#createNewsletterStepOne").show();
    $("#createNewsletterStepTwo").hide();
    $("#txtSubjectHeader").hide();
    $("#newsletter-options").show();
    $("#newsletter-preview").hide();

    var step = window.location.hash.substr(1);
    if (step == "step2") {
        history.back();
    } 
};

newsletter.stepTwoSubmit = function () {

    if ($("#chkHasCustomRecipients").is(':checked')) {
        var customRecipients = $("#txtCustomRecipients").val();
        var html = $.parseHTML(customRecipients);
        if (customRecipients.indexOf('<') >= 0 || customRecipients.indexOf('>') >= 0 || customRecipients.indexOf('/>') >= 0) {
            $("#txtCustomRecipients").addClass('has-error');
            $("#spantxtCustomRecipients").text('Please enter valid emails.');
            return false;
        }
        else {
            $("#spantxtCustomRecipients").text('');
            $("#txtCustomRecipients").removeClass('has-error');
        }
    }

    // if using custom header, remove hidden header so it is never rendered.
    if ($("#divNewsletterColorHeader").css('display') == 'none') {
        $("#divNewsletterColorHeader").remove();
    }

    newsletter.addRecipientsSave();

    if ($("#RecipientsList").find(".recipient-group").length <= 0) {
        $("#recipientsListContent").addClass("has-error");
        return false;
    } else {
        $("#recipientsListContent").removeClass("has-error");
    }

    $(".btnStepTwoSubmit").attr("disabled", "disabled");
    $(".btnStepTwoSubmit i").addClass('fa-spinner');

    //remove custom header if not set - hiding wont work in all email clients
    
    if ($("#imgNewsletterHeader").css('display') == 'none') {
        $("#imgNewsletterHeader").remove();
    }
    
    // Retrieve News Categories included to save
    $("#hdnSelectedNewsCategoryIds").val($("#chkListCategories").val());    

    newsletter.getPreviewModal(false, true);
};

newsletter.showStepTwo = function () {
    
    $("#createNewsletterStepOne").hide();
    $("#createNewsletterStepTwo").show();
    newsletter.getPreviewModal(false, false);
};

newsletter.loadAddRecipientsModal = function () {
    var model = {
        OrganisationId: $("#OrganisationId").val(),
        HasCustomRecipients: $("#chkHasCustomRecipients").is(":checked"),
        CustomListRecipients: $("#hdnCustomRecipientsCsv").val(),
        SelectedNoticesSubscriberSiteIds: $("#hdnNoticesSubscribersSiteIds").val(),
        SelectedEditorsSiteIds: $("#hdnSelectedEditorsSiteIds").val()
    };
    $.ajax({
        url: '/dashboard/newsletter/selectrecipients',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            $("#recipientsListContent").html(data);		   
            newsletter.addRecipientsSave();
            newsletter.formTreeCheckboxHandler();
            $("#txtCustomRecipients").val($("#hdnrecipientsWithBreaks").val());
        }
    });
};

newsletter.formTreeCheckboxHandler = function () {
    // enable nested checkboxes
    $('.chkHasFormSubscribers:checkbox')
      .each(function () {
          var $checkbox = $(this),
            checked = this.checked = $checkbox.is('[checked]'), // explicitly set "checked" property for elements with checked attribute
            $ariaCheckbox, attributes;

          // Add aria-checked and checked attribute
          $checkbox.attr({
              'role': 'checkbox',
              'aria-checked': $checkbox.attr('aria-checked') || checked,
              'checked': checked
          });
      });

    $('.chkHasFormSubscribers:checkbox').change(function () {
        var checked = this.checked,
            container = $(this).parent(),
            siblings = container.siblings();
        container.find(':checkbox, input[role="checkbox"]').prop({
            indeterminate: false,
            checked: checked
        }).attr({
            'aria-checked': checked,
            'checked': checked
        });

        function checkSiblings(el) {
            var parent = el.parent().parent(),
                all = true;

            el.siblings().each(function () {
                return all = ($(this).children(':checkbox, input[role="checkbox"]').prop("checked") === checked);
            });

            if (all && checked) {
                parent.children(':checkbox, input[role="checkbox"]').prop({
                    indeterminate: false,
                    checked: checked
                }).attr({
                    'aria-checked': checked,
                    'checked': checked
                });
                checkSiblings(parent);
            } else if (all && !checked) {
                parent.children(':checkbox, input[role="checkbox"]').attr({
                    'aria-checked': checked,
                    'checked': checked
                }).prop({
                    indeterminate: (parent.find(':checkbox:checked, input[role="checkbox"]:checked').length > 0),
                    checked: checked
                });
                checkSiblings(parent);
            } else {
                el.parents("li").children(':checkbox, input[role="checkbox"]').prop({
                    indeterminate: true,
                    checked: false
                }).attr({
                    'aria-checked': 'mixed',
                    'checked': false
                });
            }
        }
        checkSiblings(container);

    });
};

newsletter.addRecipientsSave = function () {
    var recipientsListHtml = $("#RecipientsList").html("");
    // Build lists of selected site notices, editors, & formids.
    var selectedSiteNoticesIds = [];
    var selectedSiteEditorsIds = [];
    var selectedFormIdsForNewRegistrants = [];
    var selectedFormIdsForReturningRegistrants = [];
    $.each($(".chkHasNoticesSubscribers"), function () {
        if ($(this).is(":checked")) {
            recipientsListHtml.append("<label class='recipient-group label label-info'>" + $(this).data("sitename") + " Notices</label>&nbsp;");
            selectedSiteNoticesIds.push($(this).data("siteid"));
        }
    });
    $.each($(".chkHasSiteEditors"), function () {
        if ($(this).is(":checked")) {
            recipientsListHtml.append("<label class='recipient-group label label-info'>" + $(this).data("sitename") + " Editors</label>&nbsp;");
            selectedSiteEditorsIds.push($(this).data("siteid"));
        }
    });
    $.each($(".chkHasFormSubscribers"), function () {
        if ($(this).is(":checked")) {
            recipientsListHtml.append("<label class='recipient-group label label-info'>" + $(this).data("formname") + "</label>&nbsp;");
            if ($(this).data("formid") != undefined) {
                selectedFormIdsForNewRegistrants.push($(this).data("formid"));
                selectedFormIdsForReturningRegistrants.push($(this).data("formid"));
            }
            else if ($(this).data("parentform") != undefined) {
                var formChildren = $("#subtree_" + $(this).data("parentform"));
                if (formChildren.find('input[data-newregistrants="true"]').is(":checked") && formChildren.find('input[data-returningregistrants="true"]').is(":checked")) {
                    //do nothing as it must have been added in if part(loop only comes here when either of childs are selected)
                }
                else if (formChildren.find('input[data-newregistrants="true"]').is(":checked")) {
                    selectedFormIdsForNewRegistrants.push($(this).data("parentform"));
                }
                else if (formChildren.find('input[data-returningregistrants="true"]').is(":checked")) {
                    selectedFormIdsForReturningRegistrants.push($(this).data("parentform"));
                }
            }
        }
    });
   
    $("#hdnNoticesSubscribersSiteIds").val(selectedSiteNoticesIds.join(","));
    $("#hdnSelectedEditorsSiteIds").val(selectedSiteEditorsIds.join(","));
    $("#hdnSelectedFormIds").val(selectedFormIdsForNewRegistrants.join(","));
    $("#hdnSelectedReturningFormIds").val(selectedFormIdsForReturningRegistrants.join(","));
    
    // Update Custom Recipients
    var recipients = $("#txtCustomRecipients").val();

    if ( recipients.length > 0 ) {
        // Extract email addresses from textbox area
        recipients = recipients.match(/(([a-zA-Z0-9._-])[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);

        // Update the hidden field to reflect this
        if (recipients != null) {
            $("#hdnCustomRecipientsCsv").val(recipients.join(","));
        }
    }
    else {
        $("#hdnCustomRecipientsCsv").val("");
    }

    if ($("#chkHasCustomRecipients").is(":checked")) {
        $("#hdnHasCustomRecipients").val(true);
        recipientsListHtml.append("<label class='recipient-group label label-info'>Custom Recipients</label>&nbsp;");
    }

    // Save the newsletters custom recipients against organisation
    var model = {
        organisationId: $("#OrganisationId").val(),
        customRecipients: $("#hdnCustomRecipientsCsv").val()
    };

    $.ajax({
        url: '/dashboard/newsletter/updatenewslettercustomrecipients',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model)
    });
 
};

/* -------- SPONSORS ---------- */

newsletter.renderSponsors = function (sponsors) {
          
    var gifSponsorTemplate = Handlebars.compile($('#hbtGifSponsor').html());
    $.each(sponsors, function(key) {

        if (this.checked) {
            //  render the sponsors in the newsletter markup
            var html = gifSponsorTemplate(this);
            $(".newsletter-gifs-sponsors").append(html);
        }

    });
};

newsletter.loadSelectSponsorsModal = function (sponsors) {
    var model = {
        OrganisationId: $("#OrganisationId").val(),
        SelectedOrganisationSponsorIds: $("#hdnSelectedOrganisationSponsorIds").val()
    }
    // open modal containing the list of organisationsponsors
    $.ajax({
        url: '/dashboard/newsletter/getnewsletteroganisationsponsors',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            if (sponsors == null)
                return false;
            // prepopulate the selected sponsors
            $("#myModal").html(data);
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false  // to prevent closing with Esc button (if you want this too)
            }).modal('show');
            $("#btnSaveNewsletterSponsors").on('click', newsletter.updateNewsletterGifSponsors);

            var gifSponsorTemplate = Handlebars.compile($('#hbtSponsorListItem').html());               
            $.each(newsletter.Sponsors, function() {
                var html = gifSponsorTemplate(this);
                $("#sponsor-list-group").append(html);
            });

            // Add sorting handler for sponsors
            $('#sponsor-list-group').sortable({
                cancel: 'input',
                cursor: 'move',
                items: '> .list-group-item',
                handle: '.drag',
                update: function () {
                    var sortedIds = $('#sponsor-list-group').sortable('toArray');
                    var sortedSponsors = [];
                    for (var si = 0; si < sortedIds.length; si++) {
                        for (var ui = 0; ui < newsletter.Sponsors.length; ui++) {
                            if (sortedIds[si] == newsletter.Sponsors[ui].id) {
                                sortedSponsors[si] = newsletter.Sponsors[ui];
                                break;
                            }
                        }
                    }
                    newsletter.Sponsors = sortedSponsors;
                }
            });
        }
    });
	
};

newsletter.updateNewsletterGifSponsors = function() {
    var selectedSponsorIds = [];
           
    $.each(newsletter.Sponsors, function () {
        var isChecked = $("#chkHasSponsor-" + this.id).is(":checked");

        this.checked = isChecked;

        if (isChecked) {
            selectedSponsorIds.push(this.id);
        }
	
    });
    // store sponsor ids in hidden field
    $("#hdnSelectedOrganisationSponsorIds").val(selectedSponsorIds.join(","));
	
	var model = {
		organisationId: $("#OrganisationId").val(),
		sponsorsCsv: selectedSponsorIds.join(",")
	};

	$.ajax({
		url: '/dashboard/newsletter/' + $("#OrganisationId").val() + '/savesponsors',
		type: 'POST',
		contentType: 'application/json; charset=utf-8',
		data: JSON.stringify(model),
	});

    // Hide modal
    $("#myModal").modal("hide");
};

//initial load to get the sponsors
newsletter.getOrganisationSponsors = function () {
       
    $.ajax({
        url: '/cms/site/' + $("#OrganisationId").val() + '/sponsors',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function(sponsors, textStatus, xhr) {               
            newsletter.Sponsors = [];
            var sponsorOrder = $( "#hdnSponsorsOrderCsv" ).val() ? $( "#hdnSponsorsOrderCsv" ).val().split( "," ) : [];
            var sponsorUnchecked = $( "#hdnSponsorsUnselectedCsv" ).val() ? $( "#hdnSponsorsUnselectedCsv" ).val().split( "," ) : [];
            $.each(sponsors, function (key) {
                var imageUrl = sportsground.utils.prependHttpForWwwLinks(this.ImageUrl);
                var woSizedSrc = sportsground.utils.convertImageSrc(imageUrl, 'WEBOPTIMIZED', 160, true);

                var sponsor = {
                    id: this.Id,
                    name: this.Name,
                    imageUrl: woSizedSrc,
                    link: this.Link,
                    sortOrder: $.inArray(this.Id.toString(), sponsorOrder ),
                    checked: $.inArray(this.Id.toString(), sponsorUnchecked) === -1
                }

                newsletter.Sponsors.push(sponsor);
            });
	        newsletter.Sponsors.sort(function (a, b) {
		        if (a.sortOrder < b.sortOrder)
			        return -1;
		        if (a.sortOrder > b.sortOrder)
			        return 1;
		        return 0;
	        });
        }
    });
};

/* -------- EXCLUSIONS ---------- */

newsletter.initExclusionManager = function () {
    $(".btnManageExclusionList").on("click", newsletter.showExlusionsModal);
};

newsletter.showExlusionsModal = function () {
    $(".btnManageExclusionList i").addClass('fa-spinner');
    $(".btnManageExclusionList").attr('disabled','disabled');
    $.ajax({
        url: '/dashboard/newsletter/' + $("#OrganisationId").val() + '/manageexlcusions',
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        success: function (data, textStatus, xhr) {
            $("#myModal").html(data);
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false  // to prevent closing with Esc button (if you want this too)
            }).modal('show');
            $(".btnManageExclusionList i").removeClass('fa-spinner');
            $(".btnManageExclusionList").attr('disabled', false);
            newsletter.attachExclusionModalHandlers();
        }
    });
};

newsletter.attachExclusionModalHandlers = function () {
    $("#addEmailExclusion").on("click", function () {
        // Disable modal actions
        $(this).hide();
        // Remove info text
        $("#alertNoExclusions").hide();
        // Add Empty Row
        var template = Handlebars.compile($('#hbtNewExclusion').html());
        $(".tblEmailExclusions").prepend(template);
        // Attach Save/Cancel Handlers
        $(".btnAddNewExcludedEmail").on('click', function() {
            var tableRow = $(this).closest("tr");
            var emailAddress = tableRow.find('.edit-email').val();
            if (!sportsground.utils.validateMultipleEmailAddress(emailAddress)) {
                tableRow.find(".form-group").addClass("has-error");
                return false;
            } else {
                tableRow.find(".form-group").removeClass("has-error");
            }
            var model = {
                OrganisationId: $("#OrganisationId").val(),
                EmailAddress: emailAddress
            };
            $.ajax({
                url: '/dashboard/newsletter/' + $("#OrganisationId").val() + '/newexclusion',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(model),
                success: function (data, textStatus, xhr) {
                    // Hide 'add-new' row & show add button
                    $(".addExcludedEmailRow").remove();
                    $('#addEmailExclusion').show();
                    $(".exclusion-action-buttons").show();
                    // Check the exclusion was successfully added
                    if (data.length > 0)
                        return false;
                    if (data.Id == 0)
                        return false;
                    // Append new row
                    var tableRow = Handlebars.compile($('#hbtExclusion').html());
                    $(".tblEmailExclusions").prepend(tableRow(data));		
                }
            });
        });
        $(".btnCancelNewExcludedEmail").on('click', function() {
            $(".addExcludedEmailRow").remove();
            $('#addEmailExclusion').show();
            $(".exclusion-action-buttons").show();
        });
    });

    $(".tblEmailExclusions").on('click', ".btnEditExcludedEmail", function () {
        var tableRow = $(this).closest("tr");
        // hide edit/remove buttons and display save
        $(this).hide();
        tableRow.find(".btnDeleteNewsletterAdvert").hide();
        tableRow.find(".btnSaveExcludedEmail").show();
        $('#addEmailExclusion').hide();
        // switch edit input for display
        tableRow.find(".display-email").parent().hide();
        tableRow.find(".edit-email").show();
    });

    $(".tblEmailExclusions").on("click", ".btnSaveExcludedEmail", function () {
        var tableRow = $(this).closest("tr");
        var emailDisplay = tableRow.find(".display-email");
        var emailInput = tableRow.find(".edit-email");
        // Validate email address before saving
        if (!sportsground.utils.validateMultipleEmailAddress(emailInput.val())) {
            emailInput.closest(".form-group").addClass("has-error");
            return false;
        } else {
            emailInput.closest(".form-group").removeClass("has-error");
        }

        var model = {
            exclusionId: tableRow.data("id"),
            updatedEmail: emailInput.val()
        };
        $.ajax({
            url: '/dashboard/newsletter/' + tableRow.data("id") + '/updateexclusion',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function(data, textStatus, xhr) {
                // Switch edit input to display
                emailDisplay.html(emailInput.val());
                emailInput.hide();
                emailDisplay.parent().show();
                // Change buttons
                tableRow.find('.btnEditExcludedEmail').show();
                tableRow.find('.btnSaveExcludedEmail').hide();
                tableRow.find(".btnDeleteNewsletterAdvert").show();
                $('#addEmailExclusion').show();
            }
        });
    });

    $(".tblEmailExclusions").on("click", ".btnDeleteNewsletterAdvert", function () {
        var tableRow = $(this).closest("tr");
        if (tableRow.data("recipient-requested") == "True") {
            bootbox.confirm("<p>This exclusion has been requested by the user (" + $.trim(tableRow.find('.display-email').text()) + "), are you sure you would like to remove it?</p>", function (result) {
                if (result) {
                    newsletter.removeExclusion(tableRow.data("id"));
                }
            });
        } else {
            newsletter.removeExclusion(tableRow.data("id"));
        }
    });
};

newsletter.detachExclusionModalHandlers = function () {
    $(".tblEmailExclusions").off('click', ".btnEditExcludedEmail");

    $(".tblEmailExclusions").off("click", ".btnSaveExcludedEmail");

    $(".tblEmailExclusions").off("click", ".btnDeleteNewsletterAdvert");
};

newsletter.removeExclusion = function(id)
{
    var model = {
        exclusionId: id
    };
    $.ajax({
        url: '/dashboard/newsletter/' + id + '/removeexclusion',
        type: 'DELETE',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model),
        success: function (data, textStatus, xhr) {
            $("#excluded-email-" + id).remove();
        }
    });
}

/* --------- SETTINGS --------- */

newsletter.initSettingsManager = function () {

    $("#btnNewsletterSettings").unbind("click");
    $("#btnNewsletterSettings").on("click.newsletter-settings", newsletter.showSettingsModal);
    newsletter.changesMade = false;
    newsletter.sportyUnload = false;
    newsletter.unsavedNewsletterChangesMessage = "<p><b>Unsaved Changes. </b>Press OK to save the changes you've made to the newsletter or press Cancel to discard your changes.</p>";
    newsletter.unsavedNewsletterChangesMessageBrowserTriggered = "You have unsaved changes to your newsletter. If you leave before saving, you will lose your changes."
    newsletter.saveChangesClick();
    newsletter.loadPreviewModal();
    newsletter.getOrganisationSponsors();

    var stepTwoHandler = function () {
        var step = window.location.hash.substr(1);
        if (step == "step2") {
            newsletter.showStepTwo();
        }
    }

    
    if (window.onpopstate != undefined) {
        $(window).on('popstate', function (event) {
            stepTwoHandler();
        });
    } else { //ie 11 doesnt support popstate, cheers microsoft
        window.onhashchange = stepTwoHandler;
    }
   

    $(".newsletter-exit").bind("click", function (event) {
        newsletter.sportyUnload = true;
        var hrefClicked = $(this).attr('href');
        if (newsletter.changesMade) {
            event.preventDefault();        
            bootbox.confirm(newsletter.unsavedNewsletterChangesMessage, function (result) {                                
                if (result) {
                    newsletter.saveChanges();
                }
                window.location = hrefClicked;
            });
        }
       
    });

    $(window).bind("beforeunload", function (event) {
        if (newsletter.changesMade && !newsletter.sportyUnload) {
            return newsletter.unsavedNewsletterChangesMessageBrowserTriggered;
        }
    });
};

newsletter.showSettingsModal = function() {
    $.ajax({
        url: '/dashboard/newsletter/' + $("#OrganisationId").val() + '/settings',
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data, textStatus, xhr) {
            $("#myModal").html(data);
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false // to prevent closing with Esc button (if you want this too)
            }).modal('show');

            newsletter.attachSettingsHandlers();
        }
    });
};

newsletter.attachSettingsHandlers = function () {
    $("#btnHeaderImageUpload").on('click.header-image-upload', function () {
        $("#header-image-upload").trigger('click');

        return false;
    });

    $('#header-image-upload').fileupload({
        add: function (e, data) {
            var uploadErrors = [];
            var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
            if (data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
                uploadErrors.push('Not an accepted file type');
            }
            if (data.originalFiles[0]['size'] > 20000000) {
                uploadErrors.push('Filesize is too big');
            }
            if (uploadErrors.length > 0) {
                // TODO: Change this from alert??
                alert(uploadErrors.join("\n"));
            } else {
                data.formData = {
                    OrganisationId: $('#OrganisationId').val()
                }
                data.submit();
            }
        },
        dataType: 'json',
        url: '/dashboard/newsletter/' + $("#OrganisationId").val() + '/addheaderimage',
        maxFileSize: 20000000,
        done: function (e, data) {
            // Flag image has changed so we can move the blob
            $("#hdnHasUpdatedImage").val("True");

            // Save file extension
            var fileExtension = data.result.substr((data.result.lastIndexOf('.') + 1));

            $("#hdnFileExtension").val(fileExtension);

            $("#preview-header").show();
            $("#preview-header").attr("src", data.result + "?qs=" + $.now());
        }
    });

    $("#btnSubmitNewsletterSettings").on('click.submit-header-settings', function () {
        var hasNewsletter = $("#hdnHasNewsletterHeader").is(":checked");
        var fileExt = $("#hdnFileExtension").val();

        if ((fileExt == null || fileExt == "") && hasNewsletter) {
            bootbox.alert({
                title: "Unable to proceed",
                message: "You must upload a header before you can include a custom header in your newsletter."
            });
            return false;
        }

        if ($("#preview-header").height() > $("#preview-header").width() && hasNewsletter) {
            bootbox.alert({
                title: "Unable to proceed",
                message: "Please upload an image in landscape orientation (image width greater than image height)."
            });
            return false;
        }

        var model = {
            HasNewsletterHeader: hasNewsletter,
            HasUpdatedHeader: $("#hdnHasUpdatedImage").val(),
            NewsletterHeaderFileExtension: fileExt,
            OrganisationId: $("#OrganisationId").val()
        };

        $.ajax({
            url: '/dashboard/ManageNewsletterSettings',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data, textStatus, xhr) {
                $("#myModal").hide();

                if (model.HasNewsletterHeader) {
                    if (model.HasUpdatedHeader) {
                        var imageUrl = $("#preview-header").attr("src").replace("-temp", "");
                        $("#imgNewsletterHeader").attr("src", imageUrl);
                    }
                    $("#imgNewsletterHeader").show();
                    $("#divNewsletterColorHeader").hide();
                    $(".header-image").attr("bgcolor", "");
                    $(".header-image").css("background-color", "");
                } else {
                    var bgColor = $("#hdnBackgroundColor").val();
                    $("#imgNewsletterHeader").hide();
                    $("#divNewsletterColorHeader").show();
                    $(".header-image").attr("bgcolor", bgColor);
                    $(".header-image").css("background-color", bgColor);
                }
            }
        });

    });

};;
var subsiteModule = extend( sportsground, 'sportsground.dashboard.subsite' );

subsiteModule.init = function () {
    $( 'li.disabled a' ).addClass( 'disabled' );
    $( '[data-toggle="tooltip"]' ).tooltip();

    $( '.hide-site' ).on( 'click', subsiteModule.showHideEventHandler );
    $( '.del-site' ).on( 'click', subsiteModule.deleteSiteEventHandler );
    $( '.site-settings' ).on( 'click', subsiteModule.siteSettingsEventHandler );
    $( '.manage-editors' ).on( 'click', subsiteModule.manageEditorsEventHandler );
};

subsiteModule.showHideEventHandler = function () {
    var button = $( this );
    var siteItem = $( this ).closest( 'li' );
    var isHidden = siteItem.data( 'hidden' ) == 'True';
    var siteId = siteItem.data( 'id' );
    // If already hidden, show it
    if ( isHidden ) {
        $.ajax( {
            url: '/api/sites/setvisibility/' + siteId + '?hidden=false',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function ( data ) {
                if ( data.success ) {
                    siteItem.removeClass( 'hidden-site' );
                    siteItem.data( 'hidden', 'False' );
                    button.find( 'i' ).removeClass( 'icon-show' ).addClass( 'icon-hide' );
                    siteItem.find( '.site-span' ).removeClass( 'disabled' );
                }
            }
        } );
    }
    else {
        $.ajax( {
            url: '/api/sites/setvisibility/' + siteId + '?hidden=true',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function ( data ) {
                if ( data.success ) {
                    siteItem.addClass( 'hidden-site' );
                    siteItem.data( 'hidden', 'True' );
                    button.find( 'i' ).removeClass( 'icon-hide' ).addClass( 'icon-show' );
                    siteItem.find( '.site-span' ).addClass( 'disabled' );
                }
            }
        } );
    }
    return false;
};

subsiteModule.deleteSiteEventHandler = function () {
    var siteItem = $( this ).closest( 'li' );
    var siteId = siteItem.data( 'id' );
    bootbox.confirm( '<h3>Are you sure?</h3><p>Are you sure you want to delete this site?</p>', function ( result ) {
        if ( result ) {
            $.ajax( {
                url: '/api/sites/' + siteId,
                type: 'DELETE',
                contentType: 'application/json; charset=utf-8',
                success: function ( data ) {
                    if ( data.success ) {
                        siteItem.remove();
                    }
                }
            } );
        }
        return true;
    } );
    return false;
};

subsiteModule.siteSettingsEventHandler = function () {
    var siteItem = $( this ).closest( 'li' );
    var currentName = siteItem.data( 'name' );
    var currentSlug = siteItem.data('slug');
    var showInMobileApp = siteItem.data('showinmobileapp').toString().toLowerCase();
 
    $( '#tbSubsiteName' ).val( currentName );
    $( '#tbSubsiteEasyWebAddress' ).val( currentSlug );
    $( "#divSettingsErrors" ).hide();
    $( '#settingsModal' ).modal( 'show' );
    $('#cbSubsiteInMobileApp')[0].checked = showInMobileApp === 'true';
    $( '#btnSaveSiteChanges' ).off();
    $( '#btnSaveSiteChanges' ).on( 'click', { siteItem: siteItem }, subsiteModule.saveSiteChangesEventHandler );
};

subsiteModule.saveSiteChangesEventHandler = function (event) {
    $('#tbSubsiteEasyWebAddress').val($('#tbSubsiteEasyWebAddress').val().toLowerCase())
    var model = {
        Id: event.data.siteItem.data( 'id' ),
        Name: $( '#tbSubsiteName' ).val(),
        EasyWebAddress: $('#tbSubsiteEasyWebAddress').val(),
        IsSubsiteVisibleInMobileApp: $('#cbSubsiteInMobileApp')[0].checked
    }
    $.ajax( {
        url: '/api/sites/updatesubsite',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify( model ),
        success: function ( data ) {
            if ( data.success ) {
                event.data.siteItem.find( '.site-edit' ).attr( 'href', '/' + model.EasyWebAddress + '?em=1' );

                var siteSpan = event.data.siteItem.find( '.site-span' );
                siteSpan.html( model.Name );
                siteSpan.attr( 'href', '/' + model.EasyWebAddress );

                event.data.siteItem.data( 'name', model.Name );
                event.data.siteItem.data('slug', model.EasyWebAddress);
                event.data.siteItem.data('showinmobileapp', model.IsSubsiteVisibleInMobileApp);

                $( '#settingsModal' ).modal( 'hide' );
            } else {
                $( "#divSettingsErrors" ).show();
                $( "#divSettingsErrors" ).html( data.error );

                return false;
            }
        }
    } );
};

subsiteModule.manageEditorsEventHandler = function () {
    var teamItem = $( this ).closest( 'li' );
    var teamId = teamItem.data( 'id' );
    $.ajax( {
        url: '/dashboard/teams/permissions/' + teamId,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        cache: false,
        success: function ( data ) {
            $( '#permissionsModalBody' ).html( data );
            $( '#permissionsModal' ).modal( 'show' );

            $( '#teamPermissionsDeleteSelected' ).on( 'click', subsiteModule.removeEditorEventHandler );
        }
    } );
    return false;
};

subsiteModule.removeEditorEventHandler = function () {
    var model = {
        ids: $.map( $( '.editorcb:selected' ), function ( editorCb ) {
            return $( editorCb ).closest( 'li' ).data( 'id' );
        } )
    };

    $.ajax( {
        url: '/api/teams/removeeditors',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify( model ),
        success: function () {
            $( '.editorcb:selected' ).closest( 'li' ).remove();
        }
    } );
};;
var formAdmin = extend(sportsground, 'sportsground.forms.admin');
var unsavedChangesMessage = "<p><b>Unsaved Changes. </b>Press OK to save the changes you've made to the records on this page or press Cancel to discard your changes.</p>";

// Remove transfer status from drop list (those status are only used when transfers are enabled 
// in which case the drop list is replaced by label)
$('.response-status').find("option[value='6'],[value='7'],[value='8']").remove();

formAdmin.coalesce = function () {

	for (var i = 0; i < arguments.length; i++) {
		var obj = $(arguments[i]);
		if (obj != null && obj.length > 0)
			return obj;
	}

	return [];
};


formAdmin.prompt = function(message, confirmText, cancelText, callBack) {
    bootbox.confirm({
        message: message,
        buttons: {
            confirm: {
                label: confirmText,
                className: 'btn-success'
            },
            cancel: {
                label: cancelText,
                className: 'btn-danger'
            }
        },
        callback: callBack
    });
}

formAdmin.setSportyStatus = function (responseId, status) {
    var btn = $('#' + responseId).find('.sporty-status');
    var icon = btn.find('i');

    if ($("#IsCurrentUserSuperAdmin").val() == "True") {
        $('#' + responseId).find("#response_Status").val(status);
    }
    else {
        var statusLabel = btn.parents('tr').find('td.response-status');
        statusLabel.text(formAdmin.getStatusText(status));
    }

    icon.removeClass('fa-check');
    icon.removeClass('fa-exchange');
    icon.removeClass('fa-exclamation');
    btn.removeClass('btn-disabled');
    btn.removeClass('disabled');
    btn.removeClass('sporty-status-locked');        
    icon.removeClass('fa-plus');


    if (status == 0 || status == 7) {
        icon.addClass('fa-plus');
    } else {
        btn.addClass('btn-disabled');
        btn.addClass('sporty-status-locked');
        if (status == 8) {
            icon.addClass('fa-exchange');
        } else if (status == 6) {
            icon.addClass('fa-exclamation');
        }
        else {
            icon.addClass('fa-check');
        }
    }

};

formAdmin.getStatusText = function(status) {
    switch (status) {
        case 0:
            return 'Pending';
        case 1:
            return 'Active';
        case 2:
            return 'Inactive';
        case 4:
            return 'Retired';
        case 6:
            return 'TransferPending';
        case 7:
            return 'TransferDeclined';
        case 8:
            return 'Transferred';
        default:
            return '';
    }
};

formAdmin.selectDroplistAfterLoad = function(selector, selects, responseText) {
    $(selector).on('populatedDroplist', function () {
        var option = selects.find('option[value="' + responseText + '"]');
        if (option.length > 0)
            option.prop('selected', true);
    });
};

formAdmin.selectMultiselectAfterLoad = function(selector, responseText) {
    $(selector).on('populatedMultiselect', function () {
        var selectedValues = responseText.split(",");
        var checkboxes = $(this).find('input[type=checkbox]');
        for (var j = 0; j < checkboxes.length; j++) {
            var cb = $(checkboxes[j]);
            for (var k = 0; k < selectedValues.length; k++) {
                var selectedValue = selectedValues[k];
                if (selectedValue == "true") {
                    $(cb).trigger('click');
                } else if (cb.val() == selectedValue) {
                    $(cb).trigger('click');
                } else if (cb.val() == selectedValue) {
                    $(cb).trigger('click');
                }
            }
        }
    });
};


formAdmin.populateForm = function (formContainer, previousRegistrationId) {
	$.ajax({
		url: '/formsapi/getresponse/' + previousRegistrationId,
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
		cache: false,
		success: function (data) {

			for (var i = 0; i < data.length; i++) {
				var firstMappingField = data[i].firstMappingField ? data[i].firstMappingField : "";
				var questionContainer = formAdmin.coalesce(
                formContainer.find('.form-group-question[data-questionid="' + data[i].questionId + '"]'),
                formContainer.find('.form-group-question[data-firstmappingfield="' + firstMappingField + '"][data-questiontext="' + data[i].questionText.replace(/"/g, "") + '"]'),
                formContainer.find('.form-group-question[data-questiontext="' + data[i].questionText.replace(/"/g, "") + '"]')
                );

				if (questionContainer.length <= 0) {
					continue;
				}


                if (questionContainer.find('.form-nrdethnicity-selection').length) {
                    formAdmin.selectMultiselectAfterLoad('.form-nrdethnicity-selection', data[i].responseText);
                } else if (questionContainer.find('.form-secondary-nrdethnicity-selection').length) {
                    formAdmin.selectMultiselectAfterLoad('.form-secondary-nrdethnicity-selection', data[i].responseText);
                } else if (questionContainer.find('.form-ethnicity-selection').length) {
                    formAdmin.selectMultiselectAfterLoad('.form-ethnicity-selection', data[i].responseText);
                } else if (questionContainer.find('.form-secondary-ethnicity-selection').length) {
                    formAdmin.selectMultiselectAfterLoad('.form-secondary-ethnicity-selection', data[i].responseText);
                } 

                var checkboxes = questionContainer.find('input[type=checkbox]');
                if (checkboxes.length) {
					for (var j = 0; j < checkboxes.length; j++) {
						var cb = $(checkboxes[j]);
						if (data[i].responseText == "true") {
                            $(cb).trigger('click');
						}
						else if (cb.val() == data[i].responseText) {
                            $(cb).trigger('click');
						}
						else if (cb.val() == data[i].responseId) {
                            $(cb).trigger('click');
                        }
                    }
				}

				var inputs = questionContainer.find('input[type!=checkbox][type!=file], textarea');
				if (inputs.length) {
					var responseValue = data[i].responseText;
					inputs.val(responseValue);
					inputs.trigger('change');

					// reload the address data
					if (data[i].additionalAnswerData) {
						var ad = data[i].additionalAnswerData;
						$.each(ad, function (key, value) {
							questionContainer.find("input[id$='" + key + "']").val(value);
						});
					}
				}

				var files = questionContainer.find('input[type=file]');
				if (files.length) {
					var filename = data[i].responseText;
					if (filename != null) {
						$(files).rules('remove', 'required');
					}
				}

				var formDoc = questionContainer.find('.form-document');
				if (formDoc.length) {
					var formDocFilename = data[i].responseText;
					var splitFormDocFilename = formDocFilename.split('/');

					if (formDocFilename != null) {
						formDoc.after("<a target='_blank' href='" + formDocFilename + "'>" + splitFormDocFilename[splitFormDocFilename.length - 1] + "</a>");
						var remove = questionContainer.find('.remove-document');
						remove.show();
						files.hide();
					}
				}

				var selects = questionContainer.find('select');
				if (selects.length) {
					var option = selects.find('option').filter(function () {
						return $(this).val() == data[i].responseText || $(this).val() == data[i].responseId || $(this).text() == data[i].responseText;
					});

					// if we are a teams list, it may not have been populated yet via ajax
                    if (selects.hasClass('form-teamlist')) {
                        formAdmin.selectDroplistAfterLoad('.form-teamlist', selects, data[i].responseText);
                    } else if (selects.hasClass('form-nrdteam')) {
                        formAdmin.selectDroplistAfterLoad('.form-nrdteam', selects, data[i].responseText);
                    } else if (option.length != 0) {
						option.prop('selected', true);
						selects.trigger('change');
					}
				}
			}

			// disable edit date of birth for nrd forms
			if ($('.isnrdform .form-dob input').val()) {
				$('.form-dob input').attr('readonly', true);
            }

            if ($("#LockWeight").val().toLowerCase() === 'true') {
                $("div[data-firstmappingfield='Weight'] input").attr('readonly', true);
            }

            

            $.each($('div[data-questiontype="2"]'), function () {
                if ($(this).find('textarea').val().length > 0) {
                    sportsground.forms.rendering.checkMulitiLineTextLength($(this).find('textarea'));
                }
            });

            setTimeout(function () { responseModule.setSerializedFormData(); }, 400); 
		}
	});
};


formAdmin.viewResponsesDashboardPage = {
	init: function () {
		formAdmin.viewResponsesDashboardPage.registerHandlebarsPartials();
		formAdmin.sportyUnload = false;

		$(".page-header a, .nav a, .response-register, .response-edit, .response-pdf, .add-new-form").bind("click", function (event) {

			var hrefClicked = $(this).attr('href');
			if (formAdmin.changesMade) {
				event.preventDefault();
				formAdmin.sportyUnload = true;
				bootbox.confirm(unsavedChangesMessage, function (result) {

					if (result) {
						saveAllResponses();
					}
					window.location = hrefClicked;
				});
			}
		});

		$(".person-search").bind("click", function (event) {

			if (formAdmin.changesMade) {
				event.preventDefault();
				formAdmin.sportyUnload = true;
				bootbox.confirm(unsavedChangesMessage, function (result) {

					if (result) {
						saveAllResponses();
					}
					$("#search-form").submit();
				});
			}
		});

		$('.pagination li:not(.active) a').on('click', function () {

			var page = $(this).data('page');
			var pageHref = sportsground.utils.updateQueryStringParameter(window.location.href, 'page', page);

			if (formAdmin.changesMade) {
				formAdmin.sportyUnload = true;
				bootbox.confirm(unsavedChangesMessage, function (result) {

					if (result) {
						saveAllResponses();
					}
					window.location.href = pageHref;
					return false;
				});
			}
			else {
				window.location.href = pageHref;
				return false;
			}
		});

		$(window).bind("beforeunload", function (event) {
			if (formAdmin.changesMade && !formAdmin.sportyUnload) {
				$('#saveAllResponses').addClass("unsaved-changes-alert");
				setTimeout(function () { $('#saveAllResponses').removeClass("unsaved-changes-alert"); }, 1000);
				return "You have unsaved changes to your summary notes. If you leave before saving, you will lose your changes.";
			}
		});

		function saveAllResponses() {

			var model = $.map($('tr.modified'), function (row) {
			    return {
			        id: $(row).data('id'),
			        status: $(row).find('.response-status').val(),
			        notes: $(row).find('.response-notes').val(),
			        weight: $(row).find('.response-weight').val(),
                    email: $(row).find('.email').is(':checked'),
                    photoIdCardEnabled: $(row).find('.photoIdcard').is(':checked')
			};
			});

			$.ajax({
				url: '/formsapi/updateresponsebulk',
				type: 'POST',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(model),
				cache: false,
				success: function (data) {
					if (data.success) {
						$('#saveAllResponses').effect("pulsate", {}, 2000);
						var moddedRows = $('tr.modified');
                        moddedRows.each(function (index, row) {
                            var rowElement = $(row);
                            rowElement.removeClass('modified');
                            rowElement.find('.response-save').attr('disabled', 'disabled');
                            formAdmin.setSportyStatus(rowElement.attr('id'), rowElement.find('.response-status').val());
						});
						moddedRows.effect("highlight", { color: '#2B9C2A' }, 2000);
						formAdmin.changesMade = false;
					}
				}
			});
			return false;

		}

		$('.response-notes').on('keyup', function () {
			var row = $(this).closest('tr');
			row.find('.response-save').removeAttr('disabled');
			row.addClass('modified');
			formAdmin.changesMade = true;
		});

		$('.response-weight').on('keyup', function () {
			var row = $(this).closest('tr');
			row.find('.response-save').removeAttr('disabled');
			row.addClass('modified');
			formAdmin.changesMade = true;
		});

        $('.response-status').on('change', function () {
	        var row = $(this).closest('tr');
	        row.find('.response-save').removeAttr('disabled');
	        row.addClass('modified');
	        formAdmin.changesMade = true;
        });

        $('.photoIdcard').on('change', function () {
            var row = $(this).closest('tr');
            var responseId = row.data('id');
            var photoIdCardEnabled = $(row).find('.photoIdcard').is(':checked');

            var model = {
                responseId: responseId,
                photocardEnabled: photoIdCardEnabled
            };

            $.ajax({
                url: '/formsapi/updatephotocardstatusforresponse',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(model),
                cache: false,
                success: function (data) {
                    if (data) {
                        $('td', row).effect("highlight", { color: '#2B9C2A' }, 2000);
                    }
                }
            });
            return false;
        });

        $('.email').on('change', function () {
            var row = $(this).closest('tr');
            var responseId = row.data('id');
            var email = $(row).find('.email').is(':checked');

            var model = {
                responseId: responseId,
                email: email
            };

            $.ajax({
                url: '/formsapi/updateemailstatusforresponse',
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                data: JSON.stringify(model),
                cache: false,
                success: function (data) {
                    if (data) {
                        if (email) {
                            $(row).find('.response-email').attr('disabled', false);
                        }
                        else {
                            $(row).find('.response-email').attr('disabled', 'disabled');
                        }
                        $('td', row).effect("highlight", { color: '#2B9C2A' }, 2000);
                    }
                }
            });
            return false;
        });

		$('.response-save').on('click', function () {
			var row = $(this).closest('tr');
			var status = row.find('.response-status').val();

			var temp = row.find('.response-weight').val();
            var weight = parseInt(temp);
            var email = $(row).find('.email').is(':checked');
            var photoIdCardEnabled = $(row).find('.photoIdcard').is(':checked');

			if (isNaN(weight) || weight < 1) {
				weight = undefined;
				row.find('.response-weight').val('');
            }

			var model = {
				id: row.data('id'),
				status: status,
				notes: row.find('.response-notes').val(),
                weight: weight,
                email: email,
                photoIdCardEnabled: photoIdCardEnabled
			};
			$.ajax({
				url: '/formsapi/updateResponse',
				type: 'POST',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(model),
				cache: false,
				success: function (data) {
					if (data.success) {
						$('td', row).effect("highlight", { color: '#2B9C2A' }, 2000);
						row.removeClass('modified');
						row.find('.response-save').attr('disabled', 'disabled');

						if (status === '5') {
							row.find('.response-email').attr('disabled', 'disabled');
						}
                        else {
                            var emailDisabledAttr = row.find('.response-save').attr('disabled');

                            if (emailDisabledAttr == undefined || emailDisabledAttr == false) {
                                row.find('.response-email').removeAttr('disabled');
                            }
                        }
					    formAdmin.setSportyStatus('response_' + model.id, status);
						formAdmin.changesMade = false;
					}
				}
			});
			return false;
		});

		$('.response-delete').on('click', function () {
			var row = $(this).closest('tr');
			bootbox.confirm('<h3>Are you Sure?</h3><p>Are you sure you would like to delete this registrant?</p>', function (result) {
				if (result) {
					$.ajax({
						url: '/formsapi/deleteresponse/' + row.data('id'),
						type: 'POST',
						contentType: 'application/json; charset=utf-8',
						success: function (data) {
                            if (data.success) {
                                row.remove();
                            } else {
                                bootbox.alert(data.errorMessage);
                            }
						}
					});
				}
				return true;
			});
			return false;
		});

		$('.response-payments').on('click', function () {
			if ($(this).hasClass('active')) {
				$(this).removeClass('active');
				$(this).closest('tr').next().remove();
				return false;
			}

			var responsePaymentBtn = $(this);
			var row = $(this).closest('tr');
			var responseId = row.data('id');

			$.ajax({
				url: '/formsapi/transactions/' + responseId,
				type: 'GET',
				contentType: 'application/json; charset=utf-8',
				cache: false,
				success: function (data) {
					if (data.success) {
						data.id = responseId;
						responsePaymentBtn.addClass('active');
						var template = Handlebars.compile($('#hbTemplatePayments').html());
						row.after(template(data));
						return false;
					}
					else {
						bootbox.alert(data.message);
					}
				}
			});
			return false;
		});

		$(document).on('click', '.btn-add-payment', function () {
			var input = $(this).closest('.input-group').find('input');
			var amount = input.val();
			if (!$.isNumeric(amount))
				return false;

			var model = {
				amount: amount
			};
			var btn = $(this);
			btn.button('loading');
			var responseId = $(this).closest('.payment-summary').data('id');
			var container = $(this).closest('table').find('tbody');
			$.ajax({
				url: '/formsapi/transactions/' + responseId,
				type: 'PUT',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(model),
				cache: false,
				success: function (data) {
					btn.button('reset');
					if (data.success) {
						// remove 'no transaction' row if exists
						container.find('.no-transactions').remove();

						// clear input
						input.val('');

						// update balance paid amount
						var $response = $('#response_' + responseId);
						var currentBal = parseFloat($response.data('bpaid'));
						var transactionAmount = parseFloat(model.amount);
						var updatedBal = currentBal + transactionAmount;
						$response.data('bpaid', updatedBal);
						$response.find('.balance-paid').html('$' + updatedBal.toFixed(2));

						// Add new transaction row
						var template = Handlebars.compile($('#hbTemplateTransaction').html());
						container.append(template(data.transaction));
					} else {
						bootbox.alert(data.message);
					}
				}
			});
		});

        $('.response-register').on('click', function () {

            if ($(this).attr('disabled'))
                return false;

			var responseId = $(this).closest('tr').data('id');
            var orgFormId = $('#OrganisationFormId').val();

            // if coach registration type, show cannot roll over next season modal and do not execute ajax call
            var isCoachRegistration = $('#IsCoachRegistration').val();
            if (isCoachRegistration == 'True') {
                var rollOverNextSeasonMessage = '<p>' + $('.response-register').attr("title") + '</p>';
                $('#coachRegistrationModal').find('.modal-body').html(rollOverNextSeasonMessage);
                $('#coachRegistrationModal').modal('show');
                return;
            }

			$.ajax({
				url: '/formsapi/' + orgFormId + '/rolloverid',
				type: 'GET',
				contentType: 'application/json; charset=utf-8',
				cache: false,
				success: function (data) {
                    if (data.success) {
                        if (data.rolloverId && data.rolloverId > 0) {
                            window.location.href = '/dashboard/forms/view/' + data.rolloverId + '/reregister/' + responseId;
                        }
						else {
							if ($('#HasSuperForm').val() == "True") {
								$('#requestNextSeasonForSuperformModal').modal('show');
							}
							else {
								$('#createNewSeasonFormModal').data('responseid', responseId);
								$('#createNewSeasonFormModal').modal('show');
							}
						}
					}
				}
			});
			return false;
		});

		$('#copyFormConfirm').on('click', function () {
			var model = {
				formId: $('#OrganisationFormId').val(),
				seasonRollover: true
			};
			$.ajax({
				url: '/formsapi/copyform',
				type: 'POST',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(model),
				cache: false,
				success: function (data) {
					if (data.success) {
						window.location.href = '/dashboard/forms/view/' + data.id + '/reregister/' + $('#createNewSeasonFormModal').data('responseid');
					}
				}
			});
		});

		$('.response-email').on('click', function () {

			if ($(this).attr('disabled'))
				return false;

			var row = $(this).closest('tr');
			var hasSuperform = $('#HasSuperForm').val() === 'True';
			var organisationFormId = $('#OrganisationFormId').val();
            var responseId = row.data('id');
            var orgName = $('#OrganisationName').val();
            $('#emailRegistrant_RegistrantName').text(row.data('firstname') + ' ' + row.data('lastname'));
			$('#emailDatabaseTextBlurb').val('You are invited to register with ' + orgName + ' for the upcoming season. You can do this now - please click here to re-register with ' + orgName + '.\n\rIf you have any questions about this email, please contact ' + orgName + ' \n\rIf you do not wish to re-register with ' + orgName + ' for the next season, please ignore this email.');
			$.ajax({
				url: '/formsapi/' + organisationFormId + '/rolloverid',
				type: 'GET',
				contentType: 'application/json; charset=utf-8',
				cache: false,
				success: function (data) {
					if (data.success) {
						if (data.rolloverId && data.rolloverId > 0) {
							$('#emailRegistrantModal').data('responseid', responseId);
							$('#emailDatabaseAutoCreateNewForm').hide();
							$('#emailRegistrantModal').modal('show');
						}
						else {
							if (hasSuperform) {
								$('#requestNextSeasonForSuperformModal').modal('show');
							}
							else {
								$('#emailRegistrantModal').data('responseid', responseId);
								$('#emailDatabaseAutoCreateNewForm').show();
								$('#emailRegistrantModal').modal('show');
							}
						}
					}
				}
			});
			return false;
		});

		$('#emailDatabaseConfirm').on('click', function () {
			var currentId = $('#emailRegistrantModal').data('responseid');
			var model = {
				responseId: currentId,
                content: $('#emailDatabaseTextBlurb').val()
			};
			$.ajax({
				url: '/formsapi/emailregistrant',
				type: 'POST',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(model),
				cache: false,
				success: function (data) {
                    if (data.success)
                        bootbox.alert('Database has been emailed.');
					else
                        bootbox.alert(data.message);
				}
			});
			$('#emailRegistrantModal').modal('hide');
		});

		$('#requestNextSeasonFormConfirm').on('click', function () {
			var model = {
				organisationFormId: $('#OrganisationFormId').val()
			};
			$.ajax({
				url: '/formsapi/requestnewform',
				type: 'POST',
				contentType: 'application/json; charset=utf-8',
				data: JSON.stringify(model),
				cache: false,
				success: function (data) {
					if (data.success) {
						window.scrollTo(0, 0);
						$('#formRequested').show('highlight', { color: '#FF42EC' }, 1500);
						setTimeout(function () {
							$('#formRequested').slideUp(1000);
						}, 5500);
					}
				}
			});

			$('#requestNextSeasonForSuperformModal').modal('hide');
        });

        $('.nrdstatus').click(function () {
            var btn = $(this);
            var icon = btn.find('i');
            var loadingClasses = 'fa-spinner fa-spin';
            var formResponseId = $(this).data('formresponseid');
            var parent = btn.parent(".nrdstatus-wrapper");

            if (!btn.hasClass('disabled')) {
                btn.addClass('disabled');
                icon.addClass(loadingClasses);

                $.ajax('/dashboard/forms/UpdateNrdStatus',
                    {
                        type: 'POST',
                        data: { formResponseId: formResponseId }
                    }
                ).done(function (response) {
                    icon.removeClass(loadingClasses);
                    icon.height(icon.height()); // IE FIX
                    if (response.success) {
                        if (response.overseasClearanceRequired) {
                            btn.removeClass('btn-success');
                            btn.removeClass('nrdstatus');
                            btn.removeClass('disabled');
                            btn.addClass('btn-danger');
                            icon.removeClass("fa-plus");
                            icon.html('!');
                            parent.prop('title', 'Overseas clearance required. Please contact your Provincial Union');
                            btn.parents('tr').find('.nrd-status-text').html('Pending');
                        }
                        else {
                            btn.addClass('btn-disabled');
                            btn.addClass('nrdstatus-locked');
                            icon.removeClass("fa-plus");
                            icon.addClass("fa-check");
                            parent.prop('title', 'Approved');
                            btn.parents('tr').find('.nrd-status-text').html('Active');
                        }
                    }
                    else if (response.customPrompt) {
                        btn.removeClass('disabled');
                        bootbox.alert(response.customPrompt);
                    }
                    else {
                        btn.removeClass('disabled');

                        if (response.promptTransfer) {

                            formAdmin.prompt(response.error, 'Request Transfer', 'Cancel', function (result) {
                                console.log('This was logged in the callback: ' + result);

                                if (!result)
                                    return;

                                bootbox.alert(response.transferConfirmationMessage);

                                sportsground.ui.loadingFullScreen();
                                $.ajax('/dashboard/forms/TransferNrdRegistration',
                                    {
                                        type: 'POST',
                                        data: { formResponseId: formResponseId, existingNrdRegistrationId: response.existingNrdRegistrationId }
                                    }).done(function (response) {

                                        if (!response.success) {
                                            bootbox.alert(response.message);
                                        } else {
                                            location.reload();
                                        }
                                    });

                            });
                        }
                        else if (response.overseasClearanceProblem) {
                            bootbox.alert('There was a problem updating the NRD database. ' + response.error
                                , function () {
                                    window.location.search += '?reloadNrd=true';
                                }
                            );
                        }
                        else {
                            bootbox.alert('There was a problem updating the NRD database. ' + response.error);
                        }
                    }
                });
            }
        });

        $('.sporty-status').click(function () {
            var btn = $(this);
            var icon = btn.find('i');
            var loadingClasses = 'fa-spinner fa-spin';
            var formResponseId = $(this).data('formresponseid');
            
            if (!btn.hasClass('disabled')) {
                btn.addClass('disabled');
                icon.addClass(loadingClasses);
                icon.html('');

                $.ajax('/dashboard/forms/ActivateSportyRegistration',
                    {
                        type: 'POST',
                        data: { formResponseId: formResponseId }
                    }
                ).done(function(response) {
                    icon.removeClass(loadingClasses);
                    icon.height(icon.height()); // IE FIX
                    btn.removeClass('disabled');
                    if (response.success) {
                        formAdmin.setSportyStatus('response_' + formResponseId, 1);
                        btn.attr('title', '');
                    }
                    else if (response.transferMessage) {
                        
                       formAdmin.prompt(response.transferMessage, 'Request Transfer', 'Cancel', function (result) {
                            console.log('This was logged in the callback: ' + result);

                            if (!result)
                                return;

                            bootbox.alert(response.transferConfirmationMessage);

                            btn.addClass('disabled');
                            icon.addClass(loadingClasses);    
                            $.ajax('/dashboard/forms/RequestSportyTransfer',
                                {
                                    type: 'POST',
                                    data: { requestingResponseId: formResponseId, existingResponseId: response.existingResponseId }
                                }).done(function (response) {
                                    icon.removeClass(loadingClasses);
                                    icon.height(icon.height()); // IE FIX
                                    if (response.success) {
                                        formAdmin.setSportyStatus('response_' + formResponseId, 6);
                                    } else {
                                        btn.removeClass('disabled');
                                        bootbox.alert(response.message);
                                    }
                            });

                        });
                    }
                    else if ( response.isRedFlagged) {
                        btn.addClass('btn-danger');
                        btn.attr('title', 'Player has red flag. Click button to retry approval once resolved');
                        icon.removeClass('fa-plus');
                        icon.html('!');
                        bootbox.alert(response.error);
                    }
                    else {
                            btn.removeClass('disabled');
                            bootbox.alert('There was a problem updating the registration. ' + response.error);
                        }
                });
            }
        });
    },



	registerHandlebarsPartials: function () {
		Handlebars.registerPartial('transaction', $('#hbTemplateTransaction').html());
	}
};
;
var forms = extend(sportsground, 'sportsground.forms');

forms.deletedRegistrantFields = [];
forms.deletedSections = [];
forms.deletedQuestions = [];
forms.deletedConditions = [];
forms.deletedQuestionOptions = [];

forms.initializeNewForm = function () {
    $(function () {
        Handlebars.registerHelper("uid", function () {
            return '_' + Math.random().toString(36).substr(2, 9);
        });
        Handlebars.registerHelper("booleantochecked", function (boolValue) {
            if (boolValue)
                return "checked";
            return "";
        });
        Handlebars.registerHelper('questiontype', function (questionType) {
            var questionTypes = [
                [1, "SingleLineText", "text"],
                [2, "MultiLineText", "text"],
                [3, "SingleChoice", "option"],
                [4, "MultiChoice", "option"],
                [5, "YesNo", "bool"],
                [16, 'DateOfBirth', "text"],
                [6, 'Date', "text"],
                [7, 'Address', "address"],
                [11, 'Email', "text"],
                [9, 'GradeList', "grade"],
                [10, 'TeamList', "team"],
                [13, "Gender", "text"],
                [25, "Document", "text"],
                [30, "AddText", "label"],
                [12, "Checkbox", "bool"],
                [26, "DriversLicence", "text"]
            ];

            var ret = '';
            for (var i = 0; i < questionTypes.length; i++) {
                var selectedVal = "";
                if (parseInt(questionType) === questionTypes[i][0]) {
                    selectedVal = "selected";
                }
                ret += "<option " + selectedVal + " value='" + questionTypes[i][0] + "' data-group='" + questionTypes[i][2] + "'>" + questionTypes[i][1] + "</option>";
            }
            return new Handlebars.SafeString(ret);
        });

        // only register the handlebar partial if the element can be found
        if ($('#question-template').length) {
            Handlebars.registerPartial("question", $('#question-template').html());
        }
        if ($('#question-options-template').length) {
            Handlebars.registerPartial("questionoptions", $('#question-options-template').html());
        }
        if ($('#question-option-template').length) {
            Handlebars.registerPartial("questionoption", $('#question-option-template').html());
        }
        if ($('#static-question-template').length) {
            Handlebars.registerPartial("staticquestion", $('#static-question-template').html());
        }
        if ($('#static-question-options-template').length) {
            Handlebars.registerPartial("staticquestionoptions", $('#static-question-options-template').html());
        }
        if ($('#static-question-option-template').length) {
            Handlebars.registerPartial("staticquestionoption", $('#static-question-option-template').html());
        }
        if ($('#section-condition-template').length) {
            Handlebars.registerPartial("condition", $('#section-condition-template').html());
        }

        Handlebars.registerHelper("conditionaction", function (action) {
            if (action == 1)
                return new Handlebars.SafeString('checked');

            return '';
        });

        Handlebars.registerHelper("conditionQuestionOptions", function (questionId) {

            var optionValues = [];
            $('.div-form-section').each(function () {
                var sectionName = $(this).find('.input-sectionName').val();
                $('.question', this).each(function () {
                    var currentQuestionId = $(this).data('id');
                    var selected = questionId == currentQuestionId ? 'selected' : '';
                    var optionValue = sectionName + ' - ' + $(this).find('.question-questiontext').val();
                    optionValues.push({ qid: currentQuestionId, optionText: optionValue, selected: selected });
                });
            });
            var options = '<option value="-1"> -- choose question -- </option>';
            $.each(optionValues, function (valueIndex) {
                options += '<option data-questionid="' + this.qid + '" value="' + valueIndex + '" ' + this.selected + '>' + this.optionText + '</option>';
            });

            // init popover
            //conditionsContainer.find('.condition-info-popover').popover({ html: true });
            return new Handlebars.SafeString(options);
        });


        $(document).on('click', '.btn-add-question', function () {
            var questionsDiv = $(this).closest('.div-form-section').find('.div-questions');
            forms.addQuestion(questionsDiv);
            return false;
        });

        $(document).on('change', '.question-questiontype', function () {
            // if we have a gradelist or teamlist, ensure no others
            if ($(this).val() == 9 || $(this).val() == 10) {
                var value = $(this).val();
                var otherQuestionsOfSameType = $('.question-questiontype option:selected[value="' + value + '"]');
                if (otherQuestionsOfSameType.length > 1) {
                    $(this).val(1);
                    var questionTypeString;
                    if (value == 9)
                        questionTypeString = 'Grade List';
                    else
                        questionTypeString = 'Team List';
                    bootbox.alert('<h3>Only 1 ' + questionTypeString + ' allowed on page</h3><p>Sorry, you can only have one ' + questionTypeString + ' on a form. Please remove the other question that is of the ' + questionTypeString + ' type or change its type and try again.</p>');
                    return false;
                }
            }
            forms.changeQuestionType($(this).closest('.question'), $(this).val());
        });

        $(document).on('click', '.btn-remove-section', function () {
            var section = $(this).closest('.div-form-section');
            if (section.data('id') != 0)
                forms.deletedSections.push(section.data('id'));

            section.remove();
        });

        $(document).on('click', '.btn-remove-question', function () {
            var question = $(this).closest('.question');
            var id = question.data('id');

            if ($('[data-selected-questionid=' + id + ']').length > 0) {
                bootbox.confirm('There is a condition linked to this question. If you delete this question the condition will be removed. Are you sure?',
                    function (e) {
                        if (e && id != 0) {
                            forms.deletedQuestions.push(id);
                            question.find(".btn-remove-question-option").trigger('click');//Remove any selection options
                            question.remove();
                            $('[data-selected-questionid=' + id + ']').closest('.condition').find('.btn-remove-condition').trigger('click'); //Remove conditions
                        }
                    });
                return false;
            }

            if (id != 0)
                forms.deletedQuestions.push(id);

            question.find(".btn-remove-question-option").trigger("click");//Remove any selection options
            question.remove();
            return false;
        });

        $(document).on('click', '.btn-remove-question-option', function () {
            var questionOption = $(this).parent().parent();
            if (questionOption.data('id') != 0)
                forms.deletedQuestionOptions.push(questionOption.data('id'));

            questionOption.remove();
            return false;
        });

        $(document).on('click', '.btn-add-question-option', function () {
            forms.addQuestionOption($(this).parent().find('.question-options-sortable'));
            return false;
        });

        $(document).on('click', '.btn-add-condition', function () {
            var conditionsDiv = $(this).closest('.div-form-section').find('.div-conditions');
            forms.addCondition(conditionsDiv);
            $(this).attr('disabled', '');
            return false;
        });

        $(document).on('click', '.btn-remove-condition', function () {
            $(this).closest('.div-form-section').find('.btn-add-condition').removeAttr('disabled');

            var condition = $(this).closest('.condition');

            // hide popover in case it is showing
            condition.find('.condition-info-popover').popover('hide');

            if (condition.data('id') != 0)
                forms.deletedConditions.push(condition.data('id'));

            condition.remove();
            return false;
        });

        var hasSuperform = $('#hdnSuperFormId').length > 0 && $('#hdnSuperFormId').val().length > 0;
        if (hasSuperform)
            forms.loadSuperForm($('#hdnSuperFormId').val());
        if ($('#hdnFormId').length > 0 && $('#hdnFormId').val().length > 0) {
            forms.loadForm($('#hdnFormId').val());
        }
        else if (!hasSuperform) {
            // This is a new Form at this point
            forms.addRequiredRegistrantFields();
            forms.syncAvailableRegistrantFields();
        }

        var hasRegistrantForm = $('#hdnRegistrantFormId').length > 0 && $('#hdnRegistrantFormId').val().length > 0;
        if (hasRegistrantForm)
            forms.loadRegistrantForm($('#hdnRegistrantFormId').val());

        $('#registrantFields').sortable({
            cancel: 'input',
            handle: '.registrant-field-drag'
        });

        $(document).on('click', '.remove-registrant-field', function () {
            var registrantField = $(this).closest('.registrant-field');
            if (registrantField.data('questionid') != 0)
                forms.deletedRegistrantFields.push(registrantField.data('questionid'));
            ///$('#registrantFieldSelect').append('<option')
            //.remove();
            registrantField.remove();
            forms.syncAvailableRegistrantFields();
            return false;
        });

        $("#btnAssignToFolderAndSaveForm").on('click', function () {
            var button = $(".btnSaveForm");
            forms.saveFormWithFolderId(button);
            return false;
        });

        $('#chkXeroAutoCreateInvoices').on('change', function () {
            if ( $(this).is(':checked') ) {
                $("#chkXeroAutoCreateContacts").prop("checked", "checked");
            }
            return false;
        });

        if ($('#hdnHasProductsEnabled').val() == 'true')
            forms.productsPreInit();
    });

}

forms.loadSuperForm = function (id) {
    $(".btnSaveForm").attr("disabled", true);
    if (!id) {
        $('#div_superformsections').html('');
        return;
    }
    $.ajax({
        type: 'GET',
        url: '/formservice/GetFormJson?id=' + id + '&isSuperForm=true',
        cache: false,
    }).done(function (result) {
        $('#div_superformsections').html('');
        //$('#hdnSuperFormEditable').val(result.UsersCanAddToSections);
        var sectionTemplate = Handlebars.compile($('#static-section-template').html());
        for (var sectionIndex = 0; sectionIndex < result.Sections.length; sectionIndex++) {
            var model = result.Sections[sectionIndex];
            model.firstSection = sectionIndex == 0;
            $('#div_superformsections').append(sectionTemplate(model));
        }
        $(".btnSaveForm").attr("disabled", false);
    });
}

forms.loadRegistrantForm = function (id) {
    $(".btnSaveForm").attr("disabled", true);
    $.ajax({
        type: 'GET',
        url: '/formservice/GetRegistrantFormJson?id=' + id,
        cache: false,
    }).done(function (result) {
        var registrantDomObject = $('.registrant-details');
        var registrantFieldDiv = $('#registrantFields', registrantDomObject);
        var template = Handlebars.compile($('#registrant-field-template').html());
        for (var i = 0; i < result.length; i++) {
            registrantFieldDiv.append(template(result[i]));
        }
        registrantDomObject.show();
        forms.syncAvailableRegistrantFields();
        $(".btnSaveForm").attr("disabled", false);
    });
};

forms.loadForm = function (id) {
    $(".btnSaveForm").attr("disabled", true);
    $.ajax({
        type: 'GET',
        url: '/formservice/GetFormJson?id=' + id,
        cache: false
    }).done(function (result) {
        $('#div_formsections').html('');
        var sectionTemplate = Handlebars.compile($('#section-template').html());
        for (var sectionIndex = 0; sectionIndex < result.Sections.length; sectionIndex++) {
            var model = result.Sections[sectionIndex];
            model.firstSection = sectionIndex == 0;
            $('#div_formsections').append(sectionTemplate(model));
        }

        forms.loadConditions();

        $('#div_formsections').sortable({
            cancel: 'input',
            handle: '.section-drag',
            update: function () {
                forms.loadConditions();
            }
        });

        $('.div-questions').sortable({
            cancel: 'input',
            handle: '.question-drag'
        });

        $('.question-options-sortable').sortable({
            cancel: 'input',
            handle: '.option-drag'
        });

        $('.condition-action').bootstrapSwitch();
        $('.condition-info-popover').popover({ html: true });
        $('#EmailFromAddress').keyup(function () {
            $('#chkSendEmailToEmailFromAddress').prop('checked', true);
        });

        forms.preventExistingQuestionsChangingTypes();

        $(".btnSaveForm").attr("disabled", false);
    });
};

forms.changeQuestionType = function (questionDiv, questionType) {
    // If it is a questionType with Options, assert options select HTML exists
    if ((questionType == 3 || questionType == 4) && questionDiv.find('.question-options').length == 0)
        forms.addQuestionOptionsContainer(questionDiv);
    // Otherwise make sure it doesn't
    else if (questionType != 3 && questionType != 4)
        questionDiv.find('.question-options').remove();
}

forms.addSection = function () {
    var data = {
        Questions: undefined,
        Id: 0,
        Name: ''
    };
    var templateHtml = $('#section-template').html();
    var template = Handlebars.compile(templateHtml);
    var html = template(data);
    $('#div_formsections').append(html);
    $('#div_formsections').find('.div-form-section:last').find('.div-questions').sortable({
        cancel: 'input',
        handle: '.question-drag'
    });

    $.validator.unobtrusive.parseDynamicContent('.div-form-section:last');
}

forms.addQuestion = function (questionsContainer) {
    var data = {
        QuestionOptions: undefined,
        Id: 0,
        QuestionText: '',
        HasOptionsSection: false
    };
    var templateHtml = $('#question-template').html();
    var template = Handlebars.compile(templateHtml);
    var html = template(data);
    questionsContainer.append(html);

    // attach validation
    var questionId = $(html.trim()).attr('id');
    $.validator.unobtrusive.parseDynamicContent('#' + questionId);

    //focus
    $('#' + questionId).find('.question-questiontext').focus();
}

forms.addQuestionOption = function (questionOptionsContainer) {
    var data = {
        Id: 0,
        OptionText: ''
    };
    var templateHtml = $('#question-option-template').html();
    var template = Handlebars.compile(templateHtml);
    var html = template(data);
    questionOptionsContainer.append(html);

    questionOptionsContainer.find('.question-option-input').focus();
}

forms.addQuestionOptionsContainer = function (questionContainer) {
    var parent = questionContainer.find('.type-option-container');
    var data = {
        QuestionOptions: undefined
    };
    var templateHtml = $('#question-options-template').html();
    var template = Handlebars.compile(templateHtml);
    var html = template(data);
    parent.append(html);

    questionContainer.find('.question-options-sortable').sortable({
        cancel: 'input',
        handle: '.option-drag'
    });
}

forms.loadConditions = function () {

    $('.div-form-section').each(function () {
        var optionValues = [];
        var prevSections = $($(this).prevAll().get().reverse());
        prevSections.each(function () {
            var sectionName = $(this).find('.input-sectionName').val();
            $('.question', this).each(function () {
                var questionId = $(this).data('id');
                var optionValue = sectionName + ' - ' + $(this).find('.question-questiontext').val();
                optionValues.push({ qid: questionId, optionText: optionValue });
            });
        });

        var options = '<option value="-1"> -- choose question -- </option>';
        $.each(optionValues, function (valueIndex) {
            options += '<option data-questionid="' + this.qid + '" value="' + valueIndex + '" >' + this.optionText + '</option>';
        });

        $(this).find('.condition-question').each(function () {
            $(this).children().remove();
            $(this).append(options);
            var selectedQuestionId = $(this).data('selected-questionid');
            $(this).find('[data-questionid=' + selectedQuestionId + ']').prop('selected', true);
        });
    });
    $(".btn-add-condition").removeClass("first-condition");
    $(".div-form-section:first").find(".btn-add-condition").addClass("first-condition");
    $(".div-form-section:first").find(".btn-remove-condition").trigger("click");
}

forms.addCondition = function (conditionsContainer) {
    var data = {
        Id: 0,
        QuestionId: 0,
        ConditionValue: ''
    };
    var templateHtml = $('#section-condition-template').html();
    var template = Handlebars.compile(templateHtml);
    var html = template(data);
    conditionsContainer.append(html);

    conditionsContainer.find('.condition-action').bootstrapSwitch();

    var questionsDropdown = conditionsContainer.find('.condition-question');


    var optionValues = [];
    var prevSections = $(conditionsContainer.closest('.div-form-section').prevAll().get().reverse());
    prevSections.each(function () {
        var sectionName = $(this).find('.input-sectionName').val();
        $('.question', this).each(function () {
            var questionId = $(this).data('id');
            var optionValue = sectionName + ' - ' + $(this).find('.question-questiontext').val();
            optionValues.push({ qid: questionId, optionText: optionValue });
        });
    });
    questionsDropdown.html('');
    questionsDropdown.append('<option value="-1"> -- choose question -- </option>');
    $.each(optionValues, function (valueIndex) {
        questionsDropdown.append('<option data-questionid="' + this.qid + '" value="' + valueIndex + '">' + this.optionText + '</option>');
    });

    // Attach validation
    var conditionId = $(html.trim()).attr('id');
    $.validator.unobtrusive.parseDynamicContent('#' + conditionId);

    // init popover
    conditionsContainer.find('.condition-info-popover').popover({ html: true });

    ////focus
    $('#' + conditionId).find('.condition-question').focus();
};

forms.clearValidation = function (form) {
    var $validator = form.validate();

    $(form).find(".has-error").removeClass("has-error");
    $(form).find(".field-validation-error").children().remove();
};

forms.isEmailValid = function (email) {

    if (email == undefined || email === "")
        return true;

    return sportsground.utils.validateMultipleEmailAddress(email);
};

/*
 * Checks if the question text within each form section is unique.
 *
 * This ideally should be part of the standard form validation,
 * but I was unable to get that to work. DR20170228
 */
forms.isUnique = function () {
    var isUnique = true;
    $('.div-form-section').each(function (index, formSection) {
        var values = [];
        $('.question', formSection).each(function (index, question) {
            var value = $('.question-questiontext', question).val().toLowerCase();
            if ($.inArray(value, values) >= 0) {
                $('.form-group', question).removeClass('has-success').addClass('has-error');
                isUnique = false;
            } else {
                values.push(value);
            }
        });
    });
    if (!isUnique) {
        bootbox.alert("You are unable to have the same field name on the form more than once.");
        return false
    }
    return isUnique;
};

/*
 * Helper function that checks if a form is valid.
 * The check includes the isUnique check above.
 */
forms.isValid = function (form) {
    return forms.isUnique() && form.valid();
};

forms.saveForm = function (button) {
    

    var form = $('#formMain');
    if (!forms.isValid(form)) {
        $('html, body').animate({
            scrollTop: $(".has-error:first").offset().top
        }, 2000);
        $(button).prop("disabled", false);
        return false;
    }

    if (($('#chkDeclineRegistrationIfNoPayment').is(':checked')) && ($('#products tr').length == 0)) {
        bootbox.alert({
            title: 'Unable to proceed',
            message: 'Please add a product or de-select<br>"Decline Registration if Payment Unsuccessful"'
        });
        $(button).removeAttr("disabled");
        return false;
    }

    if ($('#chkAllowPhotoIdCard').is(':checked') && ($("select.question-questiontype :selected[value=16]").length == 0 && $('div[data-field="DateOfBirth"]').length == 0)) {
        bootbox.alert({
            title: 'Unable to proceed',
            message: 'Please add a Date of Birth question field to enable PhotoCards for this form.'
        });
        $(button).removeAttr("disabled");
        return false;
    }

    var unspecifiedAccountCodes = $('td.product-xero-account-code').filter(function() {
        return $(this).text() === ''
    }).length;

    if ($('#chkXeroAutoCreateInvoices').is(':checked') && unspecifiedAccountCodes > 0 && $("select#XeroDefaultAccountCode :selected[value='']").length == 1 ) {
        bootbox.alert({
            title: 'Unable to proceed',
            message: 'You must select an Account Code for your products to create an invoice in Xero.'
        });
        $(button).removeAttr("disabled");
        return false;
    }

    var errors = {};
    var $validator = form.validate();
    forms.clearValidation(form);

    if (CKEDITOR.instances.IntroText.getData().length > 10000) {
        errors.IntroText = "- Length cannot exceed 10000 characters";
    }

    if (CKEDITOR.instances.TermsAndConditions.getData().length > 10000) {
        errors.TermsAndConditions = "- Length cannot exceed 10000 characters";
    }

    if (Object.keys(errors).length > 0) {
        $validator.showErrors(errors);
        $(button).prop("disabled", false);
        return false;
    }

    if (!forms.validateProducts()) {
        $(button).prop("disabled", false);
        return false;
    }

    if ($("#chkXeroAutoCreateInvoices").is(':checked') ) {
        $('#chkXeroAutoCreateContacts').prop('checked', 'checked');
        $('#chkXeroAutoCreateContacts').prop('disabled', 'disabled');
    }

    var addingForm = $("#assignFormToFolderOrCopyFormModal").length > 0;

    if (addingForm) { //we dont want to update folder on edit form
        $("#dvAddFolderFromModal").addClass('hidden');
        $("#copyFormConfirm").addClass('hidden');
        $("#dvCopyForm").addClass('hidden');
        $("#btnAssignToFolderAndSaveForm").removeClass('hidden');
        $("#assignFormToFolderOrCopyFormModal").find('#myModalLabel').html("Save Form");
        $("#assignFormToFolderOrCopyFormModal").modal('show');
    }
    else {
        forms.saveFormWithFolderId(button); 
    }

    return false;
}

forms.saveFormWithFolderId = function (button) {
    $(button).button("loading");
    $(button).prop("disabled", true);

    var addingForm = $("#assignFormToFolderOrCopyFormModal").length > 0;

    if (addingForm) {
        $("#btnAssignToFolderAndSaveForm i").addClass('fa-spinner');
        $("#btnAssignToFolderAndSaveForm").prop("disabled", true);
    }

    //If a grade list is a question type, and no grades have been checked. Check them
    if ($("select.question-questiontype :selected[value=9]").length > 0 && $('.grade:checked').length == 0 && $("#IsTeamTeamCreationForm").length === 0) {
        $('input.grade').prop("checked", "checked");
    }

    var model = {
        DeletedSections: forms.deletedSections,
        DeletedQuestions: forms.deletedQuestions,
        DeletedQuestionOptions: forms.deletedQuestionOptions,
        DeletedSectionConditions: forms.deletedConditions,
        DeletedRegistrantFields: forms.deletedRegistrantFields,
        RegistrantDetailsSectionTitle: $('#input-registrant-details-sectionTitle').val(),
        RegistrantFields: $.map($('.registrant-field'), function (field, fieldIndex) {
            var $field = $(field);
            return {
                QuestionId: $field.data('questionid'),
                FieldName: $field.data('field'),
                QuestionLabel: $field.find('.question-label').val(),
                SortOrder: fieldIndex + 1,
                IsRequired: $field.find('.chk-required').is(':checked')
            }
        }),
        FormId: $('#hdnFormId').val(),
        RegistrantFormId: $('#hdnRegistrantFormId').val(),
        Name: $('#uxFormName').val(),
        SendEmail: $('#chkSendEmail').is(':checked'),
        VisibleInMobileApp: $('#chkVisibleInMobileApp').is(':checked'),
        EmailFromAddress: $('#EmailFromAddress').val(),
        SendEmailToEmailFromAddress: false,  //$('#chkSendEmailToEmailFromAddress').is(':checked'),
        EmailCopyOfRegistrationConfirmationToAddress: $("#EmailCopyOfRegistrationConfirmationToAddress").val(),
        StartDate: $('#DisplayForStartDate').val(),
        EndDate: $('#DisplayForEndDate').val(),
        AllowRegistrantEdit: $('#chkAllowRegistrantEdit').is(':checked'),
        AllowPhotoIdCard: $('#chkAllowPhotoIdCard').is(':checked'),
        NextSeasonFormId: $('#NextSeasonFormId').val(),
        XeroAutoCreateContacts: $('#chkXeroAutoCreateContacts').is(':checked'),
        XeroAutoCreateInvoices: $('#chkXeroAutoCreateInvoices').is(':checked'),
        XeroDefaultAccountCode: $('#XeroDefaultAccountCode').val(),
        XeroDefaultTaxType: $('#XeroDefaultTaxType').val(),
        IntroText: CKEDITOR.instances.IntroText.getData(), // $('#IntroText').val(),
        TermsAndConditions: CKEDITOR.instances.TermsAndConditions.getData(), // $('#TermsAndConditions').val(),
        SportId: $('#SportId').val(),
        SeasonId: $('#SeasonId').val(),
        GradeIds: $.map($('.grade:checked'), function (g, gi) {
            return $(g).val();
        }),
        Sections: $.map($('#div_formsections .div-form-section'), function (s, si) {
            var section = $(s);
            return {
                Id: section.data('id'),
                Name: section.find('.input-sectionName').val(),
                SortOrder: si + 1,
                Conditions: [sportsground.forms.buildConditionModel(section.find('.condition'))],
                Questions: $.map(section.find('.question'), function (q, qi) {
                    return {
                        Id: $(q).data('id'),
                        QuestionText: $(q).find(".question-questiontext").val(),
                        QuestionType: $(q).find('.question-questiontype').val(),
                        SortOrder: qi + 1,
                        IsAdminOnly: $(q).find('.chk-adminonly').is(':checked'),
                        IsRequired: $(q).find('.chk-required').is(':checked'),
                        QuestionOptions: $.map($(q).find('.question-question-option'), function (qo, qoi) {
                            if ($(qo).find('input:first').val().length <= 0) return;
                            return {
                                Id: $(qo).data('id') || 0,
                                OptionText: $(qo).find('input:first').val(),
                                SortOrder: qoi + 1
                            };
                        })
                    };
                })
            };
        }),
        AcceptCreditCardOnly: $('#chkAcceptCreditCardOnly').is(':checked'),
        DeclineRegistrationIfNoPayment: $('#chkDeclineRegistrationIfNoPayment').is(':checked'),
        AcceptPeriodicPayment: $('#chkAcceptPeriodicPayment').is(':checked'),
        NumberOfPayments: $('#NumberOfPayments').val(),
        PaymentFrequency: $('#PaymentFrequency').val(),
        EmailCopyOfTransactionEmailToAddresses: $('#EmailCopyOfTransactionEmailToAddresses').val(),
        OrganisationFormContainerId: addingForm ? $("#uxFormFoldersArea li.active").data('id') : $("#hdnOrganisationFormContainerId").val(),
        Products: $.map($('#products .product'), function (p, idx) {
            var product = $(p);
            return {
                Id: product.data('id'),
                Name: product.find('.product-name').text(),
                Price: product.find('.product-price').text(),
                MaxQuantity: product.find('.product-quantity').text(),
                AllowPartialPayments: product.find('.product-allow-partial-payments').is(':checked'),
                IsRequired: product.find('.product-is-required').is(':checked'),
                XeroAccountCode: product.find('.product-xero-account-code').text(),
                XeroTaxRate: product.find('.product-xero-tax-rate').text(),
                XeroTrackingName1: product.find('.product-xero-tracking-name1').text(),
                XeroTrackingOption1: product.find('.product-xero-tracking-option1').text(),
                XeroTrackingName2: product.find('.product-xero-tracking-name2').text(),
                XeroTrackingOption2: product.find('.product-xero-tracking-option2').text(),
                SortOrder: idx
            }
        })
    };

    $.ajax({
        type: 'POST',
        cache: false,
        url: document.location,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(model)
    }).done(function (result) {
        if (result.success) {
            window.location.href = '/dashboard/forms?folderid=' + result.folderId; // = window.location.pathname.replace("/new", "");
        }
        else {
            bootbox.alert({
                title: 'Unable to proceed',
                message: result.error
            });
           
            $(button).prop('disabled', false);
            $(button).html('<i class="glyphicon glyphicon-floppy-disk"></i> Save Form');

            $("#btnAssignToFolderAndSaveForm i").removeClass('fa-spinner');
            $("#btnAssignToFolderAndSaveForm").prop("disabled", false);

            return false;
        }
    });
    return false;
}

forms.buildConditionModel = function (conditionContainer) {
    if (conditionContainer.length == 0)
        return null;

    var section = conditionContainer.closest('.div-form-section');

    return {
        QuestionIndex: parseInt(conditionContainer.find('.condition-question').val()),
        Comparer: '1', // Enum Value for EQUALS (currently the only option so OK to hardcode for performance)
        Value: conditionContainer.find('.condition-value').val(),
        Action: conditionContainer.find('.condition-action').is(':checked') ? 1 : 0, // ConditionAction enum, 1 for show, 0 for hide
        SectionId: section.data('id'),
        SectionName: section.find('.input-sectionName').val()
    };
}

forms.syncAvailableRegistrantFields = function () {
    // Populate list with all available fields
    $('#registrantFieldSelect option').remove();
    var availableFields = JSON.parse($('#hdnAvailableRegistrantFields').val());
    for (var i = 0; i < availableFields.length; i++)
        $('#registrantFieldSelect').append('<option value="' + availableFields[i].name + '">' + availableFields[i].display + '</option>');

    // Remove used fields
    $.each($('.registrant-field'), function (index, value) {
        var field = $(value);
        var selectList = $('#registrantFieldSelect');
        $('option[value="' + field.data('field') + '"]', selectList).remove();
    });

    // Disable if no more available fields
    if ($('#registrantFieldSelect option').length <= 0)
        $('#registrantFooter').hide();
    //$('#addRegistrantBtn').attr('disabled', 'disabled');
    else
        $('#registrantFooter').show();
    //$('#addRegistrantBtn').removeAttr('disabled');
};

forms.preventExistingQuestionsChangingTypes = function () {
    $(".question-questiontype").each(function (index, el) {
        var selectedGroup = $(el).find(":selected").data("group");
        $(el).find("option[data-group!='" + selectedGroup + "']").remove();
    });
}

forms.addRequiredRegistrantFields = function () {
    var template = Handlebars.compile($('#registrant-field-template').html());
    var model = {
        FieldName: "FirstName",
        FieldDisplay: "First Name",
        IsRequired: true,
        Fixed: true,
        QuestionLabel: "First Name",
        QuestionId: 0
    };
    $('#registrantFields').append(template(model));
    model = {
        FieldName: "LastName",
        FieldDisplay: "Last Name",
        IsRequired: true,
        Fixed: true,
        QuestionLabel: "Last Name",
        QuestionId: 0
    };
    $('#registrantFields').append(template(model));
    model = {
        FieldName: "Email",
        FieldDisplay: "Email",
        IsRequired: true,
        Fixed: true,
        QuestionLabel: "Email",
        QuestionId: 0
    };
    $('#registrantFields').append(template(model));
};

$('#addRegistrantBtn').on('click', function () {
    var selectedOption = $('#registrantFieldSelect').find(":selected");
    var model = {
        FieldName: selectedOption.val(),
        FieldDisplay: selectedOption.text(),
        QuestionLabel: selectedOption.text(),
        QuestionId: 0
    };
    var template = Handlebars.compile($('#registrant-field-template').html());
    $('#registrantFields').append(template(model));
    forms.syncAvailableRegistrantFields();
    return false;
});

forms.productsPreInit = function () {
    if ($('#hdnFormId').length > 0 && $('#hdnFormId').val().length > 0) {
        $.ajax({
            type: 'GET',
            url: '/formservice/GetFormProductsJson?id=' + $('#hdnFormId').val(),
            cache: false
        })
            .done(function (result) {
                var productTemplate = Handlebars.compile($('#product-template').html());
                for (var productIndex = 0; productIndex < result.length; productIndex++) {
                    $('#products').append(productTemplate(result[productIndex]));
                }
                forms.initProducts();

                $('#products').sortable({
                    cancel: 'input',
                    cursor: 'move',
                    axis: 'y',
                    handle: '.drag',
                    helper: fixWidthHelper
                });
            });
    }
    else {
        forms.initProducts();
    }
};

forms.initProducts = function () {
    // product settings for form
    var allowOnlinePayments = $('#chkAcceptPeriodicPayment').is(':checked');
    if (allowOnlinePayments)
        $('#productsPeriodicPaymentSettings').show();

    $('#chkAcceptPeriodicPayment').on('change', function () {
        if ($(this).is(':checked')) {
            $('#productsPeriodicPaymentSettings').slideDown();
        } else {
            $('#productsPeriodicPaymentSettings').slideUp();
            $('.product-allow-partial-payments, .product-allow-partial-payments').prop('checked', false);
        }
    });

    //show message if no products
    if ($('#products').html().length == 0) {
        $('#products').parent().hide();
        $('#noProductsNote').show();
    }
    else {
        $('#noProductsNote').hide();
        $('#products').parent().show();
    }

    $(document).on('click', '.product-edit', function () {
        var row = $(this).closest('tr');
        row.hide();
        var editRow = row.next();

        if (!$('#chkAcceptPeriodicPayment').is(':checked'))
            editRow.find('.product-allow-partial-payments').attr('disabled', 'disabled');
        else
            editRow.find('.product-allow-partial-payments').removeAttr('disabled');

        editRow.show();
        return false;
    });
    $(document).on('click', '.product-save', function () {
        var editRow = $(this).closest('tr');
        var savedRow = editRow.prev();
        var name = editRow.find('.product-edit-name').val();
        var price = editRow.find('.product-edit-price').val();
        var quantity = editRow.find('.product-edit-quantity').val();
        var xeroAccountCode = editRow.find('.product-edit-xero-account-code option:selected').val();
        var xeroTaxRate = editRow.find('.product-edit-xero-tax-rate option:selected').val();
        var xeroTrackingName1 = editRow.find('.product-edit-xero-tracking-name1').val();
        var xeroTrackingOption1 = editRow.find('.product-edit-xero-tracking-option1').val();
        var xeroTrackingName2 = editRow.find('.product-edit-xero-tracking-name2').val();
        var xeroTrackingOption2 = editRow.find('.product-edit-xero-tracking-option2').val();

        // validation:
        var errors = [];
        if (name.length == 0)
            errors.push('Product Name is Required');
        if (price.length == 0)
            errors.push('Price is Required');
        else if (!$.isNumeric(price))
            errors.push('Price must be a Number');
        //if (quantity.length == 0) //Removing for now but it could be re-enabled at a later
        //	errors.push('Maximum Quantity Required');
        if (!$.isNumeric(quantity))
            errors.push('Quantity Must be a Number');

        if (errors.length > 0) {
            var validationList = '<li>';
            validationList += errors.join('</li><li>');
            validationList += '</li>';
            $('#productValidationContainer').show();
            $('#productValidationList').html(validationList);
            return false;
        }

        // clear validation
        $('#productValidationList').html('');
        $('#productValidationContainer').hide();

        // copy data to actual row
        savedRow.find('.product-name').html(name);
        savedRow.find('.product-price').html(parseFloat(Math.round(price * 100) / 100).toFixed(2));
        savedRow.find('.product-quantity').html(quantity);
        savedRow.find('.product-allow-partial-payments').prop('checked', editRow.find('.product-allow-partial-payments').is(':checked'));
        savedRow.find('.product-is-required').prop('checked', editRow.find('.product-is-required').is(':checked'));
        savedRow.find('.product-xero-account-code').html(xeroAccountCode);
        savedRow.find('.product-xero-tax-rate').html(xeroTaxRate);
        savedRow.find('.product-xero-tracking-name1').html(xeroTrackingName1);
        savedRow.find('.product-xero-tracking-option1').html(xeroTrackingOption1);
        savedRow.find('.product-xero-tracking-name2').html(xeroTrackingName2);
        savedRow.find('.product-xero-tracking-option2').html(xeroTrackingOption2);

        editRow.hide();
        savedRow.show();

        return false;
    });
    $(document).on('click', '.product-cancel', function () {
        var row = $(this).closest('tr');
        row.hide();
        row.prev().show();
        return false;
    });
    $(document).on('click', '.product-delete', function () {
        var editRow = $(this).closest('tr');
        var savedRow = editRow.next();
        editRow.remove();
        savedRow.remove();

        //show message if no products
        if ($('#products tr').length == 0) {
            $('#products').parent().hide();
            $('#noProductsNote').show();
        }

        return false;
    });


};

forms.addProduct = function () {
    // validation:
    var errors = [];
    if ($('#newProductName').val().length == 0)
        errors.push('Product Name is Required');
    if ($('#newProductPrice').val().length == 0)
        errors.push('Price is Required');
    else if (!$.isNumeric($('#newProductPrice').val()))
        errors.push('Price must be a Number');
    //if (!$.isNumeric($('#newProductQuantity').val())) //Removing for now but it could be re-enabled at a later
    //	errors.push('Maximum Quantity Required');

    if (errors.length > 0) {
        var validationList = '<li>';
        validationList += errors.join('</li><li>');
        validationList += '</li>';
        $('#productValidationContainer').show();
        $('#productValidationList').html(validationList);
        return false;
    }

    var xeroEnabled = $('#XeroEnabled').val() === 'True';

    // Copy the available options for new items from the select lists at the top of the form.
    var xeroAccountCodes = [];
    $('#XeroDefaultAccountCode option').each(function () {
        xeroAccountCodes.push({ Value: $(this).val(), Text: $(this).text(), SelectedMarkup: "" });
    });

    var xeroTaxRates = [];
    $('#XeroDefaultTaxType option').each(function () {
        xeroTaxRates.push({ Value: $(this).val(), Text: $(this).text(), SelectedMarkup: "" });
    });


    // Create model and add row
    var data = {
        Name: $('#newProductName').val(),
        Price: parseFloat(Math.round($('#newProductPrice').val() * 100) / 100).toFixed(2),
        MaxQuantity: $('#newProductQuantity').val(),
        AllowPartialPayments: false,
        XeroEnabled: xeroEnabled,
        XeroAccountCodes: xeroAccountCodes,
        XeroTaxRates: xeroTaxRates
    };

    var templateHtml = $('#product-template').html();
    var template = Handlebars.compile(templateHtml);
    var html = template(data);
    $('#productValidationList').html('');
    $('#productValidationContainer').hide();
    $('#noProductsNote').hide();
    $('#products').parent().show();
    $('#products').append(html);

    $('#products').sortable({
        cancel: 'input',
        cursor: 'move',
        axis: 'y',
        handle: '.drag',
        helper: fixWidthHelper
    });

    // clear fields
    $('#newProductName').val('');
    $('#newProductPrice').val('');
    $('#newProductQuantity option:first').prop('selected', true);

    return false;
};

forms.validateProducts = function () {
    $('#productValidationList').html('');
    var numberOfPayments = parseInt($('#NumberOfPayments').val());
    var errors = [];
    $('#products .product').each(function (idx, p) {
        var $product = $(p);
        var price = parseFloat($product.find('.product-price').html());

        // if partial payments not selected, move along please
        //if (!$product.find('.product-allow-partial-payments').is(':checked')) {
        //	if (price < 10)
        //		errors.push('Sorry, unable to save. The minimum value for any individual online payment (including period payment instalments) is $10');
        //	return true;
        //}

        var individualPaymentAmount = price / numberOfPayments;
        if (decimalPlaces(individualPaymentAmount) > 2 && $('#chkAcceptPeriodicPayment').is(':checked')) {
            var name = $product.find('.product-name').text();
            errors.push('Sorry, unable to save. The price of $' + price + ' for ' + name + ' cannot be equally divided across ' + numberOfPayments + ' instalments. Please either disable periodic payments for this item or nominate another price');
        }
        //if (individualPaymentAmount < 10) {
        //	errors.push('Sorry, unable to save. The minimum value for any individual online payment (including period payment instalments) is $10');
        //}
    });

    if (errors.length == 0)
        return true;

    for (var i = 0; i < errors.length; i++) {
        $('#productValidationList').append('<li>' + errors[i] + '</li>');
    }
    $('#productValidationContainer').show();
    $('html, body').animate({
        scrollTop: $('#productValidationContainer').offset().top
    }, 2000);
    return false;
};

function decimalPlaces(num) {
    var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
    if (!match) { return 0; }
    return Math.max(
        0,
        // Number of digits right of decimal point.
        (match[1] ? match[1].length : 0)
        // Adjust for scientific notation.
        - (match[2] ? +match[2] : 0));
}

function fixWidthHelper(e, ui) {
    ui.children().each(function() {
        $(this).width($(this).width());
        $(this).css('border-bottom', 'crimson');
    });
    return ui;
}
;
var formRendering = extend(sportsground, 'sportsground.forms.rendering');

formRendering.coalesce = function () {

	for (var i = 0; i < arguments.length; i++) {
		var obj = $(arguments[i]);

		if (obj != null && obj.length > 0)
			return obj;
	}

	return [];
};

formRendering.init = function (id, container) {
	formRendering.id = id;
	formRendering.container = container;
	formRendering.registerHandlebarsHelpers();
	Handlebars.registerPartial("question", $('#question-template').html());
	formRendering.hbSectionTemplate = Handlebars.compile($('#section-template').html());

};

formRendering.removeFileHandler = function () {

	$(".remove-document").click(function (e) {
		$(this).siblings(".form-document").val();
		$(this).siblings(".form-document").show();
		$(this).hide();
		$(this).siblings("a").hide();
	});

};

formRendering.updateHeading = function (id, headingDomElement, callback) {
	var response = $.ajax({
		url: '/formservice/GetOrganisationFormName?id=' + id,
		type: 'GET',
		cache: false,
		contentType: 'application/json; charset=utf-8',
		success: function (data) {

			var parentWidget = formRendering.getParentWidget(headingDomElement);
			var elementsToHide = '.terms-and-conditions, .intro-text, .nzru-logo, .submit-button, #dvFormContainer, .requiredTextBlurb, .dvAcceptTermsCbContainer';

			if (data.success)
				headingDomElement.html(data.name);

            if (data.registrationClosed) {               
				parentWidget.find('.form-registrations-closed').show();
				parentWidget.find(elementsToHide).hide();
			}

			if (data.registrationNotStarted) {
				parentWidget.find('.form-not-started').show();
				parentWidget.find(elementsToHide).hide();
            }

            if (data.formDeleted) {
                parentWidget.find('.form-deleted').show();
                parentWidget.find(elementsToHide).hide();
            }

            var json = response.responseJSON;
            json.haltProcessing = (json.registrationClosed || json.registrationNotStarted);

            if (!json.haltProcessing && callback) {
                callback();
            }
		}
	});

	
};

formRendering.scrollTo = function (el) {
    if ($(el).length > 0) {
        $('html, body').animate({
            scrollTop: $(el).offset().top
        }, 500);
    }
}

formRendering.customValidationIsValid = function () {
	$("div.atleastonerequired").closest(".form-group").removeClass("has-error has-success ");
	//Validate 'atleastonerequired' for checkboxes
	var toReturn = true;

	$("div.atleastonerequired").each(function (index) {
        var div = $(this);

        if ( div.closest('fieldset').hasClass('hidden') ) {
            return true;
        }

        if (div.find("input[type=checkbox]:checked").length === 0) {
            div.closest(".form-group").addClass("has-error");
            toReturn = false;
        }
        else {
            div.closest(".form-group").addClass("has-success");
        }
    });

    $("div[data-questiontype='12']").each(function (index) {
        var div = $(this);
        if ( !div.find("input[type=checkbox]").hasClass('requiredCheckbox') || div.closest('fieldset').hasClass('hidden') ) {
            return true;
        }

        if (!div.find("input[type=checkbox]").is(':checked')) {
            div.removeClass("requiredCheckboxHasSuccess");
            div.addClass("requiredCheckboxHasError");
            toReturn = false;
        }
        else {
            div.removeClass("requiredCheckboxHasError");
            div.addClass("requiredCheckboxHasSuccess");
        }
    });

    var hasInvalidNumber = false;
    $('div[data-questiontype="15"]').each(function (index) {
        var div = $(this);
        if ( div.closest('fieldset').hasClass('hidden') ) {
            return true;
        }

        if (!formRendering.validateNumberFormat($(this).find('input'))) {
            toReturn = false;
            hasInvalidNumber = true;
        }
    });

    if (hasInvalidNumber)
        bootbox.alert("Enter only number in this field.");

	return toReturn;
}

formRendering.cmsFormLayoutInit = function (id, container, formLoadedCallback) {

	$(".submit-button").click(function (e) {
        if (!formRendering.customValidationIsValid()) {
            var firstElementWithError = $(".has-error").first();
            formRendering.scrollTo(firstElementWithError);
            e.preventDefault();
            return false;
        }
    });

	var formTitle = $('.form-title');
    formRendering.updateHeading($('#OrganisationFormId').val(), formTitle, formRendering.loadFormInit(id, container, formLoadedCallback));


};

formRendering.loadFormInit = function (id, container, formLoadedCallback) {

    formRendering.loadForm(id, container, formLoadedCallback);
    container.closest('form').ajaxForm(
        {
            beforeSubmit: function () {

                var form = container.closest('form');
                if (!form.valid() || !formRendering.customValidationIsValid())
                    return false;

                var hasTermsAndConditions = $('.dvAcceptTermsCb').is(':visible');
                if (hasTermsAndConditions && !$('.chkAcceptTerms').is(':checked')) {
                    $('.dvAcceptTermsCb').parent().addClass('has-error');
                    bootbox.alert('<h3>Terms and Conditions Apply</h3><p>Please accept the terms and conditions</p>');
                    return false;
                }

                if ($("body").hasClass("isnrdform"))
                    sportsground.ui.loadingNrdFullScreen();
                else
                    sportsground.ui.loadingFullScreen();

                $('.submit-button').button("loading");
                $('.submit-button').attr('disabled', 'disabled');
                return true;
            },
            success: function (data) {

                if (data.success) {
                    window.location = data.redirectUrl;
                }
                else if (data.success === false) {
                    sportsground.ui.loadingFullScreen(true);
                    if (data.message)
                        bootbox.alert(data.message);
                    else
                        bootbox.alert("I'm sorry but there was an issue. Please contact Sportsground support.");

                    $('.submit-button').button("reset");
                    $('.submit-button').removeAttr('disabled');
                }
            }
        }
    );

};

formRendering.getParentWidget = function (container) {
	var parentWidget = container.closest('body');

	if (container.closest('.widget').length > 0)
		parentWidget = container.closest('.widget');

	return parentWidget;
};

formRendering.loadForm = function (id, container, formLoadedCallback) {



	container.html('<div class="center-page"><div class="sporty-spinner"></div></div>');

	if (id == 0)
		return;

	formRendering.init(id, container);

	// load terms and conditions
	$.ajax({
		url: '/formservice/getformtermsandintro?id=' + id,
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
		cache: false,
		success: function (data, textStatus, xhr) {
			if (data.success) {
				var formContainer = container.parent();
                formContainer.find('.intro-text').html(data.introText);
				if (data.termsAndConditions) {
					formContainer.find('.terms-and-conditions').html('<h4 style="padding-top:10px">Terms & Conditions</h4>' + data.termsAndConditions);
				}
				if (data.termsAndConditions && data.termsAndConditions.length > 0) {
                    formContainer.find('.dvAcceptTermsCb').show();
                    $('.chkAcceptTerms').closest('label').addClass("site-style");
                }
			}
		}
	});

	var url = '/formservice/GetOrganisationFormJson?id=' + id;

    $.ajax({
        type: 'GET',
        url: url,
        cache: false
    })
        .done(function (result) {
            container.html('');
          
            var startDate, endDate, now = new Date();

            if (result.IsNrdForm) {
                $('body').addClass('isnrdform');
                $(".nzru-logo").show();
                $("#nrdRegistrationType").val(result.NrdRegistrationType);
            }

            // parse the start date
            if (result.StartDate && result.StartDate.length) {
                startDate = moment(result.StartDate).toDate();
                startDate.setHours(0, 0, 0, 0); // zero out the time
            }

            // parse the end date
            if (result.EndDate && result.EndDate.length) {
                endDate = moment(result.EndDate).toDate();
                endDate.setHours(23, 59, 59, 59); // set hours to midnight tonight like the backend comparison is doing
            }

            var parentWidget = formRendering.getParentWidget(container);

            var editingForm = sportsground.utils.getQueryStringParameterByName('so') === "0" || 
                                sportsground.utils.getQueryStringParameterByName('so') === "1";

            result.CanEdit = result.CanEdit && editingForm;

            // if the start date is in the future, hide the form
            if ( !result.CanEdit && startDate && startDate > now ) {
                parentWidget.find('.form-not-started').show();
                parentWidget.find('.submit-button').hide();
                return;
            }

            // if the end date is in the past, hide the form
            if ( !result.CanEdit && endDate && endDate < now ) {
                parentWidget.find('.form-registrations-closed').show();
                parentWidget.find('.submit-button').hide();
                return;
            }

            for (var sectionIndex = 0; sectionIndex < result.Sections.length; sectionIndex++) {
                container.append(formRendering.hbSectionTemplate(result.Sections[sectionIndex]));
            }

            container.find('.form-field-info').popover({ container: 'body' });
            formRendering.questionTypes.initAll(container);

            if (formLoadedCallback) {
                formLoadedCallback();
            }

            var conditions = [];

            // load conditions
            for (var index = 0; index < result.Sections.length; index++) {
                for (var conditionIndex = 0; conditionIndex < result.Sections[index].Conditions.length; conditionIndex++) {
                    var condition = result.Sections[index].Conditions[conditionIndex];
                    conditions.push(condition);

                    var question = container.find('[name="question_' + condition.QuestionId + '"]');
                    if (question.length > 0) {

                        // if action is show
                        if (condition.Action == 1) {
                            $('#section_' + condition.SectionId).addClass('hidden');
                        }
                        $(question).each(function (e) {

                            $(this).on('keyup change click', function () {

                                var questionName = $(this).prop("name");
                                $(conditions).each(function (i, d) {

                                    if (questionName === 'question_' + d.QuestionId) {
                                        var id = d.SectionId;
                                        var section = $('#section_' + id);
                                        // if show is action
                                        if (d.Comparer == 1) {
                                            if (d.Action == 1)
                                                section.addClass('hidden');
                                            else
                                                section.removeClass('hidden');
                                        }
                                    }
                                });

                                var inputValue = $(this).val();

                                if ($(this).prop("type") === "select-one" || $(this).prop("type") === "select-multiple")
                                    inputValue = $(this).find("option:selected").text();

                                //map roles
                                if ($(this).prop("type") === "checkbox") {

                                    if (inputValue === "1")
                                        inputValue = "player";
                                    else if (inputValue === "2")
                                        inputValue = "manager";
                                    else if (inputValue === "4")
                                        inputValue = "assistant manager";
                                    else if (inputValue === "8")
                                        inputValue = "coach";
                                    else if (inputValue === "16")
                                        inputValue = "assistant coach";
                                    else if (inputValue === "32")
                                        inputValue = "trainer";
                                    else if (inputValue === "64")
                                        inputValue = "medical";
                                    else if (inputValue === "128")
                                        inputValue = "official/referee/umpire";
                                    else if (inputValue === "512")
                                        inputValue = "volunteer";
                                    else if (inputValue === "1024")
                                        inputValue = "other";
                                }
                                else {
                                    //inputValue
                                }

                                var loadedCondition = $.grep(conditions, function (n) { return n.Value.toUpperCase() === inputValue.toUpperCase(); }) || [];

                                if (loadedCondition.length < 1) {
                                    return;
                                }

                                var condition = loadedCondition[0];
                                var id = condition.SectionId;
                                var section = $('#section_' + id);

                                // comparer is equals
                                if (condition.Comparer == 1 && condition.Value.toUpperCase() === inputValue.toUpperCase()) {
                                    if (condition.Action == 1)
                                        section.removeClass('hidden');
                                    else
                                        section.addClass('hidden');
                                }// comparer contains
                                else if (condition.Comparer == 2 && condition.Value.toUpperCase() === inputValue.toUpperCase() && $(this).is(':checked')) {
                                  
                                    if (condition.Action == 1)
                                        section.removeClass('hidden');
                                    else
                                        section.addClass('hidden');
                                }
                                else {
                                    // if show is action
                                    if (condition.Action == 1)
                                        section.addClass('hidden');
                                    else
                                        section.removeClass('hidden');
                                }
                            });
                        
                        });
                    }
                   
			}
		}

		// Attach unobtrusive validation
		$.validator.unobtrusive.parseDynamicContent(container);
		overrideUnobtrusiveDefaults();

		formRendering.removeFileHandler();

        $('.form-group-question').find('label').addClass("site-style");

		//photo upload handlers
		$("#profile-image").click(function () {

            if ($("#LockPhoto").val().toLowerCase() === 'true') {
                bootbox.alert("Unable to edit player photo, please contact your Provincial Union to make changes.");
            }
            else {
                $(":file", "[data-questiontype=8]").click();
            }
			
		});

		$(":file", "[data-questiontype=8]").change(function () {
			$(":file", "[data-questiontype=8]").show();
			$("#changePhoto").hide();
        });

        $(".requiredCheckbox").on('change', function () {
            var div = $(this).parent('.form-group');
            if (div.hasClass('requiredCheckboxHasError') && $(this).is(':checked')) {
                div.removeClass('requiredCheckboxHasError');
                div.addClass('requiredCheckboxHasSuccess');
            }
        });

	});

	$.ajax({
		url: '/formsapi/hasproducts/' + id,
		type: 'GET',
		cache: false,
		contentType: 'application/json; charset=utf-8',
		success: function (data) {
			if (data.hasProducts === true)
				$('.onlinePaymentNotification').show();
			else
				$('.onlinePaymentNotification').hide();

			if (data.requiresPayment === true)
                $('.onlinePaymentNotification .description').html("<h3 style='color:#FF0039 !important;margin:0'>Payment must be made to complete this registration.</h3>");
                //have used inline style above as even after using a class with !important tag, it is overwritten by site-style here.
		}
	});

	//submitButton.on('click', function() {
	//	var model = $(this).closest('form').serialize();
	//	//model.FormId = siteFormId;
	//	$.post('/cms/submitform', model);
	//	return false;
	//});
};

formRendering.onFileSelected = function (event) {
    var profileImage = $("#profile-image");
    if (profileImage.length == 0) {
        $(event.target).after('<div class="thumbnail"><img id="profile-image"></div>');
        profileImage = $("#profile-image");
    }
    var selectedFile = event.target.files[0];
    profileImage.title = selectedFile.name;
    var reader = new FileReader();
    reader.onload = function (event) {
        $("#btnImageSettingRotateLeft").attr("disabled", false);
        $("#btnImageSettingRotateRight").attr("disabled", false);
        profileImage.attr('src', event.target.result);

        $("#AddingRotatedImage").val(false);
    };
    reader.readAsDataURL(selectedFile);
};

formRendering.registerHandlebarsHelpers = function () {

	Handlebars.registerHelper('escapeDoubleQuotes', function (str) {
		return str.replace(/"/g, "");
	});

	Handlebars.registerHelper('escapeDoubleQuotesToLowerCase', function (str) {
		return str.toLowerCase().replace(/"/g, "");
	});

	Handlebars.registerHelper('toLowerCase', function (str) {
		return str.toLowerCase();
	});

	Handlebars.registerHelper("questiontype", function (question) {
		var ret = '';
		var validation = 'data-val="true"';
		if (question.IsRequired)
            validation += ' data-val-required';

        //please update regex in utils.js and Validate email attribute if you are updating this
		if (question.QuestionType == 11) // Email
            validation += ' data-val-validateemail="Invalid Email" data-val-validateemail-email="Email"';

		if (question.QuestionType == 26) // Drivers Licence
            validation += ' data-val-regex-pattern="[A-Za-z]{2}[0-9]{6}|" data-val-regex="A valid drivers licence is required"';

		//Single choice
		if (question.QuestionType == 3) {
			ret = '<select name="question_' + question.Id + '" class="form-control" ' + validation + '>';
			ret += '<option value="">Please Choose</option>';
			for (var i = 0; i < question.QuestionOptions.length; i++) {
				ret += '<option value="' + question.QuestionOptions[i].Id + '">' + question.QuestionOptions[i].OptionText + '</option>';
			}
			ret += '</select>';
        } //Multi choice
		else if (question.QuestionType == 4) {

			if (question.IsRequired)
				ret += "<div class='atleastonerequired'>";
			else
				ret += "<div>";

			for (var i = 0; i < question.QuestionOptions.length; i++) {
				ret += '<div><label><input type="checkbox" class="old" name="question_' + question.Id + '" value="' + question.QuestionOptions[i].Id + '" /> ' + question.QuestionOptions[i].OptionText + '</label></div>';
			}
			ret += "</div>";

		}// yes/no
		else if (question.QuestionType == 5) {
			ret = '<select name="question_' + question.Id + '" class="form-control"' + validation + ' ><option value="">Please Choose</option><option value="true">Yes</option><option value="false">No</option></select>';
		} // multiline text
		else if (question.QuestionType == 2) {
            ret = '<div class="pull-right"><label class="lblRemainingChars"><i>Characters remaining: &nbsp;</i></label><label id=lbl_' + question.Id + ' class="lblRemainingChars"><i>4000</i></label></div><textarea name="question_' + question.Id + '" class="form-control"  maxlength="4000" ' + validation + ' />';
		} // Date
		else if (question.QuestionType == 6) {
			ret = '<input name="question_' + question.Id + '" type="text" class="form-control form-date" placeholder="dd/mm/yyyy" maxlength="10" readonly="readonly" ' + validation + ' />';
		} // Photo
		else if (question.QuestionType == 8) {

			//if photoexists and not the dummy photo then roll this photo forward
			if ($("#profile-image").length > 0 && $("#profile-image").attr('src').indexOf("profile_pic") == -1) {

				ret = '<br/><label id="changePhoto" for="question_' + question.Id + '">Change Photo</label>';
                ret += '<input id="question_' + question.Id + '" name="question_' + question.Id + '" type="file" accept="image/*" ' + validation + ' style="display:none" onchange="sportsground.forms.rendering.onFileSelected(event);" />';

                var kamarPhoto = "";
                if ($("#hdnKamarPhoto").length > 0) {
                    kamarPhoto = $("#hdnKamarPhoto").val();
                    ret += '<input name="question_' + question.Id + '" type="hidden" value="' + kamarPhoto + '"/>';
                }
                else {
                    ret += '<input name="question_' + question.Id + '" type="hidden"/>';
                }
			}
			else {
                ret = '<input name="question_' + question.Id + '" type="file" accept="image/*" ' + validation + ' onchange="sportsground.forms.rendering.onFileSelected(event);" />';
            }

		} // Address
		else if (question.QuestionType == 7) {
			ret = '<input data-questionid="' + question.Id + '" name="question_' + question.Id + '" type="text" class="form-control form-address" autocomplete="off" maxlength="2048" ' + validation + ' />';
			ret += '<input type="hidden" id="' + question.Id + '_StreetAddress" name="' + question.Id + '_StreetAddress" data-noreload />';
			ret += '<input type="hidden" id="' + question.Id + '_Suburb" name="' + question.Id + '_Suburb" data-noreload />';
			ret += '<input type="hidden" id="' + question.Id + '_City" name="' + question.Id + '_City" data-noreload />';
			ret += '<input type="hidden" id="' + question.Id + '_Region" name="' + question.Id + '_Region" data-noreload />';
			ret += '<input type="hidden" id="' + question.Id + '_Country" name="' + question.Id + '_Country" data-noreload />';
			ret += '<input type="hidden" id="' + question.Id + '_PostCode" name="' + question.Id + '_PostCode" data-noreload />';
			ret += '<input type="hidden" id="' + question.Id + '_Lat" name="' + question.Id + '_Lat" data-noreload />';
			ret += '<input type="hidden" id="' + question.Id + '_Long" name="' + question.Id + '_Long" data-noreload />';
		} // Grade List
		else if (question.QuestionType == 9) {
			ret = '<select name="question_' + question.Id + '" class="form-control form-gradelist" ' + validation + ' ></select>';
		} // Team List
		else if (question.QuestionType == 10) {
			ret = '<select name="question_' + question.Id + '" class="form-control form-teamlist" ' + validation + ' ><option value="">Choose Grade First</option></select>';
		}// Checkbox
        else if (question.QuestionType == 12) {
            var requiredCss = "";
            if (question.IsRequired) {
                requiredCss = " requiredCheckbox";
            }
            ret = '<input type="checkbox" name="question_' + question.Id + '" class="old pull-left' + requiredCss + '" style="margin-right:10px" ' + validation + ' />';
		}// Gender
		else if (question.QuestionType == 13) {
			ret = '<select name="question_' + question.Id + '" class="form-control" ' + validation + ' ><option value="">-Select-</option><option value="Male">Male</option><option value="Female">Female</option></select>';
		} // ethnicity
		else if (question.QuestionType == 14) {
            ret = '<select name="question_' + question.Id + '" class="form-control form-ethnicity" ' + validation + ' ></select>';
        } // DOB
		else if (question.QuestionType == 16) {
            ret = '<div class="form-dob input-group"><input  name="question_' + question.Id + '" type="text" class="form-control dobdaterange" ' + validation + ' maxlength="10" placeholder="dd/mm/yyyy"' + ' /></div>';
		}  // NrdGrade
		else if (question.QuestionType == 18) {
			ret = '<select name="question_' + question.Id + '" class="form-control form-nrdgradelist" ' + validation + ' ></select>';
        } // NrdEthnicityGroup
		else if (question.QuestionType == 19) {
			ret = '<select name="question_' + question.Id + '" class="form-control form-nrdethnicity-group" ' + validation + ' ></select>';
		} //NrdGender
		else if (question.QuestionType == 21) {
			ret = '<select name="question_' + question.Id + '" class="form-control form-nrdgender" ' + validation + ' ><option value="">Choose gender</option><option value="M">Male</option><option value="F">Female</option> </select>';
		} // NrdRefereeFunction
		else if (question.QuestionType == 22) {
			ret = '<select name="question_' + question.Id + '" class="form-control form-nrdrefereefunction" ' + validation + ' ></select>';
		} // NrdSchools
		else if (question.QuestionType == 23) {
			ret = '<select name="question_' + question.Id + '" class="form-control form-nrdschool" ' + validation + ' ></select>';
		} // NrdTeams
		else if (question.QuestionType == 24) {
			ret = '<select name="question_' + question.Id + '" class="form-control form-nrdteam" ' + validation + ' ></select>';
		} // singleline text
		else if (question.QuestionType == 25) {
			ret = '<div class="document-wrapper"><input type="file" accept=".xls,.xlsx,.csv,.doc,.docx,.ppt,.txt,.pdf" id="question_' + question.Id + '" name="question_' + question.Id + '" class="form-document" ' + validation + ' /><button style="display:none;" type="button" class="btn btn-primary btn-sm remove-document"><span class="icon-trash"></span></button></div>';
		}// NrdOrganisationRole
        else if (question.QuestionType == 27) {
            var requiredCss = "";
            if (question.IsRequired) {
                requiredCss = " atleastonerequired";
            }
            ret = '<div name="' + question.Id + '" data class="input-group form-nrdorganisationrole' + requiredCss + '" ></div>';
		}
        else if (question.QuestionType == 28) {
            var requiredCss = "";
            if (question.IsRequired) {
                requiredCss = " atleastonerequired";
            }
            ret = '<div name="' + question.Id + '" data class="input-group form-registrationrole' + requiredCss + '"></div>';
        }
        else if (question.QuestionType == 29) {
		    ret = '<input name="question_' + question.Id + '" type="text" class="form-control" disabled="disabled" readonly="readonly" ' + validation + ' />';
		}
		else if (question.QuestionType == 30) {
            ret = '';
        }
		else if (question.QuestionType == 31) {
		    ret = '<select name="question_' + question.Id + '" class="form-control form-level" ' + validation + ' ></select>';
        } 
        // NrdSecondaryEthnicityGroup
        else if (question.QuestionType == 32) {
            ret = '<select name="question_' + question.Id + '" class="form-control form-secondary-nrdethnicity-group" ' + validation + ' ></select>';
        }
        // NrdEthnicitySelection
        else if (question.QuestionType == 33) {
            if (question.IsRequired)
                ret = "<div name='" + question.Id + "' class='atleastonerequired form-nrdethnicity-selection'></div>";
            else
                ret = "<div name='" + question.Id + "' class='form-nrdethnicity-selection'></div>";
        }
        // NrdSecondaryEthnicitySelection
        else if (question.QuestionType == 34) {
            if (question.IsRequired)
                ret = "<div name='" + question.Id + "' class='atleastonerequired form-secondary-nrdethnicity-selection'></div>";
            else
                ret = "<div name='" + question.Id + "' class='form-secondary-nrdethnicity-selection'></div>";
        }
        // SecondaryEthnicity
        else if (question.QuestionType == 35) {
            ret = '<select name="question_' + question.Id + '" class="form-control form-secondary-ethnicity" ' + validation + ' ></select>';
        }
        // EthnicitySelection
        else if (question.QuestionType == 36) {
            if (question.IsRequired)
                ret = "<div name='" + question.Id + "' class='atleastonerequired form-ethnicity-selection'></div>";
            else
                ret = "<div name='" + question.Id + "' class='form-ethnicity-selection'></div>";
        }
        // SecondaryEthnicitySelection
        else if (question.QuestionType == 37) {
            if (question.IsRequired)
                ret = "<div name='" + question.Id + "' class='atleastonerequired form-secondary-ethnicity-selection'></div>";
            else
                ret = "<div name='" + question.Id + "' class='form-secondary-ethnicity-selection'></div>";
        }
        // NzFootballEthnicity
        else if (question.QuestionType == 38) {
            ret = '<select name="question_' + question.Id + '" class="form-control form-nzfootball-ethnicity" ' + validation + ' ></select>';
        }
        // ISO country code
        else if (question.QuestionType == 39) {
            ret = '<select name="question_' + question.Id + '" class="form-control form-iso-countrycode" ' + validation + ' ></select>';
        }
		else {
			var id = '';

			// if this is an NRD address field, mark it with an Id
			var field = question.QuestionDatabaseMappings ? question.QuestionDatabaseMappings.length > 0 ? question.QuestionDatabaseMappings[0].Field : null : null;
			if (field === "PostalAddressAddressLine" || field === "PostalAddressPostCode" || field === "PostalAddressCity" || field === "Address" || field === "Town" || field === "Suburb") {
				id = 'id="' + field + '" ';
			}

            var maxLength = 2048;

            if (question.FirstMappingField == "FirstName" || question.FirstMappingField == "LastName"){
                maxLength = 100;
            }

            ret = '<input ' + id + 'name="question_' + question.Id + '" type="text" class="form-control" maxlength="' + maxLength + '" ' + validation + ' />';
		}

		return new Handlebars.SafeString(ret);
	});
	Handlebars.registerHelper("infotext", function (question) {
		if (!question.InfoText)
			return '';

		return new Handlebars.SafeString('<span class="input-group-btn"><button type="button" class="btn btn-info form-field-info" data-toggle="popover" title="' + question.QuestionText + '" data-content="' + question.InfoText + '"><i class="fa fa-info"></i></button></span>');
	});
};

formRendering.populate = function(element, url, select, userData, callback) {

    if (element.length === 0)
        return;

    $(element).children().remove();

    var defaultOption = '<option value="">' + select + '</option>';
    element.append(defaultOption);

    $.ajax({
        url: url,
        type: 'GET',
        data: userData,
        cache: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data) {
            var options = '';
            for (var i = 0; i < data.length; i++) {
                options += '<option value="' + data[i].value + '">' + data[i].text + '</option>';
            }
            element.append(options);

            if (callback)
                callback();
        }
    });
};

formRendering.populateMultiselect = function (element, url, callback) {
    if (element.length === 0)
        return;

    $(element).children().remove();
    var questionId = $(element).attr('name');

    $.ajax({
        url: url,
        type: 'GET',
        data: null,
        cache: false,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            var options = '';
            for (var i = 0; i < data.length; i++) {
                options +=
                    '<div> <label class="site-style">';
                options += '<input type="checkbox" name="question_' + questionId + '" value="' + data[i].value + '" class="old pull-left" style="margin-right:10px">';
                options += data[i].text + '</label>';
                options += '</div>';
            }
            element.append(options);

            if (callback)
                callback();
        },
        error: function () {
            element.append("");
            if (callback)
                callback();
        }
    });
};

formRendering.hideMultiselectIfEmpty = function(multiselect) {
    multiselect.siblings("label").hide();
    if (multiselect.children().length) {
        multiselect.parent().show();
    } else {
        multiselect.parent().hide();
    }
};

formRendering.getMaxEthnicitySelections = function(groupName) {
    var maxSelections = 2;
    if (groupName == "Maori") maxSelections = 4;
    return maxSelections;
};


formRendering.disableEthnicitySelectionsIfRequired = function(groupName, ethnicitySelection) {
    var maxAllowed = formRendering.getMaxEthnicitySelections(groupName);

    if (ethnicitySelection.find(':checked').length >= maxAllowed) {
        ethnicitySelection.find('input:unchecked').attr("disabled", true);
    } else {
        ethnicitySelection.find('input').removeAttr("disabled");
    }
};

formRendering.limitLabelForEthnicitySelection = function(groupName, selectionControl) {
    var numberToSelect = formRendering.getMaxEthnicitySelections(groupName);
    var label = "Please select up to " + numberToSelect;
    if (groupName == "Maori") {
        label = "What is your Iwi? " + label;
    }
    selectionControl.prepend("<div>" + label + "</div>");
};

formRendering.questionTypes = {
	initAll: function (parent) {
		formRendering.questionTypes.initAddressQuestions(parent);
		formRendering.questionTypes.initGradeLists(parent);
		formRendering.questionTypes.initDateQuestions();
        formRendering.questionTypes.initNrdLists(parent);
        formRendering.questionTypes.initSportyEthnicityLists(parent);
        formRendering.questionTypes.initNrdAddress(parent);
        formRendering.questionTypes.initNumberFields(parent);
        formRendering.questionTypes.initMultiLineFields(parent);
        formRendering.questionTypes.initNzFootballAddress(parent);

    },
   

    initAddressQuestions: function (parent) {
        parent.find('.form-address').each(function () {
            var questionId = $(this).data('questionid');
            var field = $(this);

            $(field).locationAutoComplete({
                addressField: '#' + questionId + '_StreetAddress',
                suburbField: '#' + questionId + '_Suburb',
                cityField: '#' + questionId + '_City',
                countryField: '#' + questionId + '_Country',
                postCodeField: '#' + questionId + '_PostCode',
                latField: '#' + questionId + '_Lat',
                lngField: '#' + questionId + '_Long'
            });

        });
        
	},
	initGradeLists: function (parent) {
		var gradeLists = parent.find('.form-gradelist');

		var organisationFormId = parent.closest("form").find(".organisationFormId").val() || $("#OrganisationFormId").val();
        var formResponseId = $("#OrganisationFormResponseId").val();

		if (gradeLists.length > 0) {
            $.ajax({
                url: '/api/forms/' + organisationFormId + '/getgrades',
                type: 'GET',
                data: { formResponseId: formResponseId },
                contentType: 'application/json; charset=utf-8',
				success: function (data) {
					var options = '<option value="">Choose Grade</option>';
					for (var i = 0; i < data.length; i++) {
						options += '<option value="' + data[i].value + '">' + data[i].text + '</option>';
					}
					gradeLists.append(options);
				}
			});

			gradeLists.on('change', function () {

				$.ajax({
					url: '/api/grades/' + $(this).val() + '/getteams?ofid=' + organisationFormId,
					type: 'GET',
					contentType: 'application/json; charset=utf-8',
					success: function (data) {
						var options = '<option value="">Choose Team</option>';
						for (var i = 0; i < data.length; i++) {
							options += '<option value="' + data[i].value + '">' + data[i].text + '</option>';
						}
						$('.form-teamlist').html('');
						$('.form-teamlist').append(options);
						$('.form-teamlist').trigger('populatedDroplist');
					}
				});
			});
		}
    },
    initSportyEthnicityLists: function (parent) {
        var organisationFormId = parent.closest("form").find(".organisationFormId").val() || $("#OrganisationFormId").val();
        var ethnicity = parent.find('.form-ethnicity');
        var secondaryEthnicity = parent.find('.form-secondary-ethnicity');
	var ethnicitySelections = parent.find('.form-ethnicity-selection');

	ethnicitySelections.parent().hide(); 

        formRendering.populate(ethnicity, '/api/forms/' + organisationFormId + '/getSportyEthnicityGroups', 'Choose ethnicity');
        formRendering.populate(secondaryEthnicity, '/api/forms/' + organisationFormId + '/getSportyEthnicityGroups', 'Choose ethnicity');

        var populateEthnicitySelection = function () {
            var selectedEthnicityId = $('.form-ethnicity option:selected').text();
            var ethnicitySelection = parent.find('.form-ethnicity-selection');
            if (selectedEthnicityId == null || selectedEthnicityId == "") {
                ethnicitySelection.children().remove();
                ethnicitySelection.parent().hide();
            }
            else {
                    formRendering.populateMultiselect(ethnicitySelection,
                    '/api/forms/' + organisationFormId + '/getSportyEthnicitySelections?ethnicityGroup=' + selectedEthnicityId,
                    function() {
                        formRendering.hideMultiselectIfEmpty(ethnicitySelection);
                        formRendering.limitLabelForEthnicitySelection(selectedEthnicityId, ethnicitySelection);
                        $('.form-ethnicity-selection').trigger('populatedMultiselect');
                    }
                );
            }
        };

        var populateSecondaryEthnicitySelection = function () {
            var selectedSecondaryEthnicityId = $('.form-secondary-ethnicity option:selected').text();
            var secondaryEthnicitySelection = parent.find('.form-secondary-ethnicity-selection');
            if (selectedSecondaryEthnicityId == null || selectedSecondaryEthnicityId == "") {
                secondaryEthnicitySelection.children().remove();
                secondaryEthnicitySelection.parent().hide();
            }
            else {
                    formRendering.populateMultiselect(secondaryEthnicitySelection,
                    '/api/forms/' + organisationFormId + '/getSportyEthnicitySelections?ethnicityGroup=' + selectedSecondaryEthnicityId,
                    function() {
                        formRendering.hideMultiselectIfEmpty(secondaryEthnicitySelection);
                        formRendering.limitLabelForEthnicitySelection(selectedSecondaryEthnicityId, secondaryEthnicitySelection);
                        $('.form-secondary-ethnicity-selection').trigger('populatedMultiselect');
                    }
                );
            }
        };

        populateEthnicitySelection();
        populateSecondaryEthnicitySelection();

        $('.form-ethnicity').change(function () {
            populateEthnicitySelection();
        });

        $('.form-secondary-ethnicity').change(function () {
            populateSecondaryEthnicitySelection();
        });

        $('.form-ethnicity-selection').change(function() {
            var selectedEthnicityGroupName = $('.form-ethnicity option:selected').text();
            var selection = $('.form-ethnicity-selection');
            formRendering.disableEthnicitySelectionsIfRequired(selectedEthnicityGroupName, selection);
        });

        $('.form-secondary-ethnicity-selection').change(function() {
            var selectedEthnicityGroupName = $('.form-secondary-ethnicity option:selected').text();
            var selection = $('.form-secondary-ethnicity-selection');
            formRendering.disableEthnicitySelectionsIfRequired(selectedEthnicityGroupName, selection);
        });

    },

    initNrdLists: function (parent) {

        var gradeList = parent.find('.form-nrdgradelist');
        var nrdEthnicityGroup = parent.find('.form-nrdethnicity-group');
        var secondaryNrdEthnicityGroup = parent.find('.form-secondary-nrdethnicity-group');
        var nrdEthnicitySelections = parent.find('.form-nrdethnicity-selection');
        var refereeFunction = parent.find('.form-nrdrefereefunction');
		var school = parent.find('.form-nrdschool');
		var team = parent.find('.form-nrdteam');
		var organisationRole = parent.find('.form-nrdorganisationrole');
        var registrationRole = parent.find('.form-registrationrole');
	    var levels = parent.find('.form-level');
        var nzFootballEthnicity = parent.find('.form-nzfootball-ethnicity');
        var isoCountryCode = parent.find('.form-iso-countrycode');

        nrdEthnicitySelections.parent().hide();

		var organisationFormId = parent.closest("form").find(".organisationFormId").val() || $("#OrganisationFormId").val();

		var populateTeam = function () {
            formRendering.populate(team, '/api/forms/' + organisationFormId + '/getnrdteams', 'Choose team',
			{ nrdGradeId: parent.find('.form-nrdgradelist').val() },
			function () {
                $('.form-nrdteam').trigger('populatedDroplist');
			});
		};

		var populateGrades = function () {
            var registrationType = $("#nrdRegistrationType").val();
		    var formResponseId = $("#OrganisationFormResponseId").val();
			gradeList.children().remove();
            formRendering.populate(gradeList, '/api/forms/' + organisationFormId + '/getnrdgrades', 'Choose grade', {
				registrationType: registrationType,
                formResponseId: formResponseId
			}, function () {

			});
		};

        var populateNrdEthnicitySelection = function () {
            var selectedNrdEthnicityGroupId = $('.form-nrdethnicity-group').val();
            var selectedNrdEthnicityGroupName = $('.form-nrdethnicity-group option:selected').text();
            var nrdEthnicitySelection = parent.find('.form-nrdethnicity-selection');
            if (selectedNrdEthnicityGroupId == null || selectedNrdEthnicityGroupId == "") {
                nrdEthnicitySelection.children().remove();
                nrdEthnicitySelection.parent().hide();
            }
            else {
                formRendering.populateMultiselect(nrdEthnicitySelection,
                    '/api/forms/' + organisationFormId + '/getnrdEthnicitySelections?ethnicityGroup=' + selectedNrdEthnicityGroupId,
                    function() {
                        formRendering.hideMultiselectIfEmpty(nrdEthnicitySelection);
                        formRendering.limitLabelForEthnicitySelection(selectedNrdEthnicityGroupName, nrdEthnicitySelection);
                        $('.form-nrdethnicity-selection').trigger('populatedMultiselect');
                    }
                );
            }
        };

        var populateSecondaryNrdEthnicitySelection = function () {
            var selectedSecondaryNrdEthnicityGroupId = $('.form-secondary-nrdethnicity-group').val();
            var selectedSecondaryNrdEthnicityGroupName = $('.form-secondary-nrdethnicity-group option:selected').text();
            var secondaryNrdEthnicitySelection = parent.find('.form-secondary-nrdethnicity-selection');
            if (selectedSecondaryNrdEthnicityGroupId == null || selectedSecondaryNrdEthnicityGroupId == "") {
                secondaryNrdEthnicitySelection.children().remove();
                secondaryNrdEthnicitySelection.parent().hide();
            }
            else {
                    formRendering.populateMultiselect(secondaryNrdEthnicitySelection,
                    '/api/forms/' + organisationFormId + '/getnrdEthnicitySelections?ethnicityGroup=' + selectedSecondaryNrdEthnicityGroupId,
                    function() {
                        formRendering.hideMultiselectIfEmpty(secondaryNrdEthnicitySelection);
                        formRendering.limitLabelForEthnicitySelection(selectedSecondaryNrdEthnicityGroupName, secondaryNrdEthnicitySelection);
                        $('.form-secondary-nrdethnicity-selection').trigger('populatedMultiselect');
                    }
                );
            }
        };

	    var populateNrdEthnicityGroup = function() {
            formRendering.populate(nrdEthnicityGroup, '/api/forms/' + organisationFormId + '/getnrdEthnicityGroups', 'Choose ethnicity');
            formRendering.populate(secondaryNrdEthnicityGroup, '/api/forms/' + organisationFormId + '/getnrdEthnicityGroups', 'Choose ethnicity');
            populateNrdEthnicitySelection();
            populateSecondaryNrdEthnicitySelection();
        };

        var addNrdEthnicitySelectionsEvents = function () {
            $('.form-nrdethnicity-group').change(function () {
                populateNrdEthnicitySelection();
            });

            $('.form-secondary-nrdethnicity-group').change(function () {
                populateSecondaryNrdEthnicitySelection();
            });

        };
        var populateRefereeFunctions = function () {
            formRendering.populate(refereeFunction, '/api/forms/' + organisationFormId + '/getnrdrefereefunctions', 'Choose referee function');
		};

	    var populateSchools = function() {
            formRendering.populate(school, '/api/forms/getnrdschools', 'Choose school');
	    };

	    var populateRegistrationRoles = function(element) {
            formRendering.populateMultiselect(element, '/api/forms/' + organisationFormId + '/getregistrationroles');
	    };

	    var populateOrganisationRoles = function(element) {
            formRendering.populateMultiselect(element, '/api/forms/' + organisationFormId + '/getnrdorganisationroles');
	    };

	    var populateLevels = function() {
            formRendering.populate(levels, '/api/forms/' + organisationFormId + '/getlevels', 'Choose level');
	    };

        var populateNzFootballEthnicities = function() {
            formRendering.populate(nzFootballEthnicity, '/api/forms/getNzFootballEthnicities', 'Choose ethnicity');
        };

        var populateIsoCountryCodes = function() {
            formRendering.populate(isoCountryCode, '/api/forms/getIsoCountryCodes', 'Choose country');
        };

		populateGrades();
        populateNrdEthnicityGroup();
        addNrdEthnicitySelectionsEvents();
		populateRefereeFunctions();
		populateSchools();
		populateTeam();
		populateRegistrationRoles(registrationRole);
        populateOrganisationRoles(organisationRole);
	    populateLevels();
        populateNzFootballEthnicities();
        populateIsoCountryCodes();

		parent.find('.form-nrdgradelist').change(function () {
			populateTeam();
		});

        $('.form-nrdethnicity-selection').change(function() {
            var selectedNrdEthnicityGroupName = $('.form-nrdethnicity-group option:selected').text();
            var selection = $('.form-nrdethnicity-selection');
            formRendering.disableEthnicitySelectionsIfRequired(selectedNrdEthnicityGroupName, selection);
        });

        $('.form-secondary-nrdethnicity-selection').change(function() {
            var selectedSecondaryNrdEthnicityGroupName = $('.form-secondary-nrdethnicity-group option:selected').text();
            var selection = $('.form-secondary-nrdethnicity-selection');
            formRendering.disableEthnicitySelectionsIfRequired(selectedSecondaryNrdEthnicityGroupName, selection);
        });
    },
	initDateQuestions: function () {
		var settings = {
			dateFormat: 'dd/mm/yy',
			showOtherMonths: true,
			selectOtherMonths: true,
			changeMonth: true,
			changeYear: true
		};
		$('.form-date').datepicker(settings);

		var maxSetDate = new Date();
		var minSetDate = new Date();
		minSetDate.setYear(minSetDate.getFullYear() - 120);

		settings.maxDate = maxSetDate;
		settings.minDate = minSetDate;

		$('.form-dob').datetimepicker({ allowInputToggle: true, format: 'D/MM/YYYY', locale: 'en-nz', viewMode: 'years', maxDate: settings.maxDate, minDate: settings.minDate });

		$('.form-dob').on("dp.error", function (e) {

			$(this).parent(".form-group-question").removeClass("has-success");
			$(this).parent(".form-group-question").addClass("has-error");

		});

		var dobFormatAlert = function (e) {
			if ($(e).find('input').val() == "") {
				bootbox.alert("Please enter the Date of Birth field in dd/mm/yyyy format.", function () {
					$('.form-dob').one("focusout", function () { dobFormatAlert(this) });
				});
			}
		};

        $('.form-dob').one("focusout", function () { dobFormatAlert(this) });

	},
	initNrdAddress: function (parent) {
		$('#PostalAddressAddressLine').locationAutoComplete();
    },
    initNzFootballAddress: function (parent) {
        $('#Address').locationAutoComplete(
            {
                addressField: '#Address',
                suburbField: '#Suburb',
                cityField: '#Town'
            });
    },
    initNumberFields: function (parent) {
        $('div[data-questiontype="15"]').find('input').on("focusout", formRendering.validateNumberFormat);
    },
    initMultiLineFields: function (parent) {
        $('div[data-questiontype="2"]').find('textarea').on("keyup", formRendering.checkMulitiLineTextLength);
        $('div[data-questiontype="2"]').find('textarea').on("paste", function () {
            setTimeout(function () {
                $('div[data-questiontype="2"]').find('textarea').keyup();
            }, 0);
        });
        
    }
};

formRendering.checkMulitiLineTextLength = function (self) {
    var input = $(self).is('textarea') ? $(self) : $(this);
    var count = input.val().length;
    var allowed = input.attr("maxlength");
    var available = allowed - count;
    var questionId = input.closest('div[data-questiontype="2"]').data("questionid");
    $('#lbl_' + questionId).text(available);
}

formRendering.validateNumberFormat = function (self) {
    var input = $(self).is('input') ? $(self) : $(this);
    if (input.val() != "") {
        // only validate "weight" question text. (other number fields like phone numbers accept spaces and dash)
        if (input.closest('div[data-questiontype="15"]').data("questiontext").toLowerCase().indexOf('weight') > -1) {
            if (isNaN(input.val())) {
                input.closest('div[data-questiontype="15"]').removeClass('has-success');
                input.closest('div[data-questiontype="15"]').addClass('has-error');
                if (!$(self).is('input'))
                    bootbox.alert("Enter only number in this field.");
                return false;
            }
            else {
                input.closest('div[data-questiontype="15"]').removeClass('has-error');
                input.closest('div[data-questiontype="15"]').addClass('has-success');
                return true;
            }
        }
    }
    return true;
};

formRendering.populateForm = function (formContainer, previousRegistrationId) {
	$.ajax({
		url: '/formsapi/getresponse/' + previousRegistrationId,
		type: 'GET',
		contentType: 'application/json; charset=utf-8',
		cache: false,
		success: function (data) {

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

				// try each of these mapping until one is found
				var questionContainer = formAdmin.coalesce(
					// question id
					formContainer.find('.form-group-question[data-questionid="' + data[i].questionId + '"]'),
					// form section, question text, mapping
					formContainer.find('.form-group-question[data-formsectionname="' + data[i].sectionName + '"][data-questiontext="' + data[i].questionText.replace(/"/g, "") + '"][data-firstmappingfield="' + data[i].firstMappingField + '"]'),
					// form section, question text, no mapping
					formContainer.find('.form-group-question[data-formsectionname="' + data[i].sectionName + '"][data-questiontext="' + data[i].questionText.replace(/"/g, "") + '"][data-firstmappingfield=""]'),
					// question text, mapping
					formContainer.find('.form-group-question[data-questiontext="' + data[i].questionText.replace(/"/g, "") + '"][data-firstmappingfield="' + data[i].firstMappingField + '"]'),
					// question text, no mapping
					formContainer.find('.form-group-question[data-questiontext="' + data[i].questionText.replace(/"/g, "") + '"][data-firstmappingfield=""]'),
					// question text
					formContainer.find('.form-group-question[data-questiontext="' + data[i].questionText.replace(/"/g, "") + '"]')
				);

				if (questionContainer.length <= 0) {
					continue;
				}

				var checkboxes = questionContainer.find('input[type=checkbox]');
				if (checkboxes.length) {
					for (var j = 0; j < checkboxes.length; j++) {
						var cb = $(checkboxes[j]);
						if (data[i].responseText == "true") {
							cb.prop('checked', true);
						}
						else if (cb.val() == data[i].responseText) {
							cb.prop('checked', true);
						}
						else if (cb.val() == data[i].responseId) {
							cb.prop('checked', true);
                        }
                        // Since the checkbox value will not be the same due to new form with new checkbox IDs, check if the texts are equal.
                        else if ( $.trim( cb.parents( 'label' ).text() ) == $.trim( data[i].responseText ) ) {
                            cb.prop( 'checked', true );
                        }


                    }

				}

				var inputs = questionContainer.find('input[type!=checkbox][type!=file], textarea');
				if (inputs.length) {

					inputs.val(data[i].responseText);
					inputs.trigger('change');

					// reload the address data
					if (data[i].additionalAnswerData) {
						var ad = data[i].additionalAnswerData;
						$.each(ad, function (key, value) {
							questionContainer.find("input[id$='" + key + "']").val(value);
						});
					}
				}

				var selects = questionContainer.find('select');
				if (selects.length) {
					var option = selects.find('option').filter(function () {
						return $(this).val() == data[i].responseText || $(this).val() == data[i].responseId || $(this).text() == data[i].responseText;
					});

					// if we are a teams list, it may not have been populated yet via ajax
					if (option.length == 0 || selects.hasClass('form-teamlist')) {

						var teamList = selects;
						var teamListValue = data[i].responseText;
						$('.form-teamlist,.form-nrdteam').on('loadedTeams', function () {
							option = teamList.find('option[value="' + teamListValue + '"]');
							if (option.length > 0)
								option.prop('selected', true);
						});
					} else {
						option.prop('selected', true);
						selects.trigger('change');
					}
				}

				var formDoc = questionContainer.find('.form-document');
				if (formDoc.length) {
					var formDocFilename = data[i].responseText;
					var splitFormDocFilename = formDocFilename.split('/');
					var files = questionContainer.find('input[type=file]');
					if (formDocFilename != null) {
						formDoc.after("<a target='_blank' href='" + formDocFilename + "'>" + splitFormDocFilename[splitFormDocFilename.length - 1] + "</a>");
						var remove = questionContainer.find('.remove-document');
						remove.show();
						files.hide();
					}
				}
			}

			// disable edit date of birth for nrd forms
			if ($('.isnrdform .form-dob input').val()) {
				$('.form-dob input').attr('readonly', true);
			}

			// disable the grade list if this is not a re-registration for the next season.
			if (!$('#reregistration')) {
				$('select.form-nrdgradelist').attr('readonly', true);
				$('select.form-nrdgradelist option[value!="' + $('select.form-nrdgradelist').val() + '"]').remove();
			}
		}
	});
};
;
$(function () {
	$('#ddSport').on('change', function () {
		var gradeList = $('#ulCurrentGrades');
		gradeList.html('');
		$.ajax({
			url: '/api/getgrades?sportId=' + $(this).val(),
			type: 'GET',
			contentType: 'application/json; charset=utf-8',
			cache: false,
			success: function (data) {
				if (data.success) {
					var template = Handlebars.compile($('#gradeTemplate').html());
					for (var i = 0; i < data.grades.length; i++) {
						gradeList.append(template(data.grades[i]));
                    }
                    $('#ulCurrentGrades').sortable({
                        cancel: 'input',
                        cursor: 'move',
                        handle: '.drag',
                        update: function () {
                            var gradeIds = $('#ulCurrentGrades').sortable('toArray');
                            var sortedgradeIds = [];
                            for (var si = 0; si < gradeIds.length; si++) {
                                for (var ui = 0; ui < data.grades.length; ui++) {
                                    if (gradeIds[si].replace("grade_", "") == data.grades[ui].value) {
                                        sortedgradeIds[si] = data.grades[ui].value;
                                        break;
                                    }
                                }
                            }

                            var model = {
                                sportId: $('#ddSport').val(),
                                gradeIds: sortedgradeIds
                            };

                            $.ajax({
                                url: '/api/grades/reorder',
                                type: 'POST',
                                cache: false,
                                contentType: 'application/json; charset=utf-8',
                                data: JSON.stringify(model)
                            });
                        }
                    });

				}
			}
		});
	}).change();

	$(document).on('click', '.delete-grade', function () {
		var gradeListItem = $(this).closest('.grade');
        var gradeId = gradeListItem.data('id');

        var isDependent = GradeUsedBySuperFormOrSked(gradeId);
        if (isDependent) {
            var isSuperAdmin = CheckUserRole();
            if (isSuperAdmin) {
                bootbox.dialog({
                    message: '<div class="alert alert-warning">Are you sure? This grade is being used by a Superform or Competition. There is no undo. Please type "DELETE" below to confirm you wish to delete grade.</div><div class="form-group"><input class="form-control" id="gradeSecondWarningDeleteText" type="text" autofocus/></div>',
                    title: "Confirm Delete",
                    buttons: {
                        cancel: {
                            label: "Cancel"
                        },
                        delete: {
                            label: "Delete",
                            className: "btn-danger",
                            callback: function () {
                                var pwCheck = $("#gradeSecondWarningDeleteText").val();
                                if (pwCheck.toLowerCase() === "delete") {
                                    deleteGrade(gradeId, gradeListItem, false);
                                }
                                else {
                                    bootbox.dialog({
                                        message: "Please type DELETE.",
                                        title: "Warning",
                                        buttons: {
                                            main: {
                                                label: "Ok",
                                                className: "btn-info"
                                            }
                                        }
                                    });
                                    return false;
                                }
                            }
                        }
                    }
                }).on("shown.bs.modal", function () {
                    $(this).find('[autofocus]').focus();
                });
            }
            else {
                bootbox.dialog({
                    message: 'Grade unable to be deleted, please contact Sporty support',
                    title: "Unable to proceed",
                    buttons: {
                        main: {
                            label: "Ok",
                            className: "btn-info"
                        }
                    }
                });
                return false;
            }
        }
        else {
            deleteGrade(gradeId, gradeListItem, true);
        }
	});

	$(document).on('click', '.rename-grade', function () {
		var li = $(this).closest('li');
		$('#gradeRename').val(li.data('name'));
		$('#renameModal').data('id', li.data('id'));
		toggleRenameButtons('reset');
		$('#renameModal').modal('show');
    });

    $('#renameModal').on('shown.bs.modal', function () {
        $("#gradeRename").removeClass('input-has-error');
    });

    $(document).on('click', '#btnCancelRenameGrade', function () {
        $('#renameModal').modal('hide');
        return false;
    });

	var toggleRenameButtons = function (option) {
		if (option == "confirm") {
			$("#renameModal .modal-footer").first().hide();
			$("#renameModal .modal-footer").last().show();
		} else {
			$("#renameModal .modal-footer").first().show();
			$("#renameModal .modal-footer").last().hide();
		}
	};

	var isGradeInUse = function () {
		var model = {
			id: $('#renameModal').data('id'),
			name: $('#gradeRename').val()
		}
		return $.ajax({
			url: '/api/gradeusagecheck',
			cache: false,
			type: 'POST',
			data: model
		});
	};

	var renameGrade = function () {
		var model = {
			id: $('#renameModal').data('id'),
			name: $('#gradeRename').val()
		}
		$.ajax({
			url: '/api/renamegrade',
			type: 'POST',
			cache: false,
			data: model,
			success: function (data) {
				if (data.success) {
					$('li#grade_' + model.id).find('.displaytext').html(model.name);
					$('li#grade_' + model.id).data('name', model.name);
					$('#renameModal').modal('hide');
				}
			}
		});
    };

    var deleteGrade = function (gradeId, gradeListItem, checkGradeLinks) {
        $.ajax({
            url: '/api/grades?gradeId=' + gradeId + '&checkGradeLinks=' + checkGradeLinks,
            type: 'DELETE',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function (data) {
                if (data.success) {
                    gradeListItem.remove();
                } else {
                    bootbox.dialog({
                        message: data.message,
                        title: "Unable to proceed",
                        buttons: {
                            main: {
                                label: "Ok",
                                className: "btn-info"
                            }
                        }
                    });
                }
            }
        });
    };

    var GradeUsedBySuperFormOrSked = function (gradeId) {
        var returnVal = false;
        var model = {
            gradeId: gradeId
        }
        $.ajax({
            url: '/api/GradeUsedBySuperFormOrSked',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            async: false,
            success: function (data) {
                if (data.success) {
                    returnVal = data.success;
                }
            }
        });
        return returnVal;
    };

    var CheckUserRole = function () {
        var returnVal = false;
        $.ajax({
            url: '/api/CheckUserRole',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            async: false,
            success: function (data) {
                if (data.success) {
                    returnVal = data.success;
                }
            }
        });
        return returnVal;
    }

	$('#renameSaveCheck').on('click', function () {
        var grade = $("#gradeRename").val();
        if (grade == "") {
            $("#gradeRename").addClass('input-has-error');
            return false;
        }
        else {
            $("#gradeRename").removeClass('input-has-error');
        }
		isGradeInUse().done(function (data) {
			if (data.gradeInUse) {
				toggleRenameButtons('confirm');
			} else {
				renameGrade();
			}
		});
	});

	$('#renameSave').on('click', function () {
		renameGrade();
	});

	$('#btnAddGrade').on('click', function () {
		if ($('#tbNewGrade').val().length <= 0) {
			$(this).closest('.form-group').addClass('has-error');
			return false;
		}
		$(this).closest('form-group').removeClass('has-error');

        if ($('#ddSport').val() == 0) {
            bootbox.alert('Please select a valid Team.');
            return false;
        }

		var model = {
			sportId: $('#ddSport').val(),
			name: $('#tbNewGrade').val()
		};
		$.ajax({
			url: '/api/grades',
			type: 'POST',
			contentType: 'application/json; charset=utf-8',
			data: JSON.stringify(model),
			cache: false,
			success: function (data) {
				if (data.success) {
					var template = Handlebars.compile($('#gradeTemplate').html());
					$('#ulCurrentGrades').append(template(data.grade));
                    $('#tbNewGrade').val('');
                    $('#ddSport').val(model.sportId).trigger('change');
				}
			}
		});
	});
});


;
var onlineRegistration = extend(sportsground, 'sportsground.forms.onlineregistration');

onlineRegistration.init = function () {

    onlineRegistration.initFormFolders();

    var cachebuster = Math.round(new Date().getTime() / 1000);
    CKEDITOR.replace('emailDatabaseTextBlurb', {
        customConfig: '/Content/ckeditor/noncms_config.js?cb=' + cachebuster,
    });

    CKEDITOR.replace('elearningReminderTextBlurb', {
        customConfig: '/Content/ckeditor/noncms_config.js?cb=' + cachebuster,
    });

    $('#emailReportButton').on('click', function () {
        if (!$('#emailToText').valid())
            return false;

        $("#reportTypeSelect").removeClass('has-error');
        $("#consolidatedReportError").hide();

        $('#emailReportButton').find('i').addClass('fa-spinner');
        $('#emailReportButton').attr('disabled', 'disabled');

        var model = {
            formId: $('#reportModal').data('id'),
            type: $('#reportTypeSelect').val(),
            emailTo: $('#emailToText').val()
        };

        $.ajax({
            url: '/dashboard/forms/consolidatedReport',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data) {
                if (data.success) {
                    $('#emailReportButton').find('i').removeClass('fa-spinner');
                    $('#emailReportButton').attr('disabled', false);
                    $('#reportModal').modal('hide');
                } else {
                    $("#consolidatedReportError").show();
                }
            }
        });

        return false;
    });

    $("#reportModal").on("hide.bs.modal", function () {
        $("#consolidatedReportError").hide();
    });

    $('#copyFormConfirm').on('click', function () {
        $(this).find('.fa').addClass('fa-spinner');
        $(this).attr('disabled', true);
        var model = {
            formId: $('#assignFormToFolderOrCopyFormModal').data('formid'),
            seasonRollover: $('#copyFormSeasonRollover').is(':checked'),
            formContainerId: $("#uxFormFoldersArea li.active").data('id')
        }
        $.ajax({
            url: '/formsapi/copyform',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data) {
                if (data.success) {
                    window.location = "/dashboard/forms?folderId=" + model.formContainerId;
                }
            }
        });
    });

    $('#paymentreport').on('click', function () {
        $("#paymentreportStartDate").val('');
        $("#paymentreportEndDate").val('');
        $('#paymemtreportModal').modal('show');
        return false;
    });

    $("#paymentreportStartDate").datetimepicker({ format: 'DD/MM/YYYY' });
    $("#paymentreportEndDate").datetimepicker({ format: 'DD/MM/YYYY'});

    $("#exportPaymentReport").click(function () {
        var startDate = null;
        var endDate = null;
        if ($("#paymentreportStartDate").val() != "") {
             startDate = $("#paymentreportStartDate").data("DateTimePicker").date().format('YYYY-MM-DD');
        }
        if ($("#paymentreportEndDate").val() != ""){
            endDate = $("#paymentreportEndDate").data("DateTimePicker").date().format('YYYY-MM-DD');
        }
        window.open("/formservice/ExportFormTransactionsForOrganisation" +
            "?FromDate=" + startDate +
            "&ToDate=" + endDate
           );
    });

    $('#emailDatabaseConfirm').on('click', function (e) {
        if (!onlineRegistration.validateConfirmEmailReply() || !onlineRegistration.validateConfirmSubject()) {
            e.preventDefault();
            return;
        }
        var currentId = $('#emailDatabaseModal').data('formid');
        var btn = $(this);
        btn.button("loading");
        btn.prop("disabled", "disabled");
        var model = {
            excludeAlreadyRegistered: $('#emailDatabaseExludeRegistered').is(':checked'),
            content: CKEDITOR.instances['emailDatabaseTextBlurb'].getData(),
            fromReply: $('#emailDatabaseFromReply').val(),
            subject: $('#emailDatabaseSubject').val()
        };
        $.ajax({
            url: '/formsapi/' + currentId + '/emaildatabase',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data) {
                if (data.success) {
                    $("#hdnReRegisterEmailContent_" + currentId).val(model.content);
                    $("#hdnReRegisterEmailSubject_" + currentId).val(model.subject);
                    window.scrollTo(0, 0);
                    $('#databaseEmailedNotification').show('highlight', { color: '#FF42EC' }, 1000);
                    setTimeout(function () {
                        $('#databaseEmailedNotification').slideUp(1000);
                    }, 5500);
                }
                $('#emailDatabaseModal').modal('hide');
                btn.button("reset");
            },
            error: function () {
                $('#emailDatabaseModal').modal('hide');
                btn.button("reset");
            }
        });
    });

    $('#elearningReminderConfirm').on('click', function (e) {
        if (!onlineRegistration.validateConfirmElearningEmailReply() || !onlineRegistration.validateConfirmElearningEmailSubject()) {
            e.preventDefault();
            return;
        }
        var currentId = $('#emailElearningReminderModal').data('formid');
        var btn = $(this);
        btn.button("loading");
        btn.prop("disabled", "disabled");
        var model = {
            content: CKEDITOR.instances['elearningReminderTextBlurb'].getData(),
            fromReply: $('#elearningReminderFromReply').val(),
            subject: $('#elearningReminderSubject').val()
        };
        $.ajax({
            url: '/formsapi/' + currentId + '/EmailElearningReminder',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            success: function (data) {
                if (data.success) {
                    window.scrollTo(0, 0);
                    $('#elearningReminderNotification').show('highlight', { color: '#FF42EC' }, 1000);
                    setTimeout(function () {
                        $('#elearningReminderNotification').slideUp(1000);
                    }, 5500);
                }
                $('#emailElearningReminderModal').modal('hide');
                btn.button("reset");
            },
            error: function () {
                $('#emailElearningReminderModal').modal('hide');
                btn.button("reset");
            }
        });
    });

    onlineRegistration.validateConfirmElearningEmailReply = function () {
        if (sportsground.utils.validateEmailAddress($('#elearningReminderFromReply').val())) {
            $('#elearningReminderFromReply').parent().removeClass('has-error');
            return true;
        } else {
            $('#elearningReminderFromReply').parent().addClass('has-error');
            return false;
        }
    };

    onlineRegistration.validateConfirmElearningEmailSubject = function () {
        if ($("#elearningReminderSubject").val() != "") {
            $('#elearningReminderSubject').parent().removeClass('has-error');
            return true;
        } else {
            $('#elearningReminderSubject').parent().addClass('has-error');
            return false;
        }
    };
   
    $('#elearningReminderFromReply').on('focusout', function () {
        onlineRegistration.validateConfirmElearningEmailReply();
    });

    $('#elearningReminderSubject').on('focusout', function () {
        onlineRegistration.validateConfirmElearningEmailSubject();
    });

    $( '#emailDatabaseFromReply' ).on( 'focusout', function () {
        onlineRegistration.validateConfirmEmailReply();
    });

    $('#emailDatabaseSubject').on('focusout', function () {
        onlineRegistration.validateConfirmSubject();
    });

    $('.addNewForm').on('click', function () {
        if ($(this).attr('disabled') === 'disabled')
            return false;

        if ( parseInt($('#hdnMaxForms').val()) > parseInt($('#hdnCountForActiveNonSuperForms').val()) ) {
            window.location.href = '/dashboard/forms/new';
        } else {
            $('#noMoreFormsAllowed').modal('show');
        }
    });

    onlineRegistration.initFolderSelectModal();
};

onlineRegistration.initFolderSelectModal = function () {
    $("#assignFormToFolderOrCopyFormModal").on('shown.bs.modal', function () {
        onlineRegistration.bindOrganisationFormContainersToModal();
        return false;
    });

    $("#btnAddFormFolderFromModal").on('click', function () {
        $("#txtFolderNameFromModal").val('');
        $("#dvAddFolderFromModal").removeClass('has-error');
        $("#dvAddFolderFromModal").removeClass('hidden');
        $("#txtFolderNameFromModal").focus();
        return false;
    });

    $(".btnCancelAddingFolderFromModal").on('click', function () {
        $("#dvAddFolderFromModal").addClass('hidden');
        return false;
    });

    $("#btnAddFolderFromModal").on('click', function () {
        var folderName = $("#txtFolderNameFromModal").val();
        if (folderName == "") {
            $("#dvAddFolderFromModal").addClass('has-error');
            return false;
        }
        else
            $("#dvAddFolderFromModal").removeClass('has-error');

        $(this).attr('disabled', 'disabled');
        onlineRegistration.saveFormFolderFromModal(folderName);
        return false;
    });
};

onlineRegistration.validateConfirmEmailReply = function () {
    if ( sportsground.utils.validateEmailAddress( $( '#emailDatabaseFromReply' ).val() ) ) {
        $( '#emailDatabaseFromReply' ).parent().removeClass( 'has-error' );
        return true;
    } else {
        $( '#emailDatabaseFromReply' ).parent().addClass( 'has-error' );
        return false;
    }
};

onlineRegistration.validateConfirmSubject = function () {
    if ($("#emailDatabaseSubject").val() != "") {
        $('#emailDatabaseSubject').parent().removeClass('has-error');
        return true;
    } else {
        $('#emailDatabaseSubject').parent().addClass('has-error');
        return false;
    }
};

onlineRegistration.initFormFolders = function () {

    $(".form-folders").parents('body').css('overflow', 'hidden');

    onlineRegistration.getFormContainersSortTypeAndUpdateSortArrow();

    onlineRegistration.getFormContainers();

    onlineRegistration.attachEditIconVisibilityHandlers();

    $(document).on('click.editFolderGlyph', '.editFolderGlyph', onlineRegistration.triggerContextMenu);

    $('#contextActionRename').on('click', function () {
        $('.modal-content:not(#folderContextMenu)').off('click.cancelcontextmenu');

        var folderNode = $($('#folderContextMenu').data('contextitem-el'));
        var folderId = $('#folderContextMenu').data('contextitem-id');

        var model = {
            Id: folderId,
            Name: folderNode.data('name')
        };
        var rawHtml = $('#hbtFolderEdit').html();
        var template = Handlebars.compile(rawHtml);
        var html = template(model);
        folderNode.after(html);
        folderNode.remove();

        $('#folderContextMenu').hide();

        var folderEditNode = $('#folderEdit_' + folderId);
        folderEditNode.find('input').focus();
        folderEditNode.find('.btn-edit-folder-save').on('click', onlineRegistration.renameSave);
        folderEditNode.find('.btn-edit-folder-cancel').on('click', onlineRegistration.renameCancel);
        return false;
    });

    $("#btnAddFormFolder").on('click', function () {
        $("#txtFormFolderName").val('');
        $("#txtFormFolderName").parent('.form-group').removeClass('has-error');
        $("#addFormFolderModal").modal('show');
        return false;
    });

    $("#addFormFolderModal").on('shown.bs.modal', function () {
        $("#txtFormFolderName").focus();
    });

    $("#btnSaveFormFolder").on('click', function () {
        var formName = $("#txtFormFolderName").val();
        if (formName == "") {
            $("#txtFormFolderName").parent('.form-group').addClass('has-error');
            return false;
        }
        else 
            $("#txtFormFolderName").parent('.form-group').removeClass('has-error');

        $("#btnSaveFormFolder i").addClass('fa-spinner');
        $("#btnSaveFormFolder").attr('disabled','disabled');

        onlineRegistration.saveFormFolder(formName, null);
        return false;
    });

    $('#contextActionCreateSubFolder').on('click', function () {
        $('body:not(#folderContextMenu)').off('click.cancelcontextmenu');
        var folder = $('#folderContextMenu').data('contextitem-el');
        onlineRegistration.addFolder(folder);
        $('#folderContextMenu').hide();
        return false;
    });

    $('#contextActionDelete').on('click', function () {
        $('body:not(#folderContextMenu)').off('click.cancelcontextmenu');
        var formContainerId = $('#folderContextMenu').data('contextitem-id');
        var folder = $('#folderContextMenu').data('contextitem-el');
        onlineRegistration.checkIfContainerHasFormsAndDeleteIfNot(formContainerId, folder);
        return false;
    });

    $(".formFolderSortType").click(function () {
        var newSortType = 'Desc';
        if ($(".formFolderSortType i").hasClass('fa-caret-down')) {
            $(".formFolderSortType i").removeClass('fa-caret-down');
            $(".formFolderSortType i").addClass('fa-caret-up');
            newSortType = 'Asc';
        }
        else {
            $(".formFolderSortType i").removeClass('fa-caret-up');
            $(".formFolderSortType i").addClass('fa-caret-down');
            newSortType = 'Desc';
        }
        onlineRegistration.changeFoldersSortType(newSortType);
        return false;
    });

    $("#btn-form-search").on('click', function () {
        var name = $("#txtName").val();
        var transactionRef = $("#txtTransactionRef").val();

        if (name == "" && transactionRef == "") {
            $("#txtName").parent('.form-group').addClass('has-error');
            $("#txtTransactionRef").parent('.form-group').addClass('has-error');
            return false;
        }
        else {
            $("#txtName").parent('.form-group').removeClass('has-error');
            $("#txtTransactionRef").parent('.form-group').removeClass('has-error');
        }
        $('#uxFormContainersList .active').removeClass('active');
        onlineRegistration.getFormsByFolderIdOrSearchItem(0, name, transactionRef);
    });
};

onlineRegistration.bindFormActionsClickHandler = function () {

    $('.form-email-database').on('click', function () {

        var row = $(this).closest('tr');
        var hasNextSeasonForm = row.data('nextseasonformid') != '';

        if ( parseInt($('#hdnMaxForms').val()) < parseInt($('#hdnCountForActiveNonSuperForms').val()) && !(hasNextSeasonForm) ) {
            $('#noMoreFormsAllowed').modal('show');
            return false;
        }

        $('#databaseEmailedNotification').hide();

        var hasSuperform = row.data('hassuperform') === 'True';
        var currentId = row.data('id');
        var formName = row.find("td:first a").text();
        var organisationName = $('#OrganisationName').val();
        var emailFromAddress = $(this).data('email-from-address');
        var emailDatabaseTextBlurbValue = $("#hdnReRegisterEmailContent_" + currentId).val();
        if (emailDatabaseTextBlurbValue == null || emailDatabaseTextBlurbValue == "") {
            emailDatabaseTextBlurbValue = "<p>You are invited to register with " + organisationName + " for the upcoming season. You can do this now - please click here to re-register with " + organisationName + ".</p><p>If you have any questions about this email, please contact " + organisationName + " </p><p>If you do not wish to re-register with " + organisationName + " for the next season, please ignore this email.</p>";
        }
        else {
            emailDatabaseTextBlurbValue = emailDatabaseTextBlurbValue.replace(/\n/g, '<br />');
        }
        CKEDITOR.instances['emailDatabaseTextBlurb'].setData(emailDatabaseTextBlurbValue);

        var emailSubject = $("#hdnReRegisterEmailSubject_" + currentId).val();
        if (emailSubject == null || emailSubject == "") {
            emailSubject = "Invitation to register with " + organisationName;
        }
        $("#emailDatabaseSubject").val(emailSubject);

        $.ajax({
            url: '/formsapi/' + currentId + '/rolloverid',
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                if (data.success) {
                    $('#emailDatabaseModal').find(".formName").text(formName).prop("href", "/dashboard/forms/list/" + currentId);
                    if (data.rolloverId && data.rolloverId > 0) {
                        $('#emailDatabaseModal').data('formid', currentId);
                        $('#emailDatabaseFromReply').val(emailFromAddress);
                        $('#emailDatabaseAutoCreateNewForm').hide();
                        $('#emailDatabaseModal').modal('show');
                    } else {
                        if (hasSuperform) {
                            $('#emailDatabaseWrongSeasonModal').modal('show');
                        } else {
                            $('#emailDatabaseModal').data('formid', currentId);
                            $('#emailDatabaseFromReply').val(emailFromAddress);
                            $('#emailDatabaseAutoCreateNewForm').show();
                            $('#emailDatabaseModal').modal('show');
                        }
                    }
                }
            }
        });
        return false;
    });

    $('.form-email-elearningReminder').on('click', function () {
        var row = $(this).closest('tr');
        var currentId = row.data('id');

        $('#emailElearningReminderModal').data('formid', currentId);

        var formName = row.find("td:first a").text();
        $('#emailElearningReminderModal').find(".formName").text(formName).prop("href", "/dashboard/forms/list/" + currentId);

        var emailFromAddress = $(this).data('email-from-address');
        $("#elearningReminderFromReply").val(emailFromAddress);

        var registrationType = row.data('registrationtype');

        var subject = "";
        var elearningTextBlurbValue = "";

        if (registrationType == "6") { //coach reg
            subject = "RugbySmart Online Course Reminder";

            elearningTextBlurbValue = "<p>Thank you for registering to coach this season.  This year RugbySmart consists of two parts: (1) an online course and (2) a practical session. Both are compulsory. The online course takes 15 minutes to complete and must be done before you attend the practical RugbySmart session.</p>"
            elearningTextBlurbValue += "<p>Our records show that you have not yet completed the online course. Please click here to complete the course before your practical session.</p>";
            elearningTextBlurbValue += "<p>We look forward to seeing you at your RugbySmart practical session</p>";
        }
        else {//refree reg
            subject = "RugbySmart & Blue Card Online Course Reminder";

            elearningTextBlurbValue = "<p>Thank you for registering to referee this season. This year RugbySmart consists of two parts: (1) an online RugbySmart and Blue Card course and (2) a practical RugbySmart session. Both are compulsory. The online course takes 20 minutes to complete and must be done before you attend the practical RugbySmart session.</p>"
            elearningTextBlurbValue += "<p>Our records show that you have not yet completed the online course. Please click here to complete the course before your practical session.</p>";
            elearningTextBlurbValue += "<p>We look forward to seeing you at your RugbySmart practical session</p>";
        }

        $("#elearningReminderSubject").val(subject);
        CKEDITOR.instances['elearningReminderTextBlurb'].setData(elearningTextBlurbValue);

        $("#emailElearningReminderModal").modal('show');
        return false;
    });

    $('.form-link-create').on('click', function () {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
            $(this).closest('tr').next().remove();
            return false;
        }

        $(this).addClass('active');
        var row = $(this).closest('tr');
        var model = {
            formId: row.data('id'),
            allowPhotoIdCard: row.data('allowphotoidcard')
        };
        var template = Handlebars.compile($('#hbCreateLink').html());
        row.after(template(model));
        return false;
    });

    $(document).on('click', '.btn-update-link', function () {
        var row = $(this).closest('tr');
        var baseUrl = row.find('.create-link-url').data('url');
        var returnUrl = row.find('.create-link-url-suffix').val();
        if (returnUrl.length > 0) {
            row.find('.create-link-url').val(baseUrl + '?returnUrl=' + returnUrl);
        } else {
            row.find('.create-link-url').val(baseUrl);
        }
        return false;
    });

    $(document).on('click', '.btn-copy-registration-link', function () {
        var row = $(this).closest('tr');
        var registrationUrl = row.find('.create-link-url');
        registrationUrl.prop('disabled', false);
        registrationUrl.focus();
        registrationUrl.select();
        document.execCommand("copy");
        registrationUrl.prop('disabled', 'disabled');
        return false;
    });

    $('.form-copy:not([disabled])').on('click', function () {
        if ( parseInt($('#hdnMaxForms').val()) > parseInt($('#hdnCountForActiveNonSuperForms').val()) ) {

            $('#assignFormToFolderOrCopyFormModal').data('formid', $(this).closest('tr').data('id'));

            $("#dvAddFolderFromModal").addClass('hidden');
            $("#copyFormConfirm").removeClass('hidden');
            $("#dvCopyForm").removeClass('hidden');
            $("#btnAssignToFolderAndSaveForm").addClass('hidden');
            $("#assignFormToFolderOrCopyFormModal").find('#myModalLabel').html("Copy Form");
            $("#assignFormToFolderOrCopyFormModal").modal('show');
        } else {
            $('#noMoreFormsAllowed').modal('show');
        }
        return false;
    });

    $('.form-reporting:not([disabled])').on('click', function () {
        var formId = $(this).closest('tr').data('id');
        $('#reportModal').data('id', formId);
        $('#reportModal').modal('show');
    });

    $('.form-delete:not([disabled])').on('click', function () {
        var row = $(this).closest('tr');
        var formName = row.find('a').first().text();
        var id = row.data('id');
        var hasComp = hasCompetition(id);
        if (hasComp) {
            bootbox.alert('A competition utilizes this form. Please delete the competition before deleting this form.');
            return false;
        }
        var message = 'Are you sure you wish to delete this form?<p>All records will be deleted and this operation is not reversable.';
        $.ajax("/Form/IsWidget/" + id, {
            async: false
        }).done(function (r) {
            if (r)
                message += "<br/>This form is currently displayed on your site. Continuing will remove it from your website.";
        });
        message += "</p>";

        bootbox.dialog({
            message: message,
            title: "Delete Form",
            buttons: {
                cancel: {
                    label: "Cancel"
                },
                delete: {
                    label: "Delete",
                    className: "btn-danger",
                    callback: function () {
                        var registrants = row.data('registrants');
                        if (registrants == 0)
                            deleteForm(row.data('id'), row);
                        else {
                            bootbox.dialog({
                                message: '<div class="alert alert-warning">' + registrants + ' entries exist for ' + formName + '. This will delete ALL entries. Please type "DELETE" to confirm deletion.</div><div class="form-group"><input class="form-control" id="secondWarningDeleteText" type="text" autofocus/></div>',
                                title: "Confirm Delete",
                                buttons: {
                                    cancel: {
                                        label: "Cancel"
                                    },
                                    delete: {
                                        label: "Delete",
                                        className: "btn-danger",
                                        callback: function () {
                                            var pwCheck = $("#secondWarningDeleteText").val();
                                            if (pwCheck.toLowerCase() === "delete") {
                                                deleteForm(row.data('id'), row);
                                            }
                                            else {
                                                bootbox.dialog({
                                                    message: "Please type DELETE.",
                                                    title: "Warning",
                                                    buttons: {
                                                        main: {
                                                            label: "Ok",
                                                            className: "btn-info"
                                                        }
                                                    }
                                                });
                                                return false;
                                            }
                                        }
                                    }
                                }
                            }).on("shown.bs.modal", function () {
                                $(this).find('[autofocus]').focus();
                            });
                        }
                    }
                }
            }
        });
    });

    var deleteForm = function (id, row) {

        if (!id)
            return;

        $.ajax({
            url: '/formsapi/' + id,
            type: 'DELETE',
            contentType: 'application/json; charset=utf-8',
            success: function (data, textStatus, xhr) {
                if (data.success) {
                    var activeNonSuperForms = $("#hdnCountForActiveNonSuperForms").val();
                    if (activeNonSuperForms > 0)
                        activeNonSuperForms = $("#hdnCountForActiveNonSuperForms").val(activeNonSuperForms - 1);

                    row.remove();
                }
            }
        });
    };

    var hasCompetition = function (id) {

        if (!id)
            return;

        var returnVal = false;
        var model = {
            organisationFormId: id
        }
        $.ajax({
            url: '/formsapi/HasCompetition',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(model),
            async: false,
            success: function (data) {
                if (data.success) {
                    returnVal = data.success;
                }

            }
        });
        return returnVal;
    };
}

onlineRegistration.getFormContainersSortTypeAndUpdateSortArrow = function () {
    $.ajax({
        url: '/formsapi/getformcontainerssorttype',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#formfolderHeader i").removeClass('fa-caret-down');
            $("#formfolderHeader i").removeClass('fa-caret-up');

            if (data == "Desc") {
                $("#formfolderHeader i").addClass('fa-caret-down');
            }
            else {
                $("#formfolderHeader i").addClass('fa-caret-up');
            }

        }
    });
    return false;
}

onlineRegistration.getFormContainers = function () {

    var container = $("#uxFormContainersList");
    container.html('');
    $("#folder-loader").removeClass('hidden');

    $.ajax({
        url: '/formsapi/getformcontainers',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data != null) {
                $("#folder-loader").addClass('hidden');

                var template = Handlebars.compile($('#frmFolder').html());
                for ( var i = 0; i < data.length; i++ ) {
                    container.append( template( data[i] ) );
                }

                $(".form-folder").on('click', onlineRegistration.folderSelect);

                var folderIdToSelect = $("#hdnSelectedFolderId").val();
                if (folderIdToSelect !== '0') {
                    $("#hdnSelectedFolderId").val('0');
                    window.history.replaceState(null, null, window.location.pathname);
                }
                else {
                    var firstContainerWithForms = $('#uxFormContainersList li[data-hasforms="true"]:first');
                    if (firstContainerWithForms.length > 0)
                        folderIdToSelect = $(firstContainerWithForms).data('id');
                    else
                        folderIdToSelect = $('#uxFormContainersList li a:first').data('id');
                }

                var folderToSelect = $("#folder_" + folderIdToSelect);
                var isSubFolder = folderToSelect.data('isroot') == false;
                if (isSubFolder) {
                    folderToSelect.parent('ul').collapse("show");
                }
                folderToSelect.find('a:first').click();
            }
        }
    });
};

onlineRegistration.folderSelect = function () {

    $("#txtName").parent('.form-group').removeClass('has-error');
    $("#txtName").val('');
    $("#txtTransactionRef").parent('.form-group').removeClass('has-error');
    $("#txtTransactionRef").val('');

    var anchor = $(this);
    $('#uxFormContainersList .active').removeClass('active');
    var li = anchor.parent();
    li.addClass('active');

    var folderId = li.data('id');
    onlineRegistration.getFormsByFolderIdOrSearchItem(folderId, "", "");

    return true;
}

onlineRegistration.getFormsByFolderIdOrSearchItem = function (folderId, name, transactionRef) {
   
    var container = $("#bodyOrgForms");
    container.html('');

    $("#form-loader").removeClass('hidden');

    $.ajax({
        url: '/formsapi/getorganisationformsbycontaineridorsearchitem?formContainerId=' + folderId + '&name=' + name + '&transactionreference=' + transactionRef,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#form-loader").addClass('hidden');
            if (data != null) {
                if (data.length > 0) {

                    container.html('');

                    var nrdForms = [];
                    nrdForms = data.filter(function (x) {
                        return x.IsNrdForm == "True";
                    });

                    if (nrdForms.length > 0 && $("#hdnMappedToNrdOrganisation") == "False") {
                        $(".nrd-map-error").removeClass('hidden');
                    }

                    var template = Handlebars.compile($('#hbtForms').html());
                    for (var i = 0; i < data.length; i++) {
                        container.append(template(data[i]));
                    }

                    onlineRegistration.bindFormActionsClickHandler();
                }
                else {
                    container.html('');
                    var alertMessage = "No registration forms in this folder";
                    if ( name != "" || transactionRef != "" ) {
                        alertMessage = "No search results found";
                    }
                    var html = "<tr><td class='td-center'>" + alertMessage + "</td></tr>";
                    container.append(html);
                }
                onlineRegistration.doDraggable();
            }
        },
        error: function (r) {
            $("#form-loader").addClass('hidden');
            bootbox.alert(r.responseJSON);
            onlineRegistration.getFormContainers();
        }
    });

    return true;
}

onlineRegistration.attachEditIconVisibilityHandlers = function () {
    $(document).on('mouseenter.folderedit', '#uxFormContainersList li', function () {
        $(this).find('>.editFolderGlyph').show();
    });
    $(document).on('mouseleave.folderedit', '#uxFormContainersList li', function () {
        $(this).find('>.editFolderGlyph').hide();
    });
}

onlineRegistration.detachEditIconVisibilityHandlers = function () {
    $(document).off('mouseenter.folderedit');
    $(document).off('mouseleave.folderedit');
}

onlineRegistration.triggerContextMenu = function () {
    var editIcon = $(this);

    editIcon.show();

    onlineRegistration.detachEditIconVisibilityHandlers();
    var contextMenu = $("#folderContextMenu");
    var folderDomElement = editIcon.closest('li');
    var isRoot = folderDomElement.data("isroot");

    if (isRoot) {
        $("#contextActionCreateSubFolder").show();
    } else {
        $("#contextActionCreateSubFolder").hide();
    }

    // set the folder id as the data-contextitem-id attribute on the context menu root
    contextMenu.data('contextitem-id', folderDomElement.data('id'));
    contextMenu.data('contextitem-el', folderDomElement);

    // reverse the visibility of the context menu
    contextMenu.css({
        display: contextMenu.is(':visible') ? "none" : "block",
        left: editIcon.offset().left,
        top: editIcon.offset().top + 28
    });

    // set the handler to hide the menu if clicked outside of the both context menu and edit icon
    $('body:not(#folderContextMenu)').one('click.cancelcontextmenu', function (event) {
        if (event.target.className != "icon-img_pencil") {
            onlineRegistration.attachEditIconVisibilityHandlers();
            contextMenu.hide();
            editIcon.hide();
        }
    });
    return false;
}

onlineRegistration.renameSave = function () {
    var li = $(this).closest('li');
    var input = li.find('input').val();
  
    var formGroup = li.find('.input-group').removeClass('has-error');
    if (input.length > 100 || input == "") {
        li.find('.input-group').addClass('has-error');
        return false;
    }

    var model = {
        formContainerId: li.data('id'),
        name: li.find('input').val()
    };
    $.ajax({
        url: '/formsapi/renameorganisationformcontainer',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data) {
                onlineRegistration.attachEditIconVisibilityHandlers();
                onlineRegistration.getFormContainers();
            }
            else {
                bootbox.alert("Folder name already exists.");
            }
        },
        error: function (r) {
            bootbox.alert(r.responseJSON);
            onlineRegistration.getFormContainers();
        }
    });
    return false;
}

onlineRegistration.renameCancel = function () {
    var li = $(this).closest('li');
    var model = {
        Id: li.data('id'),
        Name: li.data('name')
    };
    var rawHtml = $('#frmFolder').html();
    var template = Handlebars.compile(rawHtml);
    var html = template(model);
    li.after(html);
    li.remove();
    onlineRegistration.attachEditIconVisibilityHandlers();
    $('#folder_' + model.Id).find('.form-folder').on('click', onlineRegistration.folderSelect);
    return false;
}

onlineRegistration.addFolder = function (folder) {

    var container = {};

    // no folder selected
    if (folder == null) {
        container = $("#uxFormContainersList");
    } else {
        container = folder
    }

    if (container.length < 1)
        container = $("#uxFormContainersList");

    onlineRegistration.addFolderItem(container);
}

onlineRegistration.addFolderItem = function (container) {

    onlineRegistration.detachEditIconVisibilityHandlers();
    $('#btnAddFormFolder').attr('disabled', 'disabled');
    var model = {
        Id: '',
        Name: ''
    }
    var rawHtml = $('#hbtFolderEdit').html();
    var template = Handlebars.compile(rawHtml);
    var html = template(model);
    container.append(html);

    if (container.hasClass('collapse'))
        container.collapse('show');

    var folderEditNode = $('#folderEdit_');
    folderEditNode.find('input').focus();
    folderEditNode.find('.btn-edit-folder-save').on('click', onlineRegistration.createSaveFormContainer);
    folderEditNode.find('.btn-edit-folder-cancel').on('click', onlineRegistration.cancelAddingFormContainer);
    return false;
}

onlineRegistration.createSaveFormContainer = function () {
    var li = $('#folderEdit_');
    var container = li.closest("#uxFormContainersList");

    var parentContainerId = null;
    
    if (li.parents("li").data("isroot")) {
        parentContainerId = li.parents("li").data("id");
    }

    var containerName = li.find('input').val();
    if (containerName == "") {
        li.find('.input-group').addClass('has-error');
        return false;
    }
    else {
        li.find('.input-group').removeClass('has-error');
    }

    onlineRegistration.saveFormFolder(containerName, parentContainerId);
}

onlineRegistration.saveFormFolder = function (formContainerName, parentContainerId) {
    var model = { name: formContainerName, parentContainerId: parentContainerId };
    $.ajax({
        url: '/formsapi/addorganisationformcontainer',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data.success) {
                onlineRegistration.attachEditIconVisibilityHandlers();
                onlineRegistration.getFormContainers();
                $("#addFormFolderModal").modal('hide');
            }
            else {
                bootbox.alert("Folder name already exists.");
            }
            $("#btnSaveFormFolder").attr('disabled', false);
            $("#btnSaveFormFolder i").removeClass('fa-spinner');
        }
    });
    return false;
}

onlineRegistration.cancelAddingFormContainer = function () {
    $('#folderEdit_').remove();
    onlineRegistration.attachEditIconVisibilityHandlers();
    $('#btnAddFormFolder').removeAttr('disabled');
}

onlineRegistration.checkIfContainerHasFormsAndDeleteIfNot = function (formContainerId, folder) {
    $.ajax({
        url: '/formsapi/organisationformcontainerhasforms?formContainerId=' + formContainerId,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data) {
                bootbox.alert("This folder contains registration forms. Please move the registration forms to a different folder or delete the forms before deleting this folder.");
                $('#folderContextMenu').hide();
                folder.find('.editFolderGlyph').hide();
                onlineRegistration.attachEditIconVisibilityHandlers();
                return false;
            }
            else {
                if (folder.data('isroot'))
                    onlineRegistration.checkIfContainerHasSubFoldersWithFormsAndDeleteIfNot(formContainerId, folder);
                else
                    onlineRegistration.deleteFormContainer(formContainerId, folder);
            }
        }
    });
    return false;
}

onlineRegistration.checkIfContainerHasSubFoldersWithFormsAndDeleteIfNot = function (parentContainerId, folder) {
    $.ajax({
        url: '/formsapi/organisationformcontainerhassubfolderswithforms?parentContainerId=' + parentContainerId,
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data) {
                bootbox.alert("This folder contains subfolders with registration forms. Please move the registration forms to a different folder or delete the forms before deleting this folder.");
                $('#folderContextMenu').hide();
                folder.find('.editFolderGlyph').hide();
                onlineRegistration.attachEditIconVisibilityHandlers();
                return false;
            }
            else 
                onlineRegistration.deleteFormContainer(parentContainerId, folder);
        }
    });
    return false;
}

onlineRegistration.deleteFormContainer = function (formContainerId, folder) {
    $.ajax({
        url: '/formsapi/deleteorganisationformcontaineranditssubcontainers?formContainerId=' + formContainerId,
        type: 'DELETE',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data) {
                var parentId = folder.data('parent');
                folder.remove();

                if ( !isNaN(parentId) ) {
                    var subfoldersCount = $("#subfolders_" + parentId).find('li').length;
                    if (subfoldersCount == 0)
                        $("#folder_" + parentId).find('.form-folder ').find('span').remove();
                }
               
                $('#folderContextMenu').hide();
                if ($('#uxFormContainersList li.active').length == 0) {
                    if ($('#uxFormContainersList li a:first').length > 0)
                        $('#uxFormContainersList li a:first').click();
                    else
                        $('.folder-forms').html('');
                }
                onlineRegistration.attachEditIconVisibilityHandlers();
                return false;
            }
            else {
                bootbox.alert("Something went wrong while deleting folder.");
            }
        }
    });
    return false;
}

onlineRegistration.changeFoldersSortType = function (sortType) {
    var model = {
        sortType: sortType
    };
    $.ajax({
        url: '/formsapi/updateformcontainersorttype/',
        type: 'PUT',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data) {
                var list = $('#uxFormContainersList');
                var listItems = list.children('li');
                list.append(listItems.get().reverse());
                var folderid = listItems.last().attr("data-id");
                listItems.removeClass('active');
                $("#folder_" + folderid).addClass('active');
                onlineRegistration.getFormsByFolderIdOrSearchItem(folderid, "", "");
            } else {
                bootbox.alert('<h3>Sorry</h3><p>An error occurred, please try again.</p>');
            }
        }
    });
}

onlineRegistration.doDraggable = function () {

    $("#uxFormContainersList .ui-draggable").draggable({
        appendTo: 'body',
        revert: true,
        zIndex: 20000,
        distance: 10,
        refreshPositions: true,
        helper: function () {
            var divElem = $('<div />')

            var html = '<div style="width:200px;background-color:#aaa;"><ul><li>';
            html += $(this).html();
            html += '</li></ul></div>';
            var helper = divElem.append(html);
            helper.find('.editFolderGlyph').addClass('hidden');

            return helper;
        },
        stop: function () {
            onlineRegistration.clearIntervals();
        }
    });

    $("#bodyOrgForms .ui-draggable").draggable({
        appendTo: 'body',
        revert: true,
        zIndex: 20000,
        distance: 10,
        refreshPositions: true,
        helper: function () {
            var helper = $('<div />').append($(this).html());
            $(helper).addClass('thumbnail');
            $(helper).attr( 'data-id', $(this).data('id') );
            return helper;
        },
        stop: function () {
            onlineRegistration.clearIntervals();
        }
    });

    $("#dvformfolderHeader > .ui-droppable").droppable({
        greedy: true,
        activeClass: 'activeDroppable',
        hoverClass: 'hoverDroppable',
        tolerance: 'pointer',
        drop: function (event, ui) {
            ui.helper.fadeOut();

            var draggedFolderId = ui.draggable.data('id');
            var draggedFolderIsRootFolder = ui.draggable.data('isroot');

            if (draggedFolderIsRootFolder) {
                $(ui.draggable).draggable({ revert: true });
                return false;
            }
            else {
                var draggedFolder = ui.draggable.data('name');
                bootbox.dialog({
                    message: 'Are you sure you want to move the ' + draggedFolder + ' folder?',
                    buttons: {
                        danger: {
                            label: 'Cancel',
                            className: 'btn-info',
                            callback: function (result) {
                                if (result) {
                                    $(ui.draggable).draggable({ revert: true });
                                }
                            }
                        },
                        success: {
                            label: 'Proceed',
                            className: 'btn-primary',
                            callback: function (result) {
                                if (result) {
                                    onlineRegistration.moveFolder(event, ui, true);
                                }
                            }
                        }
                    }
                });
            }
        },
        over: function (e, ui) {
            onlineRegistration.over(e, ui, this);
        }
    });

    $("#uxFormContainersList > .ui-droppable").filter(function () { return !$(this).children().is('.add'); }).droppable({
        activeClass: 'activeDroppable',
        hoverClass: 'hoverDroppable',
        tolerance: 'pointer',
        drop: function (event, ui) {
            ui.helper.fadeOut();

            if (ui.draggable[0].id.indexOf('folder') < 0) {
                onlineRegistration.moveForm(event, ui);
            }
            else {
                var draggedFolderId = ui.draggable.data('id');
                var draggedFolderIsRootFolder = ui.draggable.data('isroot');

                //should not be able to move rootfolder with subfolder to a subfolder
                if (draggedFolderIsRootFolder && $("#subfolders_" + draggedFolderId).find('li').length > 0) {
                    bootbox.alert('Unable to move a folder that would result in the creation of a folder under a sub-folder');
                    $(ui.draggable).draggable({ revert: true });
                    return false;
                }

                var draggedFolder = ui.draggable.data('name');
                var droppedFolder = $(event.target).data('name');

                if (droppedFolder != undefined && droppedFolder != "") {
                    bootbox.dialog({
                        message: 'Are you sure you want to move the ' + draggedFolder + ' folder inside the ' + droppedFolder + ' folder?',
                        buttons: {
                            danger: {
                                label: 'Cancel',
                                className: 'btn-info',
                                callback: function (result) {
                                    if (result) {
                                        $(ui.draggable).draggable({ revert: true });
                                    }
                                }
                            },
                            success: {
                                label: 'Proceed',
                                className: 'btn-primary',
                                callback: function (result) {
                                    if (result) {
                                        onlineRegistration.moveFolder(event, ui, false);
                                    }
                                }
                            }
                        }
                    });
                }
            }
        },
        over: function (e, ui) {
            onlineRegistration.over(e, ui, this);
        }
    });

    $("#uxFormContainersList .subfolders > .ui-droppable").filter(function () { return !$(this).children().is('.add'); }).droppable({
        greedy: true,
        activeClass: 'activeDroppable',
        hoverClass: 'hoverDroppable',
        tolerance: 'pointer',
        drop: function (event, ui) {
            ui.helper.fadeOut();

            if (ui.draggable[0].id.indexOf('folder') >= 0 || ui.draggable.hasClass('folder')) {
                bootbox.alert('Unable to move a folder that would result in the creation of a folder under a sub-folder');
                $(ui.draggable).draggable({ revert: true });
                return false;
            }

            onlineRegistration.moveForm(event, ui);
        },
        over: function (e, ui) {
            onlineRegistration.over(e, ui, this);
        }
    });
}

onlineRegistration.moveForm = function (event, ui) {
    var model = {
        formContainerId: $(event.target).data('id'),
        formId: ui.draggable.data('id')
    };
    $.ajax({
        url: '/formsapi/moveform',
        type: 'PUT',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        beforeSend: function () {
            $('#image-loader').modal('show');
        },
        complete: function () {
            $('#item_' + ui.draggable.data('id')).remove();
            $('#image-loader').modal('hide');
        }
    });  
}

onlineRegistration.moveFolder = function (event, ui, creatingRoot) {

    var parentContainerId = null;
    if (!creatingRoot) {
        parentContainerId = $(event.target).data('id');
    }

    var model = {
        formContainerId: ui.draggable.data('id'),
        parentContainerId: parentContainerId
    };
    $.ajax({
        url: '/formsapi/moveformfolder',
        type: 'PUT',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            onlineRegistration.attachEditIconVisibilityHandlers();
            onlineRegistration.getFormContainers();
        }
    });
};

onlineRegistration.bindOrganisationFormContainersToModal = function () {

    $("#folder-modal-loader").removeClass('hidden');

    var container = $("#uxFormFoldersArea");
    container.html('');

    $.ajax({
        url: '/formsapi/getformcontainers/',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            $("#folder-modal-loader").addClass('hidden');
            if (data != null) {
                var html = "";

                var template = Handlebars.compile($('#selectfrmFolder').html());
                for (var i = 0; i < data.length; i++) {
                    container.append(template(data[i]));
                }

                $("#uxFormFoldersArea li").removeClass('active');
                var selectedId = $("#OrganisationFormContainerId").val();
                if (selectedId != undefined && selectedId != null && selectedId != "") {
                    var folderToSelect = $("#modal-folder-" + selectedId);
                    var isSubFolder = folderToSelect.data('isroot') == false;
                    if (isSubFolder) {
                        var parentId = folderToSelect.data('parent');
                        $("#modal-folder-" + parentId).find('a').click();
                    }
                    $("#modal-folder-" + selectedId).addClass('active');
                }
                else {
                    $("#uxFormFoldersArea li:first").addClass('active');
                }

                $(".folder-list-item-modal a").on('click', function () {
                    $("#uxFormFoldersArea li").removeClass('active');
                    $(this).parent('.folder-list-item-modal').addClass('active');
                });

                return false;
            }
        }
    });

    return false;
};

onlineRegistration.saveFormFolderFromModal = function (name) {
    var model = { name: name, parentContainerId: null };
    $.ajax({
        url: '/formsapi/addorganisationformcontainer',
        type: 'POST',
        data: JSON.stringify(model),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data.success) {

                $("#dvAddFolderFromModal").addClass('hidden');

                var folder = { Id: data.id, Name: name, SubFolders: null, ParentOrganisationFormContainerId: null }
                var container = $("#uxFormFoldersArea");

                var template = Handlebars.compile($('#selectfrmFolder').html());
                container.prepend(template(folder));

                $("#uxFormFoldersArea li").removeClass('active');
                $("#uxFormFoldersArea li:first").addClass('active');
            }
            else {
                bootbox.alert("Folder name already exists.");
            }
            $("#btnAddFolderFromModal").attr('disabled', false);
        }
    });
    return false;
}

onlineRegistration.over = function (e, ui, element) {
    
    var dropScrollContainer = $('.form-folders');
    var offset = dropScrollContainer.offset();
    var offsetWidth = offset.left + dropScrollContainer.width();
    var offsetHeight = offset.top + dropScrollContainer.height();

    var distance = 70;
    var timer = 100;
    var step = 10;

    var isMoving = false;
    //Left
    if ((e.pageX - offset.left) <= distance) {
        isMoving = true;
        clearIntervals();
        onlineRegistration.intLeftHandler = setInterval(function () {
            dropScrollContainer.scrollLeft(dropScrollContainer.scrollLeft() - step)
        }, timer);
        console.log('left');
    }

    //Right
    if (e.pageX >= (offsetWidth - distance)) {
        isMoving = true;
        onlineRegistration.clearIntervals();
        onlineRegistration.intRightHandler = setInterval(function () {
            dropScrollContainer.scrollLeft(dropScrollContainer.scrollLeft() + step)
        }, timer);
        console.log('right')
    }

    //Top
    if ((e.pageY - offset.top) <= distance) {
        isMoving = true;
        onlineRegistration.clearIntervals();
        onlineRegistration.intTopHandler = setInterval(function () {
            dropScrollContainer.scrollTop(dropScrollContainer.scrollTop() - step)
        }, timer);
        console.log('top')
    }

    //Bottom
    if (e.pageY >= (offsetHeight - distance)) {
        isMoving = true;
        onlineRegistration.clearIntervals();
        onlineRegistration.intBottomHandler = setInterval(function () {
            dropScrollContainer.scrollTop(dropScrollContainer.scrollTop() + step)
        }, timer);
        console.log('bottom');
    }

    //No events
    if (!isMoving)
        onlineRegistration.clearIntervals();
}

onlineRegistration.intRightHandler = null;
onlineRegistration.intLeftHandler = null;
onlineRegistration.intTopHandler = null;
onlineRegistration.intBottomHandler = null;

onlineRegistration.clearIntervals = function () {
    clearInterval(onlineRegistration.intRightHandler);
    clearInterval(onlineRegistration.intLeftHandler);
    clearInterval(onlineRegistration.intTopHandler);
    clearInterval(onlineRegistration.intBottomHandler);
};;
var organisation = extend( sportsground, 'sportsground.forms.organisation' );

organisation.init = function () {
    if ( $( "#orgType" ).val() == 1 ) {
        $( '#chooseSportDiv' ).show();
    }
    $( '#orgType' ).on( 'change', function () {
        if ( $( this ).val() === 1 )
            $( '#chooseSportDiv' ).show();
        else
            $( '#chooseSportDiv' ).hide();
    } );
    select2Dropdown( 'sports-hdn', 'sports', 'Search for sport(s)', 'SearchSport', 'GetSport', true );
    $( "#txtOrgName" ).on( 'keyup', function () {
        var orgName = $( this ).val();

        if ( $( "#hasCustomEwa" ).val() == "false" ) {
            // Generate Easy web address based on name
            $.ajax( {
                url: '/organisation/generateewa?ewa=' + orgName,
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                success: function ( ewa ) {
                    $( "#txtOrgEwa" ).val( ewa );
                }
            } );
        }
    } );
    // -- Once Easywebaddress is input by user then stop auto-generating ewa suggestions
    $( "#hasCustomEwa" ).val( false );
    $( "#txtOrgEwa" ).on( 'keypress', function () {
        $( "#hasCustomEwa" ).val( true );
    } );
    $( '#btnSubmit' ).on( 'click', function () {
        if ($(this).attr("disabled") == true)
            return false;

        $("#txtOrgEwa").val($("#txtOrgEwa").val().toLowerCase());

        if ($("#sportSelect").val() != undefined || $("#sportSelect").val() != null) {
            $('#hdnSport').val($("#sportSelect").val().join(","));
        }
        
        if ( $( '#chooseSportDiv' ).is( ':visible' ) && $( '#hdnSport' ).val().length <= 0 ) {
            $( '#chooseSportDiv' ).removeClass( 'has-success' ).addClass( 'has-error' );
            return false;
        }

        if ($('#Regions').val() == null || $('#Regions').val().length <= 0) {
            $('#Regions').closest('.form-group').removeClass('has-success').addClass('has-error');
            return false;
        }
        
        $("#createOrgSpinner").addClass('fa-spinner');
        $(this).attr("disabled", true);

        $(this).closest('form').submit()
    } );
};;
$.validator.unobtrusive.adapters.addSingleVal('consecutivedate', 'datefield');
$.validator.addMethod('consecutivedate', function (value, element) {

	// contains a list of dates and the date elements
	var dates = [];

	var validatorSettings = $(element).closest('form').data('validator').settings;

	// adds the element and the date to the array of dates, if the date is valid and not empty
	function add(dateElement) {
		if (dateElement.val()) {
			var parts = dateElement.val().split('/');
			if (parts.length == 3) {
				var date = new Date(parts[2], parts[1], parts[0])

				if (!isNaN(date.getTime())) { // clever trick to see if date is Date
					dates.push({element:dateElement, date: date});
				}
				else {
					validatorSettings.highlight(dateElement);
					return false;
				}
			}
			else {
				validatorSettings.highlight(dateElement);
				return false;
			}
		}
		validatorSettings.unhighlight(dateElement);
		return true;
	};

	var result = true;

	// add the dates to the array, in order
	result &= add($('#DisplayForStartDate'));
	result &= add($('#DisplayForTeamStartDate'));
	result &= add($('#DisplayForTeamEndDate'));
	result &= add($('#DisplayForEndDate'));

	// the dates in the array should be in chronological order
	for (var index = 1; index < dates.length; index++) {
		if (dates[index - 1].date <= dates[index].date) {
			validatorSettings.unhighlight(dates[index].element);
		}
		else {
			validatorSettings.highlight(dates[index].element);
			result = false;
		}
	}

	return result;
});

$(function () {
    var pageLoad = true;

	$('a.add-grades').on('click', function() {
		$('#ddSport').val($('#SportId').val()).change();
		$('#addGradesModal').modal('show');

		$('#addGradesModal').on('hide.bs.modal', function(e) {
			$('#SportId').change();
		});
	});

    $('#SportId').on('change', function () {
        if (pageLoad) {
            sportsground.forms.onlineregistration.initFolderSelectModal();
        }
		$.ajax({
			url: '/formsapi/availablegrades',
			data: { sportId : $(this).val(), id : $('#OrganisationFormDetails_ID').val() },
			type: 'GET',
			cache: false,
			contentType: 'application/json; charset=utf-8',
			success: function(data) {
				if (data.success) {
					var template = Handlebars.compile($('#hbtGrade').html());
					var container = $('#dvGradeList');
					container.html('');
					for (var i = 0; i < data.grades.length; i++) {
						container.append(template(data.grades[i]));
                    }
                }
                pageLoad = false;
			}
		});
    }).change();
});
;
(function ($) {
    $.fn.croppable = function (callback) {
        var image = $(this);
        var width = image.width();
        var height = parseInt(image.data('height'));
        var isMobile = $(this).data("ismobileheader");

        var containerOffset = image.offset();
        var x1 = containerOffset.left;
        var y1 = containerOffset.top - image.height() + height;
        var x2 = x1;
        var y2 = containerOffset.top;

        image.css('position', 'absolute');
        var initialPosition = (image.height() - height) / 2 * -1;
        image.css('top', initialPosition + 'px');
        image.wrap("<div class='croppable-container' style='position: relative;overflow:hidden;width:" + width + "px;height:" + height + "px;' />");

        var actionWrapper = $("<div style='position:relative;top:0px;'></div>");

        var cancel = $("<input id='btnCropCancel' type='button' class='btn btn-danger' value='Cancel' />");
        cancel.click(function () {
            $('#cropoverlay').remove();
            $('.croppable-container').remove();
            if (isMobile) {
                $('#uxHeaderPreviewWrapperMobile').show();
            }
            else {
                $('#uxHeaderPreviewWrapper').show();
            }
            if (callback)
                callback('cancel');
        });

        var save = $("<input type='button' class='btn btn-default' value='Save'/>");
        save.click(function () {
            var imageWidth = image.outerWidth();
            var headerWidth = 1170;
            if (isMobile) {
                headerWidth = 585;
            }
            var scaledOffset = parseInt(image.css('top')) * -1;
            var actualOffset = Math.round(headerWidth / imageWidth * scaledOffset);
            var height = image.outerHeight() < $('.croppable-container').outerHeight() ? image.outerHeight() : $('.croppable-container').outerHeight();

            $.post("/asset/saveheader",
                {
                    modalSiteId: $('#SiteId').val(),
                    url: image.attr('src'),
                    y: actualOffset,
                    height: height,
                    isMobile: isMobile
                },
                function (data) {
                    
                    $('#cropoverlay').remove();
                    $('.croppable-container').remove();
                    var wrapperDiv = $('#uxHeaderPreviewWrapper');
                    if (isMobile) {
                        wrapperDiv = $('#uxHeaderPreviewWrapperMobile');
                        wrapperDiv.css('height', height + 'px');
                        wrapperDiv.css('background-size', wrapperDiv.outerWidth() + 'px ' + height + 'px');
                    }
                    else {
                        var wrapperWidth = wrapperDiv.outerWidth();
                        var wrapperHeight = (wrapperWidth / 1170) * height;
                        wrapperDiv.css('height', wrapperHeight + 'px');
                        wrapperDiv.css('background-size', wrapperDiv.outerWidth() + 'px ' + wrapperHeight + 'px');
                    }

                    wrapperDiv.css('background-image', "url('" + data + '?' + new Date().getTime() + "')");
                    wrapperDiv.show();

                    if (callback)
                        callback(data);

                }
            );
        });

        actionWrapper.append(save);
        actionWrapper.append(cancel);

        $('.croppable-container').after('<div id="cropoverlay" ></div>');
        $('#cropoverlay').on('click', function() {
            $('#btnCropCancel').trigger('click');
        });

        image.draggable({
            containment: [x1, y1, x2, y2],
            axis: "y"
        });
        image.after(actionWrapper);
        var actionsLeftOffset = width - save.outerWidth() - cancel.outerWidth();
        actionWrapper.css('left', actionsLeftOffset + 'px');
    };
})(jQuery);

;
(function ($) {
    var isTrusted = true;
    $.fn.sportsgroundMobiscroll = function () {
        var me = this;
        return {
            // date picker - event handlers
            datePicker: function (date, widget, widgetType, callback) {
                me.val(ConvertDateToText(date));
                if (!sportsground.ui.isMobile()) {
                    me.datetimepicker({ format: 'DD/MM/YYYY', defaultDate: date, widgetPositioning: { horizontal: 'auto', vertical: 'bottom' } });

                    // datetimepicker on change only for date picker of competition widget
                    if (widgetType === 'competition') {
                        me.on("dp.change", function () {
                            $($(widget).find('.apply-comp-filters')[0]).click();

                            // if isTrusted, it means that user changed the date using date picker
                            if (isTrusted && callback != undefined)
                                callback(widget);
                            isTrusted = true;
                        });
                    }
                }
                else {
                    // mobiscroll on change only for date picker of competition widget
                    if (widgetType === 'competition') {
                        me.mobiscroll()
                            .date({
                                theme: 'auto',
                                dateFormat: 'dd/mm/yyyy',
                                onShow: function (event, inst) {
                                    $('.mbsc-fr-btn0').css('padding-right', '50%');
                                    inst.setVal(ConvertTextToDate(me.val()));
                                },
                                onSet: function () {
                                    $($(widget).find('.apply-comp-filters')[0]).click();

                                    // on set is only trigger on clicking the set button which is a user action
                                    if (callback != undefined)
                                        callback(widget);
                                }
                            });
                    }
                    else {
                        me.mobiscroll()
                            .date({
                                theme: 'auto',
                                dateFormat: 'dd/mm/yyyy',
                                onShow: function (event, inst) {
                                    inst.setVal(ConvertTextToDate(me.val()));
                                }
                            });
                    }
                }
            },
            setDate: function (date) {
                if (!sportsground.ui.isMobile()) {
                    // if date was changed by javascript, set isTrusted to false
                    if (me && me.data("DateTimePicker") != undefined && me.data("DateTimePicker").date().format('MM/DD/YYYY') != moment(date).format('MM/DD/YYYY')) {
                        isTrusted = false;
                        me.data("DateTimePicker").date(date);
                    }
                }
                else {
                    me.val(ConvertDateToText(date));
                }
            },
            getDate: function () {
                try {
                    if (!sportsground.ui.isMobile() && me && me.data("DateTimePicker") != undefined) {
                        return me.data("DateTimePicker").date()._d;
                    }
                    else {
                        return ConvertTextToDate(me.val());
                    }
                }
                catch (Exception) {
                    return moment(new Date()).format('MM/DD/YYYY');
                }
            },
            // date picker - end

            // select html - event handlers
            selectBasic: function (onChangeCallback) {
                sportsground.mobiscroll.dropdown.selectBasic(me, onChangeCallback);
            },
            selectMultiple: function (multiSelectSettings) {
                sportsground.mobiscroll.dropdown.selectMultiple(me, multiSelectSettings);
            },
            selectDestroy: function () {
                sportsground.mobiscroll.dropdown.destroy(me);
            },
            selectInitialize: function (selectedItems, multiSelectSettings) {
                sportsground.mobiscroll.dropdown.initialize(me, selectedItems, multiSelectSettings);
            },
            selectGetVal: function () {              
                return sportsground.mobiscroll.dropdown.getValue(me);
            },
            selectGetOptionsSelected: function () {
                return sportsground.mobiscroll.dropdown.getOptions(me, true);
            },
            selectGetOptionsNotSelected: function () {
                return sportsground.mobiscroll.dropdown.getOptions(me, false);
            }
            // select html - end
        };
    };

    // convertion only applicable to custom sportsground mobiscroll
    function ConvertDateToText(date) {
        return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
    };
    function ConvertTextToDate(text) {
        var dateArray = text.split(/\//);
        return new Date(dateArray[2], (dateArray[1] - 1), dateArray[0]);
    };
})(jQuery);
;
(function ($) {
	if ($.fn.style) {
		return;
	}

	// Escape regex chars with \
	var escape = function (text) {
		return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
	};

	// For those who need them (< IE 9), add support for CSS functions
	var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
	if (!isStyleFuncSupported) {
		CSSStyleDeclaration.prototype.getPropertyValue = function (a) {
			return this.getAttribute(a);
		};
		CSSStyleDeclaration.prototype.setProperty = function (styleName, value, priority) {
			this.setAttribute(styleName, value);
			var priority = typeof priority != 'undefined' ? priority : '';
			if (priority != '') {
				// Add priority manually
				var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
            '(\\s*;)?', 'gmi');
				this.cssText =
            this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
			}
		};
		CSSStyleDeclaration.prototype.removeProperty = function (a) {
			return this.removeAttribute(a);
		};
		CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
			var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
				'gmi');
			return rule.test(this.cssText) ? 'important' : '';
		};
	}

	// The style function
	$.fn.style = function (styleName, value, priority) {
		// DOM node
		var node = this.get(0);
		// Ensure we have a DOM node
		if (typeof node == 'undefined') {
			return;
		}
		// CSSStyleDeclaration
		var style = this.get(0).style;
		// Getter/Setter
		if (typeof styleName != 'undefined') {
			if (typeof value != 'undefined') {
				// Set style property
				priority = typeof priority != 'undefined' ? priority : '';
				style.setProperty(styleName, value, priority);
			} else {
				// Get style property
				return style.getPropertyValue(styleName);
			}
		} else {
			// Get CSSStyleDeclaration
			return style;
		}
	};
})(jQuery);
;
var sgMobiscrollEventHandlerModule = extend(sportsground, 'sportsground.mobiscroll.dropdown');

sgMobiscrollEventHandlerModule.selectBasic = function (me, multiSelectSettings) {
    if (!multiSelectSettings) {
        multiSelectSettings = {
            dropdown: {
                inputClass: '',
                defaultText: 'Select...',
                selectedText: 'selected',
                onChangeCallback: function (element, checked) { }
            }
        };
    }
    if (!sportsground.ui.isMobile()) {
        me.change(multiSelectSettings.dropdown.onChangeCallback);
    }
    else {
        me.mobiscroll()
            .select({
                inputClass: 'form-control ' + multiSelectSettings.dropdown.inputClass,
                filter: true,
                onSet: multiSelectSettings.dropdown.onChangeCallback
            });
    }
};

sgMobiscrollEventHandlerModule.selectMultiple = function (me, multiSelectSettings) {
    if (!multiSelectSettings) {
        multiSelectSettings = {
            dropdown: {
                inputClass: '',
                defaultText: 'Select...',
                selectedText: 'selected',
                onChangeCallback: function (element, checked) { }
            }
        };
    }
    me.attr("multiple", "multiple");
    if (!sportsground.ui.isMobile()) {
        me.multiselect({
            numberDisplayed: 1,
            includeSelectAllOption: true,
            //onChange: multiSelectSettings.dropdown.onChangeCallback,
            // settings for adding custom overflow:hidden to multiselect
            buttonClass: 'btn btn-default multiselect-overflow',
            buttonText: function (options, select) {
                if (options.length === 0) {
                    return '<div class="multiselect-overflow-text">' + multiSelectSettings.dropdown.defaultText + '</div><b class="caret"></b>';
                }
                else if (options.length === 1) {
                    return '<div class="multiselect-overflow-text">' + $(options).text() + '</div><b class="caret"></b>';
                }
                return '<div class="multiselect-overflow-text">' + options.length + ' ' + multiSelectSettings.dropdown.selectedText + '</div><b class="caret"></b>';
            }
        })
    }
    else {
        me.mobiscroll()
            .select({
                inputClass: 'form-control ' + multiSelectSettings.dropdown.inputClass,
                filter: true,
                buttons: [
                    {
                        text: 'Set All',
                        handler: function (event, inst) {
                            var allItems = [];
                            $.each($(me).find('option'), function (index, option) {
                                allItems.push($(option).attr('value'));
                            });
                            inst.setVal(allItems);
                            inst.cancel();
                        }
                    },
                    'set',
                    'clear',
                    'cancel'
                ],
                onInit: function (event, inst) {
                    sportsground.mobiscroll.dropdown.selectHtmlDisplayedText(me, inst.getVal().length, multiSelectSettings.dropdown.defaultText, multiSelectSettings.dropdown.selectedText);

                    // initialize item count
                    $(me).data('item-count', inst.getVal().length);

                    // customize style using sportsground styling
                    $(me).before('<span class="caret" style="position: absolute; top: 18px; right: 10px;"></span>');
                    $(me).parent().find('input.mbsc-control').css('background', 'none');
                },
                onShow: function (event, inst) {
                    // customize style of the set-all button
                    if ($(event.target).find('.mbsc-fr-btn1').hasClass('mbsc-ic-checkmark')) {
                        $(event.target).find('.mbsc-fr-btn0').addClass('mbsc-ic mbsc-ic-checkmark');
                    }
                    $(event.target).find('.mbsc-fr-btn0').parent().addClass('mbsc-fr-btn-s');
                },
                onSet: function (event, inst) {
                    sportsground.mobiscroll.dropdown.selectHtmlDisplayedText(me, inst.getVal().length, multiSelectSettings.dropdown.defaultText, multiSelectSettings.dropdown.selectedText);
                },
                onBeforeShow: function (event, inst) {
                    sportsground.mobiscroll.dropdown.selectHtmlDisplayedText(me, inst.getVal().length, multiSelectSettings.dropdown.defaultText, multiSelectSettings.dropdown.selectedText);
                },
                onClose: function (event, inst) {
                    
                    sportsground.mobiscroll.dropdown.selectHtmlDisplayedText(me, inst.getVal().length, multiSelectSettings.dropdown.defaultText, multiSelectSettings.dropdown.selectedText);
                    // trigger callback when count changed
                    if ($(me).data('item-count') !== inst.getVal().length) {
                        multiSelectSettings.dropdown.onChangeCallback('mobiscroll_event', $(me));
                    }
                    else if ($(me).data('item-count') == 1) {
                        multiSelectSettings.dropdown.onChangeCallback('mobiscroll_event', $(me));
                    }
                    $(me).data('item-count', inst.getVal().length);
                },
                onBeforeClose: function (event, inst) {
                    if (event.button == "clear") {
                        inst.setVal([]);
                        return false;
                    }
                }
            });
    }
};

// Handles displaying selected text
// for selected items equal to 1, let mobiscroll onSet handle the displaying of text.
// for selected items equal to 0 or more than 1, customize the displayed text.
sgMobiscrollEventHandlerModule.selectHtmlDisplayedText = function (selectHtml, instLength, defaultText, selectedText) {
    if (instLength !== 1) {
        var textHtml = '';
        var count = instLength;
        if (count === 0) {
            textHtml = defaultText;
        }
        else {
            textHtml = count + ' ' + selectedText;
        }
        $(selectHtml).parent().find('input.mbsc-control').val(textHtml);
    }
};

sgMobiscrollEventHandlerModule.destroy = function (me) {
    me.multiselect('destroy');
    me.removeAttr("multiple");
    if (!sportsground.ui.isMobile()) {
        me.find('option').remove();
    }
    else {
        me.mobiscroll('destroy');
    }
};

sgMobiscrollEventHandlerModule.initialize = function (me, selectedItems, multiSelectSettings) {
    if (!sportsground.ui.isMobile()) {
        me.multiselect('deselectall', false);
        me.multiselect('select', selectedItems);
    }
    else {
        me.mobiscroll('clear');
        me.mobiscroll('setVal', selectedItems);
        sportsground.mobiscroll.dropdown.selectHtmlDisplayedText(me, selectedItems.length, multiSelectSettings.dropdown.defaultText, multiSelectSettings.dropdown.selectedText);

        // on initialize, mobiscroll selected text should be set manually.
        if (selectedItems.length === 1) {
            var selectedText = $(me).find('option[value=' + me.mobiscroll('getVal') + ']')[0].text;
            $(me).parent().find('input.mbsc-control').val(selectedText);
            me.mobiscroll('disable');
        }
    }
};

sgMobiscrollEventHandlerModule.getValue = function (me) {
    if (!sportsground.ui.isMobile()) {
        return me.val();
    }
    else {
        return me.mobiscroll('getVal');
    }
};

sgMobiscrollEventHandlerModule.getOptions = function (me, isSelected) {
    if (!sportsground.ui.isMobile()) {
        return isSelected ? me.find('option:selected') : me.find('option:not(:selected)');
    }
    else {
        var selectedValues = me.mobiscroll('getVal');

        var options = [];
        if (isSelected) {
            $.each(selectedValues, function (index, value) {
                options.push($(me).find('option[value=' + value + ']')[0]);
            });
        }
        else {
            $.each($(me).find('option'), function (index, option) {
                var exists = false;
                $.each(selectedValues, function (index, value) {
                    if ($(me).find('option[value=' + value + ']').val() == $(option).attr('value')) {
                        exists = true;
                        return false;
                    }
                });

                if (!exists) {
                    options.push(option);
                }
            });
        }

        return $(options);
    }
};
;
/*!
 * fancyBox - jQuery Plugin
 * version: 2.1.5 (Fri, 14 Jun 2013)
 * @requires jQuery v1.6 or later
 *
 * Examples at http://fancyapps.com/fancybox/
 * License: www.fancyapps.com/fancybox/#license
 *
 * Copyright 2012 Janis Skarnelis - janis@fancyapps.com
 *
 */

(function (window, document, $, undefined) {
	"use strict";

	var H = $("html"),
		W = $(window),
		D = $(document),
		F = $.fancybox = function () {
			F.open.apply( this, arguments );
		},
		IE =  navigator.userAgent.match(/msie/i),
		didUpdate	= null,
		isTouch		= document.createTouch !== undefined,

		isQuery	= function(obj) {
			return obj && obj.hasOwnProperty && obj instanceof $;
		},
		isString = function(str) {
			return str && $.type(str) === "string";
		},
		isPercentage = function(str) {
			return isString(str) && str.indexOf('%') > 0;
		},
		isScrollable = function(el) {
			return (el && !(el.style.overflow && el.style.overflow === 'hidden') && ((el.clientWidth && el.scrollWidth > el.clientWidth) || (el.clientHeight && el.scrollHeight > el.clientHeight)));
		},
		getScalar = function(orig, dim) {
			var value = parseInt(orig, 10) || 0;

			if (dim && isPercentage(orig)) {
				value = F.getViewport()[ dim ] / 100 * value;
			}

			return Math.ceil(value);
		},
		getValue = function(value, dim) {
			return getScalar(value, dim) + 'px';
		};

	$.extend(F, {
		// The current version of fancyBox
		version: '2.1.5',

		defaults: {
			padding : 15,
			margin  : 20,

			width     : 800,
			height    : 600,
			minWidth  : 100,
			minHeight : 100,
			maxWidth  : 9999,
			maxHeight : 9999,
			pixelRatio: 1, // Set to 2 for retina display support

			autoSize   : true,
			autoHeight : false,
			autoWidth  : false,

			autoResize  : true,
			autoCenter  : !isTouch,
			fitToView   : true,
			aspectRatio : false,
			topRatio    : 0.5,
			leftRatio   : 0.5,

			scrolling : 'auto', // 'auto', 'yes' or 'no'
			wrapCSS   : '',

			arrows     : true,
			closeBtn   : true,
			closeClick : false,
			nextClick  : false,
			mouseWheel : true,
			autoPlay   : false,
			playSpeed  : 3000,
			preload    : 3,
			modal      : false,
			loop       : true,

			ajax  : {
				dataType : 'html',
				headers  : { 'X-fancyBox': true }
			},
			iframe : {
				scrolling : 'auto',
				preload   : true
			},
			swf : {
				wmode: 'transparent',
				allowfullscreen   : 'true',
				allowscriptaccess : 'always'
			},

			keys  : {
				next : {
					13 : 'left', // enter
					34 : 'up',   // page down
					39 : 'left', // right arrow
					40 : 'up'    // down arrow
				},
				prev : {
					8  : 'right',  // backspace
					33 : 'down',   // page up
					37 : 'right',  // left arrow
					38 : 'down'    // up arrow
				},
				close  : [27], // escape key
				play   : [32], // space - start/stop slideshow
				toggle : [70]  // letter "f" - toggle fullscreen
			},

			direction : {
				next : 'left',
				prev : 'right'
			},

			scrollOutside  : true,

			// Override some properties
			index   : 0,
			type    : null,
			href    : null,
			content : null,
			title   : null,

			// HTML templates
			tpl: {
				wrap     : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',
				image    : '<img class="fancybox-image" src="{href}" alt="" />',
				iframe   : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen' + (IE ? ' allowtransparency="true"' : '') + '></iframe>',
				error    : '<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',
				closeBtn : '<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',
				next     : '<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',
				prev     : '<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'
			},

			// Properties for each animation type
			// Opening fancyBox
			openEffect  : 'fade', // 'elastic', 'fade' or 'none'
			openSpeed   : 250,
			openEasing  : 'swing',
			openOpacity : true,
			openMethod  : 'zoomIn',

			// Closing fancyBox
			closeEffect  : 'fade', // 'elastic', 'fade' or 'none'
			closeSpeed   : 250,
			closeEasing  : 'swing',
			closeOpacity : true,
			closeMethod  : 'zoomOut',

			// Changing next gallery item
			nextEffect : 'elastic', // 'elastic', 'fade' or 'none'
			nextSpeed  : 250,
			nextEasing : 'swing',
			nextMethod : 'changeIn',

			// Changing previous gallery item
			prevEffect : 'elastic', // 'elastic', 'fade' or 'none'
			prevSpeed  : 250,
			prevEasing : 'swing',
			prevMethod : 'changeOut',

			// Enable default helpers
			helpers : {
				overlay : true,
				title   : true
			},

			// Callbacks
			onCancel     : $.noop, // If canceling
			beforeLoad   : $.noop, // Before loading
			afterLoad    : $.noop, // After loading
			beforeShow   : $.noop, // Before changing in current item
			afterShow    : $.noop, // After opening
			beforeChange : $.noop, // Before changing gallery item
			beforeClose  : $.noop, // Before closing
			afterClose   : $.noop  // After closing
		},

		//Current state
		group    : {}, // Selected group
		opts     : {}, // Group options
		previous : null,  // Previous element
		coming   : null,  // Element being loaded
		current  : null,  // Currently loaded element
		isActive : false, // Is activated
		isOpen   : false, // Is currently open
		isOpened : false, // Have been fully opened at least once

		wrap  : null,
		skin  : null,
		outer : null,
		inner : null,

		player : {
			timer    : null,
			isActive : false
		},

		// Loaders
		ajaxLoad   : null,
		imgPreload : null,

		// Some collections
		transitions : {},
		helpers     : {},

		/*
		 *	Static methods
		 */

		open: function (group, opts) {
			if (!group) {
				return;
			}

			if (!$.isPlainObject(opts)) {
				opts = {};
			}

			// Close if already active
			if (false === F.close(true)) {
				return;
			}

			// Normalize group
			if (!$.isArray(group)) {
				group = isQuery(group) ? $(group).get() : [group];
			}

			// Recheck if the type of each element is `object` and set content type (image, ajax, etc)
			$.each(group, function(i, element) {
				var obj = {},
					href,
					title,
					content,
					type,
					rez,
					hrefParts,
					selector;

				if ($.type(element) === "object") {
					// Check if is DOM element
					if (element.nodeType) {
						element = $(element);
					}

					if (isQuery(element)) {
						obj = {
							href    : element.data('fancybox-href') || element.attr('href'),
							title   : element.data('fancybox-title') || element.attr('title'),
							isDom   : true,
							element : element
						};

						if ($.metadata) {
							$.extend(true, obj, element.metadata());
						}

					} else {
						obj = element;
					}
				}

				href  = opts.href  || obj.href || (isString(element) ? element : null);
				title = opts.title !== undefined ? opts.title : obj.title || '';

				content = opts.content || obj.content;
				type    = content ? 'html' : (opts.type  || obj.type);

				if (!type && obj.isDom) {
					type = element.data('fancybox-type');

					if (!type) {
						rez  = element.prop('class').match(/fancybox\.(\w+)/);
						type = rez ? rez[1] : null;
					}
				}

				if (isString(href)) {
					// Try to guess the content type
					if (!type) {
						if (F.isImage(href)) {
							type = 'image';

						} else if (F.isSWF(href)) {
							type = 'swf';

						} else if (href.charAt(0) === '#') {
							type = 'inline';

						} else if (isString(element)) {
							type    = 'html';
							content = element;
						}
					}

					// Split url into two pieces with source url and content selector, e.g,
					// "/mypage.html #my_id" will load "/mypage.html" and display element having id "my_id"
					if (type === 'ajax') {
						hrefParts = href.split(/\s+/, 2);
						href      = hrefParts.shift();
						selector  = hrefParts.shift();
					}
				}

				if (!content) {
					if (type === 'inline') {
						if (href) {
							content = $( isString(href) ? href.replace(/.*(?=#[^\s]+$)/, '') : href ); //strip for ie7

						} else if (obj.isDom) {
							content = element;
						}

					} else if (type === 'html') {
						content = href;

					} else if (!type && !href && obj.isDom) {
						type    = 'inline';
						content = element;
					}
				}

				$.extend(obj, {
					href     : href,
					type     : type,
					content  : content,
					title    : title,
					selector : selector
				});

				group[ i ] = obj;
			});

			// Extend the defaults
			F.opts = $.extend(true, {}, F.defaults, opts);

			// All options are merged recursive except keys
			if (opts.keys !== undefined) {
				F.opts.keys = opts.keys ? $.extend({}, F.defaults.keys, opts.keys) : false;
			}

			F.group = group;

			return F._start(F.opts.index);
		},

		// Cancel image loading or abort ajax request
		cancel: function () {
			var coming = F.coming;

			if (!coming || false === F.trigger('onCancel')) {
				return;
			}

			F.hideLoading();

			if (F.ajaxLoad) {
				F.ajaxLoad.abort();
			}

			F.ajaxLoad = null;

			if (F.imgPreload) {
				F.imgPreload.onload = F.imgPreload.onerror = null;
			}

			if (coming.wrap) {
				coming.wrap.stop(true, true).trigger('onReset').remove();
			}

			F.coming = null;

			// If the first item has been canceled, then clear everything
			if (!F.current) {
				F._afterZoomOut( coming );
			}
		},

		// Start closing animation if is open; remove immediately if opening/closing
		close: function (event) {
			F.cancel();

			if (false === F.trigger('beforeClose')) {
				return;
			}

			F.unbindEvents();

			if (!F.isActive) {
				return;
			}

			if (!F.isOpen || event === true) {
				$('.fancybox-wrap').stop(true).trigger('onReset').remove();

				F._afterZoomOut();

			} else {
				F.isOpen = F.isOpened = false;
				F.isClosing = true;

				$('.fancybox-item, .fancybox-nav').remove();

				F.wrap.stop(true, true).removeClass('fancybox-opened');

				F.transitions[ F.current.closeMethod ]();
			}
		},

		// Manage slideshow:
		//   $.fancybox.play(); - toggle slideshow
		//   $.fancybox.play( true ); - start
		//   $.fancybox.play( false ); - stop
		play: function ( action ) {
			var clear = function () {
					clearTimeout(F.player.timer);
				},
				set = function () {
					clear();

					if (F.current && F.player.isActive) {
						F.player.timer = setTimeout(F.next, F.current.playSpeed);
					}
				},
				stop = function () {
					clear();

					D.unbind('.player');

					F.player.isActive = false;

					F.trigger('onPlayEnd');
				},
				start = function () {
					if (F.current && (F.current.loop || F.current.index < F.group.length - 1)) {
						F.player.isActive = true;

						D.bind({
							'onCancel.player beforeClose.player' : stop,
							'onUpdate.player'   : set,
							'beforeLoad.player' : clear
						});

						set();

						F.trigger('onPlayStart');
					}
				};

			if (action === true || (!F.player.isActive && action !== false)) {
				start();
			} else {
				stop();
			}
		},

		// Navigate to next gallery item
		next: function ( direction ) {
			var current = F.current;

			if (current) {
				if (!isString(direction)) {
					direction = current.direction.next;
				}

				F.jumpto(current.index + 1, direction, 'next');
			}
		},

		// Navigate to previous gallery item
		prev: function ( direction ) {
			var current = F.current;

			if (current) {
				if (!isString(direction)) {
					direction = current.direction.prev;
				}

				F.jumpto(current.index - 1, direction, 'prev');
			}
		},

		// Navigate to gallery item by index
		jumpto: function ( index, direction, router ) {
			var current = F.current;

			if (!current) {
				return;
			}

			index = getScalar(index);

			F.direction = direction || current.direction[ (index >= current.index ? 'next' : 'prev') ];
			F.router    = router || 'jumpto';

			if (current.loop) {
				if (index < 0) {
					index = current.group.length + (index % current.group.length);
				}

				index = index % current.group.length;
			}

			if (current.group[ index ] !== undefined) {
				F.cancel();

				F._start(index);
			}
		},

		// Center inside viewport and toggle position type to fixed or absolute if needed
		reposition: function (e, onlyAbsolute) {
			var current = F.current,
				wrap    = current ? current.wrap : null,
				pos;

			if (wrap) {
				pos = F._getPosition(onlyAbsolute);

				if (e && e.type === 'scroll') {
					delete pos.position;

					wrap.stop(true, true).animate(pos, 200);

				} else {
					wrap.css(pos);

					current.pos = $.extend({}, current.dim, pos);
				}
			}
		},

		update: function (e) {
			var type = (e && e.type),
				anyway = !type || type === 'orientationchange';

			if (anyway) {
				clearTimeout(didUpdate);

				didUpdate = null;
			}

			if (!F.isOpen || didUpdate) {
				return;
			}

			didUpdate = setTimeout(function() {
				var current = F.current;

				if (!current || F.isClosing) {
					return;
				}

				F.wrap.removeClass('fancybox-tmp');

				if (anyway || type === 'load' || (type === 'resize' && current.autoResize)) {
					F._setDimension();
				}

				if (!(type === 'scroll' && current.canShrink)) {
					F.reposition(e);
				}

				F.trigger('onUpdate');

				didUpdate = null;

			}, (anyway && !isTouch ? 0 : 300));
		},

		// Shrink content to fit inside viewport or restore if resized
		toggle: function ( action ) {
			if (F.isOpen) {
				F.current.fitToView = $.type(action) === "boolean" ? action : !F.current.fitToView;

				// Help browser to restore document dimensions
				if (isTouch) {
					F.wrap.removeAttr('style').addClass('fancybox-tmp');

					F.trigger('onUpdate');
				}

				F.update();
			}
		},

		hideLoading: function () {
			D.unbind('.loading');

			$('#fancybox-loading').remove();
		},

		showLoading: function () {
			var el, viewport;

			F.hideLoading();

			el = $('<div id="fancybox-loading"><div></div></div>').click(F.cancel).appendTo('body');

			// If user will press the escape-button, the request will be canceled
			D.bind('keydown.loading', function(e) {
				if ((e.which || e.keyCode) === 27) {
					e.preventDefault();

					F.cancel();
				}
			});

			if (!F.defaults.fixed) {
				viewport = F.getViewport();

				el.css({
					position : 'absolute',
					top  : (viewport.h * 0.5) + viewport.y,
					left : (viewport.w * 0.5) + viewport.x
				});
			}
		},

		getViewport: function () {
			var locked = (F.current && F.current.locked) || false,
				rez    = {
					x: W.scrollLeft(),
					y: W.scrollTop()
				};

			if (locked) {
				rez.w = locked[0].clientWidth;
				rez.h = locked[0].clientHeight;

			} else {
				// See http://bugs.jquery.com/ticket/6724
				rez.w = isTouch && window.innerWidth  ? window.innerWidth  : W.width();
				rez.h = isTouch && window.innerHeight ? window.innerHeight : W.height();
			}

			return rez;
		},

		// Unbind the keyboard / clicking actions
		unbindEvents: function () {
			if (F.wrap && isQuery(F.wrap)) {
				F.wrap.unbind('.fb');
			}

			D.unbind('.fb');
			W.unbind('.fb');
		},

		bindEvents: function () {
			var current = F.current,
				keys;

			if (!current) {
				return;
			}

			// Changing document height on iOS devices triggers a 'resize' event,
			// that can change document height... repeating infinitely
			W.bind('orientationchange.fb' + (isTouch ? '' : ' resize.fb') + (current.autoCenter && !current.locked ? ' scroll.fb' : ''), F.update);

			keys = current.keys;

			if (keys) {
				D.bind('keydown.fb', function (e) {
					var code   = e.which || e.keyCode,
						target = e.target || e.srcElement;

					// Skip esc key if loading, because showLoading will cancel preloading
					if (code === 27 && F.coming) {
						return false;
					}

					// Ignore key combinations and key events within form elements
					if (!e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey && !(target && (target.type || $(target).is('[contenteditable]')))) {
						$.each(keys, function(i, val) {
							if (current.group.length > 1 && val[ code ] !== undefined) {
								F[ i ]( val[ code ] );

								e.preventDefault();
								return false;
							}

							if ($.inArray(code, val) > -1) {
								F[ i ] ();

								e.preventDefault();
								return false;
							}
						});
					}
				});
			}

			if ($.fn.mousewheel && current.mouseWheel) {
				F.wrap.bind('mousewheel.fb', function (e, delta, deltaX, deltaY) {
					var target = e.target || null,
						parent = $(target),
						canScroll = false;

					while (parent.length) {
						if (canScroll || parent.is('.fancybox-skin') || parent.is('.fancybox-wrap')) {
							break;
						}

						canScroll = isScrollable( parent[0] );
						parent    = $(parent).parent();
					}

					if (delta !== 0 && !canScroll) {
						if (F.group.length > 1 && !current.canShrink) {
							if (deltaY > 0 || deltaX > 0) {
								F.prev( deltaY > 0 ? 'down' : 'left' );

							} else if (deltaY < 0 || deltaX < 0) {
								F.next( deltaY < 0 ? 'up' : 'right' );
							}

							e.preventDefault();
						}
					}
				});
			}
		},

		trigger: function (event, o) {
			var ret, obj = o || F.coming || F.current;

			if (!obj) {
				return;
			}

			if ($.isFunction( obj[event] )) {
				ret = obj[event].apply(obj, Array.prototype.slice.call(arguments, 1));
			}

			if (ret === false) {
				return false;
			}

			if (obj.helpers) {
				$.each(obj.helpers, function (helper, opts) {
					if (opts && F.helpers[helper] && $.isFunction(F.helpers[helper][event])) {
						F.helpers[helper][event]($.extend(true, {}, F.helpers[helper].defaults, opts), obj);
					}
				});
			}

			D.trigger(event);
		},

		isImage: function (str) {
			return isString(str) && str.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i);
		},

		isSWF: function (str) {
			return isString(str) && str.match(/\.(swf)((\?|#).*)?$/i);
		},

		_start: function (index) {
			var coming = {},
				obj,
				href,
				type,
				margin,
				padding;

			index = getScalar( index );
			obj   = F.group[ index ] || null;

			if (!obj) {
				return false;
			}

			coming = $.extend(true, {}, F.opts, obj);

			// Convert margin and padding properties to array - top, right, bottom, left
			margin  = coming.margin;
			padding = coming.padding;

			if ($.type(margin) === 'number') {
				coming.margin = [margin, margin, margin, margin];
			}

			if ($.type(padding) === 'number') {
				coming.padding = [padding, padding, padding, padding];
			}

			// 'modal' propery is just a shortcut
			if (coming.modal) {
				$.extend(true, coming, {
					closeBtn   : false,
					closeClick : false,
					nextClick  : false,
					arrows     : false,
					mouseWheel : false,
					keys       : null,
					helpers: {
						overlay : {
							closeClick : false
						}
					}
				});
			}

			// 'autoSize' property is a shortcut, too
			if (coming.autoSize) {
				coming.autoWidth = coming.autoHeight = true;
			}

			if (coming.width === 'auto') {
				coming.autoWidth = true;
			}

			if (coming.height === 'auto') {
				coming.autoHeight = true;
			}

			/*
			 * Add reference to the group, so it`s possible to access from callbacks, example:
			 * afterLoad : function() {
			 *     this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : '');
			 * }
			 */

			coming.group  = F.group;
			coming.index  = index;

			// Give a chance for callback or helpers to update coming item (type, title, etc)
			F.coming = coming;

			if (false === F.trigger('beforeLoad')) {
				F.coming = null;

				return;
			}

			type = coming.type;
			href = coming.href;

			if (!type) {
				F.coming = null;

				//If we can not determine content type then drop silently or display next/prev item if looping through gallery
				if (F.current && F.router && F.router !== 'jumpto') {
					F.current.index = index;

					return F[ F.router ]( F.direction );
				}

				return false;
			}

			F.isActive = true;

			if (type === 'image' || type === 'swf') {
				coming.autoHeight = coming.autoWidth = false;
				coming.scrolling  = 'visible';
			}

			if (type === 'image') {
				coming.aspectRatio = true;
			}

			if (type === 'iframe' && isTouch) {
				coming.scrolling = 'scroll';
			}

			// Build the neccessary markup
			coming.wrap = $(coming.tpl.wrap).addClass('fancybox-' + (isTouch ? 'mobile' : 'desktop') + ' fancybox-type-' + type + ' fancybox-tmp ' + coming.wrapCSS).appendTo( coming.parent || 'body' );

			$.extend(coming, {
				skin  : $('.fancybox-skin',  coming.wrap),
				outer : $('.fancybox-outer', coming.wrap),
				inner : $('.fancybox-inner', coming.wrap)
			});

			$.each(["Top", "Right", "Bottom", "Left"], function(i, v) {
				coming.skin.css('padding' + v, getValue(coming.padding[ i ]));
			});

			F.trigger('onReady');

			// Check before try to load; 'inline' and 'html' types need content, others - href
			if (type === 'inline' || type === 'html') {
				if (!coming.content || !coming.content.length) {
					return F._error( 'content' );
				}

			} else if (!href) {
				return F._error( 'href' );
			}

			if (type === 'image') {
				F._loadImage();

			} else if (type === 'ajax') {
				F._loadAjax();

			} else if (type === 'iframe') {
				F._loadIframe();

			} else {
				F._afterLoad();
			}
		},

		_error: function ( type ) {
			$.extend(F.coming, {
				type       : 'html',
				autoWidth  : true,
				autoHeight : true,
				minWidth   : 0,
				minHeight  : 0,
				scrolling  : 'no',
				hasError   : type,
				content    : F.coming.tpl.error
			});

			F._afterLoad();
		},

		_loadImage: function () {
			// Reset preload image so it is later possible to check "complete" property
			var img = F.imgPreload = new Image();

			img.onload = function () {
				this.onload = this.onerror = null;

				F.coming.width  = this.width / F.opts.pixelRatio;
				F.coming.height = this.height / F.opts.pixelRatio;

				F._afterLoad();
			};

			img.onerror = function () {
				this.onload = this.onerror = null;

				F._error( 'image' );
			};

			img.src = F.coming.href;

			if (img.complete !== true) {
				F.showLoading();
			}
		},

		_loadAjax: function () {
			var coming = F.coming;

			F.showLoading();

			F.ajaxLoad = $.ajax($.extend({}, coming.ajax, {
				url: coming.href,
				error: function (jqXHR, textStatus) {
					if (F.coming && textStatus !== 'abort') {
						F._error( 'ajax', jqXHR );

					} else {
						F.hideLoading();
					}
				},
				success: function (data, textStatus) {
					if (textStatus === 'success') {
						coming.content = data;

						F._afterLoad();
					}
				}
			}));
		},

		_loadIframe: function() {
			var coming = F.coming,
				iframe = $(coming.tpl.iframe.replace(/\{rnd\}/g, new Date().getTime()))
					.attr('scrolling', isTouch ? 'auto' : coming.iframe.scrolling)
					.attr('src', coming.href);

			// This helps IE
			$(coming.wrap).bind('onReset', function () {
				try {
					$(this).find('iframe').hide().attr('src', '//about:blank').end().empty();
				} catch (e) {}
			});

			if (coming.iframe.preload) {
				F.showLoading();

				iframe.one('load', function() {
					$(this).data('ready', 1);

					// iOS will lose scrolling if we resize
					if (!isTouch) {
						$(this).bind('load.fb', F.update);
					}

					// Without this trick:
					//   - iframe won't scroll on iOS devices
					//   - IE7 sometimes displays empty iframe
					$(this).parents('.fancybox-wrap').width('100%').removeClass('fancybox-tmp').show();

					F._afterLoad();
				});
			}

			coming.content = iframe.appendTo( coming.inner );

			if (!coming.iframe.preload) {
				F._afterLoad();
			}
		},

		_preloadImages: function() {
			var group   = F.group,
				current = F.current,
				len     = group.length,
				cnt     = current.preload ? Math.min(current.preload, len - 1) : 0,
				item,
				i;

			for (i = 1; i <= cnt; i += 1) {
				item = group[ (current.index + i ) % len ];

				if (item.type === 'image' && item.href) {
					new Image().src = item.href;
				}
			}
		},

		_afterLoad: function () {
			var coming   = F.coming,
				previous = F.current,
				placeholder = 'fancybox-placeholder',
				current,
				content,
				type,
				scrolling,
				href,
				embed;

			F.hideLoading();

			if (!coming || F.isActive === false) {
				return;
			}

			if (false === F.trigger('afterLoad', coming, previous)) {
				coming.wrap.stop(true).trigger('onReset').remove();

				F.coming = null;

				return;
			}

			if (previous) {
				F.trigger('beforeChange', previous);

				previous.wrap.stop(true).removeClass('fancybox-opened')
					.find('.fancybox-item, .fancybox-nav')
					.remove();
			}

			F.unbindEvents();

			current   = coming;
			content   = coming.content;
			type      = coming.type;
			scrolling = coming.scrolling;

			$.extend(F, {
				wrap  : current.wrap,
				skin  : current.skin,
				outer : current.outer,
				inner : current.inner,
				current  : current,
				previous : previous
			});

			href = current.href;

			switch (type) {
				case 'inline':
				case 'ajax':
				case 'html':
					if (current.selector) {
						content = $('<div>').html(content).find(current.selector);

					} else if (isQuery(content)) {
						if (!content.data(placeholder)) {
							content.data(placeholder, $('<div class="' + placeholder + '"></div>').insertAfter( content ).hide() );
						}

						content = content.show().detach();

						current.wrap.bind('onReset', function () {
							if ($(this).find(content).length) {
								content.hide().replaceAll( content.data(placeholder) ).data(placeholder, false);
							}
						});
					}
				break;

				case 'image':
					content = current.tpl.image.replace('{href}', href);
				break;

				case 'swf':
					content = '<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="' + href + '"></param>';
					embed   = '';

					$.each(current.swf, function(name, val) {
						content += '<param name="' + name + '" value="' + val + '"></param>';
						embed   += ' ' + name + '="' + val + '"';
					});

					content += '<embed src="' + href + '" type="application/x-shockwave-flash" width="100%" height="100%"' + embed + '></embed></object>';
				break;
			}

			if (!(isQuery(content) && content.parent().is(current.inner))) {
				current.inner.append( content );
			}

			// Give a chance for helpers or callbacks to update elements
			F.trigger('beforeShow');

			// Set scrolling before calculating dimensions
			current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling));

			// Set initial dimensions and start position
			F._setDimension();

			F.reposition();

			F.isOpen = false;
			F.coming = null;

			F.bindEvents();

			if (!F.isOpened) {
				$('.fancybox-wrap').not( current.wrap ).stop(true).trigger('onReset').remove();

			} else if (previous.prevMethod) {
				F.transitions[ previous.prevMethod ]();
			}

			F.transitions[ F.isOpened ? current.nextMethod : current.openMethod ]();

			F._preloadImages();
		},

		_setDimension: function () {
			var viewport   = F.getViewport(),
				steps      = 0,
				canShrink  = false,
				canExpand  = false,
				wrap       = F.wrap,
				skin       = F.skin,
				inner      = F.inner,
				current    = F.current,
				width      = current.width,
				height     = current.height,
				minWidth   = current.minWidth,
				minHeight  = current.minHeight,
				maxWidth   = current.maxWidth,
				maxHeight  = current.maxHeight,
				scrolling  = current.scrolling,
				scrollOut  = current.scrollOutside ? current.scrollbarWidth : 0,
				margin     = current.margin,
				wMargin    = getScalar(margin[1] + margin[3]),
				hMargin    = getScalar(margin[0] + margin[2]),
				wPadding,
				hPadding,
				wSpace,
				hSpace,
				origWidth,
				origHeight,
				origMaxWidth,
				origMaxHeight,
				ratio,
				width_,
				height_,
				maxWidth_,
				maxHeight_,
				iframe,
				body;

			// Reset dimensions so we could re-check actual size
			wrap.add(skin).add(inner).width('auto').height('auto').removeClass('fancybox-tmp');

			wPadding = getScalar(skin.outerWidth(true)  - skin.width());
			hPadding = getScalar(skin.outerHeight(true) - skin.height());

			// Any space between content and viewport (margin, padding, border, title)
			wSpace = wMargin + wPadding;
			hSpace = hMargin + hPadding;

			origWidth  = isPercentage(width)  ? (viewport.w - wSpace) * getScalar(width)  / 100 : width;
			origHeight = isPercentage(height) ? (viewport.h - hSpace) * getScalar(height) / 100 : height;

			if (current.type === 'iframe') {
				iframe = current.content;

				if (current.autoHeight && iframe.data('ready') === 1) {
					try {
						if (iframe[0].contentWindow.document.location) {
							inner.width( origWidth ).height(9999);

							body = iframe.contents().find('body');

							if (scrollOut) {
								body.css('overflow-x', 'hidden');
							}

							origHeight = body.outerHeight(true);
						}

					} catch (e) {}
				}

			} else if (current.autoWidth || current.autoHeight) {
				inner.addClass( 'fancybox-tmp' );

				// Set width or height in case we need to calculate only one dimension
				if (!current.autoWidth) {
					inner.width( origWidth );
				}

				if (!current.autoHeight) {
					inner.height( origHeight );
				}

				if (current.autoWidth) {
					origWidth = inner.width();
				}

				if (current.autoHeight) {
					origHeight = inner.height();
				}

				inner.removeClass( 'fancybox-tmp' );
			}

			width  = getScalar( origWidth );
			height = getScalar( origHeight );

			ratio  = origWidth / origHeight;

			// Calculations for the content
			minWidth  = getScalar(isPercentage(minWidth) ? getScalar(minWidth, 'w') - wSpace : minWidth);
			maxWidth  = getScalar(isPercentage(maxWidth) ? getScalar(maxWidth, 'w') - wSpace : maxWidth);

			minHeight = getScalar(isPercentage(minHeight) ? getScalar(minHeight, 'h') - hSpace : minHeight);
			maxHeight = getScalar(isPercentage(maxHeight) ? getScalar(maxHeight, 'h') - hSpace : maxHeight);

			// These will be used to determine if wrap can fit in the viewport
			origMaxWidth  = maxWidth;
			origMaxHeight = maxHeight;

			if (current.fitToView) {
				maxWidth  = Math.min(viewport.w - wSpace, maxWidth);
				maxHeight = Math.min(viewport.h - hSpace, maxHeight);
			}

			maxWidth_  = viewport.w - wMargin;
			maxHeight_ = viewport.h - hMargin;

			if (current.aspectRatio) {
				if (width > maxWidth) {
					width  = maxWidth;
					height = getScalar(width / ratio);
				}

				if (height > maxHeight) {
					height = maxHeight;
					width  = getScalar(height * ratio);
				}

				if (width < minWidth) {
					width  = minWidth;
					height = getScalar(width / ratio);
				}

				if (height < minHeight) {
					height = minHeight;
					width  = getScalar(height * ratio);
				}

			} else {
				width = Math.max(minWidth, Math.min(width, maxWidth));

				if (current.autoHeight && current.type !== 'iframe') {
					inner.width( width );

					height = inner.height();
				}

				height = Math.max(minHeight, Math.min(height, maxHeight));
			}

			// Try to fit inside viewport (including the title)
			if (current.fitToView) {
				inner.width( width ).height( height );

				wrap.width( width + wPadding );

				// Real wrap dimensions
				width_  = wrap.width();
				height_ = wrap.height();

				if (current.aspectRatio) {
					while ((width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight) {
						if (steps++ > 19) {
							break;
						}

						height = Math.max(minHeight, Math.min(maxHeight, height - 10));
						width  = getScalar(height * ratio);

						if (width < minWidth) {
							width  = minWidth;
							height = getScalar(width / ratio);
						}

						if (width > maxWidth) {
							width  = maxWidth;
							height = getScalar(width / ratio);
						}

						inner.width( width ).height( height );

						wrap.width( width + wPadding );

						width_  = wrap.width();
						height_ = wrap.height();
					}

				} else {
					width  = Math.max(minWidth,  Math.min(width,  width  - (width_  - maxWidth_)));
					height = Math.max(minHeight, Math.min(height, height - (height_ - maxHeight_)));
				}
			}

			if (scrollOut && scrolling === 'auto' && height < origHeight && (width + wPadding + scrollOut) < maxWidth_) {
				width += scrollOut;
			}

			inner.width( width ).height( height );

			wrap.width( width + wPadding );

			width_  = wrap.width();
			height_ = wrap.height();

			canShrink = (width_ > maxWidth_ || height_ > maxHeight_) && width > minWidth && height > minHeight;
			canExpand = current.aspectRatio ? (width < origMaxWidth && height < origMaxHeight && width < origWidth && height < origHeight) : ((width < origMaxWidth || height < origMaxHeight) && (width < origWidth || height < origHeight));

			$.extend(current, {
				dim : {
					width	: getValue( width_ ),
					height	: getValue( height_ )
				},
				origWidth  : origWidth,
				origHeight : origHeight,
				canShrink  : canShrink,
				canExpand  : canExpand,
				wPadding   : wPadding,
				hPadding   : hPadding,
				wrapSpace  : height_ - skin.outerHeight(true),
				skinSpace  : skin.height() - height
			});

			if (!iframe && current.autoHeight && height > minHeight && height < maxHeight && !canExpand) {
				inner.height('auto');
			}
		},

		_getPosition: function (onlyAbsolute) {
			var current  = F.current,
				viewport = F.getViewport(),
				margin   = current.margin,
				width    = F.wrap.width()  + margin[1] + margin[3],
				height   = F.wrap.height() + margin[0] + margin[2],
				rez      = {
					position: 'absolute',
					top  : margin[0],
					left : margin[3]
				};

			if (current.autoCenter && current.fixed && !onlyAbsolute && height <= viewport.h && width <= viewport.w) {
				rez.position = 'fixed';

			} else if (!current.locked) {
				rez.top  += viewport.y;
				rez.left += viewport.x;
			}

			rez.top  = getValue(Math.max(rez.top,  rez.top  + ((viewport.h - height) * current.topRatio)));
			rez.left = getValue(Math.max(rez.left, rez.left + ((viewport.w - width)  * current.leftRatio)));

			return rez;
		},

		_afterZoomIn: function () {
			var current = F.current;

			if (!current) {
				return;
			}

			F.isOpen = F.isOpened = true;

			F.wrap.css('overflow', 'visible').addClass('fancybox-opened');

			F.update();

			// Assign a click event
			if ( current.closeClick || (current.nextClick && F.group.length > 1) ) {
				F.inner.css('cursor', 'pointer').bind('click.fb', function(e) {
					if (!$(e.target).is('a') && !$(e.target).parent().is('a')) {
						e.preventDefault();

						F[ current.closeClick ? 'close' : 'next' ]();
					}
				});
			}

			// Create a close button
			if (current.closeBtn) {
				$(current.tpl.closeBtn).appendTo(F.skin).bind('click.fb', function(e) {
					e.preventDefault();

					F.close();
				});
			}

			// Create navigation arrows
			if (current.arrows && F.group.length > 1) {
				if (current.loop || current.index > 0) {
					$(current.tpl.prev).appendTo(F.outer).bind('click.fb', F.prev);
				}

				if (current.loop || current.index < F.group.length - 1) {
					$(current.tpl.next).appendTo(F.outer).bind('click.fb', F.next);
				}
			}

			F.trigger('afterShow');

			// Stop the slideshow if this is the last item
			if (!current.loop && current.index === current.group.length - 1) {
				F.play( false );

			} else if (F.opts.autoPlay && !F.player.isActive) {
				F.opts.autoPlay = false;

				F.play();
			}
		},

		_afterZoomOut: function ( obj ) {
			obj = obj || F.current;

			$('.fancybox-wrap').trigger('onReset').remove();

			$.extend(F, {
				group  : {},
				opts   : {},
				router : false,
				current   : null,
				isActive  : false,
				isOpened  : false,
				isOpen    : false,
				isClosing : false,
				wrap   : null,
				skin   : null,
				outer  : null,
				inner  : null
			});

			F.trigger('afterClose', obj);
		}
	});

	/*
	 *	Default transitions
	 */

	F.transitions = {
		getOrigPosition: function () {
			var current  = F.current,
				element  = current.element,
				orig     = current.orig,
				pos      = {},
				width    = 50,
				height   = 50,
				hPadding = current.hPadding,
				wPadding = current.wPadding,
				viewport = F.getViewport();

			if (!orig && current.isDom && element.is(':visible')) {
				orig = element.find('img:first');

				if (!orig.length) {
					orig = element;
				}
			}

			if (isQuery(orig)) {
				pos = orig.offset();

				if (orig.is('img')) {
					width  = orig.outerWidth();
					height = orig.outerHeight();
				}

			} else {
				pos.top  = viewport.y + (viewport.h - height) * current.topRatio;
				pos.left = viewport.x + (viewport.w - width)  * current.leftRatio;
			}

			if (F.wrap.css('position') === 'fixed' || current.locked) {
				pos.top  -= viewport.y;
				pos.left -= viewport.x;
			}

			pos = {
				top     : getValue(pos.top  - hPadding * current.topRatio),
				left    : getValue(pos.left - wPadding * current.leftRatio),
				width   : getValue(width  + wPadding),
				height  : getValue(height + hPadding)
			};

			return pos;
		},

		step: function (now, fx) {
			var ratio,
				padding,
				value,
				prop       = fx.prop,
				current    = F.current,
				wrapSpace  = current.wrapSpace,
				skinSpace  = current.skinSpace;

			if (prop === 'width' || prop === 'height') {
				ratio = fx.end === fx.start ? 1 : (now - fx.start) / (fx.end - fx.start);

				if (F.isClosing) {
					ratio = 1 - ratio;
				}

				padding = prop === 'width' ? current.wPadding : current.hPadding;
				value   = now - padding;

				F.skin[ prop ](  getScalar( prop === 'width' ?  value : value - (wrapSpace * ratio) ) );
				F.inner[ prop ]( getScalar( prop === 'width' ?  value : value - (wrapSpace * ratio) - (skinSpace * ratio) ) );
			}
		},

		zoomIn: function () {
			var current  = F.current,
				startPos = current.pos,
				effect   = current.openEffect,
				elastic  = effect === 'elastic',
				endPos   = $.extend({opacity : 1}, startPos);

			// Remove "position" property that breaks older IE
			delete endPos.position;

			if (elastic) {
				startPos = this.getOrigPosition();

				if (current.openOpacity) {
					startPos.opacity = 0.1;
				}

			} else if (effect === 'fade') {
				startPos.opacity = 0.1;
			}

			F.wrap.css(startPos).animate(endPos, {
				duration : effect === 'none' ? 0 : current.openSpeed,
				easing   : current.openEasing,
				step     : elastic ? this.step : null,
				complete : F._afterZoomIn
			});
		},

		zoomOut: function () {
			var current  = F.current,
				effect   = current.closeEffect,
				elastic  = effect === 'elastic',
				endPos   = {opacity : 0.1};

			if (elastic) {
				endPos = this.getOrigPosition();

				if (current.closeOpacity) {
					endPos.opacity = 0.1;
				}
			}

			F.wrap.animate(endPos, {
				duration : effect === 'none' ? 0 : current.closeSpeed,
				easing   : current.closeEasing,
				step     : elastic ? this.step : null,
				complete : F._afterZoomOut
			});
		},

		changeIn: function () {
			var current   = F.current,
				effect    = current.nextEffect,
				startPos  = current.pos,
				endPos    = { opacity : 1 },
				direction = F.direction,
				distance  = 200,
				field;

			startPos.opacity = 0.1;

			if (effect === 'elastic') {
				field = direction === 'down' || direction === 'up' ? 'top' : 'left';

				if (direction === 'down' || direction === 'right') {
					startPos[ field ] = getValue(getScalar(startPos[ field ]) - distance);
					endPos[ field ]   = '+=' + distance + 'px';

				} else {
					startPos[ field ] = getValue(getScalar(startPos[ field ]) + distance);
					endPos[ field ]   = '-=' + distance + 'px';
				}
			}

			// Workaround for http://bugs.jquery.com/ticket/12273
			if (effect === 'none') {
				F._afterZoomIn();

			} else {
				F.wrap.css(startPos).animate(endPos, {
					duration : current.nextSpeed,
					easing   : current.nextEasing,
					complete : F._afterZoomIn
				});
			}
		},

		changeOut: function () {
			var previous  = F.previous,
				effect    = previous.prevEffect,
				endPos    = { opacity : 0.1 },
				direction = F.direction,
				distance  = 200;

			if (effect === 'elastic') {
				endPos[ direction === 'down' || direction === 'up' ? 'top' : 'left' ] = ( direction === 'up' || direction === 'left' ? '-' : '+' ) + '=' + distance + 'px';
			}

			previous.wrap.animate(endPos, {
				duration : effect === 'none' ? 0 : previous.prevSpeed,
				easing   : previous.prevEasing,
				complete : function () {
					$(this).trigger('onReset').remove();
				}
			});
		}
	};

	/*
	 *	Overlay helper
	 */

	F.helpers.overlay = {
		defaults : {
			closeClick : true,      // if true, fancyBox will be closed when user clicks on the overlay
			speedOut   : 200,       // duration of fadeOut animation
			showEarly  : true,      // indicates if should be opened immediately or wait until the content is ready
			css        : {},        // custom CSS properties
			locked     : !isTouch,  // if true, the content will be locked into overlay
			fixed      : true       // if false, the overlay CSS position property will not be set to "fixed"
		},

		overlay : null,      // current handle
		fixed   : false,     // indicates if the overlay has position "fixed"
		el      : $('html'), // element that contains "the lock"

		// Public methods
		create : function(opts) {
			opts = $.extend({}, this.defaults, opts);

			if (this.overlay) {
				this.close();
			}

			this.overlay = $('<div class="fancybox-overlay"></div>').appendTo( F.coming ? F.coming.parent : opts.parent );
			this.fixed   = false;

			if (opts.fixed && F.defaults.fixed) {
				this.overlay.addClass('fancybox-overlay-fixed');

				this.fixed = true;
			}
		},

		open : function(opts) {
			var that = this;

			opts = $.extend({}, this.defaults, opts);

			if (this.overlay) {
				this.overlay.unbind('.overlay').width('auto').height('auto');

			} else {
				this.create(opts);
			}

			if (!this.fixed) {
				W.bind('resize.overlay', $.proxy( this.update, this) );

				this.update();
			}

			if (opts.closeClick) {
				this.overlay.bind('click.overlay', function(e) {
					if ($(e.target).hasClass('fancybox-overlay')) {
						if (F.isActive) {
							F.close();
						} else {
							that.close();
						}

						return false;
					}
				});
			}

			this.overlay.css( opts.css ).show();
		},

		close : function() {
			var scrollV, scrollH;

			W.unbind('resize.overlay');

			if (this.el.hasClass('fancybox-lock')) {
				$('.fancybox-margin').removeClass('fancybox-margin');

				scrollV = W.scrollTop();
				scrollH = W.scrollLeft();

				this.el.removeClass('fancybox-lock');

				W.scrollTop( scrollV ).scrollLeft( scrollH );
			}

			$('.fancybox-overlay').remove().hide();

			$.extend(this, {
				overlay : null,
				fixed   : false
			});
		},

		// Private, callbacks

		update : function () {
			var width = '100%', offsetWidth;

			// Reset width/height so it will not mess
			this.overlay.width(width).height('100%');

			// jQuery does not return reliable result for IE
			if (IE) {
				offsetWidth = Math.max(document.documentElement.offsetWidth, document.body.offsetWidth);

				if (D.width() > offsetWidth) {
					width = D.width();
				}

			} else if (D.width() > W.width()) {
				width = D.width();
			}

			this.overlay.width(width).height(D.height());
		},

		// This is where we can manipulate DOM, because later it would cause iframes to reload
		onReady : function (opts, obj) {
			var overlay = this.overlay;

			$('.fancybox-overlay').stop(true, true);

			if (!overlay) {
				this.create(opts);
			}

			if (opts.locked && this.fixed && obj.fixed) {
				if (!overlay) {
					this.margin = D.height() > W.height() ? $('html').css('margin-right').replace("px", "") : false;
				}

				obj.locked = this.overlay.append( obj.wrap );
				obj.fixed  = false;
			}

			if (opts.showEarly === true) {
				this.beforeShow.apply(this, arguments);
			}
		},

		beforeShow : function(opts, obj) {
			var scrollV, scrollH;

			if (obj.locked) {
				if (this.margin !== false) {
					$('*').filter(function(){
						return ($(this).css('position') === 'fixed' && !$(this).hasClass("fancybox-overlay") && !$(this).hasClass("fancybox-wrap") );
					}).addClass('fancybox-margin');

					this.el.addClass('fancybox-margin');
				}

				scrollV = W.scrollTop();
				scrollH = W.scrollLeft();

				this.el.addClass('fancybox-lock');

				W.scrollTop( scrollV ).scrollLeft( scrollH );
			}

			this.open(opts);
		},

		onUpdate : function() {
			if (!this.fixed) {
				this.update();
			}
		},

		afterClose: function (opts) {
			// Remove overlay if exists and fancyBox is not opening
			// (e.g., it is not being open using afterClose callback)
			//if (this.overlay && !F.isActive) {
			if (this.overlay && !F.coming) {
				this.overlay.fadeOut(opts.speedOut, $.proxy( this.close, this ));
			}
		}
	};

	/*
	 *	Title helper
	 */

	F.helpers.title = {
		defaults : {
			type     : 'float', // 'float', 'inside', 'outside' or 'over',
			position : 'bottom' // 'top' or 'bottom'
		},

		beforeShow: function (opts) {
			var current = F.current,
				text    = current.title,
				type    = opts.type,
				title,
				target;

			if ($.isFunction(text)) {
				text = text.call(current.element, current);
			}

			if (!isString(text) || $.trim(text) === '') {
				return;
			}

			title = $('<div class="fancybox-title fancybox-title-' + type + '-wrap">' + text + '</div>');

			switch (type) {
				case 'inside':
					target = F.skin;
				break;

				case 'outside':
					target = F.wrap;
				break;

				case 'over':
					target = F.inner;
				break;

				default: // 'float'
					target = F.skin;

					title.appendTo('body');

					if (IE) {
						title.width( title.width() );
					}

					title.wrapInner('<span class="child"></span>');

					//Increase bottom margin so this title will also fit into viewport
					F.current.margin[2] += Math.abs( getScalar(title.css('margin-bottom')) );
				break;
			}

			title[ (opts.position === 'top' ? 'prependTo'  : 'appendTo') ](target);
		}
	};

	// jQuery plugin initialization
	$.fn.fancybox = function (options) {
		var index,
			that     = $(this),
			selector = this.selector || '',
			run      = function(e) {
				var what = $(this).blur(), idx = index, relType, relVal;

				if (!(e.ctrlKey || e.altKey || e.shiftKey || e.metaKey) && !what.is('.fancybox-wrap')) {
					relType = options.groupAttr || 'data-fancybox-group';
					relVal  = what.attr(relType);

					if (!relVal) {
						relType = 'rel';
						relVal  = what.get(0)[ relType ];
					}

					if (relVal && relVal !== '' && relVal !== 'nofollow') {
						what = selector.length ? $(selector) : that;
						what = what.filter('[' + relType + '="' + relVal + '"]');
						idx  = what.index(this);
					}

					options.index = idx;

					// Stop an event from bubbling if everything is fine
					if (F.open(what, options) !== false) {
						e.preventDefault();
					}
				}
			};

		options = options || {};
		index   = options.index || 0;

		if (!selector || options.live === false) {
			that.unbind('click.fb-start').bind('click.fb-start', run);

		} else {
			D.undelegate(selector, 'click.fb-start').delegate(selector + ":not('.fancybox-item, .fancybox-nav')", 'click.fb-start', run);
		}

		this.filter('[data-fancybox-start=1]').trigger('click');

		return this;
	};

	// Tests that need a body at doc ready
	D.ready(function() {
		var w1, w2;

		if ( $.scrollbarWidth === undefined ) {
			// http://benalman.com/projects/jquery-misc-plugins/#scrollbarwidth
			$.scrollbarWidth = function() {
				var parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body'),
					child  = parent.children(),
					width  = child.innerWidth() - child.height( 99 ).innerWidth();

				parent.remove();

				return width;
			};
		}

		if ( $.support.fixedPosition === undefined ) {
			$.support.fixedPosition = (function() {
				var elem  = $('<div style="position:fixed;top:20px;"></div>').appendTo('body'),
					fixed = ( elem[0].offsetTop === 20 || elem[0].offsetTop === 15 );

				elem.remove();

				return fixed;
			}());
		}

		$.extend(F.defaults, {
			scrollbarWidth : $.scrollbarWidth(),
			fixed  : $.support.fixedPosition,
			parent : $('body')
		});

		//Get real width of page scroll-bar
		w1 = $(window).width();

		H.addClass('fancybox-lock-test');

		w2 = $(window).width();

		H.removeClass('fancybox-lock-test');

		$("<style type='text/css'>.fancybox-margin{margin-right:" + (w2 - w1) + "px;}</style>").appendTo("head");
	});

}(window, document, jQuery));;
/*
 Copyright 2011-2013 Abdulla Abdurakhmanov
 Original sources are available at https://code.google.com/p/x2js/
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 http://www.apache.org/licenses/LICENSE-2.0
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

(function (root, factory) {
    if (typeof define === "function" && define.amd) {
        define([], factory);
    } else if (typeof exports === "object") {
        module.exports = factory();
    } else {
        root.X2JS = factory();
    }
}(this, function () {
    return function (config) {
        'use strict';

        var VERSION = "1.2.0";

        config = config || {};
        initConfigDefaults();
        initRequiredPolyfills();

        function initConfigDefaults() {
            if (config.escapeMode === undefined) {
                config.escapeMode = true;
            }

            config.attributePrefix = config.attributePrefix || "_";
            config.arrayAccessForm = config.arrayAccessForm || "none";
            config.emptyNodeForm = config.emptyNodeForm || "text";

            if (config.enableToStringFunc === undefined) {
                config.enableToStringFunc = true;
            }
            config.arrayAccessFormPaths = config.arrayAccessFormPaths || [];
            if (config.skipEmptyTextNodesForObj === undefined) {
                config.skipEmptyTextNodesForObj = true;
            }
            if (config.stripWhitespaces === undefined) {
                config.stripWhitespaces = true;
            }
            config.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];

            if (config.useDoubleQuotes === undefined) {
                config.useDoubleQuotes = false;
            }

            config.xmlElementsFilter = config.xmlElementsFilter || [];
            config.jsonPropertiesFilter = config.jsonPropertiesFilter || [];

            if (config.keepCData === undefined) {
                config.keepCData = false;
            }
        }

        var DOMNodeTypes = {
            ELEMENT_NODE: 1,
            TEXT_NODE: 3,
            CDATA_SECTION_NODE: 4,
            COMMENT_NODE: 8,
            DOCUMENT_NODE: 9
        };

        function initRequiredPolyfills() {
        }

        function getNodeLocalName(node) {
            var nodeLocalName = node.localName;
            if (nodeLocalName == null) // Yeah, this is IE!! 
                nodeLocalName = node.baseName;
            if (nodeLocalName == null || nodeLocalName == "") // =="" is IE too
                nodeLocalName = node.nodeName;
            return nodeLocalName;
        }

        function getNodePrefix(node) {
            return node.prefix;
        }

        function escapeXmlChars(str) {
            if (typeof (str) == "string")
                return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;');
            else
                return str;
        }

        function unescapeXmlChars(str) {
            return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
        }

        function checkInStdFiltersArrayForm(stdFiltersArrayForm, obj, name, path) {
            var idx = 0;
            for (; idx < stdFiltersArrayForm.length; idx++) {
                var filterPath = stdFiltersArrayForm[idx];
                if (typeof filterPath === "string") {
                    if (filterPath == path)
                        break;
                }
                else
                    if (filterPath instanceof RegExp) {
                        if (filterPath.test(path))
                            break;
                    }
                    else
                        if (typeof filterPath === "function") {
                            if (filterPath(obj, name, path))
                                break;
                        }
            }
            return idx != stdFiltersArrayForm.length;
        }

        function toArrayAccessForm(obj, childName, path) {
            switch (config.arrayAccessForm) {
                case "property":
                    if (!(obj[childName] instanceof Array))
                        obj[childName + "_asArray"] = [obj[childName]];
                    else
                        obj[childName + "_asArray"] = obj[childName];
                    break;
				/*case "none":
					break;*/
            }

            if (!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {
                if (checkInStdFiltersArrayForm(config.arrayAccessFormPaths, obj, childName, path)) {
                    obj[childName] = [obj[childName]];
                }
            }
        }

        function fromXmlDateTime(prop) {
            // Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object
            // Improved to support full spec and optional parts
            var bits = prop.split(/[-T:+Z]/g);

            var d = new Date(bits[0], bits[1] - 1, bits[2]);
            var secondBits = bits[5].split("\.");
            d.setHours(bits[3], bits[4], secondBits[0]);
            if (secondBits.length > 1)
                d.setMilliseconds(secondBits[1]);

            // Get supplied time zone offset in minutes
            if (bits[6] && bits[7]) {
                var offsetMinutes = bits[6] * 60 + Number(bits[7]);
                var sign = /\d\d-\d\d:\d\d$/.test(prop) ? '-' : '+';

                // Apply the sign
                offsetMinutes = 0 + (sign == '-' ? -1 * offsetMinutes : offsetMinutes);

                // Apply offset and local timezone
                d.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset())
            }
            else
                if (prop.indexOf("Z", prop.length - 1) !== -1) {
                    d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
                }

            // d is now a local time equivalent to the supplied time
            return d;
        }

        function checkFromXmlDateTimePaths(value, childName, fullPath) {
            if (config.datetimeAccessFormPaths.length > 0) {
                var path = fullPath.split("\.#")[0];
                if (checkInStdFiltersArrayForm(config.datetimeAccessFormPaths, value, childName, path)) {
                    return fromXmlDateTime(value);
                }
                else
                    return value;
            }
            else
                return value;
        }

        function checkXmlElementsFilter(obj, childType, childName, childPath) {
            if (childType == DOMNodeTypes.ELEMENT_NODE && config.xmlElementsFilter.length > 0) {
                return checkInStdFiltersArrayForm(config.xmlElementsFilter, obj, childName, childPath);
            }
            else
                return true;
        }

        function parseDOMChildren(node, path) {
            if (node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {
                var result = new Object;
                var nodeChildren = node.childNodes;
                // Alternative for firstElementChild which is not supported in some environments
                for (var cidx = 0; cidx < nodeChildren.length; cidx++) {
                    var child = nodeChildren.item(cidx);
                    if (child.nodeType == DOMNodeTypes.ELEMENT_NODE) {
                        var childName = getNodeLocalName(child);
                        result[childName] = parseDOMChildren(child, childName);
                    }
                }
                return result;
            }
            else
                if (node.nodeType == DOMNodeTypes.ELEMENT_NODE) {
                    var result = new Object;
                    result.__cnt = 0;

                    var nodeChildren = node.childNodes;

                    // Children nodes
                    for (var cidx = 0; cidx < nodeChildren.length; cidx++) {
                        var child = nodeChildren.item(cidx); // nodeChildren[cidx];
                        var childName = getNodeLocalName(child);

                        if (child.nodeType != DOMNodeTypes.COMMENT_NODE) {
                            var childPath = path + "." + childName;
                            if (checkXmlElementsFilter(result, child.nodeType, childName, childPath)) {
                                result.__cnt++;
                                if (result[childName] == null) {
                                    result[childName] = parseDOMChildren(child, childPath);
                                    toArrayAccessForm(result, childName, childPath);
                                }
                                else {
                                    if (result[childName] != null) {
                                        if (!(result[childName] instanceof Array)) {
                                            result[childName] = [result[childName]];
                                            toArrayAccessForm(result, childName, childPath);
                                        }
                                    }
                                    (result[childName])[result[childName].length] = parseDOMChildren(child, childPath);
                                }
                            }
                        }
                    }

                    // Attributes
                    for (var aidx = 0; aidx < node.attributes.length; aidx++) {
                        var attr = node.attributes.item(aidx); // [aidx];
                        result.__cnt++;
                        result[config.attributePrefix + attr.name] = attr.value;
                    }

                    // Node namespace prefix
                    var nodePrefix = getNodePrefix(node);
                    if (nodePrefix != null && nodePrefix != "") {
                        result.__cnt++;
                        result.__prefix = nodePrefix;
                    }

                    if (result["#text"] != null) {
                        result.__text = result["#text"];
                        if (result.__text instanceof Array) {
                            result.__text = result.__text.join("\n");
                        }
                        //if(config.escapeMode)
                        //	result.__text = unescapeXmlChars(result.__text);
                        if (config.stripWhitespaces)
                            result.__text = result.__text.trim();
                        delete result["#text"];
                        if (config.arrayAccessForm == "property")
                            delete result["#text_asArray"];
                        result.__text = checkFromXmlDateTimePaths(result.__text, childName, path + "." + childName);
                    }
                    if (result["#cdata-section"] != null) {
                        result.__cdata = result["#cdata-section"];
                        delete result["#cdata-section"];
                        if (config.arrayAccessForm == "property")
                            delete result["#cdata-section_asArray"];
                    }

                    if (result.__cnt == 0 && config.emptyNodeForm == "text") {
                        result = '';
                    }
                    else
                        if (result.__cnt == 1 && result.__text != null) {
                            result = result.__text;
                        }
                        else
                            if (result.__cnt == 1 && result.__cdata != null && !config.keepCData) {
                                result = result.__cdata;
                            }
                            else
                                if (result.__cnt > 1 && result.__text != null && config.skipEmptyTextNodesForObj) {
                                    if ((config.stripWhitespaces && result.__text == "") || (result.__text.trim() == "")) {
                                        delete result.__text;
                                    }
                                }
                    delete result.__cnt;

                    if (config.enableToStringFunc && (result.__text != null || result.__cdata != null)) {
                        result.toString = function () {
                            return (this.__text != null ? this.__text : '') + (this.__cdata != null ? this.__cdata : '');
                        };
                    }

                    return result;
                }
                else
                    if (node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {
                        return node.nodeValue;
                    }
        }

        function startTag(jsonObj, element, attrList, closed) {
            var resultStr = "<" + ((jsonObj != null && jsonObj.__prefix != null) ? (jsonObj.__prefix + ":") : "") + element;
            if (attrList != null) {
                for (var aidx = 0; aidx < attrList.length; aidx++) {
                    var attrName = attrList[aidx];
                    var attrVal = jsonObj[attrName];
                    if (config.escapeMode)
                        attrVal = escapeXmlChars(attrVal);
                    resultStr += " " + attrName.substr(config.attributePrefix.length) + "=";
                    if (config.useDoubleQuotes)
                        resultStr += '"' + attrVal + '"';
                    else
                        resultStr += "'" + attrVal + "'";
                }
            }
            if (!closed)
                resultStr += ">";
            else
                resultStr += "/>";
            return resultStr;
        }

        function endTag(jsonObj, elementName) {
            return "</" + (jsonObj.__prefix != null ? (jsonObj.__prefix + ":") : "") + elementName + ">";
        }

        function endsWith(str, suffix) {
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }

        function jsonXmlSpecialElem(jsonObj, jsonObjField) {
            if ((config.arrayAccessForm == "property" && endsWith(jsonObjField.toString(), ("_asArray")))
                || jsonObjField.toString().indexOf(config.attributePrefix) == 0
                || jsonObjField.toString().indexOf("__") == 0
                || (jsonObj[jsonObjField] instanceof Function))
                return true;
            else
                return false;
        }

        function jsonXmlElemCount(jsonObj) {
            var elementsCnt = 0;
            if (jsonObj instanceof Object) {
                for (var it in jsonObj) {
                    if (jsonXmlSpecialElem(jsonObj, it))
                        continue;
                    elementsCnt++;
                }
            }
            return elementsCnt;
        }

        function checkJsonObjPropertiesFilter(jsonObj, propertyName, jsonObjPath) {
            return config.jsonPropertiesFilter.length == 0
                || jsonObjPath == ""
                || checkInStdFiltersArrayForm(config.jsonPropertiesFilter, jsonObj, propertyName, jsonObjPath);
        }

        function parseJSONAttributes(jsonObj) {
            var attrList = [];
            if (jsonObj instanceof Object) {
                for (var ait in jsonObj) {
                    if (ait.toString().indexOf("__") == -1 && ait.toString().indexOf(config.attributePrefix) == 0) {
                        attrList.push(ait);
                    }
                }
            }
            return attrList;
        }

        function parseJSONTextAttrs(jsonTxtObj) {
            var result = "";

            if (jsonTxtObj.__cdata != null) {
                result += "<![CDATA[" + jsonTxtObj.__cdata + "]]>";
            }

            if (jsonTxtObj.__text != null) {
                if (config.escapeMode)
                    result += escapeXmlChars(jsonTxtObj.__text);
                else
                    result += jsonTxtObj.__text;
            }
            return result;
        }

        function parseJSONTextObject(jsonTxtObj) {
            var result = "";

            if (jsonTxtObj instanceof Object) {
                result += parseJSONTextAttrs(jsonTxtObj);
            }
            else
                if (jsonTxtObj != null) {
                    if (config.escapeMode)
                        result += escapeXmlChars(jsonTxtObj);
                    else
                        result += jsonTxtObj;
                }

            return result;
        }

        function getJsonPropertyPath(jsonObjPath, jsonPropName) {
            if (jsonObjPath === "") {
                return jsonPropName;
            }
            else
                return jsonObjPath + "." + jsonPropName;
        }

        function parseJSONArray(jsonArrRoot, jsonArrObj, attrList, jsonObjPath) {
            var result = "";
            if (jsonArrRoot.length == 0) {
                result += startTag(jsonArrRoot, jsonArrObj, attrList, true);
            }
            else {
                for (var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {
                    result += startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);
                    result += parseJSONObject(jsonArrRoot[arIdx], getJsonPropertyPath(jsonObjPath, jsonArrObj));
                    result += endTag(jsonArrRoot[arIdx], jsonArrObj);
                }
            }
            return result;
        }

        function parseJSONObject(jsonObj, jsonObjPath) {
            var result = "";

            var elementsCnt = jsonXmlElemCount(jsonObj);

            if (elementsCnt > 0) {
                for (var it in jsonObj) {

                    if (jsonXmlSpecialElem(jsonObj, it) || (jsonObjPath != "" && !checkJsonObjPropertiesFilter(jsonObj, it, getJsonPropertyPath(jsonObjPath, it))))
                        continue;

                    var subObj = jsonObj[it];

                    var attrList = parseJSONAttributes(subObj)

                    if (subObj == null || subObj == undefined) {
                        result += startTag(subObj, it, attrList, true);
                    }
                    else
                        if (subObj instanceof Object) {

                            if (subObj instanceof Array) {
                                result += parseJSONArray(subObj, it, attrList, jsonObjPath);
                            }
                            else if (subObj instanceof Date) {
                                result += startTag(subObj, it, attrList, false);
                                result += subObj.toISOString();
                                result += endTag(subObj, it);
                            }
                            else {
                                var subObjElementsCnt = jsonXmlElemCount(subObj);
                                if (subObjElementsCnt > 0 || subObj.__text != null || subObj.__cdata != null) {
                                    result += startTag(subObj, it, attrList, false);
                                    result += parseJSONObject(subObj, getJsonPropertyPath(jsonObjPath, it));
                                    result += endTag(subObj, it);
                                }
                                else {
                                    result += startTag(subObj, it, attrList, true);
                                }
                            }
                        }
                        else {
                            result += startTag(subObj, it, attrList, false);
                            result += parseJSONTextObject(subObj);
                            result += endTag(subObj, it);
                        }
                }
            }
            result += parseJSONTextObject(jsonObj);

            return result;
        }

        this.parseXmlString = function (xmlDocStr) {
            var isIEParser = window.ActiveXObject || "ActiveXObject" in window;
            if (xmlDocStr === undefined) {
                return null;
            }
            var xmlDoc;
            if (window.DOMParser) {
                var parser = new window.DOMParser();
                var parsererrorNS = null;
                // IE9+ now is here
                if (!isIEParser) {
                    try {
                        parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
                    }
                    catch (err) {
                        parsererrorNS = null;
                    }
                }
                try {
                    xmlDoc = parser.parseFromString(xmlDocStr, "text/xml");
                    if (parsererrorNS != null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
                        //throw new Error('Error parsing XML: '+xmlDocStr);
                        xmlDoc = null;
                    }
                }
                catch (err) {
                    xmlDoc = null;
                }
            }
            else {
                // IE :(
                if (xmlDocStr.indexOf("<?") == 0) {
                    xmlDocStr = xmlDocStr.substr(xmlDocStr.indexOf("?>") + 2);
                }
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                xmlDoc.async = "false";
                xmlDoc.loadXML(xmlDocStr);
            }
            return xmlDoc;
        };

        this.asArray = function (prop) {
            if (prop === undefined || prop == null)
                return [];
            else
                if (prop instanceof Array)
                    return prop;
                else
                    return [prop];
        };

        this.toXmlDateTime = function (dt) {
            if (dt instanceof Date)
                return dt.toISOString();
            else
                if (typeof (dt) === 'number')
                    return new Date(dt).toISOString();
                else
                    return null;
        };

        this.asDateTime = function (prop) {
            if (typeof (prop) == "string") {
                return fromXmlDateTime(prop);
            }
            else
                return prop;
        };

        this.xml2json = function (xmlDoc) {
            return parseDOMChildren(xmlDoc);
        };

        this.xml_str2json = function (xmlDocStr) {
            var xmlDoc = this.parseXmlString(xmlDocStr);
            if (xmlDoc != null)
                return this.xml2json(xmlDoc);
            else
                return null;
        };

        this.json2xml_str = function (jsonObj) {
            return parseJSONObject(jsonObj, "");
        };

        this.json2xml = function (jsonObj) {
            var xmlDocStr = this.json2xml_str(jsonObj);
            return this.parseXmlString(xmlDocStr);
        };

        this.getVersion = function () {
            return VERSION;
        };
    }
}));
/*! Raygun4js - v2.6.6 - 2017-06-16
* https://github.com/MindscapeHQ/raygun4js
* Copyright (c) 2017 MindscapeHQ; Licensed MIT */

!function(a,b){function c(a,b){return Object.prototype.hasOwnProperty.call(a,b)}function d(a){return"undefined"==typeof a}var e,f={},g=a.TraceKit,h=[].slice,i="?";f.setRaygun=function(a){e||(e=a)},f.noConflict=function(){return a.TraceKit=g,f},f.wrap=function(a){function b(){try{return a.apply(this,arguments)}catch(b){throw f.report(b),b}}return b},f.report=function(){function b(a){j(),n.push(a)}function d(a){for(var b=n.length-1;b>=0;--b)n[b]===a&&n.splice(b,1)}function g(a,b){var d=null;if(!b||f.collectWindowErrors){for(var e in n)if(c(n,e))try{n[e].apply(null,[a].concat(h.call(arguments,2)))}catch(g){d=g}if(d)throw d}}function i(a,b,c,d,e){var h=null;if(e)h=f.computeStackTrace(e);else if(p)f.computeStackTrace.augmentStackTraceWithInitialElement(p,b,c,a),h=p,p=null,o=null;else{var i={url:b,line:c,column:d};i.func=f.computeStackTrace.guessFunctionName(i.url,i.line),i.context=f.computeStackTrace.gatherContext(i.url,i.line),h={mode:"onerror",message:a,url:document.location.href,stack:[i],useragent:navigator.userAgent}}return g(h,"from window.onerror"),!!l&&l.apply(this,arguments)}function j(){m!==!0&&(l=a.onerror,a.onerror=i,m=!0)}function k(b){var c;if("undefined"!=typeof document&&(c=h.call(arguments,1)),p){if(o===b)return;var d=p;p=null,o=null,g.apply(null,[d,null].concat(c))}var i=f.computeStackTrace(b);if(p=i,o=b,a.setTimeout(function(){o===b&&(p=null,o=null,g.apply(null,[i,null].concat(c)))},i.incomplete?2e3:0),!e.Utilities.isReactNative())throw b}var l,m,n=[],o=null,p=null;return k.subscribe=b,k.unsubscribe=d,k}(),f.computeStackTrace=function(){function b(a){return"string"!=typeof a?[]:""}function g(d){if(!c(x,d)){var e="";d=d||"";var f;f="undefined"!=typeof document?document.domain:a.location.hostname,d.indexOf&&d.indexOf(f)!==-1&&(e=b(d)),x[d]=e?e.split("\n"):[]}return x[d]}function h(a,b){var c,e=/function ([^(]*)\(([^)]*)\)/,f=/['"]?([0-9A-Za-z$_]+)['"]?\s*[:=]\s*(function|eval|new Function)/,h="",j=10,k=g(a);if(!k.length)return i;for(var l=0;l<j;++l)if(h=k[b-l]+h,!d(h)){if(c=f.exec(h))return c[1];if(c=e.exec(h))return c[1]}return i}function j(a,b){var c=g(a);if(!c.length)return null;var e=[],h=Math.floor(f.linesOfContext/2),i=h+f.linesOfContext%2,j=Math.max(0,b-h-1),k=Math.min(c.length,b+i-1);b-=1;for(var l=j;l<k;++l)d(c[l])||e.push(c[l]);return e.length>0?e:null}function k(a){return a.replace(/[\-\[\]{}()*+?.,\\\^$|#]/g,"\\$&")}function l(a){return k(a).replace("<","(?:<|&lt;)").replace(">","(?:>|&gt;)").replace("&","(?:&|&amp;)").replace('"','(?:"|&quot;)').replace(/\s+/g,"\\s+")}function m(a,b){for(var c,d,e=0,f=b.length;e<f;++e)if((c=g(b[e])).length&&(c=c.join("\n"),d=a.exec(c)))return{url:b[e],line:c.substring(0,d.index).split("\n").length,column:d.index-c.lastIndexOf("\n",d.index)-1};return null}function n(a,b,c){var d,e=g(b),f=new RegExp("\\b"+k(a)+"\\b");return c-=1,e&&e.length>c&&(d=f.exec(e[c]))?d.index:null}function o(b){for(var c,d,e,f,g=[a.location.href],h=document.getElementsByTagName("script"),i=""+b,j=/^function(?:\s+([\w$]+))?\s*\(([\w\s,]*)\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,n=/^function on([\w$]+)\s*\(event\)\s*\{\s*(\S[\s\S]*\S)\s*\}\s*$/,o=0;o<h.length;++o){var p=h[o];p.src&&g.push(p.src)}if(e=j.exec(i)){var q=e[1]?"\\s+"+e[1]:"",r=e[2].split(",").join("\\s*,\\s*");c=k(e[3]).replace(/;$/,";?"),d=new RegExp("function"+q+"\\s*\\(\\s*"+r+"\\s*\\)\\s*{\\s*"+c+"\\s*}")}else d=new RegExp(k(i).replace(/\s+/g,"\\s+"));if(f=m(d,g))return f;if(e=n.exec(i)){var s=e[1];if(c=l(e[2]),d=new RegExp("on"+s+"=[\\'\"]\\s*"+c+"\\s*[\\'\"]","i"),f=m(d,g[0]))return f;if(d=new RegExp(c),f=m(d,g))return f}return null}function p(a){if(!a.stack)return{tracekitResult:"nostack"};var b,c,d=/^\s*at (.*?) ?\(((?:file|https?|\s*|blob|chrome-extension|native|webpack|eval|<anonymous>).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,f=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|\[native).*?)(?::(\d+))?(?::(\d+))?\s*$/i,g=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:ms-appx|https?|webpack|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i,k=a.stack.split("\n"),l=[],m=/^(.*) is undefined$/.exec(a.message);if(e.Utilities.isReactNative())for(var o=/^(.*@)?.*\/[^\.]+(\.app|CodePush)\/?(.*)/,p="file://reactnative.local/",q=0;q<k.length;q++)if(b=o.exec(k[q]),null!==b){var r=b[1]?b[1]:"anonymous@",s=b[3];k[q]=r+p+s}for(var q=0,t=k.length;q<t;++q){if(b=f.exec(k[q]))c={url:b[3],func:b[1]||i,args:b[2]?b[2].split(","):"",line:+b[4],column:b[5]?+b[5]:null};else if(b=d.exec(k[q]))c={url:b[2],func:b[1]||i,line:+b[3],column:b[4]?+b[4]:null};else{if(!(b=g.exec(k[q])))continue;c={url:b[2],func:b[1]||i,line:+b[3],column:b[4]?+b[4]:null}}!c.func&&c.line&&(c.func=h(c.url,c.line)),"undefined"!=typeof document&&c.line&&(c.context=j(c.url,c.line)),l.push(c)}if(l[0]&&l[0].line&&!l[0].column&&m?l[0].column=n(m[1],l[0].url,l[0].line):l[0].column||"undefined"==typeof a.columnNumber||(l[0].column=a.columnNumber+1),!l.length)return null;var u={mode:"stack",name:a?a.name:"",message:a?a.message:"",url:"undefined"!=typeof document?document.location.href:"",stack:l,useragent:navigator?navigator.userAgent:"",stackstring:a&&a.stack?a.stack.toString():""};return u}function q(a){for(var b,c=a.stacktrace,d=/ line (\d+), column (\d+) in (?:<anonymous function: ([^>]+)>|([^\)]+))\((.*)\) in (.*):\s*$/i,e=c?c.split("\n"):[],f=[],g=0,i=e.length;g<i;g+=2)if(b=d.exec(e[g])){var k={line:+b[1],column:+b[2],func:b[3]||b[4],args:b[5]?b[5].split(","):[],url:b[6]};if(!k.func&&k.line&&(k.func=h(k.url,k.line)),k.line)try{k.context=j(k.url,k.line)}catch(l){}k.context||(k.context=[e[g+1]]),f.push(k)}return f.length?{mode:"stacktrace",name:a.name,message:a.message,url:document.location.href,stack:f,useragent:navigator.userAgent,stackstring:c}:null}function r(b){var d=b.message.split("\n");if(d.length<4)return null;var e,f,i,k,n=/^\s*Line (\d+) of linked script ((?:file|http|https)\S+)(?:: in function (\S+))?\s*$/i,o=/^\s*Line (\d+) of inline#(\d+) script in ((?:file|http|https)\S+)(?:: in function (\S+))?\s*$/i,p=/^\s*Line (\d+) of function script\s*$/i,q=[],r=document.getElementsByTagName("script"),s=[];for(f in r)c(r,f)&&!r[f].src&&s.push(r[f]);for(f=2,i=d.length;f<i;f+=2){var t=null;if(e=n.exec(d[f]))t={url:e[2],func:e[3],line:+e[1]};else if(e=o.exec(d[f])){t={url:e[3],func:e[4]};var u=+e[1],v=s[e[2]-1];if(v&&(k=g(t.url))){k=k.join("\n");var w=k.indexOf(v.innerText);w>=0&&(t.line=u+k.substring(0,w).split("\n").length)}}else if(e=p.exec(d[f])){var x=a.location.href.replace(/#.*$/,""),y=e[1],z=new RegExp(l(d[f+1]));k=m(z,[x]),t={url:x,line:k?k.line:y,func:""}}if(t){t.func||(t.func=h(t.url,t.line));var A=j(t.url,t.line),B=A?A[Math.floor(A.length/2)]:null;A&&B.replace(/^\s*/,"")===d[f+1].replace(/^\s*/,"")?t.context=A:t.context=[d[f+1]],q.push(t)}}return q.length?{mode:"multiline",name:b.name,message:d[0],url:document.location.href,stack:q,useragent:navigator.userAgent}:null}function s(a,b,c,d){var e={url:b,line:c};if(e.url&&e.line){a.incomplete=!1,e.func||(e.func=h(e.url,e.line)),e.context||(e.context=j(e.url,e.line));var f=/ '([^']+)' /.exec(d);if(f&&(e.column=n(f[1],e.url,e.line)),a.stack.length>0&&a.stack[0].url===e.url){if(a.stack[0].line===e.line)return!1;if(!a.stack[0].line&&a.stack[0].func===e.func)return a.stack[0].line=e.line,a.stack[0].context=e.context,!1}return a.stack.unshift(e),a.partial=!0,!0}return a.incomplete=!0,!1}function t(a,b){for(var c,d,e,g=/function\s+([_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*)?\s*\(/i,j=[],k={},l=!1,m=t.caller;m&&!l;m=m.caller)if(m!==u&&m!==f.report){if(d={url:null,func:i,line:null,column:null},m.name?d.func=m.name:(c=g.exec(m.toString()))&&(d.func=c[1]),"undefined"==typeof d.func)try{d.func=c.input.substring(0,c.input.indexOf("{"))}catch(p){}if(e=o(m)){d.url=e.url,d.line=e.line,d.func===i&&(d.func=h(d.url,d.line));var q=/ '([^']+)' /.exec(a.message||a.description);q&&(d.column=n(q[1],e.url,e.line))}k[""+m]?l=!0:k[""+m]=!0,j.push(d)}b&&j.splice(0,b);var r={mode:"callers",name:a.name,message:a.message,url:document.location.href,stack:j,useragent:navigator.userAgent};return s(r,a.sourceURL||a.fileName,a.line||a.lineNumber,a.message||a.description),r}function u(a,b){var c=null;b=null==b?0:+b;try{if(c=q(a))return c}catch(d){if(w)throw d}try{if(c=p(a))return c}catch(d){if(w)throw d}try{if(c=r(a))return c}catch(d){if(w)throw d}try{if(c=t(a,b+1))return c}catch(d){if(w)throw d}return{tracekitResult:"failedToComputeAnyStackTrace"}}function v(a){a=(null==a?0:+a)+1;try{throw new Error}catch(b){return u(b,a+1)}}var w=!1,x={};return u.augmentStackTraceWithInitialElement=s,u.guessFunctionName=h,u.gatherContext=j,u.ofCaller=v,u}(),f.extendToAsynchronousCallbacks=function(){var b=function(b){var c=a[b];a[b]=function(){var a=h.call(arguments),b=a[0];return"function"==typeof b&&(a[0]=f.wrap(b)),c.apply?c.apply(this,a):c(a[0],a[1])}};b("setTimeout"),b("setInterval")},f.remoteFetching||(f.remoteFetching=!0),f.collectWindowErrors||(f.collectWindowErrors=!0),(!f.linesOfContext||f.linesOfContext<1)&&(f.linesOfContext=11),a.TraceKit=f}(window),function(a,b){"use strict";if(a&&a.event&&a.event.add){var c=a.event.add;a.event.add=function(d,e,f,g,h){if("function"!=typeof f&&"function"!=typeof f.handler)return c.call(this,d,e,f,g,h);var i;return f.handler?(i=f.handler,f.handler=b.wrap(f.handler)):(i=f,f=b.wrap(f)),i.guid?f.guid=i.guid:f.guid=i.guid=a.guid++,c.call(this,d,e,f,g,h)};var d=a.fn.ready;a.fn.ready=function(a){return d.call(this,b.wrap(a))};var e=a.ajax;a.ajax=function(c,d){"object"==typeof c&&(d=c,c=void 0),d=d||{};for(var f,g=["complete","error","success"];f=g.pop();)a.isFunction(d[f])&&(d[f]=b.wrap(d[f]));try{return c?e.call(this,c,d):e.call(this,d)}catch(h){throw b.report(h),h}}}}(window.jQuery,window.TraceKit),Date.prototype.toISOString||!function(){function a(a){var b=String(a);return 1===b.length&&(b="0"+b),b}Date.prototype.toISOString=function(){return this.getUTCFullYear()+"-"+a(this.getUTCMonth()+1)+"-"+a(this.getUTCDate())+"T"+a(this.getUTCHours())+":"+a(this.getUTCMinutes())+":"+a(this.getUTCSeconds())+"."+String((this.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}}(),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null==this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=0|b;if(f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);c<e;){if(c in d&&d[c]===a)return c;c++}return-1}),Array.prototype.map||(Array.prototype.map=function(a){var b,c,d;if(null==this)throw new TypeError("this is null or not defined");var e=Object(this),f=e.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(b=arguments[1]),c=new Array(f),d=0;d<f;){var g,h;d in e&&(g=e[d],h=a.call(b,g,d,e),c[d]=h),d++}return c}),Array.prototype.forEach||(Array.prototype.forEach=function(a){var b,c;if(null==this)throw new TypeError("this is null or not defined");var d=Object(this),e=d.length>>>0;if("function"!=typeof a)throw new TypeError(a+" is not a function");for(arguments.length>1&&(b=arguments[1]),c=0;c<e;){var f;c in d&&(f=d[c],a.call(b,f,c,d)),c++}}),Function.prototype.bind||(Function.prototype.bind=function(a){if("function"!=typeof this)throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");var b=Array.prototype.slice.call(arguments,1),c=this,d=function(){},e=function(){return c.apply(this instanceof d&&a?this:a,b.concat(Array.prototype.slice.call(arguments)))};return d.prototype=this.prototype,e.prototype=new d,e}),window.raygunUtilityFactory=function(a,b){var c,d={getUuid:function(){function a(a){var b=(Math.random().toString(16)+"000000000").substr(2,8);return a?"-"+b.substr(0,4)+"-"+b.substr(4,4):b}return a()+a(!0)+a(!0)+a()},createCookie:function(a,b,c){if(!this.isReactNative()){var d;if(c){var e=new Date;e.setTime(e.getTime()+60*c*60*1e3),d="; expires="+e.toGMTString()}else d="";document.cookie=a+"="+b+d+"; path=/"}},readCookie:function(a,b){if(this.isReactNative())return void b(null,"none");for(var c=a+"=",d=document.cookie.split(";"),e=0;e<d.length;e++){for(var f=d[e];" "===f.charAt(0);)f=f.substring(1,f.length);if(0===f.indexOf(c)){var g=f.substring(c.length,f.length);return void b(null,g)}}b(null,null)},clearCookie:function(a){this.isReactNative()||this.createCookie(a,"",-1)},log:function(c,d){a.console&&a.console.log&&b.Options._debugMode&&(a.console.log(c),d&&a.console.log(d))},isApiKeyConfigured:function(){return!(!b.Options._raygunApiKey||""===b.Options._raygunApiKey)||(b.Utilities.log("Raygun API key has not been configured, make sure you call Raygun.init(yourApiKey)"),!1)},isReactNative:function(){return"undefined"==typeof document&&"undefined"!=typeof __DEV__},defaultReactNativeGlobalHandler:function(a,b){"function"==typeof c&&c(a,b)},localStorageAvailable:function(){try{return"localStorage"in a&&null!==a.localStorage}catch(b){return!1}},truncateURL:function(a){var b=a,c=a.split("//")[1];if(c){var d=c.indexOf("?"),e=c.toString().substring(0,d),f=e.split("/").slice(0,4).join("/"),g=e.substring(0,48);b=f.length<g.length?f:g,b!==e&&(b+="..")}return b},merge:function(a,b){var c,d={};for(c in a)d[c]=a[c];for(c in b)d[c]=b[c];return d},mergeMutate:function(a,b){var c;for(c in b)a[c]=b[c];return a},mergeArray:function(a,b){return null!=b?a.concat(b):a},forEach:function(a,b){for(var c=0;c<a.length;c++)b.call(null,c,a[c])},isEmpty:function(a){for(var b in a)if(a.hasOwnProperty(b))return!1;return!0},contains:function(a,b){for(var c=a.length;c--;)if(a[c]===b)return!0;return!1},getRandomInt:function(){return Math.floor(9007199254740992*Math.random())},getViewPort:function(){if(this.isReactNative())return{width:"Not available",height:"Not available"};var b=document.documentElement,c=document.getElementsByTagName("body")[0],d=a.innerWidth||b.clientWidth||c.clientWidth,e=a.innerHeight||b.clientHeight||c.clientHeight;return{width:d,height:e}},parseUrl:function(b,c){function d(a){return!isNaN(parseFloat(a))&&isFinite(a)}return function(b,c){if("undefined"==typeof document)return"";var e=c||a.location.toString();if(!b)return e;b=b.toString(),"//"===e.substring(0,2)?e="http:"+e:1===e.split("://").length&&(e="http://"+e),c=e.split("/");var f={auth:""},g=c[2].split("@");1===g.length?g=g[0].split(":"):(f.auth=g[0],g=g[1].split(":")),f.protocol=c[0],f.hostname=g[0],f.port=g[1]||("https"===f.protocol.split(":")[0].toLowerCase()?"443":"80"),f.pathname=(c.length>3?"/":"")+c.slice(3,c.length).join("/").split("?")[0].split("#")[0];var h=f.pathname;"/"===h.charAt(h.length-1)&&(h=h.substring(0,h.length-1));var i=f.hostname,j=i.split("."),k=h.split("/");if("hostname"===b)return i;if("domain"===b)return/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/.test(i)?i:j.slice(-2).join(".");if("sub"===b)return j.slice(0,j.length-2).join(".");if("port"===b)return f.port;if("protocol"===b)return f.protocol.split(":")[0];if("auth"===b)return f.auth;if("user"===b)return f.auth.split(":")[0];if("pass"===b)return f.auth.split(":")[1]||"";if("path"===b)return f.pathname;if("."===b.charAt(0)){if(b=b.substring(1),d(b))return b=parseInt(b,10),j[b<0?j.length+b:b-1]||""}else{if(d(b))return b=parseInt(b,10),k[b<0?k.length+b:b]||"";if("file"===b)return k.slice(-1)[0];if("filename"===b)return k.slice(-1)[0].split(".")[0];if("fileext"===b)return k.slice(-1)[0].split(".")[1]||"";if("?"===b.charAt(0)||"#"===b.charAt(0)){var l=e,m=null;if("?"===b.charAt(0)?l=(l.split("?")[1]||"").split("#")[0]:"#"===b.charAt(0)&&(l=l.split("#")[1]||""),!b.charAt(1))return l;b=b.substring(1),l=l.split("&");for(var n=0,o=l.length;n<o;n++)if(m=l[n].split("="),m[0]===b)return m[1]||"";return null}}return""}(b,c)},enhance:function(a,b,c){var d=a[b];return a[b]=function(){c.apply(this,arguments),"function"==typeof d&&d.apply(this,arguments)},function(){a[b]=d}},addEventHandler:function(a,b,c,d){var e=d||!1;return a.addEventListener?a.addEventListener(b,c,e):a.attachEvent?a.attachEvent("on"+b,c):a["on"+b]=c,function(){a.removeEventListener?a.removeEventListener(b,c,e):a.detachEvent?a.detachEvent("on"+b,c):a["on"+b]=function(){}}},nodeText:function(a){var b=a.textContent||a.innerText||"";return["submit","button"].indexOf(a.type)!==-1&&(b=a.value),b=b.replace(/^\s+|\s+$/g,"")},nodeSelector:function(a){var b=[a.tagName];return a.id&&b.push("#"+a.id),a.className&&a.className.length&&b.push("."+a.className.split(" ").join(".")),b.join("")},truncate:function(a,b){var c="(...)";return a.length>b?a.slice(0,b-c.length)+c:a}};return d.isReactNative()&&__DEV__!==!0&&a.ErrorUtils&&a.ErrorUtils.getGlobalHandler&&(c=a.ErrorUtils.getGlobalHandler()),d},window.raygunBreadcrumbsFactory=function(a,b){var c=function(){this.MAX_BREADCRUMBS=32,this.MAX_MESSAGE_SIZE=1024,this.BREADCRUMB_LEVELS=["debug","info","warning","error"],this.DEFAULT_BREADCRUMB_LEVEL="info",this.DEFAULT_XHR_IGNORED_HOSTS=["raygun"],this.breadcrumbLevel="info",this.logXhrContents=!1,this.xhrIgnoredHosts=[].concat(this.DEFAULT_XHR_IGNORED_HOSTS),this.breadcrumbs=[],this.raygunInstance={send:function(){}};var a=this;this.wrapWithHandler=function(b){return function(){try{return b.apply(this,arguments)}catch(c){a.raygunInstance.send(c)}}},this.disableConsoleFunctions=[],this.disableNavigationFunctions=[],this.disableXHRLogging=function(){},this.disableClicksTracking=function(){},this.enableAutoBreadcrumbs()};return c.prototype.recordBreadcrumb=function(a,c){var d={level:this.DEFAULT_BREADCRUMB_LEVEL,timestamp:(new Date).getTime(),type:"manual"};switch(typeof a){case"object":d=b.Utilities.merge(d,a);break;case"string":d=b.Utilities.merge(b.Utilities.merge(d,{message:a,metadata:c}));break;default:return void b.Utilities.log("expected first argument to recordBreadcrumb to be a 'string' or 'object', got "+typeof a)}this.BREADCRUMB_LEVELS.indexOf(d.level)===-1&&(b.Utilities.log("unknown breadcrumb level "+d.level+" setting to default of '"+this.DEFAULT_BREADCRUMB_LEVEL+"'"),d.level=this.DEFAULT_BREADCRUMB_LEVEL),this.shouldRecord(d)&&(d.message=b.Utilities.truncate(d.message,this.MAX_MESSAGE_SIZE),this.breadcrumbs.push(d),this.breadcrumbs=this.breadcrumbs.slice(-this.MAX_BREADCRUMBS))},c.prototype.shouldRecord=function(a){var b=this.BREADCRUMB_LEVELS.indexOf(a.level),c=this.BREADCRUMB_LEVELS.indexOf(this.breadcrumbLevel);return b>=c},c.prototype.setBreadcrumbLevel=function(a){return this.BREADCRUMB_LEVELS.indexOf(a)===-1?void b.Utilities.log("Breadcrumb level of '"+a+"' is invalid, setting to default of '"+this.DEFAULT_BREADCRUMB_LEVEL+"'"):void(this.breadcrumbLevel=a)},c.prototype.setOption=function(a,b){"breadcrumbsLevel"===a?this.setBreadcrumbLevel(b):"xhrIgnoredHosts"===a?this.xhrIgnoredHosts=b.concat(this.DEFAULT_XHR_IGNORED_HOSTS):"logXhrContents"===a&&(this.logXhrContents=b)},c.prototype.any=function(){return this.breadcrumbs.length>0},c.prototype.all=function(){return this.breadcrumbs},c.prototype.enableAutoBreadcrumbs=function(){this.enableAutoBreadcrumbsXHR(),this.enableAutoBreadcrumbsClicks(),this.enableAutoBreadcrumbsConsole(),this.enableAutoBreadcrumbsNavigation()},c.prototype.disableAutoBreadcrumbs=function(){this.disableAutoBreadcrumbsXHR(),this.disableAutoBreadcrumbsClicks(),this.disableAutoBreadcrumbsConsole(),this.disableAutoBreadcrumbsNavigation()},c.prototype.enableAutoBreadcrumbsConsole=function(){if("undefined"!=typeof a.console){var c=function(a,b){this.recordBreadcrumb({type:"console",level:a,message:Array.prototype.slice.call(b).join(", ")})}.bind(this),d=["log","warn","error"],e=this;this.disableConsoleFunctions=d.map(function(a){return b.Utilities.enhance(console,a,e.wrapWithHandler(function(){var b="log"===a?"info":"warn"===a?"warning":"error";c(b,arguments)}))})}},c.prototype.disableAutoBreadcrumbsConsole=function(){this.disableConsoleFunctions.forEach(function(a){a()})},c.prototype.enableAutoBreadcrumbsNavigation=function(){if(a.addEventListener&&a.history&&a.history.pushState){var c=function(b,c,d,e){var f=location.pathname+location.search+location.hash,g=null;return a.history.state&&(g=history.state),{message:"History "+b,type:"navigation",level:"info",metadata:{from:f,to:e||f,prevState:JSON.stringify(g)||"unsupported",nextState:JSON.stringify(c)}}}.bind(this),d=function(a){return a.split("#")[1]||""},e=["pushState","replaceState"];this.disableNavigationFunctions=this.disableNavigationFunctions.concat(e.map(function(a){return b.Utilities.enhance(history,a,this.wrapWithHandler(function(b,d,e){this.recordBreadcrumb(c(a,b,d,e))}.bind(this)))}.bind(this)));var f=function(a){var b,c=a.oldURL,e=a.newURL;return b=c&&e?{from:d(c),to:d(e)}:{to:location.hash},{type:"navigation",message:"Hash change",metadata:b}},g=function(a){return this.wrapWithHandler(function(){this.recordBreadcrumb(a.apply(null,arguments))}.bind(this))}.bind(this),h=[{element:a,event:"hashchange",handler:f},{element:a,event:"load",handler:function(){return{type:"navigation",message:"Page loaded"}}},{element:a,event:"popstate",handler:function(){return{type:"navigation",message:"Navigated back"}}},{element:a,event:"pagehide",handler:function(){return{type:"navigation",message:"Page hidden"}}},{element:a,event:"pageshow",handler:function(){return{type:"navigation",message:"Page shown"}}},{element:document,event:"DOMContentLoaded",handler:function(){return{type:"navigation",message:"DOMContentLoaded"}}}];this.disableNavigationFunctions=this.disableNavigationFunctions.concat(h.map(function(a){return b.Utilities.addEventHandler(a.element,a.event,g(a.handler))}.bind(this)))}},c.prototype.disableAutoBreadcrumbsNavigation=function(){this.disableNavigationFunctions.forEach(function(a){a()}),this.disableNavigationFunctions=[]},c.prototype.enableAutoBreadcrumbsClicks=function(){this.disableClicksTracking=b.Utilities.addEventHandler(a,"click",this.wrapWithHandler(function(a){var c,d;try{c=b.Utilities.truncate(b.Utilities.nodeText(a.target),150),d=b.Utilities.nodeSelector(a.target)}catch(e){c="[unknown]",d="[unknown]",b.Utilities.log("Error retrieving node text/selector. Most likely due to a cross domain error")}this.recordBreadcrumb({type:"click-event",message:"UI Click",level:"info",metadata:{text:c,selector:d}})}.bind(this),!0))},c.prototype.disableAutoBreadcrumbsClicks=function(){this.disableClicksTracking()},c.prototype.enableAutoBreadcrumbsXHR=function(){var c=this;this.disableXHRLogging=b.Utilities.enhance(a.XMLHttpRequest.prototype,"open",c.wrapWithHandler(function(){for(var a=(new Date).getTime(),d=arguments[1]||"Unknown",e=arguments[0],f=0;f<c.xhrIgnoredHosts.length;f++){var g=c.xhrIgnoredHosts[f];if("string"==typeof g&&d&&d.indexOf(g)>-1)return;if("object"==typeof g&&g.exec(d))return}b.Utilities.enhance(this,"send",c.wrapWithHandler(function(){var a={method:e};arguments[0]&&"string"==typeof arguments[0]&&c.logXhrContents&&(a.requestText=b.Utilities.truncate(arguments[0],500)),c.recordBreadcrumb({type:"request",message:"Opening request to "+d,level:"info",metadata:a})})),this.addEventListener("load",c.wrapWithHandler(function(){var e="N/A for non text responses";""!==this.responseType&&"text"!==this.responseType||(e=b.Utilities.truncate(this.responseText,500)),c.recordBreadcrumb({type:"request",message:"Finished request to "+d,level:"info",metadata:{status:this.status,responseURL:this.responseURL,responseText:c.logXhrContents?e:"Disabled",duration:(new Date).getTime()-a+"ms"}})})),this.addEventListener("error",c.wrapWithHandler(function(){c.recordBreadcrumb({type:"request",message:"Failed request to "+d,level:"info",metadata:{status:this.status,responseURL:this.responseURL,duration:(new Date).getTime()-a+"ms"}})})),this.addEventListener("abort",c.wrapWithHandler(function(){c.recordBreadcrumb({type:"request",message:"Request to "+d+"aborted",level:"info",metadata:{duration:(new Date).getTime()-a+"ms"}})}))}))},c.prototype.disableAutoBreadcrumbsXHR=function(){this.disableXHRLogging()},c.prototype.setCrashReportingInstance=function(a){a.init("D8pC4YA3glwX5g4N/krb6Q=="),this.raygunInstance=a;var b,d;for(b in c.prototype)d=c.prototype[b],"function"==typeof d&&(c.prototype[b]=this.wrapWithHandler(d))},c};var raygunFactory=function(a,b,c,d){function e(a){"function"==typeof z&&z(a)}function f(){t||M?h():s.Utilities.readCookie(D,g)}function g(a,b){var c;a&&(c="Unknown"),b?c=b:(c=s.Utilities.getUuid(),s.Utilities.createCookie(D,c,744)),s.setUser(c,!0,null,null,null,c),h()}function h(){if(_!==C.READY){if(_=C.READY,s.RealUserMonitoring!==d&&!O){var b=function(){X=new s.RealUserMonitoring(s.Options._raygunApiKey,T,r,t,u,R,U,V,G,Z,$,ca),X.attach()};"onLoad"===A?b():a.addEventListener?a.addEventListener("load",b):a.attachEvent("onload",b)}i(),k()}}function i(){var a;for(a=0;a<aa.length;a++)o(aa[a].stackTrace,aa[a].options,aa[a].userTriggered);for(aa=[],a=0;a<ba.length;a++)X.trackEvent(ba[a].type,ba[a].options);ba=[]}function j(a,b){var c=(new Date).toJSON();try{var d="raygunjs+"+s.Options._raygunApiKey+"="+c+"="+s.Utilities.getRandomInt();"undefined"==typeof localStorage[d]&&(localStorage[d]=JSON.stringify({url:a,data:b}))}catch(e){s.Utilities.log("Raygun4JS: LocalStorage full, cannot save exception")}}function k(){if(s.Utilities.localStorageAvailable())for(var a in localStorage)if("raygunjs="===a.substring(0,9)||a.substring(0,33)==="raygunjs+"+s.Options._raygunApiKey){try{var b=JSON.parse(localStorage[a]);r(b.url,b.data)}catch(c){s.Utilities.log("Raygun4JS: Invalid JSON object in LocalStorage")}try{localStorage.removeItem(a)}catch(c){s.Utilities.log("Raygun4JS: Unable to remove error")}}}function l(a,b){if(v)for(var c=0;c<v.length;c++)if("object"==typeof v[c]&&"function"==typeof v[c].exec){if(null!==v[c].exec(a))return"[removed by filter]"}else if(v[c]===a)return"[removed by filter]";return b}function m(a,b){if(null==a)return a;if("[object Object]"!==Object.prototype.toString.call(a))return a;var c={};for(var d in a){var e=a[d];"[object Object]"===Object.prototype.toString.call(e)?"Details"!==b||"Client"!==d?c[d]=m(l(d,e),d):c[d]=e:"[object Function]"!==Object.prototype.toString.call(e)&&("undefined"!=typeof b?c[d]=l(d,e):"OccurredOn"===d&&(c[d]=e))}return c}function n(a,b,c,e){var f="AJAX Error: "+(b.statusText||"unknown")+" "+(c.type||"unknown")+" "+(s.Utilities.truncateURL(c.url)||"unknown");(!I||0!==b.status&&b.getAllResponseHeaders())&&s.send(e||a.type,{status:b.status,statusText:b.statusText,type:c.type,url:c.url,ajaxErrorMessage:f,contentType:c.contentType,requestData:c.data&&c.data.slice?c.data.slice(0,10240):d,responseData:b.responseText&&b.responseText.slice?b.responseText.slice(0,10240):d,activeTarget:a.target&&a.target.activeElement&&a.target.activeElement.outerHTML&&a.target.activeElement.outerHTML.slice?a.target.activeElement.outerHTML.slice(0,10240):d})}function o(b,c,e){if(_!==C.READY)return void aa.push({stackTrace:b,options:c,userTriggered:e});var f="Script error",g=[],h={};if(L){if(!b.stack||!b.stack.length)return void s.Utilities.log("Raygun4JS: Cancelling send due to null stacktrace");var i=s.Utilities.parseUrl("domain"),j=f;if(b.message?j=b.message:c&&c.status&&(j=c.status),"undefined"==typeof j&&(j=f),!s.Utilities.isReactNative()&&j.substring(0,f.length)===f&&null!==b.stack[0].url&&b.stack[0].url.indexOf(i)===-1&&(0===b.stack[0].line||"?"===b.stack[0].func))return void s.Utilities.log("Raygun4JS: cancelling send due to third-party script error with no stacktrace and message");if(null!==b.stack[0].url&&b.stack[0].url.indexOf(i)===-1){var k=!1;for(var n in S)b.stack[0].url.indexOf(S[n])>-1&&(k=!0);if(!k)return void s.Utilities.log("Raygun4JS: cancelling send due to error on non-origin, non-whitelisted domain")}}if(U instanceof Array)for(var o in U)if(U.hasOwnProperty(o)&&a.location.hostname&&a.location.hostname.match(U[o]))return void s.Utilities.log("Raygun4JS: cancelling send as error originates from an excluded hostname");if(V instanceof Array&&!s.Utilities.isReactNative())for(var q in V)if(V.hasOwnProperty(q)&&navigator.userAgent.match(V[q]))return void s.Utilities.log("Raygun4JS: cancelling send as error originates from an excluded user agent");if(s.Utilities.isReactNative()||!navigator.userAgent.match("RaygunPulseInsightsCrawler")){b.stack&&b.stack.length&&s.Utilities.forEach(b.stack,function(a,b){g.push({LineNumber:b.line,ColumnNumber:b.column,ClassName:"line "+b.line+", column "+b.column,FileName:b.url,MethodName:b.func||"[anonymous]"})});var r=s.Utilities.parseUrl("?");r.length>0&&s.Utilities.forEach(r.split("&"),function(a,b){var c=b.split("=");if(c&&2===c.length){var d=decodeURIComponent(c[0]),e=l(d,c[1]);h[d]=e}}),c===d&&(c={}),s.Utilities.isEmpty(c.customData)&&("function"==typeof Q?c.customData=Q():c.customData=Q),s.Utilities.isEmpty(c.tags)&&("function"==typeof R?c.tags=R():c.tags=R),e||(c.tags||(c.tags=[]),s.Utilities.contains(c.tags,"UnhandledException")||c.tags.push("UnhandledException")),s.Utilities.isReactNative()&&!s.Utilities.contains(c.tags,"React Native")&&c.tags.push("React Native");var v,y=a.screen||{width:s.Utilities.getViewPort().width,height:s.Utilities.getViewPort().height,colorDepth:8},z=c.customData&&c.customData.ajaxErrorMessage;v="customData"===W?m(c.customData,"UserCustomData"):c.customData;try{JSON.stringify(v)}catch(A){var B="Cannot add custom data; may contain circular reference";v={error:B},s.Utilities.log("Raygun4JS: "+B)}var D=f;z?D=z:b.message?D=b.message:c&&c.status&&(D=c.status),"undefined"==typeof D&&(D=f),D&&"string"==typeof D&&(D=D.substring(0,512));var E;E=s.Utilities.isReactNative()?"/":[location.protocol,"//",location.host,location.pathname,location.hash].join("");var F={OccurredOn:new Date,Details:{Error:{ClassName:b.name,Message:D,StackTrace:g,StackString:b.stackstring},Environment:{UtcOffset:(new Date).getTimezoneOffset()/-60,"User-Language":navigator.userLanguage,"Document-Mode":s.Utilities.isReactNative()?"Not available":document.documentMode,"Browser-Width":s.Utilities.getViewPort().width,"Browser-Height":s.Utilities.getViewPort().height,"Screen-Width":y.width,"Screen-Height":y.height,"Color-Depth":y.colorDepth,Browser:navigator.appCodeName,"Browser-Name":navigator.appName,"Browser-Version":navigator.appVersion,Platform:navigator.platform},Client:{Name:"raygun-js",Version:"2.6.6"},UserCustomData:v,Tags:c.tags,Request:{Url:E,QueryString:h,Headers:{"User-Agent":navigator.userAgent,Referer:s.Utilities.isReactNative()?"Not available":document.referrer,Host:s.Utilities.isReactNative()?"Not available":document.domain}},Version:u||"Not supplied"}};if(F.Details.User=t,Y.any()){F.Details.Breadcrumbs=[];var G=Y.all();G.forEach(function(a){a.metadata&&(a.CustomData=a.metadata,delete a.metadata),F.Details.Breadcrumbs.push(a)})}if("all"===W&&(F=m(F)),"function"==typeof x&&(s.Utilities.log("Raygun4JS: calling custom grouping key"),F.Details.GroupingKey=x(F,b,c)),"function"==typeof w){var H=w(F);H&&p(H)}else p(F)}}function p(a){if(s.Utilities.isApiKeyConfigured()){s.Utilities.log("Sending exception data to Raygun:",a);var b=T+"/entries?apikey="+encodeURIComponent(s.Options._raygunApiKey);r(b,JSON.stringify(a))}}function q(b,c){var d;return d=new a.XMLHttpRequest,"withCredentials"in d||s.Utilities.isReactNative()?d.open(b,c,!0):a.XDomainRequest&&(H&&(c=c.slice(6)),d=new a.XDomainRequest,d.open(b,c)),d.timeout=1e4,d}function r(b,c){var d=q("POST",b,c);return"function"==typeof y&&y(d),s.Utilities.log("Is offline enabled? "+K),"withCredentials"in d||s.Utilities.isReactNative()?(d.onreadystatechange=function(){4===d.readyState&&(202===d.status?k():K&&403!==d.status&&400!==d.status&&429!==d.status&&j(b,c))},d.onload=function(){s.Utilities.log("posted to Raygun"),e(this)}):a.XDomainRequest&&(d.ontimeout=function(){K&&(s.Utilities.log("Raygun: saved locally"),j(b,c))},d.onload=function(){s.Utilities.log("posted to Raygun"),k(),e(this)}),d.onerror=function(){s.Utilities.log("failed to post to Raygun"),e(this)},d?(s.Utilities.isReactNative()&&d.setRequestHeader("Content-type","application/json;charset=UTF-8"),void d.send(c)):void s.Utilities.log("CORS not supported")}var s={};s.Utilities=raygunUtilityFactory(a,s),s.Breadcrumbs=raygunBreadcrumbsFactory(a,s);var t,u,v,w,x,y,z,A,B,C={LOADING:0,READY:1
},D="raygun4js-userid",E=TraceKit,F=a.Raygun,G=!1,H=!1,I=!1,J=!1,K=!1,L=!1,M=!1,N=!1,O=!0,P=!1,Q={},R=[],S=[],T="https://api.raygun.io",U=null,V=null,W="customData",X=null,Y=new s.Breadcrumbs,Z=null,$=!0,_=C.LOADING,aa=[],ba=[],ca=null,da=Math.random(),ea={Rand:da,Options:{},noConflict:function(){return F&&(a.Raygun=F),s},constructNewRaygun:function(b){var c=raygunFactory(a,a.jQuery,b);return c},init:function(a,e,g){return E.remoteFetching=!1,this.Options._raygunApiKey=a,g&&(Q=g),b&&(B=b(document)),e&&(H=e.allowInsecureSubmissions||!1,I=e.ignoreAjaxAbort||!1,J=e.ignoreAjaxError||!1,M=e.disableAnonymousUserTracking||!1,N=e.disableErrorTracking||!1,O=e.disablePulse===d||e.disablePulse,U=e.excludedHostnames||!1,V=e.excludedUserAgents||!1,Z=e.pulseMaxVirtualPageDuration||null,$=e.pulseIgnoreUrlCasing||!1,ca=e.pulseCustomLoadTimeEnabled||!1,e.apiUrl&&(T=e.apiUrl),"undefined"!=typeof e.wrapAsynchronousCallbacks&&(P=e.wrapAsynchronousCallbacks),e.debugMode&&(G=e.debugMode),this.Options._debugMode=G,e.ignore3rdPartyErrors&&(L=!0),e.apiEndpoint&&(T=e.apiEndpoint),e.from&&(A=e.from)),c||Y.setCrashReportingInstance(this.constructNewRaygun(!0)),f(),s},withCustomData:function(a){return Q=a,s},withTags:function(a){return R=a,X!==d&&null!==X&&X.withTags(a),s},attach:function(){return!s.Utilities.isApiKeyConfigured()||N?s:(a.RaygunObject&&a[a.RaygunObject]&&a[a.RaygunObject].q&&(a.onerror=null),s.Utilities.isReactNative()&&__DEV__!==!0&&a.ErrorUtils&&a.ErrorUtils.setGlobalHandler&&a.ErrorUtils.setGlobalHandler(function(a,b){var c=z;z=function(){"function"==typeof c&&c(),s.Utilities.defaultReactNativeGlobalHandler(a,b),z=c},TraceKit.report(a)}),E.report.subscribe(o),P&&E.extendToAsynchronousCallbacks(),B&&B.ajaxError&&!J&&B.ajaxError(n),s)},detach:function(){return E.report.unsubscribe(o),B&&B.unbind("ajaxError",n),s},send:function(a,b,c){if(N)return s.Utilities.log("Error not sent due to disabled error tracking"),s;try{o(E.computeStackTrace(a),{customData:"function"==typeof Q?s.Utilities.merge(Q(),b):s.Utilities.merge(Q,b),tags:"function"==typeof R?s.Utilities.mergeArray(R(),c):s.Utilities.mergeArray(R,c)},!0)}catch(d){if(a!==d)throw d}return s},setUser:function(a,b,c,e,f,g){return t={Identifier:a},"boolean"==typeof b&&(t.IsAnonymous=b),c&&(t.Email=c),e&&(t.FullName=e),f&&(t.FirstName=f),g&&(t.UUID=g),X!==d&&null!==X&&X.setUser(t),s},resetAnonymousUser:function(){s.Utilities.clearCookie("raygun4js-userid")},setVersion:function(a){return u=a,s},saveIfOffline:function(a){return"undefined"!=typeof a&&"boolean"==typeof a&&(K=a),s},filterSensitiveData:function(a){return v=a,s},setFilterScope:function(a){return"customData"!==a&&"all"!==a||(W=a),s},whitelistCrossOriginDomains:function(a){return S=a,s},onBeforeSend:function(a){return w=a,s},groupingKey:function(a){return x=a,s},onBeforeXHR:function(a){return y=a,s},onAfterSend:function(a){return z=a,s},endSession:function(){s.RealUserMonitoring!==d&&X&&X.endSession()},trackEvent:function(a,b){return _!==C.READY?void ba.push({type:a,options:b}):void(s.RealUserMonitoring!==d&&X&&("pageView"===a&&b.path?X.virtualPageLoaded(b.path):"customTimings"===a&&b.timings&&X.sendCustomTimings(b.timings)))},recordBreadcrumb:function(){Y.recordBreadcrumb.apply(Y,arguments)},enableAutoBreadcrumbs:function(a){a?Y["enableAutoBreadcrumbs"+a]():Y.enableAutoBreadcrumbs()},disableAutoBreadcrumbs:function(a){a?Y["disableAutoBreadcrumbs"+a]():Y.disableAutoBreadcrumbs()},setBreadcrumbOption:function(a,b){Y.setOption(a,b)},setBreadcrumbs:function(a){Y=a}};return s=s.Utilities.mergeMutate(s,ea),a.__raygunNoConflict||c||(a.Raygun=s),TraceKit.setRaygun(s),s};window.__instantiatedRaygun=raygunFactory(window,window.jQuery);var raygunRumFactory=function(a,b,c){c.RealUserMonitoring=function(b,c,d,e,f,g,h,i,j,k,l,m){function n(a){var b=encodeURIComponent(a).match(/%[89ABab]/g);return a.length+(b?b.length:0)}function o(a){var b=r(F.cookieName),c=null===b,d="string"==typeof exisitingCookie&&b.length>0&&b.indexOf("timestamp")===-1,e=null;if(!c&&!d){var f=new Date(q(b,"timestamp")),g=new Date(new Date-18e5);e=f<g}if(c||d||e)F.sessionId=D(32),p(F.cookieName,F.sessionId),a(!0);else{var h=r(F.cookieName),i=q(h,"id");"undefined"===i||"null"===i?(F.sessionId=D(32),p(F.cookieName,F.sessionId),a(!0)):(F.sessionId=i,a(!1))}}function p(a,b,c){var d,e;if(c){var f=new Date;f.setTime(f.getTime()+60*c*60*1e3),d="; expires="+f.toGMTString()}else d="";e=(new Date).toISOString(),document.cookie=a+"=id|"+b+"&timestamp|"+e+d+"; path=/"}function q(a,b){var c=a.split(/[|&]/);return"id"===b?c[1]:"timestamp"===b?c[3]:void 0}function r(a){for(var b=a+"=",c=document.cookie.split(";"),d=0;d<c.length;d++){for(var e=c[d];" "===e.charAt(0);)e=e.substring(1,e.length);if(0===e.indexOf(b))return e.substring(b.length,e.length)}return null}function s(){var a,b=r(F.cookieName);if(b){var c=new Date(q(b,"timestamp")),d=new Date(new Date-18e5);a=c<d}else a=!0;a&&(F.sessionId=D(32)),p(F.cookieName,F.sessionId),a&&F.pageLoaded(!0)}function t(a){return Math.min(a,3e5)}function u(a){for(var b in a)isNaN(a[b])&&"string"!=typeof a[b]&&(a[b]=0);return a}function v(b,c){var d;return d="object"==typeof a.performance&&"function"==typeof a.performance.now?a.performance.now():0,{t:"v",du:Math.min(F.maxVirtualPageDuration,d-(b||c)),o:Math.min(F.maxVirtualPageDuration,d-c)}}function w(a,b){var c={du:a.duration,t:"p"};return c.a=b+a.fetchStart,a.domainLookupStart&&a.domainLookupStart>0&&(c.b=b+a.domainLookupStart-c.a),a.domainLookupEnd&&a.domainLookupEnd>0&&(c.c=b+a.domainLookupEnd-c.a),a.connectStart&&a.connectStart>0&&(c.d=b+a.connectStart-c.a),a.connectEnd&&a.connectEnd>0&&(c.e=b+a.connectEnd-c.a),a.responseStart&&a.responseStart>0&&(c.f=b+a.responseStart-c.a),a.responseEnd&&a.responseEnd>0&&(c.g=b+a.responseEnd-c.a),a.domLoading&&a.domLoading>0&&(c.h=b+a.domLoading-c.a),a.domInteractive&&a.domInteractive>0&&(c.i=b+a.domInteractive-c.a),a.domContentLoadedEventEnd&&a.domContentLoadedEventEnd>0&&(c.j=b+a.domContentLoadedEventEnd-c.a),a.domComplete&&a.domComplete>0&&(c.k=t(b+a.domComplete-c.a)),a.loadEventStart&&a.loadEventStart>0&&(c.l=b+a.loadEventStart-c.a),a.loadEventEnd&&a.loadEventEnd>0&&(c.m=b+a.loadEventEnd-c.a),a.secureConnectionStart&&a.secureConnectionStart>0&&(c.n=b+(a.secureConnectionStart-a.connectStart)-c.a),c=u(c)}function x(a,b){var c={du:t(a.duration).toFixed(2),t:"xmlhttprequest"===a.initiatorType?"x":0===a.duration?"e":"c",a:(b+a.fetchStart).toFixed(2)};return a.domainLookupStart&&a.domainLookupStart>0&&(c.b=b+a.domainLookupStart-c.a),a.domainLookupEnd&&a.domainLookupEnd>0&&(c.c=b+a.domainLookupEnd-c.a),a.connectStart&&a.connectStart>0&&(c.d=b+a.connectStart-c.a),a.connectEnd&&a.connectEnd>0&&(c.e=b+a.connectEnd-c.a),a.responseStart&&a.responseStart>0&&(c.f=b+a.responseStart-c.a),a.responseEnd&&a.responseEnd>0&&(c.g=b+a.responseEnd-c.a),a.secureConnectionStart&&a.secureConnectionStart>0&&(c.n=b+(a.secureConnectionStart-a.connectStart)-c.a),c=u(c)}function y(){var b=a.location.pathname;F.ignoreUrlCasing&&(b=b.toLowerCase());var c=a.location.protocol+"//"+a.location.host+b;return c.length>800&&(c=c.substring(0,800)),{url:c,userAgent:navigator.userAgent,timing:w(a.performance.timing,0),size:0}}function z(b,c,d){F.ignoreUrlCasing&&(b=b.toLowerCase());var e=a.location.protocol+"//"+a.location.host+b;return e.length>800&&(e=e.substring(0,800)),{url:e,userAgent:navigator.userAgent,timing:v(c,d),size:0}}function A(b,c){var d=b.name.split("?")[0];return F.ignoreUrlCasing&&(d=d.toLowerCase()),d.length>800&&(d=d.substring(0,800)),{url:d,timing:x(b,c?0:a.performance.timing.navigationStart),size:b.decodedBodySize||0}}function B(b,c){if(void 0!==a.performance&&a.performance.getEntries)try{for(var d=a.performance.getEntries(),e=F.offset;e<d.length;e++){var f=d[e].name.split("?")[0];0!==f.indexOf(F.apiUrl)&&(f.indexOf("favicon.ico")>0||0!==f.indexOf("about:blank")&&("j"===f[0]&&1===f.indexOf("avascript:")||0!==f.indexOf("chrome-extension://")&&0!==f.indexOf("res://")&&0!==f.indexOf("file://")&&b.push(A(d[e],c))))}F.offset=d.length}catch(g){}}function C(b,c,d){if(void 0===a.performance||void 0===a.performance.timing||void 0===a.performance.timing.fetchStart||isNaN(a.performance.timing.fetchStart))return null;var e=[];if(c&&(d&&e.push(y()),B(e)),b){F.pendingVirtualPage&&(e.push(F.pendingVirtualPage),B(e,!0));var f=null==F.pendingVirtualPage;if(F.pendingVirtualPage=z(b,F.previousVirtualPageLoadTimestamp,F.initalStaticPageLoadTimestamp),!f&&e.length>0)return e}return e}function D(a){return Math.round(Math.pow(36,a+1)-Math.random()*Math.pow(36,a)).toString(36).slice(1)}function E(b,c){a.console&&a.console.log&&F.debugMode&&(a.console.log(b),c&&a.console.log(c))}var F=this,G={};this.cookieName="raygun4js-sid",this.apiKey=b,this.apiUrl=c,this.debugMode=j,this.excludedHostNames=h,this.excludedUserAgents=i,this.maxVirtualPageDuration=k||18e5,this.ignoreUrlCasing=l,this.customTimingsEnabled=m,this.pendingPerformancePayload=null,this.makePostCorsRequest=function(b,c){if(F.excludedUserAgents instanceof Array)for(var e in F.excludedUserAgents)if(F.excludedUserAgents.hasOwnProperty(e)&&navigator.userAgent.match(F.excludedUserAgents[e]))return void(F.debugMode&&E("Raygun4JS: cancelling send as error originates from an excluded user agent"));if(F.excludedHostNames instanceof Array)for(var f in F.excludedHostNames)if(F.excludedHostNames.hasOwnProperty(f)&&a.location.hostname&&a.location.hostname.match(F.excludedHostNames[f]))return void E("Raygun4JS: cancelling send as error originates from an excluded hostname");navigator.userAgent.match("RaygunPulseInsightsCrawler")||d(b,c)},this.sessionId=null,this.virtualPage=null,this.user=e,this.version=f,this.tags=g,this.heartBeatInterval=null,this.offset=0,this.attach=function(){o(function(a){F.pageLoaded(a)});var b=function(){this.updateCookieTimestamp()}.bind(G),c=function(){var a=[];if(B(a),F.pendingVirtualPage&&(a.push(F.pendingVirtualPage),B(a,!0)),a.length>0){var b={eventData:[{sessionId:F.sessionId,timestamp:(new Date).toISOString(),type:"web_request_timing",user:F.user,version:F.version||"Not supplied",device:navigator.userAgent,tags:F.tags,data:JSON.stringify(a)}]};F.makePostCorsRequest(F.apiUrl+"/events?apikey="+encodeURIComponent(F.apiKey),JSON.stringify(b))}},d=function(){"visible"===document.visibilityState&&this.updateCookieTimestamp()}.bind(G);a.addEventListener?(a.addEventListener("click",b),document.addEventListener("visibilitychange",d),a.addEventListener("beforeunload",c)):a.attachEvent&&document.attachEvent("onclick",b)},this.pageLoaded=function(b){if(b){var c={eventData:[{sessionId:F.sessionId,timestamp:(new Date).toISOString(),type:"session_start",user:F.user,version:F.version||"Not supplied",tags:F.tags,device:navigator.userAgent}]};F.makePostCorsRequest(F.apiUrl+"/events?apikey="+encodeURIComponent(F.apiKey),JSON.stringify(c))}F.sendPerformance(!0,!0),F.heartBeat(),"object"==typeof a.performance&&"function"==typeof a.performance.now?F.initalStaticPageLoadTimestamp=a.performance.now():F.initalStaticPageLoadTimestamp=0},this.sendCustomTimings=function(a){if("object"==typeof a&&("number"==typeof a.custom1||"number"==typeof a.custom2||"number"==typeof a.custom3||"number"==typeof a.custom4||"number"==typeof a.custom5||"number"==typeof a.custom6||"number"==typeof a.custom7||"number"==typeof a.custom8||"number"==typeof a.custom9||"number"==typeof a.custom10)&&F.pendingPerformancePayload){var b=JSON.parse(F.pendingPerformancePayload),c=JSON.parse(b.eventData[0].data);c[0].customTiming=a,b.eventData[0].data=JSON.stringify(c),F.makePostCorsRequest(F.apiUrl+"/events?apikey="+encodeURIComponent(F.apiKey),JSON.stringify(b)),F.pendingPerformancePayload=null}},this.setUser=function(a){F.user=a},this.withTags=function(a){F.tags=a},this.endSession=function(){var a={eventData:[{sessionId:F.sessionId,timestamp:(new Date).toISOString(),type:"session_end"}]};F.makePostCorsRequest(F.apiUrl+"/events?apikey="+encodeURIComponent(F.apiKey),JSON.stringify(a))},this.heartBeat=function(){F.heartBeatInterval=setInterval(function(){var a,b=[];if(B(b,F.virtualPage),b.length>0){var c=JSON.stringify(b);n(c)<128e3&&(a={eventData:[{sessionId:F.sessionId,timestamp:(new Date).toISOString(),type:"web_request_timing",user:F.user,version:F.version||"Not supplied",device:navigator.userAgent,tags:F.tags,data:c}]})}void 0!==a&&F.makePostCorsRequest(F.apiUrl+"/events?apikey="+encodeURIComponent(F.apiKey),JSON.stringify(a))},3e4)},this.virtualPageLoaded=function(b){var c=null==this.virtualPage;"string"==typeof b&&(b.length>0&&"/"!==b[0]&&(b+="/"),b.length>800&&(b=b.substring(0,800)),this.virtualPage=b),c?this.sendPerformance(!0,!1):this.sendPerformance(!1,!1),"string"==typeof b&&("object"==typeof a.performance&&"function"==typeof a.performance.now?this.previousVirtualPageLoadTimestamp=a.performance.now():this.previousVirtualPageLoadTimestamp=0)},this.sendPerformance=function(a,b){var c=C(this.virtualPage,a,b);if(null!==c){var d={eventData:[{sessionId:F.sessionId,timestamp:(new Date).toISOString(),type:"web_request_timing",user:F.user,version:F.version||"Not supplied",device:navigator.userAgent,tags:F.tags,data:JSON.stringify(c)}]};F.customTimingsEnabled?F.pendingPerformancePayload=JSON.stringify(d):F.makePostCorsRequest(F.apiUrl+"/events?apikey="+encodeURIComponent(F.apiKey),JSON.stringify(d))}},G.updateCookieTimestamp=s}};raygunRumFactory(window,window.jQuery,window.__instantiatedRaygun),function(a,b){if(a.RaygunObject&&a[a.RaygunObject]){var c,d,e,f,g,h,i=a[a.RaygunObject].o,j=!1,k=!1,l=[],m=["function (b,c,d,f,g){","||(g=new Error(b)),a[e].q=a[e].q||[]"];c=a[a.RaygunObject].q;var n=b,o=["trackEvent","send","recordBreadcrumb"],p=function(){i=a[a.RaygunObject].o;for(var b in i){var c=i[b];c&&(o.indexOf(c[0])===-1?q(c):l.push(c))}},q=function(a){var b=a[0],c=a[1];if(b)switch(b){case"boot":s();break;case"noConflict":h=c;break;case"apiKey":d=c,j=!0;break;case"options":e=c;break;case"attach":case"enableCrashReporting":f=c,j=!0;break;case"enablePulse":g=c,j=!0;break;case"detach":n.detach();break;case"getRaygunInstance":return n;case"setUser":n.setUser(c.identifier,c.isAnonymous,c.email,c.fullName,c.firstName,c.uuid);break;case"onBeforeSend":n.onBeforeSend(c);break;case"onBeforeXHR":n.onBeforeXHR(c);break;case"onAfterSend":n.onAfterSend(c);break;case"withCustomData":n.withCustomData(c);break;case"withTags":n.withTags(c);break;case"setVersion":n.setVersion(c);break;case"filterSensitiveData":n.filterSensitiveData(c);break;case"setFilterScope":n.setFilterScope(c);break;case"whitelistCrossOriginDomains":n.whitelistCrossOriginDomains(c);break;case"saveIfOffline":"boolean"==typeof c&&n.saveIfOffline(c);break;case"groupingKey":n.groupingKey(c);break;case"send":var i,k,l;c.error?(i=c.error,c.tags&&(k=c.tags),c.customData&&(l=c.customData)):i=c,n.send(i,l,k);break;case"trackEvent":c.type&&c.path?n.trackEvent(c.type,{path:c.path}):c.type&&c.timings&&n.trackEvent(c.type,{timings:c.timings});break;case"recordBreadcrumb":n.recordBreadcrumb(a[1],a[2]);break;case"enableAutoBreadcrumbs":n.enableAutoBreadcrumbs();break;case"disableAutoBreadcrumbs":n.disableAutoBreadcrumbs();break;case"enableAutoBreadcrumbsConsole":n.enableAutoBreadcrumbs("Console");break;case"disableAutoBreadcrumbsConsole":n.disableAutoBreadcrumbs("Console");break;case"enableAutoBreadcrumbsNavigation":n.enableAutoBreadcrumbs("Navigation");break;case"disableAutoBreadcrumbsNavigation":n.disableAutoBreadcrumbs("Navigation");break;case"enableAutoBreadcrumbsClicks":n.enableAutoBreadcrumbs("Clicks");break;case"disableAutoBreadcrumbsClicks":n.disableAutoBreadcrumbs("Clicks");break;case"enableAutoBreadcrumbsXHR":n.enableAutoBreadcrumbs("XHR");break;case"disableAutoBreadcrumbsXHR":n.disableAutoBreadcrumbs("XHR");break;case"setBreadcrumbLevel":n.setBreadcrumbOption("breadcrumbsLevel",a[1]);break;case"setAutoBreadcrumbsXHRIgnoredHosts":n.setBreadcrumbOption("xhrIgnoredHosts",a[1]);break;case"logContentsOfXhrCalls":n.setBreadcrumbOption("logXhrContents",a[1])}},r=function(){a[a.RaygunObject]=function(){return q(arguments)},k=!0},s=function(){if(p(),h&&(n=b.noConflict()),d&&(e||(e={}),g&&(e.disablePulse=!1),e.from="onLoad",n.init(d,e,null)),f){n.attach(),c=a[a.RaygunObject].q;for(var i in c)n.send(c[i].e,{handler:"From Raygun4JS snippet global error handler"})}else if("function"==typeof a.onerror){var j=a.onerror.toString();j.indexOf(m[0])!==-1&&j.indexOf(m[1])!==-1&&(a.onerror=null)}for(var o in l)q(l[o]);l=[],k||r(),a[a.RaygunObject].q=c};b.Utilities.isReactNative()?r():"complete"===document.readyState?s():a.addEventListener?a.addEventListener("load",s):a.attachEvent("onload",s)}}(window,window.__instantiatedRaygun);try{delete window.__instantiatedRaygun}catch(e){window.__instantiatedRaygun=void 0}
//# sourceMappingURL=raygun.min.js.map;

//Copyright Sportsground Limited 2016

var compWidgetApiVersion = "1.0";
var cometCompWidgetBaseUrl = "/api/" + compWidgetApiVersion + "/competition/cometwidget/";
var globalCometWidgetSelectedDates = [];
var blockCometDateUpdate = {};
var cometDrawsModule = extend(sportsground, 'sportsground.cms.widgets.cometCompetition');
var cometRoundInfo = {};

//front end client side create
cometDrawsModule.create = function (widgetInstanceId) {

    cometDrawsModule.setUpDataToggle(widgetInstanceId);

    var competitionWidget = $('#widget_' + widgetInstanceId + '.wCometCompetition');
    cometDrawsModule.initializeDateRangeSettings(widgetInstanceId);

    cometDrawsModule.initializeDropdownList(competitionWidget);

    cometDrawsModule.attachDropdownHandlers(competitionWidget);

    var drawsTabExist = $(competitionWidget).find('.draws-tab').length;
    var resultsTabExist = $(competitionWidget).find('.results-tab').length;
    var standingsTabExist = $(competitionWidget).find('.standings-tab').length;

    if (!drawsTabExist && resultsTabExist) {
        $('#widget_' + widgetInstanceId + ' .results-tab').trigger('click');
    }
    else if (!drawsTabExist && !resultsTabExist && standingsTabExist) {
        $('#widget_' + widgetInstanceId + ' .standings-tab').trigger('click');
    }

    $(competitionWidget).find('.apply-comp-filters').click(function (e) {

        var widgetId = $(this).parents('.wCometCompetition').data("id");
        if (!blockCometDateUpdate["w_" + widgetId + ""]) {
            cometDrawsModule.getDraws(widgetId);
        }
    });

    var excludeAdsOnTheseSites = []; 

    //hack/hard code so ad doesnt show for nzfootball
    if (excludeAdsOnTheseSites.indexOf($('#OrganisationId').val()) > -1) {

        $(".competition-desktop-ad").remove();
        $(".competition-mobile-ad").remove();

    }

    $(".calendar-icon").unbind('click');
    $(".calendar-icon").click(function (e) {
        try {
            $($(e)[0].currentTarget).prev().data("DateTimePicker").show();
        }
        catch (e) {
            $(".comp-widget-from").click();
        }

    });

    $(".calendar-icon-from").unbind('click');
    $(".calendar-icon-from").click(function (e) {
        try {
            var widgetId = $($(this).parents('.wCometCompetition')[0]).data("id");
            $("#widget_" + widgetId + " .comp-widget-from").click();
            $("#widget_" + widgetId + " .comp-widget-from").focus();
        }
        catch (e) {

        }

    });

    $(".calendar-icon-to").unbind('click');
    $(".calendar-icon-to").click(function (e) {

        try {
            var widgetId = $($(this).parents('.wCometCompetition')[0]).data("id");
            $("#widget_" + widgetId + " .comp-widget-to").click();
            $("#widget_" + widgetId + " .comp-widget-to").focus();
        }
        catch (e) {

        }

    });

    $(".toggle-widget-filters").unbind('click');
    $(".toggle-widget-filters").click(function (e) {

        var widgetId = $($(this).parents('.wCometCompetition')[0]).data("id");

        $("#widget_" + widgetId + " .comp-widget-filters-wrapper").toggle();
        $("#widget_" + widgetId + " .toggle-widget-filters .fa-chevron-up").toggle();
        $("#widget_" + widgetId + " .toggle-widget-filters .fa-chevron-down").toggle();

        if ($("#widget_" + widgetId + " .toggle-filter-text").html() == "Hide Filters") {
            $("#widget_" + widgetId + " .toggle-filter-text").html("Show Filters");
        }
        else {
            $("#widget_" + widgetId + " .toggle-filter-text").html("Hide Filters");
        }

    });

    $(".round-picker .fa-caret-right").unbind('click');
    $(".round-picker .fa-caret-right").click(function (e) {
        try {
            var widgetId = $($(this).parents('.wCometCompetition')[0]).data("id");
            cometDrawsModule.nextRound(widgetId);
        }
        catch (e) {

        }

    });

    $(".round-picker .fa-caret-left").unbind('click');
    $(".round-picker .fa-caret-left").click(function (e) {
        try {
            var widgetId = $($(this).parents('.wCometCompetition')[0]).data("id");
            cometDrawsModule.previousRound(widgetId);
        }
        catch (e) {

        }

    });      

    cometDrawsModule.toggleExpand(widgetInstanceId);

};

cometDrawsModule.initializeDropdownList = function (competitionWidget) {

    $(competitionWidget).find('select.fe-comp-comps').each(function (i) {
        var dropdownList = $(this);
        var compIds = dropdownList.data("compids");
        var sortedCompIds = dropdownList.data("sortedcompids");
        if (sortedCompIds) {
            sortedCompIds = sortedCompIds.split(',');
        }
        var widgetInstanceId = competitionWidget.data("id");
        var compWidget = $("#widget_" + widgetInstanceId);
        var seasonId = $(compWidget).find('.hdnSelectedSeasonId').val();
        var model = {
            compIds: compIds,
            seasonId: seasonId
        };

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: cometCompWidgetBaseUrl + 'competitionsfromids',
            data: JSON.stringify(model),
            cache: false,
            success: function (data) {

                //add sorting
                for (var index = 0; index < data.length; index++) {

                    var sortOrder = sortedCompIds.indexOf(data[index].Id);
                    data[index].SortOrder = sortOrder;
                }

                //apply sort order
                data.sort(function (a, b) {
                    return a.SortOrder - b.SortOrder;
                });

                //create list
                for (var i = 0; i < data.length; i++) {

                    $(dropdownList).append('<option value="' + data[i].Id + '" data-sortorder="' + sortOrder + '">' + data[i].Name + '</option>');
                }

                var widgetInstanceId = competitionWidget.data("id");
                var compId = competitionWidget.find('select.fe-comp-comps').val();

                if (data.length == 1) {
                    $(dropdownList).addClass("single-dropdown");
                    $(dropdownList).prop("disabled", "disabled");
                    $((dropdownList).parent()).addClass("single-dropdown-wrapper");
                }
                else {
                    $(dropdownList).removeClass("single-dropdown");
                    $(dropdownList).prop("disabled", false);
                    $((dropdownList).parent()).removeClass("single-dropdown-wrapper");
                }

                cometDrawsModule.getFEPhases(widgetInstanceId, compId, true);

            }
        });

    });
};

cometDrawsModule.attachDropdownHandlers = function (competitionWidget) {
    $(competitionWidget).find('select.fe-comp-comps').change(cometDrawsModule.dropdownHandlers.competition);

    // attaches dropdown handlers on select html for desktop only
    if (!sportsground.ui.isMobile()) {
        $(competitionWidget).find('select.fe-comp-orgs').change(cometDrawsModule.dropdownHandlers.organisation);
        $(competitionWidget).find('select.fe-comp-grades').change(cometDrawsModule.dropdownHandlers.grade);
    }
};
// list of dropdown handlers
cometDrawsModule.dropdownHandlers = {
    competition: function (e) {
        var widget = $(this).parents('.wCometCompetition');
        var widgetId = widget.data("id");
        var compId = $(this).val();

        cometDrawsModule.getFEPhases(widgetId, compId, true);
        cometDrawsModule.enableOrDisableSave();
    },
    organisation: function (e, initializer) {

        var widget;
        if (initializer){
            widget = $(initializer).parents('.wCometCompetition');
        }
        else {
            widget = $(this).parents('.wCometCompetition');
        }

        var widgetId = widget.data("id");
        cometDrawsModule.getDraws(widgetId);
        cometDrawsModule.enableOrDisableSave();
    },
    grade: function (e, initializer) {
        var widget;
        if (initializer) {
            widget = $(initializer).parents('.wCometCompetition');
        }
        else {
            widget = $(this).parents('.wCometCompetition');
        }

        var widgetId = widget.data("id");

        cometDrawsModule.getFEComps(widgetId);
        cometDrawsModule.enableOrDisableSave();
    }
};

cometDrawsModule.getFEPhases = function (widgetId, selectedCompId, loadGrades) {

    cometDrawsModule.getFEOrgs(widgetId, selectedCompId, loadGrades);

}

cometDrawsModule.getFEOrgs = function (widgetId, selectedCompId, loadGrades) {

    var compWidget = $("#widget_" + widgetId);
    var loader = $(compWidget).find('.sked-widget-loader');
    $(loader).show();

    $.get(cometCompWidgetBaseUrl + 'organisations?ids=' + selectedCompId)
        .done(function (data) {

            var compWidget = $("#widget_" + widgetId);
            var allowedOrgIds = $(compWidget).find('select.fe-comp-orgs').data("orgids");
            var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');

            orgsDropdown.sportsgroundMobiscroll().selectDestroy();
            $(compWidget).find('select.fe-comp-orgs option').remove()

            var allOrgIds = [];
            var addedOrgIds = [];
            for (var index = 0; index < data.length; index++) {

                if (allowedOrgIds.toString().indexOf(data[index].Id) != -1) {
                    orgsDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    addedOrgIds.push(data[index].Id);
                }

                allOrgIds.push(data[index].Id);

            }

            if (data.length > 0) {
                var multiSelectSettings = {
                    dropdown: {
                        inputClass: 'fe-comp-orgs',
                        defaultText: 'Select an Organisation...',
                        selectedText: 'Organisations Selected',
                        onChangeCallback: cometDrawsModule.dropdownHandlers.organisation
                    }
                };
                orgsDropdown.sportsgroundMobiscroll().selectMultiple(multiSelectSettings);
            }

            orgsDropdown.sportsgroundMobiscroll().selectInitialize(addedOrgIds, multiSelectSettings);

            $($(compWidget).find('.comp-widget-org-wrapper')[0]).find('.multiselect-item.multiselect-all').each(function (index) {
                $(this).addClass('active');
            });

            $($(compWidget).find('.comp-widget-org-wrapper')[0]).find('.multiselect-all input').each(function (index) {
                $(this).prop('checked', true);
            });

            var orgsDropdownWrapper = $(compWidget).find('.comp-widget-org-wrapper');

            if (addedOrgIds.length == 1) {
                $(orgsDropdownWrapper).find('button').prop("disabled", "disabled");
                $(orgsDropdownWrapper).find('input').prop("disabled", "disabled");
                $(orgsDropdownWrapper).find('.caret').css("display", "none");
            }
            else {
                $(orgsDropdownWrapper).find('button').prop("disabled", false);
                $(orgsDropdownWrapper).find('input').prop("disabled", false);
                $(orgsDropdownWrapper).find('.caret').css("display", "block");
            }

            if (loadGrades) {
                cometDrawsModule.getFEGrades(widgetId);
            }



            blockCometDateUpdate["w_" + widgetId + ""] = true;
            cometDrawsModule.getDraws(widgetId);
            blockCometDateUpdate["w_" + widgetId + ""] = false;

            cometDrawsModule.enableOrDisableSave();

        });

}

cometDrawsModule.enableOrDisableSave = function () {

    if ($('#comp-admin-grades').val() && $('#comp-admin-comps').val() && $('#comp-admin-orgs').val()) {

        $(".widget-settings-update").attr('disabled', false);

    }

}

cometDrawsModule.nextRound = function (widgetId) {

    blockCometDateUpdate["w_" + widgetId + ""] = true;
    var compWidget = $('#widget_' + widgetId + '.wCometCompetition');

    cometDrawsModule.saveSelectedDates(compWidget);

    //get currentRound
    var currentRoundNumber = Number($(compWidget).find('.round-number').html());

    if (isNaN(currentRoundNumber)) {
        return;
    }

    //find the current round and index
    var currentRound = cometRoundInfo[widgetId].find(function (round) {
        return round.name == currentRoundNumber;
    });

    var index = cometRoundInfo[widgetId].indexOf(currentRound);

    var nextRound = cometRoundInfo[widgetId][index + 1];    

    if (!nextRound) {
        return;
    }

    cometRoundInfo[widgetId].currentRound = nextRound.name;

    //set from
    var next = new Date(nextRound.from);
    $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(next);

    //set to
    var nextTo = new Date(nextRound.from);
    nextTo.setDate(nextTo.getDate() + 6);
    $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(nextTo);

    cometDrawsModule.getDraws(widgetId);

    blockCometDateUpdate["w_" + widgetId + ""] = false;

}

cometDrawsModule.previousRound = function (widgetId) {

    blockCometDateUpdate["w_" + widgetId + ""] = true;
    var compWidget = $('#widget_' + widgetId + '.wCometCompetition');

    cometDrawsModule.saveSelectedDates(compWidget);

    //get currentRound
    var currentRoundNumber = Number($(compWidget).find('.round-number').html());

    if (isNaN(currentRoundNumber)) {
        return;
    }

    //find the current round and index
    var currentRound = cometRoundInfo[widgetId].find(function (round) {
        return round.name == currentRoundNumber;
    });

    var index = cometRoundInfo[widgetId].indexOf(currentRound);

    var previousRound = cometRoundInfo[widgetId][index - 1];      

    if (!previousRound) {
        return;
    }

    cometRoundInfo[widgetId].currentRound = previousRound.name;

    //set from
    var next = new Date(previousRound.from);
    $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(next);

    //set to
    var previousTo = new Date(previousRound.from);
    previousTo.setDate(previousTo.getDate() + 6);
    $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(previousTo);

    cometDrawsModule.getDraws(widgetId);

    blockCometDateUpdate["w_" + widgetId + ""] = false;

}

cometDrawsModule.getFEComps = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);
    var selectedGrades = $(compWidget).find('select.fe-comp-grades').sportsgroundMobiscroll().selectGetVal();
    var seasonId = $(compWidget).find('.hdnSelectedSeasonId').val();
    var sportId = $(compWidget).find('.hdnSelectedSportId').val();
    var compIds = $(compWidget).find('select.fe-comp-comps').data("compids");

    var gradeIds = selectedGrades != null && selectedGrades != "" ? selectedGrades.join(",") : ["0"];

    $.get(cometCompWidgetBaseUrl + 'competitionsbygrades?ids=' + gradeIds + "&seasonId=" + seasonId + "&sportId=" + sportId + "&compIds=" + compIds)
        .done(function (data) {

            var compWidget = $("#widget_" + widgetId);

            var dropdown = $(compWidget).find('select.fe-comp-comps');
            dropdown.find('option').remove();

            for (var index = 0; index < data.length; index++) {
                $(dropdown).append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
            }

            if (data.length == 0) {
                $(dropdown).append('<option value="0">None selected</option>');
            }

            compWidget = $("#widget_" + widgetId);
            var compId = $(compWidget).find('select.fe-comp-comps').val();

            cometDrawsModule.getFEPhases(widgetId, compId, false);

        });
}

cometDrawsModule.getFEGrades = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);
    var phaseIds = $(compWidget).find('select.fe-comp-phases').val();

    //var fedIds = $('#comp-admin-feds').val().join(',');
    var gradeDD = $(compWidget).find('select.fe-comp-grades');
    var gradeIds = $(gradeDD).data("gradeids");
    var season = $(compWidget).find('.hdnSelectedSeasonId').val();

    $.get(cometCompWidgetBaseUrl + 'GradesFromList?gradeIds=' + gradeIds + "&season=" + season)
        .done(function (data) {

            var compWidget = $("#widget_" + widgetId);
            var allowedGradeIds = $(compWidget).find('select.fe-comp-grades').data("gradeids");
            var gradesDropdown = $(compWidget).find('select.fe-comp-grades');
            
            gradesDropdown.sportsgroundMobiscroll().selectDestroy();
            $(compWidget).find('select.fe-comp-grades option').remove();

            var allGradeIds = [];
            var addedGradeIds = [];

            for (var index = 0; index < data.length; index++) {
                if (allowedGradeIds.toString().indexOf(data[index].Id) != -1) {
                    gradesDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    addedGradeIds.push(data[index].Id);
                }
                allGradeIds.push(data[index].Id);
            }

            if (data.length > 0) {
                var multiSelectSettings = {
                    dropdown: {
                        inputClass: 'fe-comp-grades',
                        defaultText: 'Select a Grade...',
                        selectedText: 'Grades Selected',
                        onChangeCallback: cometDrawsModule.dropdownHandlers.grade
                    }
                };
                gradesDropdown.sportsgroundMobiscroll().selectMultiple(multiSelectSettings);
            }

            gradesDropdown.sportsgroundMobiscroll().selectInitialize(addedGradeIds, multiSelectSettings);

            $($(compWidget).find('.comp-widget-grade-wrapper')[0]).find('.multiselect-item.multiselect-all').each(function (index) {
                $(this).addClass('active');
            });

            $($(compWidget).find('.comp-widget-grade-wrapper')[0]).find('.multiselect-all input').each(function (index) {
                $(this).prop('checked', true);
            });

            var gradesDropdownWrapper = $(compWidget).find('.comp-widget-grade-wrapper');

            if (data.length == 1) {
                $(gradesDropdownWrapper).find('button').prop("disabled", "disabled");
                $(gradesDropdownWrapper).find('input').prop("disabled", "disabled");
                $(gradesDropdownWrapper).find('.caret').css("display", "none");
            }
            else {
                $(gradesDropdownWrapper).find('button').prop("disabled", false);
                $(gradesDropdownWrapper).find('input').prop("disabled", false);
                $(gradesDropdownWrapper).find('.caret').css("display", "block");
            }

            cometDrawsModule.getDraws(widgetId);
        });
}

cometDrawsModule.getSelectedSportId = function () {
    return $('#comp-sports').val();
}

cometDrawsModule.getSelectedSeasonId = function () {
    return $('#comp-seasons').val();
}

cometDrawsModule.loadFilters = function () {
    $(".widget-settings-update").attr('disabled', 'disabled');
    var phaseDropdown = $('#comp-admin-phases');

    $(phaseDropdown).parent().parent().hide();//get phase wrapper
    $(".grades-wrapper").prependTo(".comp-edit-second-row");

    //if label setup
    if ($("#hdnCompetitionLabel").val()) {
        cometDrawsModule.setupLoadDropdownEvent();
    }
    else {
        cometDrawsModule.getFeds(true);
    }

}

cometDrawsModule.setupLoadDropdownEvent = function () {

    $("#comp-admin-feds, #comp-admin-orgs, #comp-admin-grades, #comp-admin-comps").focus(function () {

        cometDrawsModule.loadOptions();

    });

    $(".widget-settings-update").removeAttr('disabled');

}

cometDrawsModule.loadOptions = function () {

    if ($("#comp-admin-feds option").length === 1) {
        cometDrawsModule.getFeds(true);
        $("#comp-admin-grades-loading").show();
        $("#comp-admin-comps-loading").show();
        $("#comp-admin-orgs-loading").show();
    }
   
}

cometDrawsModule.getComps = function (isSif) {

    $("#comp-admin-comps-loading").show();

    var organisationId = $('#OrganisationId').val();
    var sportId = cometDrawsModule.getSelectedSportId();
    var seasonId = cometDrawsModule.getSelectedSeasonId();

    if (sportId == "0" || seasonId == "0") {
        return;
    }

    var gradeIds = $('#comp-admin-grades').val();
    if (gradeIds) {
        gradeIds = gradeIds.join(",")
    }

    var fids = $('#comp-admin-feds').val();
    var fedIds = '';

    if (fids) {
        fedIds = fids.join(',');
    }

    var model = {
        organisationId: fedIds,
        gradeIds: gradeIds,
        sportId: sportId,
        seasonId: seasonId
    };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: cometCompWidgetBaseUrl + 'Competitions',
        data: JSON.stringify(model),
        cache: false,
        success: function (data) {

            var compsDropdown = $('#comp-admin-comps');

            cometDrawsModule.clearAllDropdowns(isSif);

            var allCompIds = [];

            for (var index = 0; index < data.length; index++) {
                compsDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                allCompIds.push(data[index].Id);
            }

            if (data.length > 0) {
                compsDropdown.attr("multiple", "multiple");
                compsDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Competitions Selected",
                    nonSelectedText: "Select a Competition...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {
                        $(".widget-settings-update").attr('disabled', 'disabled');
                        $("#hdnSelectedCompIds").val($('#comp-admin-comps').val());
                        cometDrawsModule.getPhases(isSif);

                    }
                });
            }

            compsDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedCompIds").val() != "") {
                compsDropdown.multiselect('select', $("#hdnSelectedCompIds").val().split(","));

                if ($("#hdnSelectedCompIds").val().split(",").length == allCompIds.length) {

                    $(".admin-comps-wrapper").find('.multiselect-item.multiselect-all').each(function (index) {
                        $(this).addClass('active');
                    });

                    $(".admin-comps-wrapper").find('.multiselect-all input').each(function (index) {
                        $(this).prop('checked', true);
                    });

                }

            }
            else {
                compsDropdown.multiselect('select', '');
            }

            if ($("#hdnSelectedCompIds").val().split(",").length > 0) {
                cometDrawsModule.getPhases(isSif);
            }

            $("#comp-admin-comps-loading").hide();

            if ($("#cometSortOrderModal").is(":visible")) {
                cometDrawsModule.openSortOrderModal();
            }
        }
    });
}

cometDrawsModule.clearAllDropdowns = function (isSif) {

    try {

        var compsDropdown = $('#comp-admin-comps');
        var orgsDropdown = $('#comp-admin-orgs');
        var phaseDropdown = $('#comp-admin-phases');
        var gradesDropdown = $('#comp-admin-grades');
        var teamsDropdown = $('#comp-admin-teams');
        //var fedsDropdown = $('#comp-admin-feds');

        compsDropdown.multiselect('destroy');
        compsDropdown.removeAttr("multiple");
        orgsDropdown.multiselect('destroy');
        orgsDropdown.removeAttr("multiple");
        //fedsDropdown.multiselect('destroy');
        //fedsDropdown.removeAttr("multiple");
        phaseDropdown.multiselect('destroy');
        phaseDropdown.removeAttr("multiple");

        if (!isSif) {
            gradesDropdown.multiselect('destroy');
            gradesDropdown.removeAttr("multiple");
        }

        teamsDropdown.multiselect('destroy');
        teamsDropdown.removeAttr("multiple");

        compsDropdown.find('option').remove();
        orgsDropdown.find('option').remove();
        // fedsDropdown.find('option').remove();
        phaseDropdown.find('option').remove();

        if (!isSif) {
            gradesDropdown.find('option').remove();
        }

        teamsDropdown.find('option').remove();

    }
    catch (e) {
        //first time
    }

}


cometDrawsModule.getOrgs = function (isSif) {
    $("#comp-admin-orgs-loading").show();

    var compIds = $('#comp-admin-comps').val();
    var seasonId = $('#comp-seasons').val();

    if (!compIds || compIds == "Select a Competition...") {
        compIds = ["0"];
    }

    var model = {
        ids: compIds.join(","),
        season: seasonId
    };


    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: cometCompWidgetBaseUrl + 'organisationslist',
        data: JSON.stringify(model),
        cache: false,
        success: function (data) {

            var orgDropdown = $('#comp-admin-orgs');

            try {
                orgDropdown.multiselect('destroy');
                orgDropdown.removeAttr("multiple");
            }
            catch (e) {
                //first time
            }

            orgDropdown.find('option').remove();

            var allOrgIds = [];
            for (var index = 0; index < data.length; index++) {
                orgDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                allOrgIds.push(data[index].Id);
            }

            if (data.length > 0) {
                orgDropdown.attr("multiple", "multiple");
                orgDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Organisations Selected",
                    nonSelectedText: "Select an Organisation...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {
                        $(".widget-settings-update").attr('disabled', 'disabled');
                        $("#hdnSelectedOrgIds").val($('#comp-admin-orgs').val());
                        cometDrawsModule.enableOrDisableSave();
                        if (!isSif)
                            cometDrawsModule.getGrades(isSif);
                    }
                });
            }

            orgDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedOrgIds").val() != "") {
                orgDropdown.multiselect('select', $("#hdnSelectedOrgIds").val().split(","));

                if ($("#hdnSelectedOrgIds").val().split(",").length == allOrgIds.length) {

                    $(".admin-orgs-wrapper").find('.multiselect-item.multiselect-all').each(function (index) {
                        $(this).addClass('active');
                    });

                    $(".admin-orgs-wrapper").find('.multiselect-all input').each(function (index) {
                        $(this).prop('checked', true);
                    });

                }

            }
            else {
                orgDropdown.multiselect('select', allOrgIds);
            }

            if (!isSif) {
                cometDrawsModule.getGrades(isSif);
            }

            $("#comp-admin-orgs-loading").hide();

            cometDrawsModule.enableOrDisableSave();

        }
    });

}


cometDrawsModule.getFeds = function (isSif) {
    
    $("#comp-admin-feds-loading").removeClass('hidden');
    $(".widget-settings-update").attr('disabled', 'disabled');

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        url: cometCompWidgetBaseUrl + 'federationslist',
        cache: false,
        success: function (data) {

            cometDrawsModule.clearAllDropdowns(isSif);

            var orgDropdown = $('#comp-admin-feds');

            try {
                orgDropdown.multiselect('destroy');
                orgDropdown.removeAttr("multiple");
            }
            catch (e) {
                //first time
            }

            orgDropdown.find('option').remove();

            var allOrgIds = [];
            for (var index = 0; index < data.length; index++) {
                orgDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                allOrgIds.push(data[index].Id);
            }

            if (data.length > 0) {
                orgDropdown.attr("multiple", "multiple");
                orgDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Federations Selected",
                    nonSelectedText: "Select a Federation...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {
                        $(".widget-settings-update").attr('disabled','disabled');
                        $("#hdnSelectedFedIds").val($('#comp-admin-feds').val());

                        if (isSif)
                            cometDrawsModule.getGrades(isSif);
                    }
                });
            }


            setTimeout(function () { cometDrawsModule.getGrades(isSif); }, 500);

            orgDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedFedIds").val() != "") {
                orgDropdown.multiselect('select', $("#hdnSelectedFedIds").val().split(","));

                if ($("#hdnSelectedFedIds").val().split(",").length == allOrgIds.length) {

                    $(".admin-orgs-wrapper").find('.multiselect-item.multiselect-all').each(function (index) {
                        $(this).addClass('active');
                    });

                    $(".admin-orgs-wrapper").find('.multiselect-all input').each(function (index) {
                        $(this).prop('checked', true);
                    });

                }

            }
            else {
                // orgDropdown.multiselect('deselectall', false);
                orgDropdown.multiselect('select', '');
            }

            $("#comp-admin-feds-loading").addClass('hidden');
        }
    });

}

cometDrawsModule.getPhases = function (isSif) {

    var compIds = $('#comp-admin-comps').val();

    if (!compIds || compIds == "Select a Competition...") {
        compIds = ["0"];
    }

    var model = {
        compIds: compIds
    };

    cometDrawsModule.getOrgs(isSif);


}

cometDrawsModule.getGrades = function (isSif) {

    $("#comp-admin-grades-loading").show();

    var phaseIds = $('#comp-admin-phases').val();
    var fedIds = "";

    try {
        fedIds = $('#comp-admin-feds').val().join(',');
    }
    catch (e) {

    }

    var season = $('#comp-seasons').val();

    $.get(cometCompWidgetBaseUrl + 'Grades?orgId=' + $('#OrganisationId').val() + "&fedIds=" + fedIds + "&season=" + season)
        .done(function (data) {

            var gradesDropdown = $('#comp-admin-grades');

            try {
                gradesDropdown.multiselect('destroy');
                gradesDropdown.removeAttr("multiple");
            }
            catch (e) {
                //first time
            }

            gradesDropdown.find('option').remove();

            //check an org has been selected
            var orgIds = $('#comp-admin-orgs').val();
            var allGradeIds = [];
            if (orgIds || isSif) {

                for (var index = 0; index < data.length; index++) {
                    gradesDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    allGradeIds.push(data[index].Id);
                }

            }

            if (data.length > 0) {

                gradesDropdown.attr("multiple", "multiple");
                gradesDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Grades Selected",
                    nonSelectedText: "Select a Grade...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function (element, checked) {
                        $(".widget-settings-update").attr('disabled', 'disabled');
                        $("#hdnSelectedGradeIds").val($('#comp-admin-grades').val());

                        if (isSif) {
                            setTimeout(function () { cometDrawsModule.getComps(isSif) }, 500);
                        }
                    }
                });

            }

            setTimeout(function () { cometDrawsModule.getComps(isSif) }, 500);

            gradesDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedGradeIds").val() != "") {
                gradesDropdown.multiselect('select', $("#hdnSelectedGradeIds").val().split(","));

                if ($("#hdnSelectedGradeIds").val().split(",").length == allGradeIds.length) {

                    $(".grades-wrapper").find('.multiselect-item.multiselect-all').each(function (index) {
                        $(this).addClass('active');
                    });

                    $(".grades-wrapper").find('.multiselect-all input').each(function (index) {
                        $(this).prop('checked', true);
                    });

                }
            }
            else {
                gradesDropdown.multiselect('select', '');
            }

            $("#comp-admin-grades-loading").hide();
        });
}

cometDrawsModule.setUpDataToggle = function (widgetInstanceId) {
    $('.results-tab[data-toggle=tab]').unbind('click');
    $('.results-tab[data-toggle=tab]').click(function () {

        var widgetId = $(this).parents('.wCometCompetition').data("id");
        var compWidget = $("#widget_" + widgetId);
        blockCometDateUpdate["w_" + widgetId + ""] = true;
        cometDrawsModule.getDateRangeSettings(widgetId, 'resultTab');

        setTimeout(function () { blockCometDateUpdate["w_" + widgetId + ""] = false }, 1000);
        cometDrawsModule.getDraws(widgetId);
    });

    $('.draws-tab[data-toggle=tab]').unbind('click');
    $('.draws-tab[data-toggle=tab]').click(function () {

        var widgetId = $(this).parents('.wCometCompetition').data("id");
        var compWidget = $("#widget_" + widgetId + "");
        blockCometDateUpdate["w_" + widgetId + ""] = true;

        cometDrawsModule.getDateRangeSettings(widgetId, 'drawTab');

        setTimeout(function () { blockCometDateUpdate["w_" + widgetId + ""] = false }, 1000);

        cometDrawsModule.getDraws(widgetId);
    });

    if ($("#widget_" + widgetInstanceId + " .nav-tabs li").length == 1) {
        $("#widget_" + widgetInstanceId + " .nav-tabs li").addClass("title-bar");
    }

}

cometDrawsModule.setupStyle = function () {

    $("#TitleBGColour").simplecolorpicker({ trigger: 'TitleBGColourTrigger', selectedColor: $("#TitleBGColour").val() });
    $("#TitleTextColour").simplecolorpicker({ trigger: 'TitleTextColourTrigger', selectedColor: $("#TitleTextColour").val() });
    $("#WidgetTextColour").simplecolorpicker({ trigger: 'WidgetTextColourTrigger', selectedColor: $("#WidgetTextColour").val() });
    $("#WidgetBackgroundColour").simplecolorpicker({ trigger: 'WidgetBackgroundColourTrigger', selectedColor: $("#WidgetBackgroundColour").val() });

    $("#WidgetBackgroundColour").change(function (e) {

        if ($('#cometTransparencySliderInput').val() == "100%") {
            $('#cometTransparencySlider').slider({ value: 1 });
            $('#cometTransparencySliderInput').val(Math.round(100 - (1 * 100)) + '%');
        }

    });

    // Wire up font select
    var selectedFont = $('#CometFontSelectHidden').val();
    if (selectedFont == "")
        selectedFont = $("#hdnFontFamily").val();

    $('#CometFontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedFont,
        'selected': function (style) {
            $('#CometFontSelectHidden').val(style);
        }
    });
    $('#CometFontSelectTrigger').on('click', function () {
        $('#CometFontSelect').click();
        return false;
    });

    var transparency = $('#cometTransparencySliderInput').val().replace('%', '');
    $('#cometTransparencySlider').slider({
        value: (1 - transparency),
        min: 0,
        max: 1,
        step: 0.01,
        slide: function (event, ui) {
            $('#cometTransparencySliderInput').val(Math.round(100 - (ui.value * 100)) + '%');
        }
    });

    $('#cometTransparencySliderInput').val(Math.round((transparency * 100)) + '%');

}

cometDrawsModule.checkDisplayBoxes = function () {

    var draws = $("#hdnSelectedDraws").val();
    var results = $("#hdnSelectedResults").val();
    var standings = $("#hdnSelectedStandings").val();

    if (draws === 'True') {
        $("#display-draw").prop("checked", true);
    }
    else {
        $("#display-draw").prop("checked", false);
    }

    if (results === 'True') {
        $("#display-results").prop("checked", true);
    }
    else {
        $("#display-results").prop("checked", false);
    }

    if (standings === 'True') {
        $("#display-standings").prop("checked", true);
    }
    else {
        $("#display-standings").prop("checked", false);
    }

    var hideGradeFilter = $("#hdnHideGradeFilter").val();
    var hideCompFilter = $("#hdnHideCompFilter").val();
    var hideOrgFilter = $("#hdnHideOrgFilter").val();
    var hideDateFilter = $("#hdnHideDateFilter").val();

    if (hideGradeFilter.toLowerCase() === 'true') {
        $("#hide-grade-filter").prop("checked", true);
    }
    else {
        $("#hide-grade-filter").prop("checked", false);
    }

    if (hideCompFilter.toLowerCase() === 'true') {
        $("#hide-comp-filter").prop("checked", true);
    }
    else {
        $("#hide-comp-filter").prop("checked", false);
    }

    if (hideOrgFilter.toLowerCase() === 'true') {
        $("#hide-org-filter").prop("checked", true);
    }
    else {
        $("#hide-org-filter").prop("checked", false);
    }

    if (hideDateFilter.toLowerCase() === 'true') {
        $("#hide-date-filter").prop("checked", true);
    }
    else {
        $("#hide-date-filter").prop("checked", false);
    }

    var title = $("#hdnSelectedTitle").val();
    var rounds = $("#hdnSelectedRounds").val();
    var logos = $("#hdnSelectedLogos").val();
    var time = $("#hdnSelectedTime").val();
    var team = $("#hdnSelectedTeam").val();
    var venues = $("#hdnSelectedVenues").val();
    var forAgainstDiff = $("#hdnSelectedForAgainstDiff").val();

    if (title === 'True') {
        $("#display-title").prop("checked", true);
    }
    else {
        $("#display-title").prop("checked", false);
    }

    if (rounds === 'True') {
        $("#display-rounds").prop("checked", true);
    }
    else {
        $("#display-rounds").prop("checked", false);
    }

    if (logos === 'True') {
        $("#display-logos").prop("checked", true);
    }
    else {
        $("#display-logos").prop("checked", false);
    }

    if (time === 'True') {
        $("#display-time").prop("checked", true);
    }
    else {
        $("#display-time").prop("checked", false);
    }

    if (team === 'True') {
        $("#display-team").prop("checked", true);
    }
    else {
        $("#display-team").prop("checked", false);
    }

    if (venues === 'True') {
        $("#display-venues").prop("checked", true);
    }
    else {
        $("#display-venues").prop("checked", false);
    }

    if (forAgainstDiff === 'True') {
        $("#display-foragainstdiff").prop("checked", true);
    }
    else {
        $("#display-foragainstdiff").prop("checked", false);
    }

    //height
    var isCustomHeight = $("#hdnIsCustomHeight").val();
    if (isCustomHeight == 'True') {
        $("#display-height-custom").prop("checked", true);
    }
    else {
        $("#display-height-full").prop("checked", true);
    }

    var customHeight = $("#hdnCustomHeight").val();
    $("#comet-custom-height").val(customHeight);


    //logo size
    var isLargeLogo = $("#hdnIsLargeLogo").val();
    if (isLargeLogo == 'True') {
        $("#display-logo-size-large").prop("checked", true);
    }
    else {
        $("#display-logo-size-regular").prop("checked", true);
    }


}

cometDrawsModule.toggleExpand = function (widgetId) {

        var compWidget = $("#widget_" + widgetId);
        $(compWidget).find('.expand-comet-widget').click(function (e) {

        $(compWidget).find('.mobile-comp-widget').css('height', 'auto');//For IE
        $(compWidget).find('.mobile-comp-widget').css('height', 'initial');
        $(compWidget).find('.mobile-comp-widget').css('overflow', 'initial');
        $(compWidget).find('.expand-comet-widget').hide();
        $(compWidget).find('.collapse-comet-widget').show();
    });

    $(compWidget).find('.collapse-comet-widget').click(function (e) {

        var customHeight = $(compWidget).find('.mobile-comp-widget').data("customheight");

        $(compWidget).find('.mobile-comp-widget').css('height', customHeight + 'px');
        $(compWidget).find('.mobile-comp-widget').css('overflow', 'hidden');
        $(compWidget).find('.expand-comet-widget').show();
        $(compWidget).find('.collapse-comet-widget').hide();
    });


}

cometDrawsModule.generateStatusHtml = function (isMobileHtml, fixture, showVenue) {
    var htmlContainer = '';

    if (showVenue != 'True') {
        return '';
    }
    if (isMobileHtml) {
        // statuses are generated in divs for desktop
        htmlContainer = 'div';
    }
    else {
        // statuses are generated in columns for desktop
        htmlContainer = 'td';
    }

    var html = '';

    var venueCss = !isMobileHtml ? 'full-name-venue' : 'abbr-name-venue';

    var place = (fixture.Latitude && fixture.Longitude) ? fixture.Latitude + ',' + fixture.Longitude : fixture.Address;

    // Create maps google link
    var venueAddressLink = "http://google.com/maps/search/?api=1&query=" + place;
    var defaultCss = "default-" + fixture.CssName;
    var statusCss = "status-" + fixture.CssName;
    if (fixture.Address && fixture.Latitude) {
        html = "<" + htmlContainer + " class='" + venueCss + " draw-" + defaultCss + "'><a href='" + venueAddressLink + "' target='_blank'>" + fixture.VenueName + "</a></" + htmlContainer + ">";
           
    }
    else {
        html = "<" + htmlContainer + " class='" + venueCss + " draw-" + defaultCss + "'>" + fixture.VenueName + "</" + htmlContainer + ">";
        
    }
    
    return html;
}

cometDrawsModule.getDraws = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);

    var loader = $(compWidget).find('.sked-widget-loader');
    $(loader).show();

    var compDropdown = $(compWidget).find('select.fe-comp-comps');
    var phaseDropdown = $(compWidget).find('select.fe-comp-phases');
    var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

    var compId = compDropdown.val();
    var phaseId = phaseDropdown.val();
    var orgIds = orgsDropdown.sportsgroundMobiscroll().selectGetVal();
    var gradeIds = gradesDropdown.val();

    var from = "";
    var to = "";

    try {
        from = $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().getDate().toLocalISOString();
        to = $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().getDate().toLocalISOString();
    }
    catch (e) {
        from = new Date().toLocalISOString();
        to = new Date().toLocalISOString();
    }
        
    var sportId = $(compWidget).find('.hdnSelectedSportId').val();
    var seasonId = $(compWidget).find('.hdnSelectedSeasonId').val();

    // the compId came back empty, should not try to get filteredfixtures without compId
    if (!compId ) {
        var drawDiv = $($(compWidget).find('.fe-draws-list')[0]);
        var resultsDiv = $($(compWidget).find('.fe-results-list')[0]);
        drawDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
        resultsDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
        return;
    }

    var roundId = cometRoundInfo[widgetId] ? cometRoundInfo[widgetId].currentRound : null;
    var roundsOn = $(compWidget).find('.mobile-comp-widget').data("rounds");

    var model = {
        competitionId: compId,
        phaseId: phaseId,
        orgIds: orgIds != null && orgIds != "" ? orgIds.join(",") : "",
        from: from,
        to: to,
        sportId: sportId,
        seasonId: seasonId,
        gradeIds: gradeIds != null && gradeIds != "" ? gradeIds.join(",") : "",
        gradeId: "",
        organisationId: "",
        roundId: roundId,
        roundsOn: roundsOn
    };

    var drawsTabExist = $(compWidget).find('.draws-tab').length;
    var resultsTabExist = $(compWidget).find('.results-tab').length;
    var standingsTabExist = $(compWidget).find('.standings-tab').length;

    if (drawsTabExist || resultsTabExist) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: cometCompWidgetBaseUrl + 'filteredfixtures',
            data: JSON.stringify(model),
            cache: false,
            success: function (data) {

                var loader = $(compWidget).find('.sked-widget-loader');
                $(loader).hide();

                cometDrawsModule.initializeFirstFixtureDateRange(data.firstFixtureDate, data.lastResultDate, compWidget);

                cometRoundInfo[widgetId] = data.roundInfo;

                var gradeIds = [];
                var grades = [];

                for (var i = 0; i < data.fixtures.length; i++) {

                    //comet hack for no gradeid returned
                    if (data.fixtures[i].GradeId == null || data.fixtures[i].GradeId == undefined || !data.fixtures[i].GradeId) {
                        data.fixtures[i].GradeId = data.fixtures[i].GradeName;
                    }
                    //comet hack for no sections
                    if (data.fixtures[i].SectionId == null || data.fixtures[i].SectionId == undefined || !data.fixtures[i].SectionId) {
                        data.fixtures[i].SectionId = data.fixtures[i].Round;
                        data.fixtures[i].SectionName = data.fixtures[i].RoundName;
                    }
                }
                for (var i = 0; i < data.fixtures.length; i++) {
                    if ($.inArray(data.fixtures[i].GradeId.toString() + data.fixtures[i].SectionId.toString(), gradeIds) == -1) {
                        gradeIds.push(data.fixtures[i].GradeId.toString() + data.fixtures[i].SectionId.toString());
                        grades.push({ "GradeId": data.fixtures[i].GradeId, "GradeName": data.fixtures[i].GradeName, "Fixtures": [], "SectionId": data.fixtures[i].SectionId, "SectionName": data.fixtures[i].SectionName });
                    }

                    var grade = jQuery.grep(grades, function (g) {
                        return g.GradeId == data.fixtures[i].GradeId && g.SectionId == data.fixtures[i].SectionId;
                    })[0];

                    grade.Fixtures.push(data.fixtures[i]);

                }

                var drawDiv = $($(compWidget).find('.fe-draws-list')[0]);
                drawDiv.html("<table></table>");

                var resultsDiv = $($(compWidget).find('.fe-results-list')[0]);
                resultsDiv.html("<table></table>");

                var logos = $(compWidget).find('.mobile-comp-widget').data("logos");
                var logoShowClass = logos != 'True' ? 'hidden' : '';

                var isLargeLogo = $(compWidget).find('.mobile-comp-widget').data("islargelogo");
                var logoSizeClass = isLargeLogo == 'True' ? 'large-logo' : '';
                var logoSizeWrapperClass = isLargeLogo == 'True' && logos == 'True' ? 'large-logo-wrapper' : '';

                var logoShowWrapperClass = logos != 'True' ? ' hide-logo-wrapper ' : '';

                var teamNames = $(compWidget).find('.mobile-comp-widget').data("teamnames");
                var teamNamesShowClass = teamNames != 'True' ? 'hidden' : '';

                var time = $(compWidget).find('.mobile-comp-widget').data("time");
                var timeShowClass = time != 'True' ? 'hidden' : '';

                var venues = $(compWidget).find('.mobile-comp-widget').data("venues");
                var venueShowClass = venues != 'True' ? ' hidden' : ' ';

                var hasBadStatus = false;
                for (var i = 0; i < grades.length; i++) {

                    for (var f = 0; f < grades[i].Fixtures.length; f++) {

                        var oddEven = f % 2 == 0 ? 'fixture-row-even' : 'fixture-row-odd';

                        var fixture = grades[i].Fixtures[f];

                        if (i == 0 && f == 0) {
                            $(compWidget).find('.round-number').html(fixture.matchDay);
                        }

                        var date = new Date(fixture.Date.replace("Z", "") + "Z");
                        date.setMinutes(date.getMinutes() + date.getTimezoneOffset());

                        var officialA = "";
                        if (fixture.OfficialA) {
                            officialA = fixture.OfficialA;
                        }

                        var officialB = "";
                        if (fixture.OfficialB) {
                            officialB = fixture.OfficialB;
                        }

                        var fixtureDate = date.toTimeFormatAMPM() + " | " + date.getDate() + "/" + (date.getMonth() + 1).toString() + "/" + date.getFullYear();

                        var timeAMPM = drawsModule.formatAMPM(date, fixture.HomeTeamName, fixture.AwayTeamName);

                        var fixtureDateCompressed = timeAMPM + (timeAMPM ? " | " : "") + date.getDate() + "/" + (date.getMonth() + 1).toString() + "/" + date.getFullYear().toString().substr(-2);

                        var homeLogo = '';
                        var awayLogo = '';
                        var logoClass = 'text-vs-padding ';

                        homeLogo = "<div class='home-logo '" + logoShowClass + "><div class='org-logo " + logoSizeClass + "'><img "
                            + (fixture.HomeOrganisationLogo == "" || (fixture.HomeTeamName == null || fixture.HomeTeamName.toLowerCase() == "bye") ? "" : "src='" + fixture.HomeOrganisationLogo + "'")
                            + "></div></div>";
                        awayLogo = "<div class='away-logo '" + logoShowClass + "><div class='org-logo " + logoSizeClass + "'><img "
                            + (fixture.AwayOrganisationLogo == "" || (fixture.AwayTeamName == null || fixture.AwayTeamName.toLowerCase() == "bye") ? "" : "src='" + fixture.AwayOrganisationLogo + "'")
                            + "></div></div>";
                        logoClass += ' org-logos ';

                        if (isLargeLogo == 'True') {
                            logoClass += ' big-org-logos';
                        }

                        //cancelled and postponed status
                        var isCancelled = fixture.Status == "POSTPONED" || fixture.Status == "CANCELLED" ? true : false;

                        if (isCancelled) {
                            hasBadStatus = true;
                        }

                        var status = isCancelled ? "!" : "";
                        var statusClass = isCancelled ? " cancelled-status " : "";
                        var modalTarget = isCancelled ? "data-toggle='modal' data-target='#cometWarning-" + widgetId + "-" + fixture.Status + "'" : "";

                        var drawsRow = "<tr title='" + (isCancelled ? fixture.Status : '') + "'" + modalTarget + " class='" + oddEven + ' ' + logoSizeWrapperClass + logoShowWrapperClass + statusClass + "'>";

                        drawsRow += "<td class='bad-status'>" + status + "</td><td class='fixture-date " + timeShowClass + "'>" + fixtureDate + "</td>"
                            + "<td class='full-name-comp home-team " + teamNamesShowClass + "'>" + (fixture.HomeTeamName || '') + "</td>"
                            + "<td class='abbr-name-comp home-team  " + teamNamesShowClass + "'>" + (fixture.HomeTeamName || '') + "</td>"
                            + "<td class='fe-vs'><div class='fe-vs-inner'><div class='fixture-date-mobile'>" + fixtureDateCompressed + "</div><div class='" + logoClass + "'>" + homeLogo + awayLogo
                            + "<div class='text-vs-align'>vs</div>" + cometDrawsModule.generateStatusHtml(true, fixture, venues) + "</div></div>" + "</td>"
                            + "<td class='full-name-comp away-team " + teamNamesShowClass + "'>" + (fixture.AwayTeamName || '') + "</td>"
                            + "<td class='abbr-name-comp away-team " + teamNamesShowClass + "'>" + (fixture.AwayTeamName || '') + "</td>";

                        drawsRow = drawsRow + cometDrawsModule.generateStatusHtml(false, fixture, venues);

                        drawsRow += "<td class='full-name-comp'>" + officialA + "<br/>" + officialB + "</td></tr>";

                        $($(compWidget).find('.fe-draws-list table')[0]).append(drawsRow);

                        if (fixture.PublicNotes) {
                            $($(compWidget).find('.fe-draws-list table')[0]).append("<tr class='" + oddEven + "'><td class='comp-widget-publicnotes' colspan='20'>" + fixture.PublicNotes + "</td></tr>");
                        }

                        var now = new Date();
                        if (now > date) {
                            var resultsRow = "<tr class='" + oddEven + ' ' + logoSizeWrapperClass + logoShowWrapperClass + "'>"
                                + "<td class='fixture-date " + timeShowClass + "'>" + fixtureDate + "</td>"
                                + "<td class='full-name-comp home-team " + teamNamesShowClass + "'>" + fixture.HomeTeamName + "</td>"
                                + "<td class='abbr-name-comp home-team " + teamNamesShowClass + "'>" + fixture.HomeTeamName + "</td>";

                            var defaultCss = "default-" + fixture.CssName;
                            var statusCss = "status-" + fixture.CssName;
                            resultsRow += "<td class='fe-vs result-" + defaultCss + "'><div class='fe-vs-inner'>"
                                + "<div class='fixture-date-mobile'>" + fixtureDateCompressed + "</div>"
                                + "<div class='" + logoClass + "'>" + homeLogo + awayLogo
                                + "<div class='text-vs-align'><span class='homescore " + "'>" + fixture.HomeScore + "</span><span class='score-seperator'> : </span><span class='awayscore " + "'>" + fixture.AwayScore + "</span></div>"
                                + "</div></div></td>";


                            resultsRow += "<td class='full-name-comp away-team " + teamNamesShowClass + "'>" + fixture.AwayTeamName + "</td>"
                                + "<td class='abbr-name-comp away-team " + teamNamesShowClass + "'>" + fixture.AwayTeamName + "</td>";

                            //resultsRow += "<td class='fe-vs result-" + statusCss + "'>" + fixture.Status + "</td></tr>";

                            $($(compWidget).find('.fe-results-list table')[0]).append(resultsRow);
                            if (fixture.PublicNotes) {
                                $($(compWidget).find('.fe-results-list table')[0]).append("<tr class='" + oddEven + "'><td class='comp-widget-publicnotes' colspan='20'>" + fixture.PublicNotes + "</td></tr>");
                            }
                        }

                    }
                }

                if (!hasBadStatus) {
                    $("#widget_" + widgetId + ".wCometCompetition .bad-status").hide();
                }

                if (data.fixtures.length == 0) {
                    drawDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
                    resultsDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
                } 

                if (resultsDiv.html() == "<table></table>") {
                    resultsDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
                }

                if (time == 'True' && venues != 'True' && teamNames != 'True') {
                    $("#widget_" + widgetId + ".wCometCompetition .fixture-date-mobile").show();
                    $("#widget_" + widgetId + ".wCometCompetition .fixture-date").hide();
                    $("#widget_" + widgetId + ".wCometCompetition .org-logos").addClass("override-datetime");
                }

                if (time != 'True') {
                    $("#widget_" + widgetId + ".wCometCompetition .fixture-date-mobile").hide();
                    $("#widget_" + widgetId + ".wCometCompetition .fixture-date").hide();
                }

                if (teamNames != 'True') {

                    $("#widget_" + widgetId + ".wCometCompetition .fe-results-list .org-logos").addClass("override-datetime");
                    $("#widget_" + widgetId + ".wCometCompetition .fe-draws-list .fe-vs").css("width", "60%");

                    if (time == 'True') {
                        $("#widget_" + widgetId + ".wCometCompetition .fe-results-list .fixture-date").hide();
                        $("#widget_" + widgetId + ".wCometCompetition .fe-results-list .fixture-date-mobile").show();
                        $("#widget_" + widgetId + ".wCometCompetition .fe-results-list .org-logos").addClass("override-datetime");
                   }
                }


                sportsground.cms.widgets.competitioncaching.save(widgetId);

            }
        });
    }

    if (standingsTabExist) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: cometCompWidgetBaseUrl + 'filteredstandings',
            data: JSON.stringify(model),
            cache: false,
            success: function (data) {

                var loader = $(compWidget).find('.sked-widget-loader');

                if (!drawsTabExist && !resultsTabExist) {
                    $(loader).hide();
                }

                var emptyStandingsTable = true;

                var isLargeLogo = $(compWidget).find('.mobile-comp-widget').data("islargelogo");
                var logoClass = isLargeLogo == 'True' ? 'large-logo' : '';

                var logos = $(compWidget).find('.mobile-comp-widget').data("logos");
                var logoShowClass = logos != 'True' ? 'hidden' : '';

                var teamNames = $(compWidget).find('.mobile-comp-widget').data("teamnames");
                var teamNamesShowClass = teamNames != 'True' ? 'hidden' : '';

                var forAgainst = $(compWidget).find('.mobile-comp-widget').data("foragainst");

                var columnWidthOverrideClass = teamNames != 'True' ? 'columnWidthOverrideClass' : '';
                columnWidthOverrideClass = teamNames != 'True' && forAgainst != 'True' ? 'columnWidthOverrideClass2' : columnWidthOverrideClass;

                var standingsDiv = $($(compWidget).find('.fe-standings-list')[0]);
                standingsDiv.html("<table></table>");

                var standingsHeader = "<tr class='standing-logo'><th class='" + logoShowClass + "'></th><th class='team-column " + teamNamesShowClass + "'></th>";
                standingsHeader += "<th class='played-column played-column-desktop'>Played</th><th class='played-column played-column-mobile'>P</th>";
                standingsHeader += "<th class='wins-column wins-column-desktop'>Win</th><th class='wins-column wins-column-mobile'>W</th>";
                standingsHeader += "<th class='draw-column draw-column-desktop'>Draw</th><th class='draw-column draw-column-mobile'>D</th>";
                standingsHeader += "<th class='losses-column losses-column-desktop'>Loss</th><th class='losses-column losses-column-mobile'>L</th>";

                if (forAgainst == 'True') {
                    standingsHeader += "<th class='for-column for-column-desktop'>For</th><th class='for-column for-column-mobile'>PF</th>";
                    standingsHeader += "<th class='against-column against-column-desktop'>Against</th> <th class='against-column against-column-mobile'>PA</th>";
                    standingsHeader += "<th class='dif-column dif-column-desktop'>Goal Difference</th> <th class='dif-column dif-column-mobile'>GD</th>";
                }

                standingsHeader += "<th class='total-column total-column-desktop'>Total</th><th class='total-column total-column-mobile'>Pts</th></tr>";

                $($(compWidget).find('.fe-standings-list table')[0]).append(standingsHeader);


                for (var i = 0; i < data.length; i++) {
                    var grade = data[i];

                    for (var g = 0; g < grade.Sections.length; g++) {

                        var section = grade.Sections[g];

                        var groupingTitle = "<tr class='grade-header'><td colspan='20'>" + grade.Name;
                        if (section.Name != "") {
                            groupingTitle += " (" + section.Name + ")";
                        }
                        groupingTitle += "</td></tr>";

                        emptyStandingsTable = false;
                        for (var s = 0; s < section.Standings.length; s++) {
                            var oddEven = s % 2 == 0 ? 'fixture-row-even' : 'fixture-row-odd';

                            var standing = section.Standings[s];
                            var standingLine = "<tr class='" + oddEven + "'>";
                            standingLine += "<td class='text-vs-padding org-logos " + logoShowClass + "'><div class='home-logo  " + logoClass + "'><div class='org-logo'><img src='" + standing.OrgLogo + "' /></div></div></td>";
                            standingLine += "<td class='full-name-comp team-column " + teamNamesShowClass + "'>" + standing.TeamName + "</td>";
                            standingLine += "<td class='abbr-name-comp team-column " + teamNamesShowClass + "'>" + (standing.TeamNameAbbr != null ? standing.TeamNameAbbr : standing.TeamName) + "</td>";
                            standingLine += "<td class='played-column " + columnWidthOverrideClass + " '>" + standing.Played + "</td>";
                            standingLine += "<td class='wins-column " + columnWidthOverrideClass + " '>" + standing.Wins + "</td>";
                            standingLine += "<td class='draw-column " + columnWidthOverrideClass + " '>" + standing.Draws + "</td>";
                            standingLine += "<td class='losses-column " + columnWidthOverrideClass + " '>" + standing.Losses + "</td>";

                            if (forAgainst == 'True') {
                                standingLine += "<td class='for-column " + columnWidthOverrideClass + " '>" + standing.ForPoints + "</td>";
                                standingLine += "<td class='against-column " + columnWidthOverrideClass + " '>" + standing.AgainstPoints + "</td>";
                                standingLine += "<td class='dif-column " + columnWidthOverrideClass + " '>" + standing.Differential + "</td>";
                            }
                            standingLine += "<td class='total-column " + columnWidthOverrideClass + " '>" + standing.StandingPoints + "</td>";
                            standingLine += "</tr>";

                            $($(compWidget).find('.fe-standings-list table')[0]).append(standingLine);

                        }
                    }
                }

                if (emptyStandingsTable) {

                    var standingsDiv = $($(compWidget).find('.fe-standings-list')[0]);
                    standingsDiv.html("<div class='no-fixtures'>No standings using the current filters.</div>");

                }

                //if (teamNames != 'True') {
                //    $(".for-column, .against-column, .dif-column").show();
                //}


                sportsground.cms.widgets.competitioncaching.save(widgetId);

            }
        });
    }
}

cometDrawsModule.clearSavedHidden = function () {
    $("#hdnSelectedCompIds").val("");
    $("#hdnSelectedPhaseIds").val("");
    $("#hdnSelectedOrgIds").val("");
    $("#hdnSelectedGradeIds").val("");
    $("#hdnSelectedTeamIds").val("");
    $("#hdnSelectedDraws").val("");
    $("#hdnSelectedResults").val("");
    $("#hdnSelectedStandings").val("");
    $("#hdnSelectedTitle").val("");
    $("#hdnSelectedRounds").val("");
    $("#hdnSelectedLogos").val("");
    $("#hdnSelectedTime").val("");
    $("#hdnSelectedTeam").val("");
    $("#hdnSelectedVenues").val("");
}

//admin edit modal create
cometDrawsModule.modalCreated = function (widgetInstanceId) {

    cometDrawsModule.checkDisplayBoxes();
    cometDrawsModule.setupStyle();

    $.get(cometCompWidgetBaseUrl + 'Sports')
        .done(function (data) {
            for (var index = 0; index < data.length; index++) {
                $('#comp-sports').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
            }

            var selectedSportId = $("#comp-sports").data("sportid") == "" ? 1 : $("#comp-sports").data("sportid");

            $("#comp-sports").val(selectedSportId);

            $.get(cometCompWidgetBaseUrl + 'Seasons')
                .done(function (data) {
                    for (var index = 0; index < data.length; index++) {
                        $('#comp-seasons').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    }

                    var selectedSeasonId = $("#comp-seasons").data("seasonid") == "" ? data[data.length - 1].Id : $("#comp-seasons").data("seasonid");

                    $("#comp-seasons").val(selectedSeasonId);
                    cometDrawsModule.loadFilters();

                });

        });


    $('#comp-sports').change(function (e) {
        cometDrawsModule.clearSavedHidden();
        cometDrawsModule.loadFilters();

    });


    $('#comp-seasons').change(function (e) {
        cometDrawsModule.clearSavedHidden();
        cometDrawsModule.loadFilters();
    });

    $("#setCometSortOrder").unbind('click');
    $("#setCometSortOrder").click(function (e) {

        cometDrawsModule.openSortOrderModal();

    });

    $("#cometSortDone").unbind('click');
    $("#cometSortDone").click(function (e) {

        cometDrawsModule.setCometSortOrder();

    });


};

cometDrawsModule.openSortOrderModal = function () {

    //load
    cometDrawsModule.loadOptions();

    $('#cometSortOrderModal').modal('show');

    if ($("#comp-admin-feds option").length === 1) {
        $("#sortableComps").hide();
        $("#sort-order-loading").show();
    }
    else {
        $("#sortableComps").show();
        $("#sort-order-loading").hide();
    }
    //display selected competitions
    $('#sortableComps').html('');

    var savedSortOrder = $('#hdnCompetitionIdsSortOrder').val();

    if (savedSortOrder) {
        savedSortOrder = savedSortOrder.split(',');
    }

    $("#comp-admin-comps option:selected").each(function () {
        var $this = $(this);
       
        if ($this.length) {
            var selText = $this.text();
            var selId = $this.val();
            var sortOrder = savedSortOrder.indexOf(selId);
            
            $('#sortableComps').append('<li data-sortorder="' + sortOrder + '" data-id="' + selId + '"><button type="button" class="btn btn-sm btn-info btn-block drag"><i class="icon-move"></i></button>' + selText + '</li>');
        }
    });


    $("#sortableComps").sortable({
        cancel: 'input',
        cursor: 'move',
        handle: '.drag'
    });

    $("#sortableComps").disableSelection();

    //sort based on saved sort order
    var liList = $("#sortableComps li");
    liList.sort(function (a, b) {
        return $(a).attr("data-sortorder") - $(b).attr("data-sortorder");
    });
    $("#sortableComps").html(liList);

};

cometDrawsModule.setCometSortOrder = function () {

    //set the sortOrder    
    var sortedIds = "";
    $('#sortableComps li').each(function () {
        var $this = $(this);

        var id = $($this).attr('data-id');

        sortedIds += id + ',';
    });

    $('#hdnCompetitionIdsSortOrder').val(sortedIds);
    $('#cometSortOrderModal').modal('toggle');

};

cometDrawsModule.commitChanges = function (widgetInstanceId) {

    globalCometWidgetSelectedDates = [];
    cometRoundInfo = {};

    //serialize comp widget settings
    var sportId = cometDrawsModule.getSelectedSportId();
    var seasonId = cometDrawsModule.getSelectedSeasonId();
    
    var competitionIdsSortOrder = $('#hdnCompetitionIdsSortOrder').val();

    var competitionIds = "";
    var orgIds = "";
    var gradeIds = "";
    var fedIds = "";

    if ($("#comp-admin-feds option").length != 1) {
        competitionIds = $('#comp-admin-comps').val().join(",");
        orgIds = $('#comp-admin-orgs').val().join(",");
        gradeIds = $('#comp-admin-grades').val().join(",");
        fedIds = $('#comp-admin-feds').val().join(",");
    }
    else {
        competitionIds = $('#hdnSelectedCompIds').val();
        orgIds = $('#hdnSelectedOrgIds').val();
        gradeIds = $('#hdnSelectedGradeIds').val();
        fedIds = $('#hdnSelectedFedIds').val();
    }
    

    var draws = $("#display-draw").is(":checked");
    var results = $("#display-results").is(":checked");
    var standings = $("#display-standings").is(":checked");
    var hideGradeFilter = $("#hide-grade-filter").is(":checked");
    var hideCompFilter = $("#hide-comp-filter").is(":checked");
    var hideOrgFilter = $("#hide-org-filter").is(":checked");
    var hideDateFilter = $("#hide-date-filter").is(":checked");

    var title = $("#display-title").is(":checked");
    var rounds = $("#display-rounds").is(":checked");
    var logos = $("#display-logos").is(":checked");
    var time = $("#display-time").is(":checked");
    var team = $("#display-team").is(":checked");
    var venues = $("#display-venues").is(":checked");
    var forAgainstDiff = $("#display-foragainstdiff").is(":checked");

    var isCustomHeight = $('input[name=display-height]:checked').val() != "full";
    var customHeight = $("#comet-custom-height").val();

    var isLargeLogo = $('input[name=display-logo-size]:checked').val() == "large";

    //style
    var titleBGColour = $('#TitleBGColour').val();
    var titleTextColour = $('#TitleTextColour').val();
    var cometFontSelect = $('#CometFontSelectHidden').val();
    var widgetTextColour = $('#WidgetTextColour').val();
    var widgetBackgroundColour = $('#WidgetBackgroundColour').val();
    var transparency = $('#cometTransparencySliderInput').val().replace('%', '');
    try {
        transparency = transparency / 100;
    }
    catch (e) {

    }

    var competitionLabel = "";
    var organisationLabel = "";
    var gradeLabel = "";
    var fedLabel = "";

    if ($("#comp-admin-feds option").length != 1) {
        competitionLabel = $(".admin-comps-wrapper button").html().replace('<b class="caret"></b>', '');
        organisationLabel = $(".admin-orgs-wrapper button").html().replace('<b class="caret"></b>', '');
        gradeLabel = $(".grades-wrapper button").html().replace('<b class="caret"></b>', '');
        fedLabel = $(".federations-wrapper button").html().replace('<b class="caret"></b>', '');
    }
    else {
        competitionLabel = $("#comp-admin-comps").val();
        organisationLabel = $("#comp-admin-orgs").val();
        gradeLabel = $("#comp-admin-grades").val();
        fedLabel = $("#comp-admin-feds").val();
    }

    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'CometCompetition',
        Settings: {
            SportId: sportId,
            SeasonId: seasonId,
            CompetitionIds: competitionIds,
            CompetitionLabel: competitionLabel,
            CompetitionIdsSortOrder: competitionIdsSortOrder,
            OrgIds: orgIds,
            OrganisationLabel: organisationLabel,
            PhaseIds: [],
            GradeIds: gradeIds,
            GradeLabel: gradeLabel,
            FedIds: fedIds,
            FedLabel: fedLabel,
            Draws: draws,
            Results: results,
            Standings: standings,
            HideGradeFilter: hideGradeFilter,
            HideCompFilter: hideCompFilter,
            HideOrgFilter: hideOrgFilter,
            HideDateFilter: hideDateFilter,
            Title: title,
            Rounds: rounds,
            Logos: logos,
            Time: time,
            Team: team,
            Venues: venues,
            ForAgainstDiff: forAgainstDiff,
            CustomHeight: customHeight,
            IsCustomHeight: isCustomHeight,
            IsLargeLogo: isLargeLogo,
            TitleBGColour: titleBGColour,
            TitleTextColour: titleTextColour,
            Font: cometFontSelect,
            WidgetTextColour: widgetTextColour,
            WidgetBackgroundColour: widgetBackgroundColour,
            Transparency: transparency

        }
    };

    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function (data, textStatus, xhr) {
            if (xhr.status === 202)
                $("#modal-dialog").modal('show');

            cometDrawsModule.rebuildWidget(widgetInstanceId);

        }
    });

    $("#myModal").modal('hide');
};

/*
    handles the initialization of date time picker
*/
cometDrawsModule.initializeDateRangeSettings = function (widgetInstanceId) {
    var compWidget = $('#widget_' + widgetInstanceId + '.wCometCompetition');
    var now = new Date();
    var weekAfter = new Date();
    weekAfter.setDate(weekAfter.getDate() + 6);
    //create from and to datepickers
    $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().datePicker(now, compWidget, 'competition', cometDrawsModule.saveSelectedDates);
    $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().datePicker(weekAfter, compWidget, 'competition', cometDrawsModule.saveSelectedDates);
}

/*
    handles setting of user defined date range,
    or setting default date range based on which tab is selected.
*/
cometDrawsModule.getDateRangeSettings = function (widgetInstanceId, selectedTab) {
    var compWidget = $('#widget_' + widgetInstanceId);

    var hasChangedDate = false;
    var firstFixtureDate = new Date();
    var lastResultDate = new Date();
    $.each(globalCometWidgetSelectedDates, function (i) {
        if (globalCometWidgetSelectedDates[i].WidgetId === widgetInstanceId) {
            hasChangedDate = globalCometWidgetSelectedDates[i].HasChangedDate;
            firstFixtureDate = globalCometWidgetSelectedDates[i].FirstFixtureDate;
            lastResultDate = globalCometWidgetSelectedDates[i].LastResultDate;
            return false;
        }
    });

    if (!hasChangedDate) {
        if (selectedTab == 'drawTab') {
            var weekAfter = new Date(firstFixtureDate.getTime());
            weekAfter.setDate(weekAfter.getDate() + 6);
            $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(firstFixtureDate);
            $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(weekAfter);
        }
        else if (selectedTab == 'resultTab') {
            var weekBefore = new Date(lastResultDate.getTime());
            weekBefore.setDate(weekBefore.getDate() - 6);
            $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(weekBefore);
            $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(lastResultDate);
        }
    }
}

/*
    handles saving of user defined date range on global javascript variable.
*/
cometDrawsModule.saveSelectedDates = function (widget) {
    var widgetId = $(widget).data('id');

    var isNew = true;
    $.each(globalCometWidgetSelectedDates, function (i) {
        if (globalCometWidgetSelectedDates[i].WidgetId === widgetId) {
            isNew = false;
            globalCometWidgetSelectedDates[i].HasChangedDate = true;
        }
    });

    if (isNew) {
        globalCometWidgetSelectedDates.push({
            WidgetId: widgetId,
            HasChangedDate: true
        });
    }
};

cometDrawsModule.initializeFirstFixtureDateRange = function (firstFixtureDate, lastResultDate, compWidget) {
    var isNew = true;

    $.each(globalCometWidgetSelectedDates, function (i) {
        if (globalCometWidgetSelectedDates[i].WidgetId === compWidget.data('id')) {
            isNew = false;

            var cleavedDate = firstFixtureDate.substring(0, firstFixtureDate.indexOf('T'));
            var firstDate = new Date(cleavedDate);
            var firstDateOnly = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());

            var cleavedLastDate = lastResultDate.substring(0, lastResultDate.indexOf('T'));
            var lastDate = new Date(cleavedLastDate);
            var lastResultDateOnly = new Date(lastDate.getFullYear(), lastDate.getMonth(), lastDate.getDate());

            globalCometWidgetSelectedDates[i].FirstFixtureDate = firstDateOnly;
            globalCometWidgetSelectedDates[i].LastResultDate = lastResultDateOnly;

            var tab = $(compWidget).find('.nav-tabs .active a').attr("class")

            if (tab == "draws-tab") {
                cometDrawsModule.getDateRangeSettings(compWidget.data('id'), "drawTab");
            }
            else if (tab == "results-tab") {
                cometDrawsModule.getDateRangeSettings(compWidget.data('id'), "resultTab");
            }


        }
    });
    if (isNew) {
        // the Date() conversion below will add the local offset to the already converted time on some browsers
        // so this next line removes everything after the T e.g. 2018-05-15T19:00:00 => 2018-05-15
        // Then whether or not a local offset is applied, we still get the right date. 
        var cleavedDate = firstFixtureDate.substring(0, firstFixtureDate.indexOf('T'));
        var firstDate = new Date(cleavedDate);
        var firstDateOnly = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());

        var cleavedLastDate = lastResultDate.substring(0, lastResultDate.indexOf('T'));
        var lastDate = new Date(cleavedLastDate);
        var lastResultDateOnly = new Date(lastDate.getFullYear(), lastDate.getMonth(), lastDate.getDate());

        globalCometWidgetSelectedDates.push({
            WidgetId: compWidget.data('id'),
            FirstFixtureDate: firstDateOnly,
            LastResultDate: lastResultDateOnly,
            HasChangedDate: false
        });

        setTimeout(function () { cometDrawsModule.initializeTabSettings(compWidget) }, 500);
    }
};

cometDrawsModule.initializeTabSettings = function (compWidget) {
    var drawsTabExist = $(compWidget).find('.draws-tab').length;
    var resultsTabExist = $(compWidget).find('.results-tab').length;
    var standingsTabExist = $(compWidget).find('.standings-tab').length;

    if (drawsTabExist) {
        $(compWidget).find('.draws-tab').trigger('click');
    }
    else if (!drawsTabExist && resultsTabExist) {
        $(compWidget).find('.results-tab').trigger('click');
    }
    else if (!drawsTabExist && !resultsTabExist && standingsTabExist) {
        $(compWidget).find('.standings-tab').trigger('click');
    }
};

cometDrawsModule.rebuildWidget = function (widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function (html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            cometDrawsModule.create(widgetInstanceId);
        }
    });
};
;

//Copyright Sportsground Limited 2016

var compWidgetApiVersion = "1.0";
var compWidgetBaseUrl = "/api/" + compWidgetApiVersion + "/competition/widget/";
var skedLoadAttempts = {};
var skedCacheUrl = SKEDCONFIG_SkedCache;
var windowHasFocus = true;
var globalSkedWidgetSelectedDates = [];

var blockSkedDateUpdate = {};
var PREVIOUS_DATA = {};

var drawsModule = extend(sportsground, 'sportsground.cms.widgets.competition');
drawsModule.skedFilterSettings = {};

var SPORTS = {
    Softball: { value: 29, name: "Softball" }
};  

var GAME_EVENTS = {
    Run: { value: 9, name: "Run" },
    Out: { value: 10, name: "Out" },
    Ball: { value: 11, name: "Ball" },
    Strike: { value: 12, name: "Strike" }
};

var softballInterval;

//front end client side create
drawsModule.create = function(widgetInstanceId) {
    drawsModule.setUpDataToggle(widgetInstanceId);

    var competitionWidget = $('#widget_' + widgetInstanceId + '.wCompetition');
    drawsModule.initializeDateRangeSettings(widgetInstanceId);

    var drawsTabExist = $(competitionWidget).find('.draws-tab').length;
    var resultsTabExist = $(competitionWidget).find('.results-tab').length;
    var standingsTabExist = $(competitionWidget).find('.standings-tab').length;

    if (!drawsTabExist && resultsTabExist) {
        $('#widget_' + widgetInstanceId + ' .results-tab').trigger('click');
    }
    else if (!drawsTabExist && !resultsTabExist && standingsTabExist) {
        $('#widget_' + widgetInstanceId + ' .standings-tab').trigger('click');
    }

    // get cache first, before calling back the initialize dropdown list
    sportsground.cms.widgets.competitioncaching.get(competitionWidget, drawsModule.initializeDropdownList);

    drawsModule.attachDropdownHandlers(competitionWidget);

    $(competitionWidget).find('.apply-comp-filters').click(function(e) {
        
        var widgetId = $(this).parents('.wCompetition').data("id");
        if (!blockSkedDateUpdate[widgetId]) {
            drawsModule.getDraws(widgetId, false);
            PREVIOUS_DATA[widgetId] = null;
        }

    });

    $(competitionWidget).on('click', '.softball-live-score', function () {        

        
        var fixtureId = $(this).data('id');
        var sportId = $('.hdnSelectedSportId').val();       

        var homeTeamName = $(this).data('hometeamname');
        var awayTeamName = $(this).data('awayteamname');

        var homeTeamLogo = $(this).data('hometeamlogo');
        var awayTeamLogo = $(this).data('awayteamlogo');

        var publishTeamsheetOnWidget = $(this).data('publishteamsheetonwidget');

        drawsModule.getGameEvents(competitionWidget, fixtureId, sportId, homeTeamName, awayTeamName, homeTeamLogo, awayTeamLogo, publishTeamsheetOnWidget);

        softballInterval = setInterval(function () {
            drawsModule.getGameEvents(competitionWidget, fixtureId, sportId, homeTeamName, awayTeamName, homeTeamLogo, awayTeamLogo, publishTeamsheetOnWidget);
        }, 30000);
        
    });

    $(competitionWidget).on('click', 'a.gameday-teamlist', function() {
        var data = {
            fixtureId: $(this).data('id'),
            isHome: $(this).data('is-home')
        };
        $.get(compWidgetBaseUrl + 'getGameDayTeamList', data, function(retVal) {
            $(competitionWidget).find('.gameday-teamlist-modal .modal-body').html(retVal);
            $(competitionWidget).find('.gameday-teamlist-modal').modal('show');
        }).fail(function(retVal) {
            $(competitionWidget).find('.gameday-teamlist-modal .modal-body').html('<div class="no-team-sheet red">' + retVal.statusText + '</div>');
            $(competitionWidget).find('.gameday-teamlist-modal').modal('show');
        });
    });

    $(".gameday-teamlist-modal").on("shown.bs.modal", function() {
        var urlReplace = "#modal";
        if (location.hash == "#modal") {
            // replace state that hash into the url, this prevents pushing more history when repeatedly opening modal
            history.replaceState(null, null, urlReplace);
        } else {
            // push state that hash into the url
            history.pushState(null, null, urlReplace);
        }
    });

    // If a pushstate has previously happened and the back button is clicked, hide any modals.
    $(window).on('popstate', function() {
        $(".gameday-teamlist-modal").modal('hide');
    });

    if ($('#OrganisationId').val() == "10047") { //hack/hard code so ad doesnt show for canterbury rugby crfu

        $(".competition-desktop-ad").remove();
        $(".competition-mobile-ad").remove();

    }

    $(".calendar-icon").unbind('click');
    $(".calendar-icon").click(function(e) {
        try {
            $($(e)[0].currentTarget).prev().data("DateTimePicker").show();
        }
        catch (e) {
            $(".comp-widget-from").click();
        }

    });

    $(".calendar-icon-from").unbind('click');
    $(".calendar-icon-from").click(function(e) {
        try {
            var widgetId = $($(this).parents('.wCompetition')[0]).data("id");
            $("#widget_" + widgetId + " .comp-widget-from").click();
            $("#widget_" + widgetId + " .comp-widget-from").focus();
        }
        catch (e) {

        }

    });

    $(".calendar-icon-to").unbind('click');
    $(".calendar-icon-to").click(function(e) {
        try {
            var widgetId = $($(this).parents('.wCompetition')[0]).data("id");
            $("#widget_" + widgetId + " .comp-widget-to").click();
            $("#widget_" + widgetId + " .comp-widget-to").focus();
        }
        catch (e) {

        }

    });


    $(".toggle-widget-filters").unbind('click');
    $(".toggle-widget-filters").click(function(e) {


        var widgetId = $($(this).parents('.wCompetition')[0]).data("id");

        $("#widget_" + widgetId + " .comp-widget-filters-wrapper").toggle();
        $("#widget_" + widgetId + " .toggle-widget-filters .fa-chevron-up").toggle();
        $("#widget_" + widgetId + " .toggle-widget-filters .fa-chevron-down").toggle();

        if ($("#widget_" + widgetId + " .toggle-filter-text").html() == "Hide Filters") {
            $("#widget_" + widgetId + " .toggle-filter-text").html("Show Filters");
        }
        else {
            $("#widget_" + widgetId + " .toggle-filter-text").html("Hide Filters");
        }

    });

    setInterval(function () {

        var sportId = $('.hdnSelectedSportId').val();

        var isLiveScoring = $('#OrganisationId').val() == "10047" || $('#OrganisationId').val() == "2144" || sportId == SPORTS.Softball.value; // CRFU or hbrugby or softball
        if ($('#fe-results-list-' + widgetInstanceId).is(":visible") && isLiveScoring) {

            drawsModule.getDraws(widgetInstanceId, true)
        }        

    }, 60000);

    $(".round-picker .fa-caret-right").unbind('click');
    $(".round-picker .fa-caret-right").click(function (e) {
               
        try {
            var widgetId = $($(this).parents('.wCompetition')[0]).data("id");
            drawsModule.nextRound(widgetId);
        }
        catch (e) {

        }

    });

    $(".round-picker .fa-caret-left").unbind('click');
    $(".round-picker .fa-caret-left").click(function (e) {
        try {
            var widgetId = $($(this).parents('.wCompetition')[0]).data("id");
            drawsModule.previousRound(widgetId);
        }
        catch (e) {

        }

    });

    drawsModule.toggleExpand(widgetInstanceId);

};

drawsModule.getGameEvents = function (competitionWidget, fixtureId, sportId, homeTeamName, awayTeamName, homeTeamLogo, awayTeamLogo, publishTeamsheetOnWidget) {

    var data = {
        fixtureId: fixtureId,
        sportId: sportId
    };

    homeTeamName = drawsModule.getGameDayTeamListLink(homeTeamName, publishTeamsheetOnWidget, fixtureId, true);
    awayTeamName = drawsModule.getGameDayTeamListLink(awayTeamName, publishTeamsheetOnWidget, fixtureId, false);

    $.ajax({
        type: "POST",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        url: compWidgetBaseUrl + 'fixturegameevents',
        success: function (gameEvents) {

            var template = $('#softball-template').html();
            $(competitionWidget).find('#softball-modal .modal-body').html(template);

            //batting
            if (gameEvents.IsHomeTeamPlaying == true) {
                $('.home-row .batting-team').removeClass('hidden');
            }
            else if (gameEvents.IsHomeTeamPlaying == false) {
                $('.away-row .batting-team').removeClass('hidden');
            }

            //status color
            var scoreClass = "agree-score";

            if (sportsground.cms.utils.isTrue(gameEvents.InGame)) {
                scoreClass = "live-result";
            }
            else if (fixture.ResultStatus == 1) {
                scoreClass = "dispute-score";
            }
            else if (fixture.ResultStatus == 2) {
                scoreClass = "dispute-score";
            }
            else if (fixture.ResultStatus == 3) {
                scoreClass = "dispute-score";
            }

            $('#softball-modal .live-result').addClass(scoreClass);


            //set team names
            $('#softball-modal .home-team-name').html(homeTeamName);
            $('#softball-modal .away-team-name').html(awayTeamName);

            $('#softball-modal .home-team-logo').attr('src', homeTeamLogo);
            $('#softball-modal .away-team-logo').attr('src', awayTeamLogo);

            let totalHomeRuns = 0;
            let totalAwayRuns = 0;

            //calculate runs per innings
            for (var i = 1; i <= 8; i++) {

                //home team runs
                var homeRuns = gameEvents.TeamAGameEvents.filter(function (item) { return item.Period === i && item.GameEventType === GAME_EVENTS.Run.value; }).length;
                var homeEvents = gameEvents.TeamAGameEvents.filter(function (item) { return item.Period === i; }).length;
                totalHomeRuns += homeRuns;

                if (homeRuns > 0 && homeEvents > 0) {
                    $('#softball-modal .home-row td:nth-child(' + (i + 1) + ')').html(homeRuns);
                }

                //away team runs
                var awayRuns = gameEvents.TeamBGameEvents.filter(function (item) { return item.Period === i && item.GameEventType === GAME_EVENTS.Run.value; }).length;
                var awayEvents = gameEvents.TeamBGameEvents.filter(function (item) { return item.Period === i; }).length;
                totalAwayRuns += awayRuns;

                if (awayRuns > 0 && awayEvents > 0) {
                    $('#softball-modal .away-row td:nth-child(' + (i + 1) + ')').html(awayRuns);
                }

            }


            //set totals
            $('#softball-modal .away-total').html(totalAwayRuns);
            $('#softball-modal .home-total').html(totalHomeRuns);

            //set balls strikes and outs
            var balls = gameEvents.InformationGameEvents.filter(function (item) { return item.GameEventType === GAME_EVENTS.Ball.value; }).length;
            var strikes = gameEvents.InformationGameEvents.filter(function (item) { return item.GameEventType === GAME_EVENTS.Strike.value; }).length;
            var outs = gameEvents.InformationGameEvents.filter(function (item) { return item.GameEventType === GAME_EVENTS.Out.value; }).length;

            $('#softball-modal .innings-info-row .balls').html(balls);
            $('#softball-modal .innings-info-row .strikes').html(strikes);
            $('#softball-modal .innings-info-row .outs').html(outs);

            $(competitionWidget).find('#softball-modal').modal({
                backdrop: 'static',
                keyboard: false,
                show: true
            });

            $('#softball-modal .close, #softball-modal .close-btn').on('click', function () {
                clearInterval(softballInterval);
            });

        },
        fail: function (retVal) {

            $(competitionWidget).find('#softball-modal .modal-body').html('<div class="error red">No game events found</div>');
            $(competitionWidget).find('#softball-modal').modal('show');

        }
    });

};

drawsModule.nextRound = function (widgetId) {
    
    blockSkedDateUpdate["w_" + widgetId + ""] = true;
    var compWidget = $('#widget_' + widgetId + '.wCompetition');

    drawsModule.saveSelectedDates(compWidget);

    //get currentRound
    var currentRoundNumber = Number($(compWidget).find('.round-id').html());

    if (isNaN(currentRoundNumber)) {
        return;
    }

    //ajax call to get next date
    $.get(compWidgetBaseUrl + 'rounddate?roundId=' + currentRoundNumber + '&isNext=true')
        .done(function (data) {

            //set from
            var next = new Date(data);
            $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(next);

            //set to
            var nextTo = new Date(data);
            nextTo.setDate(nextTo.getDate() + 6);
            $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(nextTo);

            drawsModule.getDraws(widgetId);

            blockSkedDateUpdate["w_" + widgetId + ""] = false;

        });


}

drawsModule.previousRound = function (widgetId) {

    blockSkedDateUpdate["w_" + widgetId + ""] = true;
    var compWidget = $('#widget_' + widgetId + '.wCompetition');

    drawsModule.saveSelectedDates(compWidget);

    //get currentRound
    var currentRoundNumber = Number($(compWidget).find('.round-id').html());

    if (isNaN(currentRoundNumber)) {
        return;
    }

    //ajax call to get previous date
    $.get(compWidgetBaseUrl + 'rounddate?roundId=' + currentRoundNumber + '&isNext=false')
        .done(function (data) {

            //set from
            var next = new Date(data);
            $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(next);

            //set to
            var previousTo = new Date(data);
            previousTo.setDate(previousTo.getDate() + 6);
            $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(previousTo);

            drawsModule.getDraws(widgetId);

            blockSkedDateUpdate["w_" + widgetId + ""] = false;

        });
    

}

drawsModule.setupStyle = function () {

    $("#TitleBGColour").simplecolorpicker({ trigger: 'TitleBGColourTrigger', selectedColor: $("#TitleBGColour").val() });
    $("#TitleTextColour").simplecolorpicker({ trigger: 'TitleTextColourTrigger', selectedColor: $("#TitleTextColour").val() });
    $("#WidgetTextColour").simplecolorpicker({ trigger: 'WidgetTextColourTrigger', selectedColor: $("#WidgetTextColour").val() });
    $("#WidgetBackgroundColour").simplecolorpicker({ trigger: 'WidgetBackgroundColourTrigger', selectedColor: $("#WidgetBackgroundColour").val() });


    $("#WidgetBackgroundColour").change(function (e) {

        if ($('#cometTransparencySliderInput').val() == "100%") {
            $('#cometTransparencySlider').slider({ value: 1 });
            $('#cometTransparencySliderInput').val(Math.round(100 - (1 * 100)) + '%');
        }

    });

    // Wire up font select
    var selectedFont = $('#CometFontSelectHidden').val();
    if (selectedFont == "")
        selectedFont = $("#hdnFontFamily").val();

    $('#CometFontSelect').fontSelector({
        'hide_fallbacks': true,
        'initial': selectedFont,
        'selected': function (style) {
            $('#CometFontSelectHidden').val(style);
        }
    });
    $('#CometFontSelectTrigger').on('click', function () {
        $('#CometFontSelect').click();
        return false;
    });

    var transparency = $('#cometTransparencySliderInput').val().replace('%', '');
    $('#cometTransparencySlider').slider({
        value: (1 - transparency),
        min: 0,
        max: 1,
        step: 0.01,
        slide: function (event, ui) {
            $('#cometTransparencySliderInput').val(Math.round(100 - (ui.value * 100)) + '%');
        }
    });

    $('#cometTransparencySliderInput').val(Math.round((transparency * 100)) + '%');

}


drawsModule.initializeDropdownList = function (competitionWidget, filterSettings) {

    var widgetInstanceId = competitionWidget.data("id");
    drawsModule.skedFilterSettings[widgetInstanceId] = filterSettings;

    $(competitionWidget).find('select.fe-comp-comps').each(function(i) {
        var dropdownList = $(this);
        var compIds = dropdownList.data("compids");
        var sortedCompIds = dropdownList.data("sortedcompids");
        if (sortedCompIds) {
            sortedCompIds = sortedCompIds.split(',');
        }


        $.get(compWidgetBaseUrl + 'competitions?ids=' + compIds)
            .done(function(data) {
                //add sorting
                for (var index = 0; index < data.length; index++) {

                    var sortOrder = sortedCompIds.indexOf(data[index].Id);
                    data[index].SortOrder = sortOrder;
                }

                //apply sort order
                data.sort(function (a, b) {
                    return a.SortOrder - b.SortOrder;
                });

                //create list
                for (var i = 0; i < data.length; i++) {

                    $(dropdownList).append('<option value="' + data[i].Id + '" data-sortorder="' + sortOrder + '">' + data[i].Name + '</option>');
                }

                if (data.length == 1) {
                    $(dropdownList).addClass("single-dropdown");
                    $(dropdownList).prop("disabled", "disabled");
                }
                else {
                    $(dropdownList).removeClass("single-dropdown");
                    $(dropdownList).prop("disabled", false);
                }
                
                var widgetInstanceId = competitionWidget.data("id");

                if (drawsModule.skedFilterSettings[widgetInstanceId].compIds) {
                    $(dropdownList[0]).val(drawsModule.skedFilterSettings[widgetInstanceId].compIds);
                }

                var compId = competitionWidget.find('select.fe-comp-comps').val();

                if (!compId) {
                    $(dropdownList[0]).val(data[0].Id);
                    compId = data[0].Id;
                    drawsModule.clearSkedCache(widgetInstanceId);
                    drawsModule.skedFilterSettings[widgetInstanceId] = {};
                }

                drawsModule.getFEPhases(widgetInstanceId, compId);

            });
    });
};

drawsModule.clearSkedCache = function (widgetId) {
  
    sportsground.cms.widgets.competitioncaching.clear(widgetId);

    if (drawsModule.skedFilterSettings[widgetId]){
        drawsModule.skedFilterSettings[widgetId].compIds = null;
        drawsModule.skedFilterSettings[widgetId].orgIds = null;
        drawsModule.skedFilterSettings[widgetId].gradeIds = null;
        drawsModule.skedFilterSettings[widgetId].phaseIds = null;
    }
    
}

drawsModule.attachDropdownHandlers = function (competitionWidget) {
    $(competitionWidget).find('select.fe-comp-comps').change(drawsModule.dropdownHandlers.competition);
    $(competitionWidget).find('select.fe-comp-phases').change(drawsModule.dropdownHandlers.phase);

    // attaches dropdown handlers on select html for desktop only
    if (!sportsground.ui.isMobile()) {
        $(competitionWidget).find('select.fe-comp-orgs').change(drawsModule.dropdownHandlers.organisation);
        $(competitionWidget).find('select.fe-comp-grades').change(drawsModule.dropdownHandlers.grade);
    }
};
// list of dropdown handlers
drawsModule.dropdownHandlers = {
    competition: function (e) {
        var widget = $(this).parents('.wCompetition');
        var widgetId = widget.data("id");
        var compId = $(this).val();

        skedLoadAttempts[widgetId] = null;

        drawsModule.clearSkedCache(widgetId);

        drawsModule.getFEPhases(widgetId, compId);

        PREVIOUS_DATA[widgetId] = null;
    },
    organisation: function (e, me) {
        if (e != 'mobiscroll_event') {
            me = this;
        }
        var widget = $(me).parents('.wCompetition');
        var compDropdown = $(widget).find('select.fe-comp-comps');
        var compId = compDropdown.val();
        var widgetId = widget.data("id");

        drawsModule.clearSkedCache(widgetId);

        drawsModule.getFEGrades(widgetId);

        PREVIOUS_DATA[widgetId] = null;

        drawsModule.refreshFEPhases(widgetId, compId);
    },
    grade: function (e, me) {
        if (e != 'mobiscroll_event') {
            me = this;
        }
        var widget = $(me).parents('.wCompetition');
        var compDropdown = $(widget).find('select.fe-comp-comps');
        var compId = compDropdown.val();
        var widgetId = widget.data("id");

        drawsModule.clearSkedCache(widgetId);

        drawsModule.getDraws(widgetId, false);

        PREVIOUS_DATA[widgetId] = null;

         drawsModule.refreshFEPhases(widgetId, compId);
    },
    phase: function (e) {
        var widget = $(this).parents('.wCompetition');
        var widgetId = widget.data("id");

        drawsModule.clearSkedCache(widgetId);
        var phaseId = $(this).val();
        cachedWidget[widgetId].currentPhaseId = phaseId;
        drawsModule.getStandings(widgetId, false);
        

        PREVIOUS_DATA[widgetId] = null;
    }
};

drawsModule.setUpExportEvent = function () {

    $(".export-draw-btn").unbind('click');
    $(".export-draw-btn").click(function (e) {
        var widgetId = $(this).parents('.wCompetition').data("id");
        drawsModule.exportDraw(widgetId, "grade");

    });

    $(".export-official-btn").unbind('click');
    $(".export-official-btn").click(function (e) {
        var widgetId = $(this).parents('.wCompetition').data("id");
        drawsModule.exportDraw(widgetId, "officials");

    });

    $('.results-export span').unbind('click');
    $(".results-export span").click(function (e) {

        var widgetId = $(this).parents('.wCompetition').data("id");
        drawsModule.exportResults(widgetId);

    });

    $('.standings-export span').unbind('click');
    $(".standings-export span").click(function (e) {

        var widgetId = $(this).parents('.wCompetition').data("id");
        drawsModule.exportStandings(widgetId);

    });
};

drawsModule.getFEPhases = function (widgetId, selectedCompId) {

    $.get(compWidgetBaseUrl + 'phases?ids=' + selectedCompId)
        .done(function (data) {

            var compWidget = $("#widget_" + widgetId);
            var allowedPhaseIds = $(compWidget).find('select.fe-comp-phases').data("phaseids");
            var phaseDropdown = $(compWidget).find('select.fe-comp-phases');

            phaseDropdown.find('option').remove();

            var allowedCount = 0;
            for (var index = 0; index < data.length; index++) {

                var phaseName = data[index].Name.split(":")[1];
                phaseDropdown.append('<option ' + (index == (data.length - 1) ? 'selected' : '') + ' value="' + data[index].Id + '">' + phaseName + '</option>');
                allowedCount++;

            }

            if (allowedCount == 1) {
                $(phaseDropdown).addClass("single-dropdown");
                $(phaseDropdown).prop("disabled", "disabled");
            }
            else {
                $(phaseDropdown).removeClass("single-dropdown");
                $(phaseDropdown).prop("disabled", false);
            }

            if (drawsModule.skedFilterSettings[widgetId].phaseIds && drawsModule.skedFilterSettings[widgetId].phaseIds != 'null') {

                phaseDropdown.val(drawsModule.skedFilterSettings[widgetId].phaseIds);
            }


            drawsModule.getFEOrgs(widgetId, selectedCompId);

        });

};

drawsModule.refreshFEPhases = function (widgetId, selectedCompId) {

    var compWidget = $("#widget_" + widgetId)[0];

    var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
    var orgIds = orgsDropdown.sportsgroundMobiscroll().selectGetVal();

    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');
    var gradeIds = gradesDropdown.sportsgroundMobiscroll().selectGetVal();

    var model = {
        orgIds: orgIds != null && orgIds != "" ? orgIds.join(",") : "",
        gradeIds: gradeIds != null && gradeIds != "" ? gradeIds.join(",") : ""
    };

    $.get(compWidgetBaseUrl + 'filteredphases?ids=' + selectedCompId + '&orgIds=' + model.orgIds + '&gradeIds=' + model.gradeIds)
        .done(function (data) {

            var compWidget = $("#widget_" + widgetId);
            var phaseDropdown = $(compWidget).find('select.fe-comp-phases');

            phaseDropdown.find('option').remove();

            var allowedCount = 0;
            for (var index = 0; index < data.length; index++) {

                var phaseName = data[index].Name.split(":")[1];
                phaseDropdown.append('<option ' + ' value="' + data[index].Id + '">' + phaseName + '</option>');
                allowedCount++;
            }

            if (allowedCount == 1) {
                $(phaseDropdown).addClass("single-dropdown");
                $(phaseDropdown).prop("disabled", "disabled");
            }
            else {
                $(phaseDropdown).removeClass("single-dropdown");
                $(phaseDropdown).prop("disabled", false);
            }

            //if (drawsModule.skedFilterSettings[widgetId].phaseIds && drawsModule.skedFilterSettings[widgetId].phaseIds != 'null') {

            //    phaseDropdown.val(drawsModule.skedFilterSettings[widgetId].phaseIds);
            //}

            

        });

};

drawsModule.getFEOrgs = function(widgetId, selectedCompId) {

    $.get(compWidgetBaseUrl + 'organisations?ids=' + selectedCompId)
        .done(function(data) {

            var compWidget = $("#widget_" + widgetId);
            var allowedOrgIds = $(compWidget).find('select.fe-comp-orgs').data("orgids");
            var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');

            orgsDropdown.sportsgroundMobiscroll().selectDestroy();

            var allowedCount = 0;
            var allOrgIds = [];
            var addedOrgIds = [];
            for (var index = 0; index < data.length; index++) {

                if (allowedOrgIds.toString().indexOf(data[index].Id) != -1) {
                    orgsDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    addedOrgIds.push(data[index].Id);
                    allowedCount++;
                }

                allOrgIds.push(data[index].Id);
            }

            if (data.length > 0) {
                var multiSelectSettings = {
                    dropdown: {
                        inputClass: 'fe-comp-orgs',
                        defaultText: 'Select an Organisation...',
                        selectedText: 'Organisations Selected',
                        onChangeCallback: drawsModule.dropdownHandlers.organisation
                    }
                };
                orgsDropdown.sportsgroundMobiscroll().selectMultiple(multiSelectSettings);
            }

            var selectedItems = [];
            if (drawsModule.skedFilterSettings[widgetId].orgIds) {              
                selectedItems = drawsModule.skedFilterSettings[widgetId].orgIds.split(",");
            }
            else {
                selectedItems = allOrgIds;
            }

            if (sportsground.ui.isMobile()) {
                if (addedOrgIds != "" && (drawsModule.skedFilterSettings[widgetId].orgIds == "" || drawsModule.skedFilterSettings[widgetId].orgIds == undefined)) {
                    selectedItems = addedOrgIds;
                }
            }

            orgsDropdown.sportsgroundMobiscroll().selectInitialize(selectedItems, multiSelectSettings);
           
            if (addedOrgIds.length == selectedItems.length) {

                $($(compWidget).find('.comp-widget-org-wrapper')[0]).find('.multiselect-item.multiselect-all').each(function (index) {
                    $(this).addClass('active');
                });

                $($(compWidget).find('.comp-widget-org-wrapper')[0]).find('.multiselect-all input').each(function (index) {
                    $(this).prop('checked', true);
                });

            }

            var orgWrapper = $($(compWidget).find('.comp-widget-org-wrapper')[0]);
            var orgButton = $("#widget_" + widgetId + ' .comp-widget-org-wrapper .form-group .btn-group button')[0];
            var orgArrow = $(orgWrapper).find('.caret');
            if (allowedCount == 1) {
                $(orgWrapper).addClass("single-multiselect");
                $(orgButton).prop("disabled", "disabled");
                $(orgArrow).each(function (i) {
                    $(this).hide();
                });
            }
            else {
                $(orgWrapper).removeClass("single-multiselect");
                $(orgButton).prop("disabled", false);
                $(orgArrow).each(function (i) {
                    $(this).show();
                });
            }

            drawsModule.getFEGrades(widgetId);

        });

}


drawsModule.getFEGrades = function(widgetId) {

    var compWidget = $("#widget_" + widgetId)[0];
    var phaseIds = $(compWidget).find('select.fe-comp-phases').val();

    $.get(compWidgetBaseUrl + 'GradesByPhases?phaseIds=' + phaseIds)
        .done(function(data) {

            var compWidget = $("#widget_" + widgetId)[0];
            var allowedGradeIds = $(compWidget).find('select.fe-comp-grades').data("gradeids");
            var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

            gradesDropdown.sportsgroundMobiscroll().selectDestroy();

            var allowed = 0;
            var allGradeIds = [];
            var addedGradeIds = [];
            for (var index = 0; index < data.length; index++) {
                if (allowedGradeIds.toString().indexOf(data[index].Id) != -1) {
                    gradesDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    allowed++;
                    addedGradeIds.push(data[index].Id);
                }
                allGradeIds.push(data[index].Id);
            }


            if (data.length > 0) {
                var multiSelectSettings = {
                    dropdown: {
                        inputClass: 'fe-comp-grades',
                        defaultText: 'Select a Grade...',
                        selectedText: 'Grades Selected',
                        onChangeCallback: drawsModule.dropdownHandlers.grade
                    }
                };
                gradesDropdown.sportsgroundMobiscroll().selectMultiple(multiSelectSettings);
            }

            var selectedItems = [];

            if (drawsModule.skedFilterSettings[widgetId].gradeIds) {
                selectedItems = drawsModule.skedFilterSettings[widgetId].gradeIds.split(",");
            }
            else {
                selectedItems = allGradeIds;
            }

            if (sportsground.ui.isMobile()) {
                if (allowedGradeIds != "" && (drawsModule.skedFilterSettings[widgetId].gradeIds == "" || drawsModule.skedFilterSettings[widgetId].gradeIds == undefined)) {
                    selectedItems = addedGradeIds;
                }
            }

            gradesDropdown.sportsgroundMobiscroll().selectInitialize(selectedItems, multiSelectSettings);

            if (addedGradeIds.length == selectedItems.length) {

                //multiselect-item multiselect-all
                $($(compWidget).find('.comp-widget-grade-wrapper')[0]).find('.multiselect-item.multiselect-all').each(function (index) {
                    $(this).addClass('active');
                });

                $($(compWidget).find('.comp-widget-grade-wrapper')[0]).find('.multiselect-all input').each(function (index) {
                    $(this).prop('checked', true);
                });

            }

            var gradeWrapper = $($(compWidget).find('.comp-widget-grade-wrapper')[0]);
            var gradeButton = $("#widget_" + widgetId + ' .comp-widget-grade-wrapper .form-group .btn-group button')[0];
            var gradeArrow = $($(gradeWrapper).find('.caret')[0]);

            if (allowed == 1) {
                $(gradeWrapper).addClass("single-multiselect");
                $(gradeButton).prop("disabled", "disabled");
                $(gradeArrow).hide();
            }
            else {
                $(gradeWrapper).removeClass("single-multiselect");
                $(gradeButton).prop("disabled", false);
                $(gradeArrow).show();
            }

            drawsModule.getDraws(widgetId, false);

        });
}

drawsModule.getSelectedSportId = function() {
    return $('#comp-sports').val();
}

drawsModule.getSelectedSeasonId = function() {
    return $('#comp-seasons').val();
}

drawsModule.getOwners = function() {

    var sportId = drawsModule.getSelectedSportId();
    var seasonId = drawsModule.getSelectedSeasonId();

    if (sportId == "0" || seasonId == "0") {
        return;
    }

    var ownerDropdown = $('#comp-admin-owner');

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: compWidgetBaseUrl + 'Owners?sportId=' + sportId + "&seasonId=" + seasonId,
        cache: false,
        success: function(data) {

            var ownersDropdown = $('#comp-admin-owner');

            drawsModule.clearAllDropdowns();

            var allOwnerIds = [];

            for (var index = 0; index < data.length; index++) {
                ownersDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                allOwnerIds.push(data[index].Id);
            }

            if (data.length > 0) {
                $(ownersDropdown).change(function () {
                    $(".widget-settings-update").attr('disabled', 'disabled');
                    $("#hdnSelectedOwnerIds").val($('#comp-admin-owner').val());
                    drawsModule.getComps();
                });
            }

            var select = $('#hdnSelectedOwnerIds').val();
            if (select == "") {
                select = $('#OrganisationId').val();
            }
            
            $(ownersDropdown).val(select);

            if ($("#hdnSelectedOwnerIds").val().split(",").length > 0) {
                drawsModule.getComps();
            }
            else {
                $(".widget-settings-update").attr('disabled', false);
            }

        }
    });

}

drawsModule.getComps = function() {

    var organisationId = $('#comp-admin-owner').val();
    var sportId = drawsModule.getSelectedSportId();
    var seasonId = drawsModule.getSelectedSeasonId();

    if (sportId == "0" || seasonId == "0") {
        return;
    }

    var model = {
        organisationId: organisationId,
        sportId: sportId,
        seasonId: seasonId
    };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: compWidgetBaseUrl + 'Competitions',
        data: JSON.stringify(model),
        cache: false,
        success: function(data) {

            var compsDropdown = $('#comp-admin-comps');

            drawsModule.clearAllDropdowns();

            var allCompIds = [];

            for (var index = 0; index < data.length; index++) {
                compsDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                allCompIds.push(data[index].Id);
            }

            if (data.length > 0) {
                compsDropdown.attr("multiple", "multiple");
                compsDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Competitions Selected",
                    nonSelectedText: "Select a Competition...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function(element, checked) {

                        $("#hdnSelectedCompIds").val($('#comp-admin-comps').val());
                        drawsModule.getPhases();

                    }
                });
            }

            compsDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedCompIds").val() != "") {
                compsDropdown.multiselect('select', $("#hdnSelectedCompIds").val().split(","));

                if ($("#hdnSelectedCompIds").val().split(",").length == allCompIds.length) {

                    $(".admin-comps-wrapper").find('.multiselect-item.multiselect-all').each(function(index) {
                        $(this).addClass('active');
                    });

                    $(".admin-comps-wrapper").find('.multiselect-all input').each(function(index) {
                        $(this).prop('checked', true);
                    });

                }

            }
            else {
                compsDropdown.multiselect('select', allCompIds);
            }

            if ($("#hdnSelectedCompIds").val().split(",").length > 0) {
                drawsModule.getPhases();
            }
            else {
                $(".widget-settings-update").attr('disabled', false);
            }

        }
    });
}

drawsModule.clearAllDropdowns = function() {

    try {

        var compsDropdown = $('#comp-admin-comps');
        var orgsDropdown = $('#comp-admin-orgs');
        var phaseDropdown = $('#comp-admin-phases');
        var gradesDropdown = $('#comp-admin-grades');
        var teamsDropdown = $('#comp-admin-teams');

        compsDropdown.multiselect('destroy');
        compsDropdown.removeAttr("multiple");
        orgsDropdown.multiselect('destroy');
        orgsDropdown.removeAttr("multiple");
        phaseDropdown.multiselect('destroy');
        phaseDropdown.removeAttr("multiple");
        gradesDropdown.multiselect('destroy');
        gradesDropdown.removeAttr("multiple");
        teamsDropdown.multiselect('destroy');
        teamsDropdown.removeAttr("multiple");

        compsDropdown.find('option').remove();
        orgsDropdown.find('option').remove();
        phaseDropdown.find('option').remove();
        gradesDropdown.find('option').remove();
        teamsDropdown.find('option').remove();

    }
    catch (e) {
        //first time
    }

}


drawsModule.getOrgs = function() {

    var compIds = $('#comp-admin-comps').val();

    if (!compIds || compIds == "Select a Competition...") {
        compIds = ["0"];
    }
    $.get(compWidgetBaseUrl + 'organisations?ids=' + compIds.join(","))
        .done(function(data) {

            var orgDropdown = $('#comp-admin-orgs');

            try {
                orgDropdown.multiselect('destroy');
                orgDropdown.removeAttr("multiple");
            }
            catch (e) {
                //first time
            }

            orgDropdown.find('option').remove();

            //dont show orgs if no phase selected
            var phaseIds = $('#comp-admin-phases').val();
            var allOrgIds = [];
            if (phaseIds) {
                for (var index = 0; index < data.length; index++) {
                    orgDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    allOrgIds.push(data[index].Id);
                }
            }

            if (data.length > 0) {
                orgDropdown.attr("multiple", "multiple");
                orgDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Organisations Selected",
                    nonSelectedText: "Select an Organisation...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function(element, checked) {
                        $(".widget-settings-update").attr('disabled', 'disabled');
                        $("#hdnSelectedOrgIds").val($('#comp-admin-orgs').val());
                        drawsModule.getGrades();
                    }
                });
            }

            orgDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedOrgIds").val() != "") {
                orgDropdown.multiselect('select', $("#hdnSelectedOrgIds").val().split(","));

                if ($("#hdnSelectedOrgIds").val().split(",").length == allOrgIds.length) {

                    $(".admin-orgs-wrapper").find('.multiselect-item.multiselect-all').each(function(index) {
                        $(this).addClass('active');
                    });

                    $(".admin-orgs-wrapper").find('.multiselect-all input').each(function(index) {
                        $(this).prop('checked', true);
                    });

                }
            }
            else {
                orgDropdown.multiselect('select', allOrgIds);
            }

            drawsModule.getGrades();

        });
}


drawsModule.getPhases = function() {

    var compIds = $('#comp-admin-comps').val();

    if (!compIds || compIds == "Select a Competition...") {
        compIds = ["0"];
    }
    $.get(compWidgetBaseUrl + 'phases?ids=' + compIds.join(","))
        .done(function(data) {

            var phaseDropdown = $('#comp-admin-phases');

            try {
                phaseDropdown.multiselect('destroy');
                phaseDropdown.removeAttr("multiple");
            }
            catch (e) {
                //first time
            }

            phaseDropdown.find('option').remove();

            var allPhaseIds = [];

            for (var index = 0; index < data.length; index++) {
                phaseDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                allPhaseIds.push(data[index].Id);
            }

            if (data.length > 0) {
                phaseDropdown.attr("multiple", "multiple");
                phaseDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Phases Selected",
                    nonSelectedText: "Select a Phase...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function(element, checked) {
                        $(".widget-settings-update").attr('disabled', 'disabled');
                        $("#hdnSelectedPhaseIds").val($('#comp-admin-phases').val());
                        drawsModule.getOrgs();

                    }
                });
            }

            phaseDropdown.multiselect('deselectall', false);

            phaseDropdown.multiselect('select', allPhaseIds);

            if ($("#hdnSelectedGradeIds").val().split(",").length > 0) {
                drawsModule.getOrgs();
            }
            else {             
                $(".widget-settings-update").attr('disabled', false);
            }

        });
}

drawsModule.getGrades = function() {

    var phaseIds = $('#comp-admin-phases').val();
    $.get(compWidgetBaseUrl + 'GradesByPhases?phaseIds=' + phaseIds)
        .done(function(data) {

            var gradesDropdown = $('#comp-admin-grades');

            try {
                gradesDropdown.multiselect('destroy');
                gradesDropdown.removeAttr("multiple");
            }
            catch (e) {
                //first time
            }

            gradesDropdown.find('option').remove();

            //check an org has been selected
            var orgIds = $('#comp-admin-orgs').val();
            var allGradeIds = [];
            if (orgIds) {

                for (var index = 0; index < data.length; index++) {
                    gradesDropdown.append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    allGradeIds.push(data[index].Id);
                }

            }

            if (data.length > 0) {

                gradesDropdown.attr("multiple", "multiple");
                gradesDropdown.multiselect({
                    numberDisplayed: 1,
                    nSelectedText: " Grades Selected",
                    nonSelectedText: "Select a Grade...",
                    buttonWidth: '100%',
                    includeSelectAllOption: true,
                    onChange: function(element, checked) {

                        $("#hdnSelectedGradeIds").val($('#comp-admin-grades').val());
                        //drawsModule.getTeams();

                    }
                });

            }

            gradesDropdown.multiselect('deselectall', false);

            if ($("#hdnSelectedGradeIds").val() != "") {
                gradesDropdown.multiselect('select', $("#hdnSelectedGradeIds").val().split(","));

                if ($("#hdnSelectedGradeIds").val().split(",").length == allGradeIds.length) {

                    $(".grades-wrapper").find('.multiselect-item.multiselect-all').each(function(index) {
                        $(this).addClass('active');
                    });

                    $(".grades-wrapper").find('.multiselect-all input').each(function(index) {
                        $(this).prop('checked', true);
                    });
                }

            }
            else {
                gradesDropdown.multiselect('select', allGradeIds);
            }

            if ($('#comp-admin-owner').val()) {

                $(".widget-settings-update").attr('disabled', false);

            }
           

        });
}

drawsModule.setUpDataToggle = function (widgetInstanceId) {
    $('.results-tab[data-toggle=tab]').click(function () {

        var widgetId = $(this).parents('.wCompetition').data("id");
        var compWidget = $("#widget_" + widgetId);

        blockSkedDateUpdate[widgetId] = true;

        $(compWidget).find('.comp-widget-dates').show();
        $(compWidget).find('.comp-widget-phase-wrapper').hide();

        drawsModule.getDateRangeSettings(widgetId, 'resultTab');

        setTimeout(function () { blockSkedDateUpdate[widgetId] = false }, 1000);

        drawsModule.getDraws(widgetId, false);
    });

    $('.draws-tab[data-toggle=tab]').click(function () {

        var widgetId = $(this).parents('.wCompetition').data("id");
        var compWidget = $("#widget_" + widgetId);

        blockSkedDateUpdate[widgetId] = true;

        $(compWidget).find('.comp-widget-dates').show();
        $(compWidget).find('.comp-widget-phase-wrapper').hide();

        drawsModule.getDateRangeSettings(widgetId, 'drawTab');

        setTimeout(function () { blockSkedDateUpdate[widgetId] = false }, 1000);

        drawsModule.getDraws(widgetId, false);
    });

    $('.standings-tab[data-toggle=tab]').click(function () {

        var widgetId = $(this).parents('.wCompetition').data("id");
        var compWidget = $("#widget_" + widgetId);

        $(compWidget).find('.comp-widget-dates').hide();
        $(compWidget).find('.comp-widget-phase-wrapper').show();

        var compDropdown = $(compWidget).find('select.fe-comp-comps');
        var compId = compDropdown.val();

        drawsModule.refreshFEPhases(widgetId, compId);

    });

};

drawsModule.toggleExpand = function (widgetId) {

    var compWidget = $("#widget_" + widgetId);
    $(compWidget).find('.expand-comet-widget').click(function (e) {

        $(compWidget).find('.mobile-comp-widget').css('height', 'auto');//For IE
        $(compWidget).find('.mobile-comp-widget').css('height', 'initial');
        $(compWidget).find('.mobile-comp-widget').css('overflow', 'initial');
        $(compWidget).find('.expand-comet-widget').hide();
        $(compWidget).find('.collapse-comet-widget').show();
    });

    $(compWidget).find('.collapse-comet-widget').click(function (e) {

        var customHeight = $(compWidget).find('.mobile-comp-widget').data("customheight");

        $(compWidget).find('.mobile-comp-widget').css('height', customHeight + 'px');
        $(compWidget).find('.mobile-comp-widget').css('overflow', 'hidden');
        $(compWidget).find('.expand-comet-widget').show();
        $(compWidget).find('.collapse-comet-widget').hide();
    });


}

drawsModule.checkDisplayBoxes = function() {

    var draws = $("#hdnSelectedDraws").val();
    var results = $("#hdnSelectedResults").val();
    var standings = $("#hdnSelectedStandings").val();

    if (draws === 'True') {
        $("#display-draw").prop("checked", true);
    }
    else {
        $("#display-draw").prop("checked", false);
    }

    if (results === 'True') {
        $("#display-results").prop("checked", true);
    }
    else {
        $("#display-results").prop("checked", false);
    }

    if (standings === 'True') {
        $("#display-standings").prop("checked", true);
    }
    else {
        $("#display-standings").prop("checked", false);
    }

    var hideGradeFilter = $("#hdnHideGradeFilter").val();
    var hideCompFilter = $("#hdnHideCompFilter").val();
    var hideOrgFilter = $("#hdnHideOrgFilter").val();
    var hideDateFilter = $("#hdnHideDateFilter").val();

    if (hideGradeFilter.toLowerCase() === 'true') {
        $("#hide-grade-filter").prop("checked", true);
    }
    else {
        $("#hide-grade-filter").prop("checked", false);
    }

    if (hideCompFilter.toLowerCase() === 'true') {
        $("#hide-comp-filter").prop("checked", true);
    }
    else {
        $("#hide-comp-filter").prop("checked", false);
    }

    if (hideOrgFilter.toLowerCase() === 'true') {
        $("#hide-org-filter").prop("checked", true);
    }
    else {
        $("#hide-org-filter").prop("checked", false);
    }

    if (hideDateFilter.toLowerCase() === 'true') {
        $("#hide-date-filter").prop("checked", true);
    }
    else {
        $("#hide-date-filter").prop("checked", false);
    }

    var title = $("#hdnSelectedTitle").val();
    var rounds = $("#hdnSelectedRounds").val();
    var logos = $("#hdnSelectedLogos").val();
    var time = $("#hdnSelectedTime").val();
    var team = $("#hdnSelectedTeam").val();
    var venues = $("#hdnSelectedVenues").val();
    var forAgainstDiff = $("#hdnSelectedForAgainstDiff").val();

    if (title === 'True') {
        $("#display-title").prop("checked", true);
    }
    else {
        $("#display-title").prop("checked", false);
    }

    if (rounds === 'True') {
        $("#display-rounds").prop("checked", true);
    }
    else {
        $("#display-rounds").prop("checked", false);
    }

    if (logos === 'True') {
        $("#display-logos").prop("checked", true);
    }
    else {
        $("#display-logos").prop("checked", false);
    }

    if (time === 'True') {
        $("#display-time").prop("checked", true);
    }
    else {
        $("#display-time").prop("checked", false);
    }

    if (team === 'True') {
        $("#display-team").prop("checked", true);
    }
    else {
        $("#display-team").prop("checked", false);
    }

    if (venues === 'True') {
        $("#display-venues").prop("checked", true);
    }
    else {
        $("#display-venues").prop("checked", false);
    }

    if (forAgainstDiff === 'True') {
        $("#display-foragainstdiff").prop("checked", true);
    }
    else {
        $("#display-foragainstdiff").prop("checked", false);
    }

    //height
    var isCustomHeight = $("#hdnIsCustomHeight").val();
    if (isCustomHeight == 'True') {
        $("#display-height-custom").prop("checked", true);
    }
    else {
        $("#display-height-full").prop("checked", true);
    }

    var customHeight = $("#hdnCustomHeight").val();
    $("#comet-custom-height").val(customHeight);


    //logo size
    var isLargeLogo = $("#hdnIsLargeLogo").val();
    if (isLargeLogo == 'True') {
        $("#display-logo-size-large").prop("checked", true);
    }
    else {
        $("#display-logo-size-regular").prop("checked", true);
    }

}

var firstFixtureDate = {};
var weekAfterFirstDate = {};
var weekBeforeFirstDate = {};

drawsModule.getFirstFixture = function(widgetId) {

    var compWidget = $("#widget_" + widgetId)[0];
    var compDropdown = $(compWidget).find('select.fe-comp-comps');
    var compId = compDropdown.val();

    var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
    var orgIds = orgsDropdown.sportsgroundMobiscroll().selectGetVal();

    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');
    var gradeIds = gradesDropdown.sportsgroundMobiscroll().selectGetVal();
   
    var model = {
        competitionId: compId,
        orgIds: orgIds != null && orgIds != "" ? orgIds.join(",") : "",
        gradeIds: gradeIds != null && gradeIds != "" ? gradeIds.join(",") : ""

    };

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: compWidgetBaseUrl + 'firstfixturedate',
        data: JSON.stringify(model),
        cache: false,
        success: function(data) {

            blockSkedDateUpdate[widgetId] = true;
            var cleavedDate = data.substring(0, data.indexOf('T'));
            var firstDate = new Date(cleavedDate);
            var firstDate2 = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
            firstFixtureDate[widgetId] = firstDate2;
            $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(firstDate2);

            var weekAfter = new Date(firstDate2.getTime());;
            weekAfter.setDate(weekAfter.getDate() + 6);
            weekAfterFirstDate[widgetId] = weekAfter;

            var weekBefore = new Date(firstDate2.getTime());;
            weekBefore.setDate(weekBefore.getDate() - 6);
            weekBeforeFirstDate[widgetId] = weekBefore;

            $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(weekAfter);
            setTimeout(function () { drawsModule.getDraws(widgetId, false); blockSkedDateUpdate[widgetId] = false;}, 500);

        }

    });

}

function sortByOrder(a, b) {
    var aOrder = Number(a.GradeSortOrder);
    var bOrder = Number(b.GradeSortOrder);
    
    var sectionAOrder = Number(a.SectionSortOrder);
    var sectionBOrder = Number(b.SectionSortOrder);
    
    if (aOrder == bOrder) {

        return ((sectionAOrder < sectionBOrder) ? -1 : ((sectionAOrder > sectionBOrder) ? 1 : 0));
    }
    else {
        return ((aOrder < bOrder) ? -1 : ((aOrder > bOrder) ? 1 : 0));
    }
}

function sortStandingsByOrder(a, b) {
    var aOrder = Number(a.Order);
    var bOrder = Number(b.Order);
    return ((aOrder < bOrder) ? -1 : ((aOrder > bOrder) ? 1 : 0));
}

function sortFixturesDate(a, b) {
    var aDate = new Date(a.Date.replace("Z", "") + "Z");
    var bDate = new Date(b.Date.replace("Z", "") + "Z");

    if (aDate.getUTCFullYear() == bDate.getUTCFullYear() && aDate.getUTCMonth() == bDate.getUTCMonth() && aDate.getUTCDate() == bDate.getUTCDate()) {
        if ((a.HomeTeamName.toLowerCase() == "bye" || a.AwayTeamName.toLowerCase() == "bye") &&
            (b.HomeTeamName.toLowerCase() != "bye" || b.AwayTeamName.toLowerCase() != "bye")) {
            return 1;
        }
        if ((a.HomeTeamName.toLowerCase() != "bye" || a.AwayTeamName.toLowerCase() != "bye") &&
            (b.HomeTeamName.toLowerCase() == "bye" || b.AwayTeamName.toLowerCase() == "bye")) {
            return -1;
        }
    }

    if (aDate > bDate) {
        return 1;
    } else if (aDate < bDate) {
        return -1;
    }

    return ((a.Id < b.Id) ? -1 : ((a.Id > b.Id) ? 1 : 0));
}

var cachedWidget = {};

drawsModule.fixturesCallback = function(from, to, orgIds, widgetId, compWidget, autoUpdate, model) {

    if (!cachedWidget[widgetId].fixtureCacheError && cachedWidget[widgetId].gradeCountNeeded == cachedWidget[widgetId].gradeCountAt) {
       
        //apply filters
        //date
        var filtered = $.grep(cachedWidget[widgetId].joinedFixtures, function(n, i) {
            if (n && n.From) {

                var cleavedFromDate = n.From.substring(0, n.From.indexOf('T'));
                var fFrom = new Date(cleavedFromDate);

                var cleavedDateTo = n.To.substring(0, n.To.indexOf('T'));
                var fTo = new Date(cleavedDateTo);
                
                return fFrom.toLocalISOString() >= from && fTo.toLocalISOString() <= to;
            }
        });

        //org
        filtered = $.grep(filtered, function(n, i) {
            if (n && (n.TeamAOrganisationId || n.TeamBOrganisationId)) {
                if (orgIds) {
                    return orgIds.includes(n.TeamAOrganisationId) || orgIds.includes(n.TeamBOrganisationId)
                }
                else {
                    return false;
                }
              
            }

        });

        drawsModule.renderFixtures(filtered, widgetId, compWidget, autoUpdate);
    }
    else if (cachedWidget[widgetId].fixtureCacheError == true && !cachedWidget[widgetId].handlingFixturesError) {
      
        if (filteredfixturesXhr[widgetId] != undefined) {
            filteredfixturesXhr[widgetId].abort();
        } 

        cachedWidget[widgetId].handlingFixturesError = true;
        filteredfixturesXhr[widgetId] = $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: compWidgetBaseUrl + 'filteredfixtures',
            data: JSON.stringify(model),
            cache: false,
            success: function(data) {
                drawsModule.renderFixtures(data, widgetId, compWidget, autoUpdate);
            }
        });
    }

    sportsground.cms.widgets.competitioncaching.save(widgetId);

}

var filteredfixturesXhr = {};

drawsModule.standingsCallback = function (compId, phaseId, gradeIds, widgetId, compWidget, autoUpdate) {

    if (!cachedWidget[widgetId].standingsCacheError && cachedWidget[widgetId].standingsGradeCountNeeded == cachedWidget[widgetId].standingsGradeCountAt) {

        //sort
        cachedWidget[widgetId].joinedStandings.sort(sortStandingsByOrder);
        $(compWidget).find('select.fe-comp-phases').val(phaseId);
        drawsModule.renderStandings(cachedWidget[widgetId].joinedStandings, widgetId, compWidget);
    }
    else if (cachedWidget[widgetId].standingsCacheError == true && !cachedWidget[widgetId].handlingStandingsError) {
        cachedWidget[widgetId].handlingStandingsError = true;
        $.get(compWidgetBaseUrl + 'filteredstandings?competitionId=' + compId + "&phaseId=" + phaseId + "&gradeIds=" + gradeIds)
            .done(function(data) {

                drawsModule.renderStandings(data, widgetId, compWidget);

            });
    }

    sportsground.cms.widgets.competitioncaching.save(widgetId);
}


drawsModule.getDraws = function (widgetId, autoUpdate) {

    try {

        var compWidget = $("#widget_" + widgetId)[0];

        var compDropdown = $(compWidget).find('select.fe-comp-comps');
        var phaseDropdown = $(compWidget).find('select.fe-comp-phases');
        var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
        var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

        var compId = compDropdown.val();
        var orgIds = orgsDropdown.sportsgroundMobiscroll().selectGetVal() || [];
        var gradeIds = gradesDropdown.sportsgroundMobiscroll().selectGetVal() || [];

        var from = "";
        var toDate = "";

        try {
            from = $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().getDate().toLocalISOString();
            toDate = $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().getDate();
        }
        catch (e) {
            from = new Date().toLocalISOString();
            toDate = new Date();
        }

        toDate.setHours(23);
        toDate.setMinutes(59);
        var to = toDate.toLocalISOString();

        var orgIdsJoined = "";
        var gradeIdsJoined = "";

        try {
            orgIdsJoined = orgIds && orgIds != "" ? orgIds.join(",") : "";
        }
        catch (e) {
            orgIdsJoined = "";
        }

        try {
            gradeIdsJoined = gradeIds && gradeIds != "" ? gradeIds.join(",") : "";
        }
        catch (e) {
            gradeIdsJoined = "";
        }

        var model = {
            competitionId: compId,
            orgIds: orgIdsJoined,
            from: from,
            to: to,
            gradeIds: gradeIdsJoined
        };

        var loader = $(compWidget).find('.sked-widget-loader');
        $(loader).show();

        var previousSelectedPhase;

        if (cachedWidget[widgetId]) {
            previousSelectedPhase = cachedWidget[widgetId].currentPhaseId;
        }
        cachedWidget[widgetId] = {};

        cachedWidget[widgetId].joinedFixtures = [];
        cachedWidget[widgetId].fixtureCacheError = false;
        cachedWidget[widgetId].gradeCountNeeded = gradeIds ? gradeIds.length : 0;
        cachedWidget[widgetId].gradeCountAt = 0;
        cachedWidget[widgetId].handlingFixturesError = false;

        if (!gradeIds) {
            gradeIds = [];
        }
        for (var i = 0; i < gradeIds.length; i++) {

            $.ajax({
                url: skedCacheUrl + 'fixtures/' + compId + '/' + gradeIds[i],
                async: true,
                success: function (data) {

                    var x2js = new X2JS();
                    var jsonObj = x2js.xml_str2json(data);

                    if (jsonObj) {
                        cachedWidget[widgetId].joinedFixtures = cachedWidget[widgetId].joinedFixtures.concat(jsonObj.ArrayOfCompWidgetFixture.CompWidgetFixture);
                    }
                    cachedWidget[widgetId].gradeCountAt++;

                    drawsModule.fixturesCallback(from, to, orgIds, widgetId, compWidget, autoUpdate, model);
                },
                error: function (data) {
                    cachedWidget[widgetId].fixtureCacheError = true;
                    drawsModule.fixturesCallback(from, to, orgIds, widgetId, compWidget, autoUpdate, model);
                }

            });


        }

        //standings
        cachedWidget[widgetId].joinedStandings = [];
        cachedWidget[widgetId].standingsCacheError = false;
        cachedWidget[widgetId].standingsGradeCountNeeded = gradeIds ? gradeIds.length : 0;
        cachedWidget[widgetId].standingsGradeCountAt = 0;
        cachedWidget[widgetId].handlingStandingsError = false;

        if (!compId || !gradeIds || gradeIds.length == 0) {
            return;
        }

        //first get the current phase
        $.get(compWidgetBaseUrl + 'getCurrentPhase?competitionId=' + compId + '&orgIds=' + orgIds + '&gradeIds=' + gradeIds + '&widgetId=' + widgetId)
            .done(function (currentPhaseId) {
                
                               
                if (previousSelectedPhase) {
                    currentPhaseId = $(phaseDropdown).val();
                }

                //set currentphase in dropdown
                $(phaseDropdown).val(currentPhaseId);

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

                    $.ajax({
                        url: skedCacheUrl + 'Standings/' + compId + '/' + currentPhaseId + '/' + gradeIds[i],
                        async: true,
                        success: function (data) {

                            var x2js = new X2JS();
                            var jsonObj = x2js.xml_str2json(data);
                            cachedWidget[widgetId].joinedStandings = cachedWidget[widgetId].joinedStandings.concat(jsonObj.CompWidgetGrade);

                            cachedWidget[widgetId].standingsGradeCountAt++;

                            drawsModule.standingsCallback(compId, currentPhaseId, gradeIds, widgetId, compWidget, autoUpdate);

                        },
                        error: function (data) {
                            cachedWidget[widgetId].standingsCacheError = true;
                            drawsModule.standingsCallback(compId, currentPhaseId, gradeIds, widgetId, compWidget, autoUpdate);
                        }

                    });


                }
            });
    }
    catch (e) {
        Raygun.send(e);
    }

}


drawsModule.getStandings = function (widgetId, autoUpdate) {

    try {

        var compWidget = $("#widget_" + widgetId)[0];

        var compDropdown = $(compWidget).find('select.fe-comp-comps');
        var phaseDropdown = $(compWidget).find('select.fe-comp-phases');
        var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
        var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

        var compId = compDropdown.val();
        var gradeIds = gradesDropdown.sportsgroundMobiscroll().selectGetVal() || [];


        var loader = $(compWidget).find('.sked-widget-loader');
        $(loader).show();

        cachedWidget[widgetId] = {};

        cachedWidget[widgetId].joinedFixtures = [];
        cachedWidget[widgetId].fixtureCacheError = false;
        cachedWidget[widgetId].gradeCountNeeded = gradeIds ? gradeIds.length : 0;
        cachedWidget[widgetId].gradeCountAt = 0;
        cachedWidget[widgetId].handlingFixturesError = false;

        if (!gradeIds) {
            gradeIds = [];
        }       

        //standings
        cachedWidget[widgetId].joinedStandings = [];
        cachedWidget[widgetId].standingsCacheError = false;
        cachedWidget[widgetId].standingsGradeCountNeeded = gradeIds ? gradeIds.length : 0;
        cachedWidget[widgetId].standingsGradeCountAt = 0;
        cachedWidget[widgetId].handlingStandingsError = false;

        if (!compId || !gradeIds || gradeIds.length == 0) {
            return;
        }

        currentPhaseId = $(phaseDropdown).val();
        for (var i = 0; i < gradeIds.length; i++) {

            $.ajax({
                url: skedCacheUrl + 'Standings/' + compId + '/' + currentPhaseId + '/' + gradeIds[i],
                async: true,
                success: function (data) {

                    var x2js = new X2JS();
                    var jsonObj = x2js.xml_str2json(data);
                    cachedWidget[widgetId].joinedStandings = cachedWidget[widgetId].joinedStandings.concat(jsonObj.CompWidgetGrade);

                    cachedWidget[widgetId].standingsGradeCountAt++;

                    drawsModule.standingsCallback(compId, currentPhaseId, gradeIds, widgetId, compWidget, autoUpdate);

                },
                error: function (data) {
                    cachedWidget[widgetId].standingsCacheError = true;
                    drawsModule.standingsCallback(compId, currentPhaseId, gradeIds, widgetId, compWidget, autoUpdate);
                }

            });

        }
    }
    catch (e) {
        Raygun.send(e);
    }

}

drawsModule.renderStandings = function (data, widgetId, compWidget) {

    var loader = $(compWidget).find('.sked-widget-loader');
    $(loader).hide();

    var firstGrade = data[0];
    var isPlayOff = sportsground.cms.utils.isTrue(firstGrade.IsPlayoff);
    var isPlayOffClass = isPlayOff ? 'playoff' : '';

    var standingsDiv = $($(compWidget).find('.fe-standings-list')[0]);
    standingsDiv.html("<div class='standings-export'><span class='export-text'>Export</span> <i class='fa fa-file-pdf-o' aria-hidden='true'></i></div><table class='" + isPlayOffClass + "'></table>");

    var forAgainst = $(compWidget).find('.mobile-comp-widget').data("foragainst");

    var isLargeLogo = $(compWidget).find('.mobile-comp-widget').data("islargelogo");
    var logoClass = isLargeLogo == 'True' ? 'large-logo' : '';

    var logos = $(compWidget).find('.mobile-comp-widget').data("logos");
    var logoShowClass = logos != 'True' ? 'hidden' : '';

    if (firstGrade != undefined && sportsground.cms.utils.isTrue(firstGrade.IsPlayoff)) {
        $($(compWidget).find('.fe-standings-list table')[0]).append("<tr><td class='" + logoShowClass + "'></td><td style='width:60px;'>Ranking</td><td>Team</td></tr>");
    }
    else {

        var standingsHeader = "<tr><th class='" + logoShowClass + "'></th><th class='team-column'></th><th class='played-column played-column-desktop'>Played</th><th class='played-column played-column-mobile'>P</th><th class='wins-column wins-column-desktop'>Win</th><th class='wins-column wins-column-mobile'>W</th><th class='losses-column losses-column-desktop'>Loss</th><th class='losses-column losses-column-mobile'>L</th><th class='draw-column draw-column-desktop'>Draw</th><th class='draw-column draw-column-mobile'>D</th>";

        standingsHeader += "<th class='byes-column byes-column-desktop'>Byes</th>";
        standingsHeader += "<th class='byes-column byes-column-desktop'>Defaults</th>";

        standingsHeader += "<th class='bonus-column bonus-column-desktop'>Bonus</th><th class='bonus-column bonus-column-mobile'>B</th><th class='bonus-column bonus-column-desktop'>Penalty</th><th class='bonus-column bonus-column-mobile'>P</th>";
        standingsHeader += "<th class='bonus-column bonus-column-desktop'>Adjust</th><th class='bonus-column bonus-column-mobile'>+/-</th>";

        if (sportsground.cms.utils.isTrue(forAgainst)) {
            standingsHeader += "<th class='for-column for-column-desktop'>For</th><th class='for-column for-column-mobile'>PF</th>";
            standingsHeader += "<th class='against-column against-column-desktop'>Against</th> <th class='against-column against-column-mobile'>PA</th>";
            standingsHeader += "<th class='dif-column dif-column-desktop'>Diff</th> <th class='dif-column dif-column-mobile'>GD</th>";
        }

        standingsHeader += "<th class='total-column total-column-desktop'>Total</th> <th class='total-column total-column-mobile'>Pts</th></tr>";

        $($(compWidget).find('.fe-standings-list table')[0]).append(standingsHeader);

    }

    var emptyStandingsTable = true;

    for (var i = 0; i < data.length; i++) {
        var grade = data[i];

        if (grade.Sections.CompWidgetSection) {
            var sections = [];
            sections = sections.concat(grade.Sections.CompWidgetSection);

            grade.Sections = sections;
        }

        if (grade.Sections) {
            grade.Sections.sort(sortStandingsByOrder);
        }

        for (var g = 0; g < grade.Sections.length; g++) {

            var section = grade.Sections[g];

            $($(compWidget).find('.fe-standings-list table')[0]).append("<tr class='grade-header'><td colspan='20'>" + grade.Name + " (" + section.Name + ")</td></tr>");
            emptyStandingsTable = false;

            if (section.Standings.CompWidgetStanding) {
                var standings = [];
                standings = standings.concat(section.Standings.CompWidgetStanding);

                section.Standings = standings;
            }

            for (var s = 0; s < section.Standings.length; s++) {
                var oddEven = s % 2 == 0 ? 'fixture-row-even' : 'fixture-row-odd';

                var standing = section.Standings[s];


                var standingLine = "<tr class='" + oddEven + "'>";

                if (grade != undefined && sportsground.cms.utils.isTrue(grade.IsPlayoff)) {
                    standingLine += "<td class='text-vs-padding org-logos " + logoShowClass + "'><div class='home-logo  " + logoClass + "'><div class='org-logo'><img src='" + standing.OrgLogo + "' /></div></div></td>";
                    standingLine += "<td style='text-align:center;'>" + '' + standing.Rank + "</td>";

                    if (firstGrade != undefined && sportsground.cms.utils.isTrue(firstGrade.IsPlayoff) && standing.Played == 0 && standing.Byes == 0) {

                        standingLine += "<td class='full-name-comp team-column'></td>";
                        standingLine += "<td class='abbr-name-comp team-column'></td>";

                    }
                    else {

                        standingLine += "<td class='full-name-comp team-column'>" + standing.TeamNameAbbr + "</td>";
                        standingLine += "<td class='abbr-name-comp team-column'>" + standing.TeamNameAbbr + "</td>";

                    }

                }
                else {
                    standingLine += "<td class='text-vs-padding org-logos " + logoShowClass + "'><div class='home-logo  " + logoClass + "'><div class='org-logo'><img src='" + standing.OrgLogo + "' /></div></div></td>";
                    standingLine += "<td class='full-name-comp team-column'>" + standing.TeamNameAbbr + "</td>";
                    standingLine += "<td class='abbr-name-comp team-column'>" + standing.TeamNameAbbr + "</td>";
                    standingLine += "<td class='played-column'>" + standing.Played + "</td>";
                    standingLine += "<td class='wins-column'>" + standing.Wins + "</td>";
                    standingLine += "<td class='losses-column'>" + standing.Losses + "</td>";
                    standingLine += "<td class='draw-column'>" + standing.Draws + "</td>";
                    standingLine += "<td class='byes-column byes-column-desktop'>" + standing.Byes + "</td>";
                    standingLine += "<td class='byes-column byes-column-desktop'>" + standing.DefaultLosses + "</td>";
                    standingLine += "<td class='bonus-column'>" + standing.BonusPoints + "</td>";
                    standingLine += "<td class='bonus-column'>" + standing.PenaltyPoints + "</td>";
                    standingLine += "<td class='bonus-column'>" + (Number(standing.PositivePointsAdjustment) + Number(standing.NegativePointsAdjustment)) + "</td>";

                    if (sportsground.cms.utils.isTrue(forAgainst)) {
                        standingLine += "<td class='for-column'>" + standing.ForPoints + drawsModule.addAsteriskCarryOver(grade) + "</td>";
                        standingLine += "<td class='against-column'>" + standing.AgainstPoints + drawsModule.addAsteriskCarryOver(grade) + "</td>";
                        standingLine += "<td class='dif-column'>" + standing.Differential + drawsModule.addAsteriskCarryOver(grade) + "</td>";
                    }

                    standingLine += "<td class='total-column'>" + standing.Total + drawsModule.addAsteriskCarryOver(grade) + "</td>";

                }
                standingLine += "</tr>";

                if (grade != undefined && sportsground.cms.utils.isTrue(grade.IsPlayoff)) {

                } else {
                    if (standing.Notes) {
                        standingLine += "<tr class='" + oddEven + "'><td colspan='20' style='font-style:italic'>" + standing.Notes + "</td></tr>";
                    }
                }



                $($(compWidget).find('.fe-standings-list table')[0]).append(standingLine);


            }
        }
    }

    if (emptyStandingsTable) {

        var standingsDiv = $($(compWidget).find('.fe-standings-list')[0]);
        standingsDiv.html("<div class='no-fixtures'>No standings using the current filters.</div>");

    }

    if (!sportsground.cms.utils.isTrue(firstGrade.IsPlayoff)) {
        standingsDiv.append("<div class='carry-over-points-label'>* includes points carried over</div>");
    }

    drawsModule.setUpExportEvent();
    drawsModule.hideHiddenFields(compWidget, widgetId);

};

drawsModule.addAsteriskCarryOver = function (grade) {

    if (sportsground.cms.utils.isTrue(grade.CarryOverPoints)) {
        return "*";
    }
    else {
        return "";
    }
};

drawsModule.addSoftballDate = function (fixture, fixtureDate) {
    
    var softballTd = "<td class='fixture-date softball-live-score' data-id='" + fixture.Id
        + "' data-hometeamlogo='" + fixture.HomeOrganisationLogo
        + "' data-awayteamlogo='" + fixture.AwayOrganisationLogo
        + "' data-publishteamsheetonwidget='" + fixture.PublishTeamsheetOnWidget
        + "' data-hometeamname='" + fixture.HomeTeamName
        + "' data-awayteamname='" + fixture.AwayTeamName + "'>"
        + fixtureDate
        + "<span class='live-label'> LIVE </span> <span class='softball-circle'></span>"
        + "</td>";

    return softballTd;
};

drawsModule.addSoftballDateMobile = function (fixture, fixtureDate) {

    var sportId = $('.hdnSelectedSportId').val();

    if (SPORTS.Softball.value == sportId && sportsground.cms.utils.isTrue(fixture.InGame)) {
        var softball = "<div class='softball-live-score' data-id='" + fixture.Id
            + "' data-hometeamlogo='" + fixture.HomeOrganisationLogo
            + "' data-awayteamlogo='" + fixture.AwayOrganisationLogo
            + "' data-publishteamsheetonwidget='" + fixture.PublishTeamsheetOnWidget
            + "' data-hometeamname='" + fixture.HomeTeamName
            + "' data-awayteamname='" + fixture.AwayTeamName + "'>"
            + fixtureDate
            //+ "<span class='live-label'> LIVE </span> <span class='softball-circle'></span>"
            + "</div>";

        return softball;
    }
    else {
        return fixtureDate;
    }

   
};

drawsModule.renderFixtures = function(data, widgetId, compWidget, autoUpdate) {
    
    var compWidget = $("#widget_" + widgetId);
    var loader = $(compWidget).find('.sked-widget-loader');
    $(loader).hide();

    var gradeIds = [];
    var grades = [];

    if (skedLoadAttempts[widgetId]) {
        skedLoadAttempts[widgetId]++;
    }
    else {
        skedLoadAttempts[widgetId] = 1;
    }

    if (data.length == 0 && skedLoadAttempts[widgetId] < 2) {
        drawsModule.getFirstFixture(widgetId);
        return;
    }
    
    for (var i = 0; i < data.length; i++) {
        if ($.inArray(data[i].GradeId.toString() + data[i].SectionId.toString(), gradeIds) == -1) {
            gradeIds.push(data[i].GradeId.toString() + data[i].SectionId.toString());
            grades.push({ "GradeId": data[i].GradeId, "GradeName": data[i].GradeName, "Fixtures": [], "SectionId": data[i].SectionId, "SectionName": data[i].SectionName, "GradeSortOrder": data[i].GradeSortOrder, "SectionSortOrder": data[i].SectionSortOrder } );
        }

        var grade = jQuery.grep(grades, function(g) {
            return g.GradeId == data[i].GradeId && g.SectionId == data[i].SectionId;
        })[0];

        grade.Fixtures.push(data[i]);

    }

    var drawDiv = $($(compWidget).find('.fe-draws-list .fe-draws-list-table')[0]);
    drawDiv.html("<table></table>");

    var resultsDiv = $($(compWidget).find('.fe-results-list')[0]);
    resultsDiv.html("<div class='results-export'><span class='export-text'>Export</span> <i class='fa fa-file-pdf-o' aria-hidden='true'></i></div><table></table>");

    var venues = $(compWidget).find('.mobile-comp-widget').data("venues");

    //order the fixtures
    grades.sort(sortByOrder);    

    for (var i = 0; i < grades.length; i++) {
        $($(compWidget).find('.fe-draws-list table')[0]).append("<tr class='grade-header'><td colspan='20'>" + grades[i].GradeName + " (" + grades[i].SectionName +  ")</td></tr>");
        $($(compWidget).find('.fe-results-list table')[0]).append("<tr class='grade-header'><td colspan='20'>" + grades[i].GradeName + " (" + grades[i].SectionName +  ")</td></tr>");

        grades[i].Fixtures.sort(sortFixturesDate);

        for (var f = 0; f < grades[i].Fixtures.length; f++) {
            var oddEven = f % 2 == 0 ? 'fixture-row-even' : 'fixture-row-odd';

            var fixture = grades[i].Fixtures[f];
            var date = new Date(fixture.Date.replace("Z", "") + "Z");
            date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
            var timeAMPM = drawsModule.formatAMPM(date, fixture.HomeTeamName, fixture.AwayTeamName);
            var fixtureDate = date.getDate() + "/" + (date.getMonth() + 1).toString() + "/" + date.getFullYear() + " " + timeAMPM;
            var fixtureDateCompressed = timeAMPM + (timeAMPM ? " | " : "") + date.getDate() + "/" + (date.getMonth() + 1).toString() + "/" + date.getFullYear().toString().substr(-2);
            var homeLogo = '';
            var awayLogo = '';
            var logoClass = 'text-vs-padding';

            if (sportsground.cms.utils.isTrue(fixture.IsSuperForm)) {
                homeLogo = "<div class='home-logo'><div class='org-logo'><img "
                    + (fixture.HomeOrganisationLogo == "" || fixture.HomeTeamName.toLowerCase() == "bye" ? "" : "src='" + fixture.HomeOrganisationLogo + "'")
                    + "></div></div>";
                awayLogo = "<div class='away-logo'><div class='org-logo'><img "
                    + (fixture.AwayOrganisationLogo == "" || fixture.AwayTeamName.toLowerCase() == "bye" ? "" : "src='" + fixture.AwayOrganisationLogo + "'")
                    + "></div></div>";
                logoClass += ' org-logos';
            }

            var isLargeLogo = $(compWidget).find('.mobile-comp-widget').data("islargelogo");
            var logos = $(compWidget).find('.mobile-comp-widget').data("logos");

            var logoSizeWrapperClass = isLargeLogo == 'True' && logos == 'True' ? ' large-logo-wrapper' : '';

            var sportId = $('.hdnSelectedSportId').val();
            var drawsRow = "<tr class='" + oddEven + logoSizeWrapperClass + " '>";

            if (SPORTS.Softball.value == sportId && sportsground.cms.utils.isTrue(fixture.InGame)) {
                drawsRow += drawsModule.addSoftballDate(fixture, fixtureDate);
            }
            else {
                drawsRow += "<td class='fixture-date' data-id='" + fixture.Id + "' >" + fixtureDate + "</td>";
            }

            drawsRow += "<td class='full-name-comp home-team'>" + drawsModule.getGameDayTeamListLink(fixture.HomeTeamName, fixture.PublishTeamsheetOnWidget, fixture.Id, true) + "</td>"
                + "<td class='abbr-name-comp home-team'>" + drawsModule.getGameDayTeamListLink(fixture.HomeTeamNameAbbr, fixture.PublishTeamsheetOnWidget, fixture.Id, true) + "</td>"
                + "<td class='fe-vs'><div class='fe-vs-inner'><div class='fixture-date-mobile'>" + drawsModule.addSoftballDateMobile(fixture, fixtureDateCompressed) + "</div><div class='" + logoClass + "'>" + homeLogo + awayLogo
                + "<div class='text-vs-align'>vs</div>" + "</div>" + "</div></td>"
                + "<td class='full-name-comp away-team'>" + drawsModule.getGameDayTeamListLink(fixture.AwayTeamName, fixture.PublishTeamsheetOnWidget, fixture.Id, false) + "</td>"
                + "<td class='abbr-name-comp away-team'>" + drawsModule.getGameDayTeamListLink(fixture.AwayTeamNameAbbr, fixture.PublishTeamsheetOnWidget, fixture.Id, false) + "</td>";

            drawsRow = drawsRow + drawsModule.generateStatusHtml(false, fixture, venues);

            $($(compWidget).find('.fe-draws-list table')[0]).append(drawsRow);

            if (venues) {
                var mobileVenueRow = "<tr class='" + oddEven + " abbr-name-venue draw-default-fixture-confirmed'><td colspan='3'>" + drawsModule.generateStatusHtml(true, fixture, venues) + "</td></tr>";
                $($(compWidget).find('.fe-draws-list table')[0]).append(mobileVenueRow);
            }

            var additionalInfoClass = (fixture.FixtureOfficials && fixture.PublicNotes) ? 'additional-info-2 ' : 'additional-info-1 ';
            if (fixture.FixtureOfficials) {
                $($(compWidget).find('.fe-draws-list table')[0]).append("<tr class='" + oddEven + "'><td class='" + additionalInfoClass + "comp-widget-fixtureofficials' colspan='20'>" + fixture.FixtureOfficials + "</td></tr>");
            }

            if (fixture.PublicNotes) {
                $($(compWidget).find('.fe-draws-list table')[0]).append("<tr class='" + oddEven + "'><td class='" + additionalInfoClass + "comp-widget-publicnotes' colspan='20'>" + fixture.PublicNotes + "</td></tr>");
            }

            if (sportsground.cms.utils.isTrue(fixture.PublishResults)) {

                var homeScoreClass = "agree-score";
                var awayScoreClass = "agree-score";

                if (sportsground.cms.utils.isTrue(fixture.InGame)) {
                    homeScoreClass = "in-game-score";
                    awayScoreClass = "in-game-score";
                }
                else if (fixture.ResultStatus == 1) {
                    homeScoreClass = "dispute-score";
                    awayScoreClass = "dispute-score";
                }
                else if (fixture.ResultStatus == 2) {
                    homeScoreClass = "dispute-score";
                    awayScoreClass = "dispute-score";
                }
                else if (fixture.ResultStatus == 3) {
                    homeScoreClass = "dispute-score";
                    awayScoreClass = "dispute-score";
                }

                var resultsRow = "<tr class='" + oddEven + logoSizeWrapperClass + "' id='fixturerow-" + fixture.Id + "'>";
                if (SPORTS.Softball.value == sportId && sportsground.cms.utils.isTrue(fixture.InGame)) {
                    resultsRow += drawsModule.addSoftballDate(fixture, fixtureDate);
                }
                else {
                    resultsRow += "<td class='fixture-date' data-id='" + fixture.Id + "' >" + fixtureDate + "</td>";
                }
                resultsRow  += "<td class='full-name-comp home-team'>" + fixture.HomeTeamName + "</td>"
                    + "<td class='abbr-name-comp home-team'>" + fixture.HomeTeamNameAbbr + "</td>";

                var defaultCss = "default-" + fixture.CssName;
                var statusCss = "status-" + fixture.CssName;

                resultsRow += "<td class='fe-vs result-" + defaultCss + "'><div class='fe-vs-inner'>"
                    + "<div class='fixture-date-mobile'>" + drawsModule.addSoftballDateMobile(fixture, fixtureDateCompressed) + "</div>"
                    + "<div class='" + logoClass + "'>" + homeLogo + awayLogo
                    + "<div class='text-vs-align'><span class='homescore " + homeScoreClass + "'>" + fixture.HomeScore + "</span> vs <span class='awayscore " + awayScoreClass + "'>" + fixture.AwayScore + "</span></div>"
                    + "</div></div></td>";
                resultsRow += "<td class='fe-vs result-" + statusCss + "'><div class='fe-vs-inner'>"
                    + "<div class='fixture-date-mobile'>" + drawsModule.addSoftballDateMobile(fixture, fixtureDateCompressed) + "</div>"
                    + "<div class='" + logoClass + "'>" + homeLogo + awayLogo
                    + "<div class='text-vs-align'>" + fixture.StatusName + "</div>"
                    + "</div></div></td>";

                resultsRow += "<td class='full-name-comp away-team'>" + fixture.AwayTeamName + "</td>"
                    + "<td class='abbr-name-comp away-team'>" + fixture.AwayTeamNameAbbr + "</td></tr>";
                $($(compWidget).find('.fe-results-list table')[0]).append(resultsRow);

                if (fixture.PublicNotes) {
                    $($(compWidget).find('.fe-results-list table')[0]).append("<tr class='" + oddEven + "'><td class='comp-widget-publicnotes' colspan='20'>" + fixture.PublicNotes + "</td></tr>");
                }
            }
            
            $(compWidget).find('.round-number').html(fixture.RoundName);
            $(compWidget).find('.round-id').html(Number(fixture.Round));

        }
    }

    if (data.length == 0) {
        drawDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
        resultsDiv.html("<div class='no-fixtures'>No fixtures using the current filters.</div>");
    }
    else if (PREVIOUS_DATA[widgetId] && autoUpdate) {
        //flash with data updates

        for (var i = 0; i < PREVIOUS_DATA[widgetId].length; i++) {
            var previousFixture = PREVIOUS_DATA[widgetId][i];
            var newRow = $("#fixturerow-" + previousFixture.Id);

            var newHomeScore = $((newRow).find('.homescore')[0]).html();
            var newAwayScore = $((newRow).find('.awayscore')[0]).html();

            if (newHomeScore != previousFixture.HomeScore || newAwayScore != previousFixture.AwayScore) {

                $(newRow).css('background-color', '#00B900')
                $(newRow).animate({ backgroundColor: "rgb(0,0,0,0)" }, 2000);

            }

        }

    }

    drawsModule.setUpExportEvent();
    PREVIOUS_DATA[widgetId] = data;
    drawsModule.hideHiddenFields(compWidget, widgetId);

}

drawsModule.hideHiddenFields = function (compWidget, widgetId) {

    //for/against/dif
    var forAgainst = $(compWidget).find('.mobile-comp-widget').data("foragainst");

    //team name
    var teamNames = $(compWidget).find('.mobile-comp-widget').data("teamnames"); 
    if (!sportsground.cms.utils.isTrue(teamNames)) {

        // hide hidden fields
        $("#widget_" + widgetId + ' .team-column').hide();
        $("#widget_" + widgetId + ' .home-team').hide();
        $("#widget_" + widgetId + ' .away-team').hide();

        $("#widget_" + widgetId + ".wCompetition .fe-draws-list .fe-vs").css("width", "60%");


    }
    else {
        $("#widget_" + widgetId + ' .for-column').addClass('hideFAD');
        $("#widget_" + widgetId + ' .against-column').addClass('hideFAD');
        $("#widget_" + widgetId + ' .dif-column').addClass('hideFAD');
    }

    //date
    var time = $(compWidget).find('.mobile-comp-widget').data("time");
    if (!sportsground.cms.utils.isTrue(time)) {

        // hide hidden fields
        $("#widget_" + widgetId + ' .fixture-date').hide();

    }

    //venues
    var venues = $(compWidget).find('.mobile-comp-widget').data("venues");
    if (!sportsground.cms.utils.isTrue(venues)) {

        // hide hidden fields
        $("#widget_" + widgetId + ' .full-name-venue').hide();
        $("#widget_" + widgetId + ' .abbr-name-venue').hide();

    }

    
    var logos = $(compWidget).find('.mobile-comp-widget').data("logos");

    if (!sportsground.cms.utils.isTrue(logos)) {
        $("#widget_" + widgetId + ' .home-logo').hide();
        $("#widget_" + widgetId + ' .away-logo').hide();
    }
    

    var isLargeLogo = $(compWidget).find('.mobile-comp-widget').data("islargelogo");

    if (sportsground.cms.utils.isTrue(isLargeLogo)) {
        $("#widget_" + widgetId + ' .org-logo').addClass('large-logo');
    }
    
    

}

drawsModule.generateStatusHtml = function (isMobileHtml, fixture, showVenue) {

    if (showVenue != 'True') {
        return '';
    }

    var htmlContainer = '';
    if (isMobileHtml) {
        // statuses are generated in divs for desktop
        htmlContainer = 'div';
    }
    else {
        // statuses are generated in columns for desktop
        htmlContainer = 'td';
    }

    var html = '';

    // check if the lat and lng has value besides zero, if zero, just use the venue address
    var place = (fixture.LocationLat != 0 && fixture.LocationLng != 0) ? fixture.LocationLat + ',' + fixture.LocationLng : fixture.VenueAddress;

    // Create maps google link
    var venueAddressLink = "http://maps.google.com/?q=" + place;
    var defaultCss = "default-" + fixture.CssName;
    var statusCss = "status-" + fixture.CssName;

    if (!sportsground.cms.utils.isTrue(fixture.PublishVenue)) {
        if (isMobileHtml)
            html = "<" + htmlContainer + " class='abbr-name-venue draw-" + defaultCss + "'></" + htmlContainer + ">";
        else
            html = "<" + htmlContainer + " class='full-name-venue draw-" + defaultCss + "'></" + htmlContainer + ">";
    }
    else if (isMobileHtml) {
        if (fixture.VenueAddress) {
            html = "<" + htmlContainer + " class='abbr-name-venue draw-" + defaultCss + "'><a href='" + venueAddressLink + "'  target='_blank'>" + fixture.VenueName + "</a></" + htmlContainer + ">";
        }
        else {
            html = "<" + htmlContainer + " class='abbr-name-venue draw-" + defaultCss + "'>" + fixture.VenueName + "</" + htmlContainer + ">";
        }
        html += "<" + htmlContainer + " class='abbr-name-comp draw-" + statusCss + "'>" + fixture.StatusName + "</" + htmlContainer + ">";

    }
    else {
        if (fixture.VenueAddress) {
            html = "<" + htmlContainer + " class='full-name-venue draw-" + defaultCss + "'><a href='" + venueAddressLink + "' target='_blank'>" + fixture.VenueName + "</a></" + htmlContainer + ">";

        }
        else {
            html = "<" + htmlContainer + " class='full-name-venue draw-" + defaultCss + "'>" + fixture.VenueName + "</" + htmlContainer + ">";
        }
        html += "<" + htmlContainer + " class='full-status-name draw-" + statusCss + "'>" + fixture.StatusName + "</" + htmlContainer + ">";
    }

    return html;
};

drawsModule.getGameDayTeamListLink = function (teamName, publishTeamsheetOnWidget, fixtureId, isHome) {
    if (sportsground.cms.utils.isTrue(publishTeamsheetOnWidget)) {
        return '<a class="btn btn-link gameday-teamlist" data-id="' + fixtureId + '" data-is-home="' + isHome + '">' + teamName + '</a>';
    }
    else {
        return teamName;
    }
};

/*
    This method compare and gets the smaller of the two Ids.
*/
drawsModule.getCompareSmallerIds = function(selectedItems, unSelectedItems) {
    var listOfIds = [];
    if (selectedItems.length <= unSelectedItems.length) {
        $.each(selectedItems, function(index, item) {
            listOfIds.push(item.value);
        });
    }
    else {
        $.each(unSelectedItems, function(index, item) {
            listOfIds.push(item.value);
        });
    }
    return listOfIds;
}

drawsModule.exportDraw = function(widgetId, groupBy) {

    var compWidget = $("#widget_" + widgetId);

    var compDropdown = $(compWidget).find('select.fe-comp-comps');
    var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

    var orgSelectedItems = orgsDropdown.sportsgroundMobiscroll().selectGetOptionsSelected();
    var orgUnSelectedItems = orgsDropdown.sportsgroundMobiscroll().selectGetOptionsNotSelected();
    var orgIds = drawsModule.getCompareSmallerIds(orgSelectedItems, orgUnSelectedItems);

    var gradeSelectedItems = gradesDropdown.sportsgroundMobiscroll().selectGetOptionsSelected();
    var gradeUnSelectedItems = gradesDropdown.sportsgroundMobiscroll().selectGetOptionsNotSelected();
    var gradeIds = drawsModule.getCompareSmallerIds(gradeSelectedItems, gradeUnSelectedItems);

    var compId = compDropdown.val();
    var from = $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().getDate().toDateOnlyLocalISOString();
    var to = $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().getDate().toDateOnlyLocalISOString();

    var inclResults = false;
    var inclOfficials = true;

    var isCustomUrl = $('#isCustomDomain').val();
    var exportUrl = "/Competition/ExportFixturesWidget";

    if (isCustomUrl != "False") {
        exportUrl = "https://www.sporty.co.nz" + exportUrl;
    }

    window.open(exportUrl +
        "?id=" + compId +
        "&wId=" + widgetId +
        "&from=" + from +
        "&to=" + to +
        "&groupBy=" + groupBy +
        "&inclResults=" + inclResults +
        "&inclOfficials=" + inclOfficials +
        "&inclGIds=" + (gradeSelectedItems.length <= gradeUnSelectedItems.length) +
        "&gIds=" + gradeIds.map(Number) +
        "&inclOIds=" + (orgSelectedItems.length <= orgUnSelectedItems.length) +
        "&oIds=" + orgIds.map(Number)
        , '_blank');

}

drawsModule.exportResults = function(widgetId) {

    var compWidget = $("#widget_" + widgetId);

    var compDropdown = $(compWidget).find('select.fe-comp-comps');
    var orgsDropdown = $(compWidget).find('select.fe-comp-orgs');
    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

    var orgSelectedItems = orgsDropdown.sportsgroundMobiscroll().selectGetOptionsSelected();
    var orgUnSelectedItems = orgsDropdown.sportsgroundMobiscroll().selectGetOptionsNotSelected();
    var orgIds = drawsModule.getCompareSmallerIds(orgSelectedItems, orgUnSelectedItems);

    var gradeSelectedItems = gradesDropdown.sportsgroundMobiscroll().selectGetOptionsSelected();
    var gradeUnSelectedItems = gradesDropdown.sportsgroundMobiscroll().selectGetOptionsNotSelected();
    var gradeIds = drawsModule.getCompareSmallerIds(gradeSelectedItems, gradeUnSelectedItems);

    var compId = compDropdown.val();
    var from = $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().getDate().toDateOnlyLocalISOString();
    var to = $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().getDate().toDateOnlyLocalISOString();

    var groupBy = "time";
    var inclResults = true;
    var inclOfficials = false;

    var isCustomUrl = $('#isCustomDomain').val();
    var exportUrl = "/Competition/ExportFixturesWidget";

    if (isCustomUrl != "False") {
        exportUrl = "https://www.sporty.co.nz" + exportUrl;
    }

    window.open(exportUrl +
        "?id=" + compId +
        "&wId=" + widgetId +
        "&from=" + from +
        "&to=" + to +
        "&groupBy=" + groupBy +
        "&inclResults=" + inclResults +
        "&inclOfficials=" + inclOfficials +
        "&inclGIds=" + (gradeSelectedItems.length <= gradeUnSelectedItems.length) +
        "&gIds=" + gradeIds.map(Number) +
        "&inclOIds=" + (orgSelectedItems.length <= orgUnSelectedItems.length) +
        "&oIds=" + orgIds.map(Number)
        , '_blank');

}

drawsModule.exportStandings = function(widgetId) {

    var compWidget = $("#widget_" + widgetId)[0];

    var compDropdown = $(compWidget).find('select.fe-comp-comps');
    var phaseDropdown = $(compWidget).find('select.fe-comp-phases');
    var gradesDropdown = $(compWidget).find('select.fe-comp-grades');

    var compId = compDropdown.val();
    var compText = compDropdown.find("option:selected").text();
    var phaseId = phaseDropdown.val();
    var gradeIds = gradesDropdown.sportsgroundMobiscroll().selectGetVal();

    var isCustomUrl = $('#isCustomDomain').val();
    var exportUrl = "/Competition/ExportStandings";

    if (isCustomUrl != "False") {
        exportUrl = "https://www.sporty.co.nz" + exportUrl;
    }

    window.open(exportUrl +
        "?competitionId=" + compId +
        "&competitionName=" + escape(compText) +
        "&phaseId=" + phaseId +
        "&gradeIds=" + gradeIds +
        "&standingsType=" + 'standings' +
        "&includeManualAdjustment=" + false +
        "&includePublicNotes=" + true +
        "&isWidget=" + true 
        , '_blank');

}

drawsModule.formatAMPM = function(date, homeTeamName, awayTeamName) {

    awayTeamName = awayTeamName ? awayTeamName.toLowerCase() : "";
    homeTeamName = homeTeamName ? homeTeamName.toLowerCase() : "";

    if (homeTeamName == "bye" || awayTeamName == "bye") {
        return "";
    }

    return date.toTimeFormatAMPM();
}

drawsModule.clearSavedHidden = function() {
    $("#hdnSelectedCompIds").val("");
    $("#hdnSelectedPhaseIds").val("");
    $("#hdnSelectedOrgIds").val("");
    $("#hdnSelectedGradeIds").val("");
    $("#hdnSelectedTeamIds").val("");
    $("#hdnSelectedDraws").val("");
    $("#hdnSelectedResults").val("");
    $("#hdnSelectedStandings").val("");
}

//admin edit modal create
drawsModule.modalCreated = function(widgetInstanceId) {
    $(".widget-settings-update").attr('disabled', 'disabled');
    drawsModule.checkDisplayBoxes();

    drawsModule.setupStyle();

    $.get(compWidgetBaseUrl + 'Sports')
        .done(function(data) {
            for (var index = 0; index < data.length; index++) {
                $('#comp-sports').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
            }

            var selectedSportId = $("#comp-sports").data("sportid") == "" ? 0 : $("#comp-sports").data("sportid");

            $("#comp-sports").val(selectedSportId);

            $.get(compWidgetBaseUrl + 'Seasons')
                .done(function(data) {
                    for (var index = 0; index < data.length; index++) {
                        $('#comp-seasons').append('<option value="' + data[index].Id + '">' + data[index].Name + '</option>');
                    }

                    var selectedSeasonId = $("#comp-seasons").data("seasonid") == "" ? 0 : $("#comp-seasons").data("seasonid");

                    $("#comp-seasons").val(selectedSeasonId);
                    drawsModule.getOwners();

                });

        });


    $('#comp-sports').change(function (e) {
        $(".widget-settings-update").attr('disabled', 'disabled');
        drawsModule.clearSavedHidden();
        drawsModule.getOwners();
    });


    $('#comp-seasons').change(function (e) {
        $(".widget-settings-update").attr('disabled', 'disabled');
        drawsModule.clearSavedHidden();
        drawsModule.getOwners();
    });

    $("#setSortOrder").unbind('click');
    $("#setSortOrder").click(function (e) {

        drawsModule.openSortOrderModal();

    });

    $("#sortDone").unbind('click');
    $("#sortDone").click(function (e) {

        drawsModule.setSortOrder();

    });

};

drawsModule.handlers = {
    init: function() {
    }
}



drawsModule.openSortOrderModal = function () {

    $('#sortOrderModal').modal('toggle');

    //display selected competitions
    $('#sortableComps').html('');

    var savedSortOrder = $('#hdnCompetitionIdsSortOrder').val();

    if (savedSortOrder) {
        savedSortOrder = savedSortOrder.split(',');
    }

    $("#comp-admin-comps option:selected").each(function () {
        var $this = $(this);

        if ($this.length) {
            var selText = $this.text();
            var selId = $this.val();
            var sortOrder = savedSortOrder.indexOf(selId);

            $('#sortableComps').append('<li data-sortorder="' + sortOrder + '" data-id="' + selId + '"><button type="button" class="btn btn-sm btn-info btn-block drag"><i class="icon-move"></i></button>' + selText + '</li>');
        }
    });


    $("#sortableComps").sortable({
        cancel: 'input',
        cursor: 'move',
        handle: '.drag'
    });

    $("#sortableComps").disableSelection();

    //sort based on saved sort order
    var liList = $("#sortableComps li");
    liList.sort(function (a, b) {
        return $(a).attr("data-sortorder") - $(b).attr("data-sortorder");
    });
    $("#sortableComps").html(liList);

};

drawsModule.setSortOrder = function () {

    //set the sortOrder    
    var sortedIds = "";
    $('#sortableComps li').each(function () {
        var $this = $(this);

        var id = $($this).attr('data-id');

        sortedIds += id + ',';
    });

    $('#hdnCompetitionIdsSortOrder').val(sortedIds);
    $('#sortOrderModal').modal('toggle');

};

drawsModule.commitChanges = function (widgetInstanceId) {

    drawsModule.clearSkedCache(widgetInstanceId);

    //wipe cached
    skedLoadAttempts = {};
    globalSkedWidgetSelectedDates = [];
    blockSkedDateUpdate = {};
    PREVIOUS_DATA = {};
    drawsModule.skedFilterSettings = {};

    //serialize comp widget settings
    var ownerIds = $('#comp-admin-owner').val();
    var sportId = cometDrawsModule.getSelectedSportId();
    var seasonId = cometDrawsModule.getSelectedSeasonId();
    var competitionIds = $('#comp-admin-comps').val().join(",");
    var competitionIdsSortOrder = $('#hdnCompetitionIdsSortOrder').val();
    var orgIds = $('#comp-admin-orgs').val().join(",");
    var gradeIds = $('#comp-admin-grades').val().join(",");
    var draws = $("#display-draw").is(":checked");
    var results = $("#display-results").is(":checked");
    var standings = $("#display-standings").is(":checked");
    var hideGradeFilter = $("#hide-grade-filter").is(":checked");
    var hideCompFilter = $("#hide-comp-filter").is(":checked");
    var hideOrgFilter = $("#hide-org-filter").is(":checked");
    var hideDateFilter = $("#hide-date-filter").is(":checked");

    var title = $("#display-title").is(":checked");
    var rounds = $("#display-rounds").is(":checked");
    var logos = $("#display-logos").is(":checked");
    var time = $("#display-time").is(":checked");
    var team = $("#display-team").is(":checked");
    var venues = $("#display-venues").is(":checked");
    var forAgainstDiff = $("#display-foragainstdiff").is(":checked");

    var isCustomHeight = $('input[name=display-height]:checked').val() != "full";
    var customHeight = $("#comet-custom-height").val();
    customHeight = customHeight == "" ? 0 : customHeight;
    var isLargeLogo = $('input[name=display-logo-size]:checked').val() == "large";

    //style
    var titleBGColour = $('#TitleBGColour').val();
    var titleTextColour = $('#TitleTextColour').val();
    var cometFontSelect = $('#CometFontSelectHidden').val();
    var widgetTextColour = $('#WidgetTextColour').val();
    var widgetBackgroundColour = $('#WidgetBackgroundColour').val();
    var transparency = $('#cometTransparencySliderInput').val().replace('%', '');
    try {
        transparency = transparency / 100;
    }
    catch (e) {

    }

    var widgetSettings = {
        WidgetId: widgetInstanceId,
        WidgetType: 'Competition',
        Settings: {
            OwnerIds: ownerIds,
            SportId: sportId,
            SeasonId: seasonId,
            CompetitionIds: competitionIds,
            CompetitionIdsSortOrder: competitionIdsSortOrder,
            OrgIds: orgIds,
            PhaseIds: [],
            GradeIds: gradeIds,
            Draws: draws,
            Results: results,
            Standings: standings,
            HideGradeFilter: hideGradeFilter,
            HideCompFilter: hideCompFilter,
            HideOrgFilter: hideOrgFilter,
            HideDateFilter: hideDateFilter,
            Title: title,
            Rounds: rounds,
            Logos: logos,
            Time: time,
            Team: team,
            Venues: venues,
            ForAgainstDiff: forAgainstDiff,
            CustomHeight: customHeight,
            IsCustomHeight: isCustomHeight,
            IsLargeLogo: isLargeLogo,
            TitleBGColour: titleBGColour,
            TitleTextColour: titleTextColour,
            Font: cometFontSelect,
            WidgetTextColour: widgetTextColour,
            WidgetBackgroundColour: widgetBackgroundColour,
            Transparency: transparency

        }
    };
    
    $.ajax({
        url: '/cms/widgets/settings',
        type: 'PUT',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(widgetSettings),
        success: function(data, textStatus, xhr) {
            if (xhr.status === 202)
                $("#modal-dialog").modal('show');

            drawsModule.rebuildWidget(widgetInstanceId);

        }
    });

    $("#myModal").modal('hide');
};

/*
    handles the initialization of date time picker
*/
drawsModule.initializeDateRangeSettings = function(widgetInstanceId) {
    var compWidget = $('#widget_' + widgetInstanceId + '.wCompetition');
       
    var firstDate = new Date();
    var firstDate2 = new Date(firstDate.getFullYear(), firstDate.getMonth(), firstDate.getDate());
    firstFixtureDate[widgetInstanceId] = firstDate2;

    var weekAfter = new Date(firstDate2.getTime());;
    weekAfter.setDate(weekAfter.getDate() + 6);
    weekAfterFirstDate[widgetInstanceId] = weekAfter;

    var weekBefore = new Date(firstDate2.getTime());;
    weekBefore.setDate(weekBefore.getDate() - 6);
    weekBeforeFirstDate[widgetInstanceId] = weekBefore;

     //create from and to datepickers
    blockSkedDateUpdate[widgetInstanceId] = true;
    $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().datePicker(firstDate2, compWidget, 'competition', drawsModule.saveSelectedDates);
    $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().datePicker(weekAfter, compWidget, 'competition', drawsModule.saveSelectedDates);
    blockSkedDateUpdate[widgetInstanceId] = false;
}

/*
    handles setting of user defined date range,
    or setting default date range based on which tab is selected.
*/
drawsModule.getDateRangeSettings = function(widgetInstanceId, selectedTab) {
    var compWidget = $('#widget_' + widgetInstanceId + '.wCompetition');

    var hasChangedDate = false;
    $.each(globalSkedWidgetSelectedDates, function(i) {
        if (globalSkedWidgetSelectedDates[i].WidgetId === widgetInstanceId) {
            hasChangedDate = true;
            return false;
        }
    });

    if (!hasChangedDate) {

        if (selectedTab == 'drawTab') {

            $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(firstFixtureDate[widgetInstanceId]);
            $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(weekAfterFirstDate[widgetInstanceId]);
        }
        else if (selectedTab == 'resultTab') {
        
            if (weekBeforeFirstDate[widgetInstanceId] !== undefined)
                $(compWidget).find('input.comp-widget-from').sportsgroundMobiscroll().setDate(weekBeforeFirstDate[widgetInstanceId]);

            if (firstFixtureDate[widgetInstanceId] !== undefined)
                $(compWidget).find('input.comp-widget-to').sportsgroundMobiscroll().setDate(firstFixtureDate[widgetInstanceId]);
        }
    }
}

/*
    handles saving of user defined date range on global javascript variable.
*/
drawsModule.saveSelectedDates = function(widget) {
    var widgetId = $(widget).data('id');

    $.each(globalSkedWidgetSelectedDates, function(i) {
        if (globalSkedWidgetSelectedDates[i].WidgetId === widgetId) {
            globalSkedWidgetSelectedDates.splice(i, 1);
            return false;
        }
    });

    globalSkedWidgetSelectedDates.push({
        WidgetId: widgetId
    });
};

drawsModule.rebuildWidget = function(widgetInstanceId) {
    $.ajax({
        url: '/cms/widgets/' + widgetInstanceId + '?em=1',
        type: 'GET',
        success: function(html, textStatus, xhr) {
            var container = $('#widget_' + widgetInstanceId);
            container.replaceWith(html);
            drawsModule.create(widgetInstanceId);
        }
    });
};

$(document).ready(function() {
    // Define an event handler for the window's `focus` event.
    $(window).on('focus', function() {
        windowHasFocus = true;
    });
    // Define an event handler for the window's `blur` event.
    $(window).on('blur', function() {
        windowHasFocus = false;
    });
});
;
