
"use strict";var slick=function(){if("function"==typeof $.fn.slick){var t=function(t,e){var a=t.find(".stage__caption");"hide"===e?a.fadeTo(1e3,0):a.fadeTo(1e3,1)},e=$(".stage__slick");e.length>0&&$.each(e,function(e,a){var n=$(a),s=n.attr("data-stage-mode");if("two-stage"!==s)if(n.find(".stage__spot--jobs").length>0)n.find(".job-filter").show();else{var i=window[n.attr("data-stage-id")];$.extend(i,{dotsClass:"stage__dots",prevArrow:'<button type="button" class="stage__prev"/>',nextArrow:'<button type="button" class="stage__next"/>'}),n.on({init:function(e,a){var n=$('<div class="stage__control-nav"/>');n.append(a.$prevArrow).append(a.$dots).append(a.$nextArrow),a.$slider.append(n),a.slideCount>1&&"default"===s&&n.show();var i=$(a.$slides[a.currentSlide]);setTimeout(function(){t(i)},1e3)},beforeChange:function(e,a,n){t($(a.$slides[a.currentSlide]),"hide")},afterChange:function(e,a){t($(a.$slides[a.currentSlide]))}}).slick(i)}})}},parallax=function(){"function"==typeof $.fn.parallax&&$(".parallax").parallax()};$(function(){slick(),parallax()});
!function(e){"use strict";var t={i18n:{ru:{months:["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],dayOfWeek:["Вск","Пн","Вт","Ср","Чт","Пт","Сб"]},en:{months:["January","February","March","April","May","June","July","August","September","October","November","December"],dayOfWeek:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},de:{months:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],dayOfWeek:["So","Mo","Di","Mi","Do","Fr","Sa"]},nl:{months:["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"],dayOfWeek:["zo","ma","di","wo","do","vr","za"]},tr:{months:["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"],dayOfWeek:["Paz","Pts","Sal","Çar","Per","Cum","Cts"]},fr:{months:["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"],dayOfWeek:["Dim","Lun","Mar","Mer","Jeu","Ven","Sam"]},es:{months:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],dayOfWeek:["Dom","Lun","Mar","Mié","Jue","Vie","Sáb"]},th:{months:["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"],dayOfWeek:["อา.","จ.","อ.","พ.","พฤ.","ศ.","ส."]},pl:{months:["styczeń","luty","marzec","kwiecień","maj","czerwiec","lipiec","sierpień","wrzesień","październik","listopad","grudzień"],dayOfWeek:["nd","pn","wt","śr","cz","pt","sb"]},pt:{months:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],dayOfWeek:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"]},ch:{months:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],dayOfWeek:["日","一","二","三","四","五","六"]},se:{months:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],dayOfWeek:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"]},kr:{months:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],dayOfWeek:["일","월","화","수","목","금","토"]},it:{months:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],dayOfWeek:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"]},da:{months:["January","Februar","Marts","April","Maj","Juni","July","August","September","Oktober","November","December"],dayOfWeek:["Søn","Man","Tir","ons","Tor","Fre","lør"]},ja:{months:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayOfWeek:["日","月","火","水","木","金","土"]},vi:{months:["Tháng 1","Tháng 2","Tháng 3","Tháng 4","Tháng 5","Tháng 6","Tháng 7","Tháng 8","Tháng 9","Tháng 10","Tháng 11","Tháng 12"],dayOfWeek:["CN","T2","T3","T4","T5","T6","T7"]}},value:"",lang:"en",format:"Y/m/d H:i",formatTime:"H:i",formatDate:"Y/m/d",startDate:!1,step:60,closeOnDateSelect:!1,closeOnWithoutClick:!0,timepicker:!0,datepicker:!0,minDate:!1,maxDate:!1,minTime:!1,maxTime:!1,allowTimes:[],opened:!1,initTime:!0,inline:!1,onSelectDate:function(){},onSelectTime:function(){},onChangeMonth:function(){},onChangeDateTime:function(){},onShow:function(){},onClose:function(){},onGenerate:function(){},withoutCopyright:!0,inverseButton:!1,hours12:!1,next:"xdsoft_next",prev:"xdsoft_prev",dayOfWeekStart:0,timeHeightInTimePicker:25,timepickerScrollbar:!0,todayButton:!0,defaultSelect:!0,scrollMonth:!0,scrollTime:!0,scrollInput:!0,lazyInit:!1,mask:!1,validateOnBlur:!0,allowBlank:!0,yearStart:1950,yearEnd:2050,style:"",id:"",roundTime:"round",className:"",weekends:[],yearOffset:0};Array.prototype.indexOf||(Array.prototype.indexOf=function(e,t){for(var n=t||0,a=this.length;n<a;n++)if(this[n]===e)return n;return-1}),e.fn.xdsoftScroller=function(t){return this.each(function(){var n=e(this);if(!e(this).hasClass("xdsoft_scroller_box")){var a=function(e){var t={x:0,y:0};if("touchstart"==e.type||"touchmove"==e.type||"touchend"==e.type||"touchcancel"==e.type){var n=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0];t.x=n.pageX,t.y=n.pageY}else"mousedown"!=e.type&&"mouseup"!=e.type&&"mousemove"!=e.type&&"mouseover"!=e.type&&"mouseout"!=e.type&&"mouseenter"!=e.type&&"mouseleave"!=e.type||(t.x=e.pageX,t.y=e.pageY);return t},r=0,o=n.children().eq(0),s=n[0].clientHeight,i=o[0].offsetHeight,d=e('<div class="xdsoft_scrollbar"></div>'),u=e('<div class="xdsoft_scroller"></div>'),c=100,l=!1;d.append(u),n.addClass("xdsoft_scroller_box").append(d),u.on("mousedown.xdsoft_scroller",function(a){s||n.trigger("resize_scroll.xdsoft_scroller",[t]);var o=a.pageY,i=parseInt(u.css("margin-top")),l=d[0].offsetHeight;e(document.body).addClass("xdsoft_noselect"),e([document.body,window]).on("mouseup.xdsoft_scroller",function f(){e([document.body,window]).off("mouseup.xdsoft_scroller",f).off("mousemove.xdsoft_scroller",r).removeClass("xdsoft_noselect")}),e(document.body).on("mousemove.xdsoft_scroller",r=function(e){var t=e.pageY-o+i;t<0&&(t=0),t+u[0].offsetHeight>l&&(t=l-u[0].offsetHeight),n.trigger("scroll_element.xdsoft_scroller",[c?t/c:0])})}),n.on("scroll_element.xdsoft_scroller",function(e,t){s||n.trigger("resize_scroll.xdsoft_scroller",[t,!0]),t=t>1?1:t<0||isNaN(t)?0:t,u.css("margin-top",c*t),o.css("marginTop",-parseInt((i-s)*t))}).on("resize_scroll.xdsoft_scroller",function(e,t,a){s=n[0].clientHeight,i=o[0].offsetHeight;var r=s/i,l=r*d[0].offsetHeight;r>1?u.hide():(u.show(),u.css("height",parseInt(l>10?l:10)),c=d[0].offsetHeight-u[0].offsetHeight,a!==!0&&n.trigger("scroll_element.xdsoft_scroller",[t?t:Math.abs(parseInt(o.css("marginTop")))/(i-s)]))}),n.mousewheel&&n.mousewheel(function(e,t,a,r){var d=Math.abs(parseInt(o.css("marginTop")));return n.trigger("scroll_element.xdsoft_scroller",[(d-20*t)/(i-s)]),e.stopPropagation(),!1}),n.on("touchstart",function(e){l=a(e)}),n.on("touchmove",function(e){if(l){var t=a(e),r=Math.abs(parseInt(o.css("marginTop")));n.trigger("scroll_element.xdsoft_scroller",[(r-(t.y-l.y))/(i-s)]),e.stopPropagation(),e.preventDefault()}}),n.on("touchend touchcancel",function(e){l=!1})}n.trigger("resize_scroll.xdsoft_scroller",[t])})},e.fn.datetimepicker=function(n){var a=48,r=57,o=96,s=105,i=17,d=46,u=13,c=27,l=8,f=37,m=38,h=39,g=40,p=9,x=116,v=65,y=67,D=86,T=90,w=89,b=!1,_=e.isPlainObject(n)||!n?e.extend(!0,{},t,n):e.extend({},t),M=0,k=function(e){e.on("open.xdsoft focusin.xdsoft mousedown.xdsoft",function t(n){e.is(":disabled")||e.is(":hidden")||!e.is(":visible")||e.data("xdsoft_datetimepicker")||(clearTimeout(M),M=setTimeout(function(){e.data("xdsoft_datetimepicker")||S(e),e.off("open.xdsoft focusin.xdsoft mousedown.xdsoft",t).trigger("open.xdsoft")},100))})},S=function(t){function n(){var e=_.value?_.value:t&&t.val&&t.val()?t.val():"";return e&&W.isValidDate(e=Date.parseDate(e,_.format))?M.data("changed",!0):e="",e||_.startDate===!1||(e=W.strToDateTime(_.startDate)),e?e:0}var M=e("<div "+(_.id?'id="'+_.id+'"':"")+" "+(_.style?'style="'+_.style+'"':"")+' class="xdsoft_datetimepicker xdsoft_noselect '+_.className+'"></div>'),k=e('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'),S=e('<div class="xdsoft_datepicker active"></div>'),O=e('<div class="xdsoft_mounthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button><div class="xdsoft_label xdsoft_month"><span></span></div><div class="xdsoft_label xdsoft_year"><span></span></div><button type="button" class="xdsoft_next"></button></div>'),F=e('<div class="xdsoft_calendar"></div>'),I=e('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'),C=I.find(".xdsoft_time_box").eq(0),H=e('<div class="xdsoft_time_variant"></div>'),Y=e('<div class="xdsoft_scrollbar"></div>'),P=(e('<div class="xdsoft_scroller"></div>'),e('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>')),A=e('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>');O.find(".xdsoft_month span").after(P),O.find(".xdsoft_year span").after(A),O.find(".xdsoft_month,.xdsoft_year").on("mousedown.xdsoft",function(t){O.find(".xdsoft_select").hide();var n=e(this).find(".xdsoft_select").eq(0),a=0,r=0;W.currentTime&&(a=W.currentTime[e(this).hasClass("xdsoft_month")?"getMonth":"getFullYear"]()),n.show();for(var o=n.find("div.xdsoft_option"),s=0;s<o.length&&o.eq(s).data("value")!=a;s++)r+=o[0].offsetHeight;return n.xdsoftScroller(r/(n.children()[0].offsetHeight-n[0].clientHeight)),t.stopPropagation(),!1}),O.find(".xdsoft_select").xdsoftScroller().on("mousedown.xdsoft",function(e){e.stopPropagation(),e.preventDefault()}).on("mousedown.xdsoft",".xdsoft_option",function(t){W&&W.currentTime&&W.currentTime[e(this).parent().parent().hasClass("xdsoft_monthselect")?"setMonth":"setFullYear"](e(this).data("value")),e(this).parent().parent().hide(),M.trigger("xchange.xdsoft"),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,W.currentTime,M.data("input"))}),M.setOptions=function(n){if(_=e.extend(!0,{},_,n),n.allowTimes&&e.isArray(n.allowTimes)&&n.allowTimes.length&&(_.allowTimes=e.extend(!0,[],n.allowTimes)),n.weekends&&e.isArray(n.weekends)&&n.weekends.length&&(_.weekends=e.extend(!0,[],n.weekends)),!_.open&&!_.opened||_.inline||t.trigger("open.xdsoft"),_.inline&&(M.addClass("xdsoft_inline"),t.after(M).hide(),M.trigger("afterOpen.xdsoft")),_.inverseButton&&(_.next="xdsoft_prev",_.prev="xdsoft_next"),_.datepicker?S.addClass("active"):S.removeClass("active"),_.timepicker?I.addClass("active"):I.removeClass("active"),_.value&&(t&&t.val&&t.val(_.value),W.setCurrentTime(_.value)),isNaN(_.dayOfWeekStart)||parseInt(_.dayOfWeekStart)<0||parseInt(_.dayOfWeekStart)>6?_.dayOfWeekStart=0:_.dayOfWeekStart=parseInt(_.dayOfWeekStart),_.timepickerScrollbar||Y.hide(),_.minDate&&/^-(.*)$/.test(_.minDate)&&(_.minDate=W.strToDateTime(_.minDate).dateFormat(_.formatDate)),_.maxDate&&/^\+(.*)$/.test(_.maxDate)&&(_.maxDate=W.strToDateTime(_.maxDate).dateFormat(_.formatDate)),O.find(".xdsoft_today_button").css("visibility",_.todayButton?"visible":"hidden"),_.mask){var k=function(e){try{if(document.selection&&document.selection.createRange){var t=document.selection.createRange();return t.getBookmark().charCodeAt(2)-2}if(e.setSelectionRange)return e.selectionStart}catch(n){return 0}},F=function(e,t){var e="string"==typeof e||e instanceof String?document.getElementById(e):e;if(!e)return!1;if(e.createTextRange){var n=e.createTextRange();return n.collapse(!0),n.moveEnd(t),n.moveStart(t),n.select(),!0}return!!e.setSelectionRange&&(e.setSelectionRange(t,t),!0)},C=function(e,t){var n=e.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g,"\\$1").replace(/_/g,"{digit+}").replace(/([0-9]{1})/g,"{digit$1}").replace(/\{digit([0-9]{1})\}/g,"[0-$1_]{1}").replace(/\{digit[\+]\}/g,"[0-9_]{1}");return RegExp(n).test(t)};switch(t.off("keydown.xdsoft"),!0){case _.mask===!0:_.mask=_.format.replace(/Y/g,"9999").replace(/F/g,"9999").replace(/m/g,"19").replace(/d/g,"39").replace(/H/g,"29").replace(/i/g,"59").replace(/s/g,"59");case"string"==e.type(_.mask):C(_.mask,t.val())||t.val(_.mask.replace(/[0-9]/g,"_")),t.on("keydown.xdsoft",function(n){var M=this.value,S=n.which;switch(!0){case S>=a&&S<=r||S>=o&&S<=s||S==l||S==d:var O=k(this),I=S!=l&&S!=d?String.fromCharCode(o<=S&&S<=s?S-a:S):"_";for(S!=l&&S!=d||!O||(O--,I="_");/[^0-9_]/.test(_.mask.substr(O,1))&&O<_.mask.length&&O>0;)O+=S==l||S==d?-1:1;if(M=M.substr(0,O)+I+M.substr(O+1),""==e.trim(M))M=_.mask.replace(/[0-9]/g,"_");else if(O==_.mask.length)break;for(O+=S==l||S==d?0:1;/[^0-9_]/.test(_.mask.substr(O,1))&&O<_.mask.length&&O>0;)O+=S==l||S==d?-1:1;C(_.mask,M)?(this.value=M,F(this,O)):""==e.trim(M)?this.value=_.mask.replace(/[0-9]/g,"_"):t.trigger("error_input.xdsoft");break;case!!~[v,y,D,T,w].indexOf(S)&&b:case!!~[c,m,g,f,h,x,i,p,u].indexOf(S):return!0}return n.preventDefault(),!1})}}_.validateOnBlur&&t.off("blur.xdsoft").on("blur.xdsoft",function(){_.allowBlank&&!e.trim(e(this).val()).length?(e(this).val(null),M.data("xdsoft_datetime").empty()):Date.parseDate(e(this).val(),_.format)?M.data("xdsoft_datetime").setCurrentTime(e(this).val()):(e(this).val(W.now().dateFormat(_.format)),M.data("xdsoft_datetime").setCurrentTime(e(this).val())),M.trigger("changedatetime.xdsoft")}),_.dayOfWeekStartPrev=0==_.dayOfWeekStart?6:_.dayOfWeekStart-1,M.trigger("xchange.xdsoft")},M.data("options",_).on("mousedown.xdsoft",function(e){return e.stopPropagation(),e.preventDefault(),A.hide(),P.hide(),!1});var N=I.find(".xdsoft_time_box");N.append(H),N.xdsoftScroller(),M.on("afterOpen.xdsoft",function(){N.xdsoftScroller()}),M.append(S).append(I),_.withoutCopyright!==!0&&M.append(k),S.append(O).append(F),e("body").append(M);var W=new function(){var e=this;e.now=function(){var e=new Date;return _.yearOffset&&e.setFullYear(e.getFullYear()+_.yearOffset),e},e.currentTime=this.now(),e.isValidDate=function(e){return"[object Date]"===Object.prototype.toString.call(e)&&!isNaN(e.getTime())},e.setCurrentTime=function(t){e.currentTime="string"==typeof t?e.strToDateTime(t):e.isValidDate(t)?t:e.now(),M.trigger("xchange.xdsoft")},e.empty=function(){e.currentTime=null},e.getCurrentTime=function(t){return e.currentTime},e.nextMonth=function(){var t=e.currentTime.getMonth()+1;return 12==t&&(e.currentTime.setFullYear(e.currentTime.getFullYear()+1),t=0),e.currentTime.setDate(Math.min(Date.daysInMonth[t],e.currentTime.getDate())),e.currentTime.setMonth(t),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,W.currentTime,M.data("input")),M.trigger("xchange.xdsoft"),t},e.prevMonth=function(){var t=e.currentTime.getMonth()-1;return t==-1&&(e.currentTime.setFullYear(e.currentTime.getFullYear()-1),t=11),e.currentTime.setDate(Math.min(Date.daysInMonth[t],e.currentTime.getDate())),e.currentTime.setMonth(t),_.onChangeMonth&&_.onChangeMonth.call&&_.onChangeMonth.call(M,W.currentTime,M.data("input")),M.trigger("xchange.xdsoft"),t},e.strToDateTime=function(t){var n,a,r=[];return(r=/^(\+|\-)(.*)$/.exec(t))&&(r[2]=Date.parseDate(r[2],_.formatDate))?(n=r[2].getTime()-1*r[2].getTimezoneOffset()*6e4,a=new Date(W.now().getTime()+parseInt(r[1]+"1")*n)):a=t?Date.parseDate(t,_.format):e.now(),e.isValidDate(a)||(a=e.now()),a},e.strtodate=function(t){var n=t?Date.parseDate(t,_.formatDate):e.now();return e.isValidDate(n)||(n=e.now()),n},e.strtotime=function(t){var n=t?Date.parseDate(t,_.formatTime):e.now();return e.isValidDate(n)||(n=e.now()),n},e.str=function(){return e.currentTime.dateFormat(_.format)}};O.find(".xdsoft_today_button").on("mousedown.xdsoft",function(){M.data("changed",!0),W.setCurrentTime(0),M.trigger("afterOpen.xdsoft")}).on("dblclick.xdsoft",function(){t.val(W.str()),M.trigger("close.xdsoft")}),O.find(".xdsoft_prev,.xdsoft_next").on("mousedown.xdsoft",function(){var t=e(this),n=0,a=!1;!function r(e){W.currentTime.getMonth();t.hasClass(_.next)?W.nextMonth():t.hasClass(_.prev)&&W.prevMonth(),!a&&(n=setTimeout(r,e?e:100))}(500),e([document.body,window]).on("mouseup.xdsoft",function o(){clearTimeout(n),a=!0,e([document.body,window]).off("mouseup.xdsoft",o)})}),I.find(".xdsoft_prev,.xdsoft_next").on("mousedown.xdsoft",function(){var t=e(this),n=0,a=!1,r=110;!function o(e){var s=C[0].clientHeight,i=H[0].offsetHeight,d=Math.abs(parseInt(H.css("marginTop")));t.hasClass(_.next)&&i-s-_.timeHeightInTimePicker>=d?H.css("marginTop","-"+(d+_.timeHeightInTimePicker)+"px"):t.hasClass(_.prev)&&d-_.timeHeightInTimePicker>=0&&H.css("marginTop","-"+(d-_.timeHeightInTimePicker)+"px"),C.trigger("scroll_element.xdsoft_scroller",[Math.abs(parseInt(H.css("marginTop"))/(i-s))]),r=r>10?10:r-10,!a&&(n=setTimeout(o,e?e:r))}(500),e([document.body,window]).on("mouseup.xdsoft",function s(){clearTimeout(n),a=!0,e([document.body,window]).off("mouseup.xdsoft",s)})});var z=0;M.on("xchange.xdsoft",function(t){clearTimeout(z),z=setTimeout(function(){for(var t="",n=new Date(W.currentTime.getFullYear(),W.currentTime.getMonth(),1,12,0,0),a=0,r=W.now();n.getDay()!=_.dayOfWeekStart;)n.setDate(n.getDate()-1);t+="<table><thead><tr>";for(var o=0;o<7;o++)t+="<th>"+_.i18n[_.lang].dayOfWeek[o+_.dayOfWeekStart>6?0:o+_.dayOfWeekStart]+"</th>";t+="</tr></thead>",t+="<tbody><tr>";var s=!1,i=!1;_.maxDate!==!1&&(s=W.strtodate(_.maxDate),s=new Date(s.getFullYear(),s.getMonth(),s.getDate(),23,59,59,999)),_.minDate!==!1&&(i=W.strtodate(_.minDate),i=new Date(i.getFullYear(),i.getMonth(),i.getDate()));for(var d,u,c,l=[];a<W.currentTime.getDaysInMonth()||n.getDay()!=_.dayOfWeekStart||W.currentTime.getMonth()==n.getMonth();)l=[],a++,d=n.getDate(),u=n.getFullYear(),c=n.getMonth(),l.push("xdsoft_date"),(s!==!1&&n>s||i!==!1&&n<i)&&l.push("xdsoft_disabled"),W.currentTime.getMonth()!=c&&l.push("xdsoft_other_month"),(_.defaultSelect||M.data("changed"))&&W.currentTime.dateFormat("d.m.Y")==n.dateFormat("d.m.Y")&&l.push("xdsoft_current"),r.dateFormat("d.m.Y")==n.dateFormat("d.m.Y")&&l.push("xdsoft_today"),(0==n.getDay()||6==n.getDay()||~_.weekends.indexOf(n.dateFormat("d.m.Y")))&&l.push("xdsoft_weekend"),_.beforeShowDay&&"function"==typeof _.beforeShowDay&&l.push(_.beforeShowDay(n)),t+='<td data-date="'+d+'" data-month="'+c+'" data-year="'+u+'" class="xdsoft_date xdsoft_day_of_week'+n.getDay()+" "+l.join(" ")+'"><div>'+d+"</div></td>",n.getDay()==_.dayOfWeekStartPrev&&(t+="</tr>"),n.setDate(d+1);t+="</tbody></table>",F.html(t),O.find(".xdsoft_label span").eq(0).text(_.i18n[_.lang].months[W.currentTime.getMonth()]),O.find(".xdsoft_label span").eq(1).text(W.currentTime.getFullYear());var f="",m="",c="",h=function(e,t){var n=W.now();n.setHours(e),e=parseInt(n.getHours()),n.setMinutes(t),t=parseInt(n.getMinutes()),l=[],(_.maxTime!==!1&&W.strtotime(_.maxTime).getTime()<n.getTime()||_.minTime!==!1&&W.strtotime(_.minTime).getTime()>n.getTime())&&l.push("xdsoft_disabled"),(_.initTime||_.defaultSelect||M.data("changed"))&&parseInt(W.currentTime.getHours())==parseInt(e)&&(_.step>59||Math[_.roundTime](W.currentTime.getMinutes()/_.step)*_.step==parseInt(t))&&(_.defaultSelect||M.data("changed")?l.push("xdsoft_current"):_.initTime&&l.push("xdsoft_init_time")),parseInt(r.getHours())==parseInt(e)&&parseInt(r.getMinutes())==parseInt(t)&&l.push("xdsoft_today"),f+='<div class="xdsoft_time '+l.join(" ")+'" data-hour="'+e+'" data-minute="'+t+'">'+n.dateFormat(_.formatTime)+"</div>"};if(_.allowTimes&&e.isArray(_.allowTimes)&&_.allowTimes.length)for(var a=0;a<_.allowTimes.length;a++)m=W.strtotime(_.allowTimes[a]).getHours(),c=W.strtotime(_.allowTimes[a]).getMinutes(),h(m,c);else for(var a=0,o=0;a<(_.hours12?12:24);a++)for(o=0;o<60;o+=_.step)m=(a<10?"0":"")+a,c=(o<10?"0":"")+o,h(m,c);H.html(f);var g="",a=0;for(a=parseInt(_.yearStart,10)+_.yearOffset;a<=parseInt(_.yearEnd,10)+_.yearOffset;a++)g+='<div class="xdsoft_option '+(W.currentTime.getFullYear()==a?"xdsoft_current":"")+'" data-value="'+a+'">'+a+"</div>";for(A.children().eq(0).html(g),a=0,g="";a<=11;a++)g+='<div class="xdsoft_option '+(W.currentTime.getMonth()==a?"xdsoft_current":"")+'" data-value="'+a+'">'+_.i18n[_.lang].months[a]+"</div>";P.children().eq(0).html(g),e(this).trigger("generate.xdsoft")},10),t.stopPropagation()}).on("afterOpen.xdsoft",function(){if(_.timepicker){var e;if(H.find(".xdsoft_current").length?e=".xdsoft_current":H.find(".xdsoft_init_time").length&&(e=".xdsoft_init_time"),e){var t=C[0].clientHeight,n=H[0].offsetHeight,a=H.find(e).index()*_.timeHeightInTimePicker+1;n-t<a&&(a=n-t),H.css("marginTop","-"+parseInt(a)+"px"),C.trigger("scroll_element.xdsoft_scroller",[parseInt(a)/(n-t)])}}});var J=0;F.on("click.xdsoft","td",function(n){n.stopPropagation(),J++;var a=e(this),r=W.currentTime;return!a.hasClass("xdsoft_disabled")&&(r.setDate(a.data("date")),r.setMonth(a.data("month")),r.setFullYear(a.data("year")),M.trigger("select.xdsoft",[r]),t.val(W.str()),(J>1||_.closeOnDateSelect===!0||0===_.closeOnDateSelect&&!_.timepicker)&&!_.inline&&M.trigger("close.xdsoft"),_.onSelectDate&&_.onSelectDate.call&&_.onSelectDate.call(M,W.currentTime,M.data("input")),M.data("changed",!0),M.trigger("xchange.xdsoft"),M.trigger("changedatetime.xdsoft"),void setTimeout(function(){J=0},200))}),H.on("click.xdsoft","div",function(t){t.stopPropagation();var n=e(this),a=W.currentTime;return!n.hasClass("xdsoft_disabled")&&(a.setHours(n.data("hour")),a.setMinutes(n.data("minute")),M.trigger("select.xdsoft",[a]),M.data("input").val(W.str()),!_.inline&&M.trigger("close.xdsoft"),_.onSelectTime&&_.onSelectTime.call&&_.onSelectTime.call(M,W.currentTime,M.data("input")),M.data("changed",!0),M.trigger("xchange.xdsoft"),void M.trigger("changedatetime.xdsoft"))}),M.mousewheel&&S.mousewheel(function(e,t,n,a){return!_.scrollMonth||(t<0?W.nextMonth():W.prevMonth(),!1)}),M.mousewheel&&C.unmousewheel().mousewheel(function(e,t,n,a){if(!_.scrollTime)return!0;var r=C[0].clientHeight,o=H[0].offsetHeight,s=Math.abs(parseInt(H.css("marginTop"))),i=!0;return t<0&&o-r-_.timeHeightInTimePicker>=s?(H.css("marginTop","-"+(s+_.timeHeightInTimePicker)+"px"),i=!1):t>0&&s-_.timeHeightInTimePicker>=0&&(H.css("marginTop","-"+(s-_.timeHeightInTimePicker)+"px"),i=!1),C.trigger("scroll_element.xdsoft_scroller",[Math.abs(parseInt(H.css("marginTop"))/(o-r))]),e.stopPropagation(),i}),M.on("changedatetime.xdsoft",function(){if(_.onChangeDateTime&&_.onChangeDateTime.call){var e=M.data("input");_.onChangeDateTime.call(M,W.currentTime,e),e.trigger("change")}}).on("generate.xdsoft",function(){_.onGenerate&&_.onGenerate.call&&_.onGenerate.call(M,W.currentTime,M.data("input"))});var j=0;t.mousewheel&&t.mousewheel(function(e,n,a,r){return!_.scrollInput||(!_.datepicker&&_.timepicker?(j=H.find(".xdsoft_current").length?H.find(".xdsoft_current").eq(0).index():0,j+n>=0&&j+n<H.children().length&&(j+=n),H.children().eq(j).length&&H.children().eq(j).trigger("mousedown"),!1):_.datepicker&&!_.timepicker?(S.trigger(e,[n,a,r]),t.val&&t.val(W.str()),M.trigger("changedatetime.xdsoft"),!1):void 0)});var L=function(){var t=M.data("input").offset(),n=t.top+M.data("input")[0].offsetHeight-1,a=t.left;n+M[0].offsetHeight>e(window).height()+e(window).scrollTop()&&(n=t.top-M[0].offsetHeight+1),n<0&&(n=0),a+M[0].offsetWidth>e(window).width()&&(a=t.left-M[0].offsetWidth+M.data("input")[0].offsetWidth),M.css({left:a,top:n})};M.on("open.xdsoft",function(){var t=!0;_.onShow&&_.onShow.call&&(t=_.onShow.call(M,W.currentTime,M.data("input"))),t!==!1&&(M.show(),M.trigger("afterOpen.xdsoft"),L(),e(window).off("resize.xdsoft",L).on("resize.xdsoft",L),_.closeOnWithoutClick&&e([document.body,window]).on("mousedown.xdsoft",function n(){M.trigger("close.xdsoft"),e([document.body,window]).off("mousedown.xdsoft",n)}))}).on("close.xdsoft",function(e){var t=!0;_.onClose&&_.onClose.call&&(t=_.onClose.call(M,W.currentTime,M.data("input"))),t===!1||_.opened||_.inline||M.hide(),e.stopPropagation()}).data("input",t);var E=0;M.data("xdsoft_datetime",W),M.setOptions(_),W.setCurrentTime(n()),M.trigger("afterOpen.xdsoft"),t.data("xdsoft_datetimepicker",M).on("open.xdsoft focusin.xdsoft mousedown.xdsoft",function(e){t.is(":disabled")||t.is(":hidden")||!t.is(":visible")||(clearTimeout(E),E=setTimeout(function(){t.is(":disabled")||t.is(":hidden")||!t.is(":visible")||(W.setCurrentTime(n()),M.trigger("open.xdsoft"))},100))}).on("keydown.xdsoft",function(t){var n=(this.value,t.which);switch(!0){case!!~[u].indexOf(n):var a=e("input:visible,textarea:visible");return M.trigger("close.xdsoft"),a.eq(a.index(this)+1).focus(),!1;case!!~[p].indexOf(n):return M.trigger("close.xdsoft"),!0}})},O=function(t){var n=t.data("xdsoft_datetimepicker");n&&(n.data("xdsoft_datetime",null),n.remove(),t.data("xdsoft_datetimepicker",null).off("open.xdsoft focusin.xdsoft focusout.xdsoft mousedown.xdsoft blur.xdsoft keydown.xdsoft"),e(window).off("resize.xdsoft"),e([window,document.body]).off("mousedown.xdsoft"),t.unmousewheel&&t.unmousewheel())};return e(document).off("keydown.xdsoftctrl keyup.xdsoftctrl").on("keydown.xdsoftctrl",function(e){e.keyCode==i&&(b=!0)}).on("keyup.xdsoftctrl",function(e){e.keyCode==i&&(b=!1)}),this.each(function(){var t;if(t=e(this).data("xdsoft_datetimepicker")){if("string"===e.type(n))switch(n){case"show":e(this).select().focus(),t.trigger("open.xdsoft");break;case"hide":t.trigger("close.xdsoft");break;case"destroy":O(e(this));break;case"reset":this.value=this.defaultValue,this.value&&t.data("xdsoft_datetime").isValidDate(Date.parseDate(this.value,_.format))||t.data("changed",!1),t.data("xdsoft_datetime").setCurrentTime(this.value)}else t.setOptions(n);return 0}"string"!==e.type(n)&&(!_.lazyInit||_.open||_.inline?S(e(this)):k(e(this)))})}}(jQuery),Date.parseFunctions={count:0},Date.parseRegexes=[],Date.formatFunctions={count:0},Date.prototype.dateFormat=function(e){if("unixtime"==e)return parseInt(this.getTime()/1e3);null==Date.formatFunctions[e]&&Date.createNewFormat(e);var t=Date.formatFunctions[e];return this[t]()},Date.createNewFormat=function(format){var funcName="format"+Date.formatFunctions.count++;Date.formatFunctions[format]=funcName;for(var code="Date.prototype."+funcName+" = function() {return ",special=!1,ch="",i=0;i<format.length;++i)ch=format.charAt(i),special||"\\"!=ch?special?(special=!1,code+="'"+String.escape(ch)+"' + "):code+=Date.getFormatCode(ch):special=!0;eval(code.substring(0,code.length-3)+";}")},Date.getFormatCode=function(e){switch(e){case"d":return"String.leftPad(this.getDate(), 2, '0') + ";case"D":return"Date.dayNames[this.getDay()].substring(0, 3) + ";case"j":return"this.getDate() + ";case"l":return"Date.dayNames[this.getDay()] + ";case"S":return"this.getSuffix() + ";case"w":return"this.getDay() + ";case"z":return"this.getDayOfYear() + ";case"W":return"this.getWeekOfYear() + ";case"F":return"Date.monthNames[this.getMonth()] + ";case"m":return"String.leftPad(this.getMonth() + 1, 2, '0') + ";case"M":return"Date.monthNames[this.getMonth()].substring(0, 3) + ";case"n":return"(this.getMonth() + 1) + ";case"t":return"this.getDaysInMonth() + ";case"L":return"(this.isLeapYear() ? 1 : 0) + ";case"Y":return"this.getFullYear() + ";case"y":return"('' + this.getFullYear()).substring(2, 4) + ";case"a":return"(this.getHours() < 12 ? 'am' : 'pm') + ";case"A":return"(this.getHours() < 12 ? 'AM' : 'PM') + ";case"g":return"((this.getHours() %12) ? this.getHours() % 12 : 12) + ";case"G":return"this.getHours() + ";case"h":return"String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + ";case"H":return"String.leftPad(this.getHours(), 2, '0') + ";case"i":return"String.leftPad(this.getMinutes(), 2, '0') + ";case"s":return"String.leftPad(this.getSeconds(), 2, '0') + ";case"O":return"this.getGMTOffset() + ";case"T":return"this.getTimezone() + ";case"Z":return"(this.getTimezoneOffset() * -60) + ";default:return"'"+String.escape(e)+"' + "}},Date.parseDate=function(e,t){if("unixtime"==t)return new Date(isNaN(parseInt(e))?0:1e3*parseInt(e));null==Date.parseFunctions[t]&&Date.createParser(t);var n=Date.parseFunctions[t];return Date[n](e)},Date.createParser=function(format){var funcName="parse"+Date.parseFunctions.count++,regexNum=Date.parseRegexes.length,currentGroup=1;Date.parseFunctions[format]=funcName;for(var code="Date."+funcName+" = function(input) {\nvar y = -1, m = -1, d = -1, h = -1, i = -1, s = -1, z = -1;\nvar d = new Date();\ny = d.getFullYear();\nm = d.getMonth();\nd = d.getDate();\nvar results = input.match(Date.parseRegexes["+regexNum+"]);\nif (results && results.length > 0) {",regex="",special=!1,ch="",i=0;i<format.length;++i)ch=format.charAt(i),special||"\\"!=ch?special?(special=!1,regex+=String.escape(ch)):(obj=Date.formatCodeToRegex(ch,currentGroup),currentGroup+=obj.g,regex+=obj.s,obj.g&&obj.c&&(code+=obj.c)):special=!0;code+="if (y > 0 && z > 0){\nvar doyDate = new Date(y,0);\ndoyDate.setDate(z);\nm = doyDate.getMonth();\nd = doyDate.getDate();\n}",code+="if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n{return new Date(y, m, d, h, i, s);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n{return new Date(y, m, d, h, i);}\nelse if (y > 0 && m >= 0 && d > 0 && h >= 0)\n{return new Date(y, m, d, h);}\nelse if (y > 0 && m >= 0 && d > 0)\n{return new Date(y, m, d);}\nelse if (y > 0 && m >= 0)\n{return new Date(y, m);}\nelse if (y > 0)\n{return new Date(y);}\n}return null;}",Date.parseRegexes[regexNum]=new RegExp("^"+regex+"$"),eval(code)},Date.formatCodeToRegex=function(e,t){switch(e){case"D":return{g:0,c:null,s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};case"j":case"d":return{g:1,c:"d = parseInt(results["+t+"], 10);\n",s:"(\\d{1,2})"};case"l":return{g:0,c:null,s:"(?:"+Date.dayNames.join("|")+")"};case"S":return{g:0,c:null,s:"(?:st|nd|rd|th)"};case"w":return{g:0,c:null,s:"\\d"};case"z":return{g:1,c:"z = parseInt(results["+t+"], 10);\n",s:"(\\d{1,3})"};case"W":return{g:0,c:null,s:"(?:\\d{2})"};case"F":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+t+"].substring(0, 3)], 10);\n",s:"("+Date.monthNames.join("|")+")"};case"M":return{g:1,c:"m = parseInt(Date.monthNumbers[results["+t+"]], 10);\n",s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};case"n":case"m":return{g:1,c:"m = parseInt(results["+t+"], 10) - 1;\n",s:"(\\d{1,2})"};case"t":return{g:0,c:null,s:"\\d{1,2}"};case"L":return{g:0,c:null,s:"(?:1|0)"};case"Y":return{g:1,c:"y = parseInt(results["+t+"], 10);\n",s:"(\\d{4})"};case"y":return{g:1,c:"var ty = parseInt(results["+t+"], 10);\ny = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",s:"(\\d{1,2})"};case"a":return{g:1,c:"if (results["+t+"] == 'am') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(am|pm)"};case"A":return{g:1,c:"if (results["+t+"] == 'AM') {\nif (h == 12) { h = 0; }\n} else { if (h < 12) { h += 12; }}",s:"(AM|PM)"};case"g":case"G":case"h":case"H":return{g:1,c:"h = parseInt(results["+t+"], 10);\n",s:"(\\d{1,2})"};case"i":return{g:1,c:"i = parseInt(results["+t+"], 10);\n",s:"(\\d{2})"};case"s":return{g:1,c:"s = parseInt(results["+t+"], 10);\n",s:"(\\d{2})"};case"O":return{g:0,c:null,s:"[+-]\\d{4}"};case"T":return{g:0,c:null,s:"[A-Z]{3}"};case"Z":return{g:0,c:null,s:"[+-]\\d{1,5}"};default:return{g:0,c:null,s:String.escape(e)}}},Date.prototype.getTimezone=function(){return this.toString().replace(/^.*? ([A-Z]{3}) [0-9]{4}.*$/,"$1").replace(/^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/,"$1$2$3")},Date.prototype.getGMTOffset=function(){return(this.getTimezoneOffset()>0?"-":"+")+String.leftPad(Math.floor(Math.abs(this.getTimezoneOffset())/60),2,"0")+String.leftPad(Math.abs(this.getTimezoneOffset())%60,2,"0")},Date.prototype.getDayOfYear=function(){var e=0;Date.daysInMonth[1]=this.isLeapYear()?29:28;for(var t=0;t<this.getMonth();++t)e+=Date.daysInMonth[t];return e+this.getDate()},Date.prototype.getWeekOfYear=function(){var e=this.getDayOfYear()+(4-this.getDay()),t=new Date(this.getFullYear(),0,1),n=7-t.getDay()+4;return String.leftPad(Math.ceil((e-n)/7)+1,2,"0")},Date.prototype.isLeapYear=function(){var e=this.getFullYear();return 0==(3&e)&&(e%100||e%400==0&&e)},Date.prototype.getFirstDayOfMonth=function(){var e=(this.getDay()-(this.getDate()-1))%7;return e<0?e+7:e},Date.prototype.getLastDayOfMonth=function(){var e=(this.getDay()+(Date.daysInMonth[this.getMonth()]-this.getDate()))%7;return e<0?e+7:e},Date.prototype.getDaysInMonth=function(){return Date.daysInMonth[1]=this.isLeapYear()?29:28,Date.daysInMonth[this.getMonth()]},Date.prototype.getSuffix=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}},String.escape=function(e){return e.replace(/('|\\)/g,"\\$1")},String.leftPad=function(e,t,n){var a=new String(e);for(null==n&&(n=" ");a.length<t;)a=n+a;return a},Date.daysInMonth=[31,28,31,30,31,30,31,31,30,31,30,31],Date.monthNames=["January","February","March","April","May","June","July","August","September","October","November","December"],Date.dayNames=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Date.y2kYear=50,Date.monthNumbers={Jan:0,Feb:1,Mar:2,
Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},Date.patterns={ISO8601LongPattern:"Y-m-d H:i:s",ISO8601ShortPattern:"Y-m-d",ShortDatePattern:"n/j/Y",LongDatePattern:"l, F d, Y",FullDateTimePattern:"l, F d, Y g:i:s A",MonthDayPattern:"F d",ShortTimePattern:"g:i A",LongTimePattern:"g:i:s A",SortableDateTimePattern:"Y-m-d\\TH:i:s",UniversalSortableDateTimePattern:"Y-m-d H:i:sO",YearMonthPattern:"F, Y"},function(e){"function"==typeof define&&define.amd?define(["jquery.flot.min"],e):"object"==typeof exports?module.exports=e:e(jQuery)}(function(e){function t(t){var r,o=t||window.event,s=[].slice.call(arguments,1),i=0,d=0,u=0,c=0,l=0;return t=e.event.fix(o),t.type="mousewheel",o.wheelDelta&&(i=o.wheelDelta),o.detail&&(i=o.detail*-1),o.deltaY&&(u=o.deltaY*-1,i=u),o.deltaX&&(d=o.deltaX,i=d*-1),void 0!==o.wheelDeltaY&&(u=o.wheelDeltaY),void 0!==o.wheelDeltaX&&(d=o.wheelDeltaX*-1),c=Math.abs(i),(!n||c<n)&&(n=c),l=Math.max(Math.abs(u),Math.abs(d)),(!a||l<a)&&(a=l),r=i>0?"floor":"ceil",i=Math[r](i/n),d=Math[r](d/a),u=Math[r](u/a),s.unshift(t,i,d,u),(e.event.dispatch||e.event.handle).apply(this,s)}var n,a,r=["wheel","mousewheel","DOMMouseScroll","MozMousePixelScroll"],o="onwheel"in document||document.documentMode>=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"];if(e.event.fixHooks)for(var s=r.length;s;)e.event.fixHooks[r[--s]]=e.event.mouseHooks;e.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var e=o.length;e;)this.addEventListener(o[--e],t,!1);else this.onmousewheel=t},teardown:function(){if(this.removeEventListener)for(var e=o.length;e;)this.removeEventListener(o[--e],t,!1);else this.onmousewheel=null}},e.fn.extend({mousewheel:function(e){return e?this.bind("mousewheel",e):this.trigger("mousewheel")},unmousewheel:function(e){return this.unbind("mousewheel",e)}})});
function _toConsumableArray(e){if(Array.isArray(e)){for(var t=0,i=Array(e.length);t<e.length;t++)i[t]=e[t];return i}return Array.from(e)}var _slice=Array.prototype.slice,_slicedToArray=function(){function e(e,t){var i=[],n=!0,r=!1,s=void 0;try{for(var a,o=e[Symbol.iterator]();!(n=(a=o.next()).done)&&(i.push(a.value),!t||i.length!==t);n=!0);}catch(l){r=!0,s=l}finally{try{!n&&o["return"]&&o["return"]()}finally{if(r)throw s}}return i}return function(t,i){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,i);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e};!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("jquery")):"function"==typeof define&&define.amd?define(["jquery"],t):e.parsley=t(e.jQuery)}(this,function(e){"use strict";function t(e,t){return e.parsleyAdaptedCallback||(e.parsleyAdaptedCallback=function(){var i=Array.prototype.slice.call(arguments,0);i.unshift(this),e.apply(t||T,i)}),e.parsleyAdaptedCallback}function i(e){return 0===e.lastIndexOf(D,0)?e.substr(D.length):e}function n(){var t=this,i=window||global;_extends(this,{isNativeEvent:function(e){return e.originalEvent&&e.originalEvent.isTrusted!==!1},fakeInputEvent:function(i){t.isNativeEvent(i)&&e(i.target).trigger("input")},misbehaves:function(i){t.isNativeEvent(i)&&(t.behavesOk(i),e(document).on("change.inputevent",i.data.selector,t.fakeInputEvent),t.fakeInputEvent(i))},behavesOk:function(i){t.isNativeEvent(i)&&e(document).off("input.inputevent",i.data.selector,t.behavesOk).off("change.inputevent",i.data.selector,t.misbehaves)},install:function(){if(!i.inputEventPatched){i.inputEventPatched="0.0.3";for(var n=["select",'input[type="checkbox"]','input[type="radio"]','input[type="file"]'],r=0;r<n.length;r++){var s=n[r];e(document).on("input.inputevent",s,{selector:s},t.behavesOk).on("change.inputevent",s,{selector:s},t.misbehaves)}}},uninstall:function(){delete i.inputEventPatched,e(document).off(".inputevent")}})}var r=1,s={},a={attr:function(e,t,i){var n,r,s,a=new RegExp("^"+t,"i");if("undefined"==typeof i)i={};else for(n in i)i.hasOwnProperty(n)&&delete i[n];if(!e)return i;for(s=e.attributes,n=s.length;n--;)r=s[n],r&&r.specified&&a.test(r.name)&&(i[this.camelize(r.name.slice(t.length))]=this.deserializeValue(r.value));return i},checkAttr:function(e,t,i){return e.hasAttribute(t+i)},setAttr:function(e,t,i,n){e.setAttribute(this.dasherize(t+i),String(n))},generateID:function(){return""+r++},deserializeValue:function(t){var i;try{return t?"true"==t||"false"!=t&&("null"==t?null:isNaN(i=Number(t))?/^[\[\{]/.test(t)?e.parseJSON(t):t:i):t}catch(n){return t}},camelize:function(e){return e.replace(/-+(.)?/g,function(e,t){return t?t.toUpperCase():""})},dasherize:function(e){return e.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()},warn:function(){var e;window.console&&"function"==typeof window.console.warn&&(e=window.console).warn.apply(e,arguments)},warnOnce:function(e){s[e]||(s[e]=!0,this.warn.apply(this,arguments))},_resetWarnings:function(){s={}},trimString:function(e){return e.replace(/^\s+|\s+$/g,"")},parse:{date:function S(e){var t=e.match(/^(\d{4,})-(\d\d)-(\d\d)$/);if(!t)return null;var i=t.map(function(e){return parseInt(e,10)}),n=_slicedToArray(i,4),r=(n[0],n[1]),s=n[2],a=n[3],S=new Date(r,s-1,a);return S.getFullYear()!==r||S.getMonth()+1!==s||S.getDate()!==a?null:S},string:function(e){return e},integer:function(e){return isNaN(e)?null:parseInt(e,10)},number:function(e){if(isNaN(e))throw null;return parseFloat(e)},"boolean":function(e){return!/^\s*false\s*$/i.test(e)},object:function(e){return a.deserializeValue(e)},regexp:function(e){var t="";return/^\/.*\/(?:[gimy]*)$/.test(e)?(t=e.replace(/.*\/([gimy]*)$/,"$1"),e=e.replace(new RegExp("^/(.*?)/"+t+"$"),"$1")):e="^"+e+"$",new RegExp(e,t)}},parseRequirement:function(e,t){var i=this.parse[e||"string"];if(!i)throw'Unknown requirement specification: "'+e+'"';var n=i(t);if(null===n)throw"Requirement is not a "+e+': "'+t+'"';return n},namespaceEvents:function(t,i){return t=this.trimString(t||"").split(/\s+/),t[0]?e.map(t,function(e){return e+"."+i}).join(" "):""},difference:function(t,i){var n=[];return e.each(t,function(e,t){i.indexOf(t)==-1&&n.push(t)}),n},all:function(t){return e.when.apply(e,_toConsumableArray(t).concat([42,42]))},objectCreate:Object.create||function(){var e=function(){};return function(t){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof t)throw TypeError("Argument must be an object");e.prototype=t;var i=new e;return e.prototype=null,i}}(),_SubmitSelector:'input[type="submit"], button:submit'},o={namespace:"data-parsley-",inputs:"input, textarea, select",excluded:"input[type=button], input[type=submit], input[type=reset], input[type=hidden]",priorityEnabled:!0,multiple:null,group:null,uiEnabled:!0,validationThreshold:3,focus:"first",trigger:!1,triggerAfterFailure:"input",errorClass:"parsley-error",successClass:"parsley-success",classHandler:function(e){},errorsContainer:function(e){},errorsWrapper:'<ul class="parsley-errors-list"></ul>',errorTemplate:"<li></li>"},l=function(){this.__id__=a.generateID()};l.prototype={asyncSupport:!0,_pipeAccordingToValidationResult:function(){var t=this,i=function(){var i=e.Deferred();return!0!==t.validationResult&&i.reject(),i.resolve().promise()};return[i,i]},actualizeOptions:function(){return a.attr(this.element,this.options.namespace,this.domOptions),this.parent&&this.parent.actualizeOptions&&this.parent.actualizeOptions(),this},_resetOptions:function(e){this.domOptions=a.objectCreate(this.parent.options),this.options=a.objectCreate(this.domOptions);for(var t in e)e.hasOwnProperty(t)&&(this.options[t]=e[t]);this.actualizeOptions()},_listeners:null,on:function(e,t){this._listeners=this._listeners||{};var i=this._listeners[e]=this._listeners[e]||[];return i.push(t),this},subscribe:function(t,i){e.listenTo(this,t.toLowerCase(),i)},off:function(e,t){var i=this._listeners&&this._listeners[e];if(i)if(t)for(var n=i.length;n--;)i[n]===t&&i.splice(n,1);else delete this._listeners[e];return this},unsubscribe:function(t,i){e.unsubscribeTo(this,t.toLowerCase())},trigger:function(e,t,i){t=t||this;var n,r=this._listeners&&this._listeners[e];if(r)for(var s=r.length;s--;)if(n=r[s].call(t,t,i),n===!1)return n;return!this.parent||this.parent.trigger(e,t,i)},asyncIsValid:function(e,t){return a.warnOnce("asyncIsValid is deprecated; please use whenValid instead"),this.whenValid({group:e,force:t})},_findRelated:function(){return this.options.multiple?e(this.parent.element.querySelectorAll("["+this.options.namespace+'multiple="'+this.options.multiple+'"]')):this.$element}};var u=function(e,t){var i=e.match(/^\s*\[(.*)\]\s*$/);if(!i)throw'Requirement is not an array: "'+e+'"';var n=i[1].split(",").map(a.trimString);if(n.length!==t)throw"Requirement has "+n.length+" values when "+t+" are needed";return n},d=function(e,t,i){var n=null,r={};for(var s in e)if(s){var o=i(s);"string"==typeof o&&(o=a.parseRequirement(e[s],o)),r[s]=o}else n=a.parseRequirement(e[s],t);return[n,r]},h=function(t){e.extend(!0,this,t)};h.prototype={validate:function(e,t){if(this.fn)return arguments.length>3&&(t=[].slice.call(arguments,1,-1)),this.fn(e,t);if(Array.isArray(e)){if(!this.validateMultiple)throw"Validator `"+this.name+"` does not handle multiple values";return this.validateMultiple.apply(this,arguments)}var i=arguments[arguments.length-1];if(this.validateDate&&i._isDateInput())return arguments[0]=a.parse.date(arguments[0]),null!==arguments[0]&&this.validateDate.apply(this,arguments);if(this.validateNumber)return!isNaN(e)&&(arguments[0]=parseFloat(arguments[0]),this.validateNumber.apply(this,arguments));if(this.validateString)return this.validateString.apply(this,arguments);throw"Validator `"+this.name+"` only handles multiple values"},parseRequirements:function(t,i){if("string"!=typeof t)return Array.isArray(t)?t:[t];var n=this.requirementType;if(Array.isArray(n)){for(var r=u(t,n.length),s=0;s<r.length;s++)r[s]=a.parseRequirement(n[s],r[s]);return r}return e.isPlainObject(n)?d(n,t,i):[a.parseRequirement(n,t)]},requirementType:"string",priority:2};var p=function(e,t){this.__class__="ValidatorRegistry",this.locale="en",this.init(e||{},t||{})},c={email:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,number:/^-?(\d*\.)?\d+(e[-+]?\d+)?$/i,integer:/^-?\d+$/,digits:/^\d+$/,alphanum:/^\w+$/i,date:{test:function(e){return null!==a.parse.date(e)}},url:new RegExp("^(?:(?:https?|ftp)://)?(?:\\S+(?::\\S*)?@)?(?:(?:[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")};c.range=c.number;var f=function(e){var t=(""+e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0},m=function(e,t){return t.map(a.parse[e])},g=function(e,t){return function(i){for(var n=arguments.length,r=Array(n>1?n-1:0),s=1;s<n;s++)r[s-1]=arguments[s];return r.pop(),t.apply(void 0,[i].concat(_toConsumableArray(m(e,r))))}},v=function(e){return{validateDate:g("date",e),validateNumber:g("number",e),requirementType:e.length<=2?"string":["string","string"],priority:30}};p.prototype={init:function(e,t){this.catalog=t,this.validators=_extends({},this.validators);for(var i in e)this.addValidator(i,e[i].fn,e[i].priority);window.Parsley.trigger("parsley:validator:init")},setLocale:function(e){if("undefined"==typeof this.catalog[e])throw new Error(e+" is not available in the catalog");return this.locale=e,this},addCatalog:function(e,t,i){return"object"==typeof t&&(this.catalog[e]=t),!0===i?this.setLocale(e):this},addMessage:function(e,t,i){return"undefined"==typeof this.catalog[e]&&(this.catalog[e]={}),this.catalog[e][t]=i,this},addMessages:function(e,t){for(var i in t)this.addMessage(e,i,t[i]);return this},addValidator:function(e,t,i){if(this.validators[e])a.warn('Validator "'+e+'" is already defined.');else if(o.hasOwnProperty(e))return void a.warn('"'+e+'" is a restricted keyword and is not a valid validator name.');return this._setValidator.apply(this,arguments)},updateValidator:function(e,t,i){return this.validators[e]?this._setValidator.apply(this,arguments):(a.warn('Validator "'+e+'" is not already defined.'),this.addValidator.apply(this,arguments))},removeValidator:function(e){return this.validators[e]||a.warn('Validator "'+e+'" is not defined.'),delete this.validators[e],this},_setValidator:function(e,t,i){"object"!=typeof t&&(t={fn:t,priority:i}),t.validate||(t=new h(t)),this.validators[e]=t;for(var n in t.messages||{})this.addMessage(n,e,t.messages[n]);return this},getErrorMessage:function(e){var t;if("type"===e.name){var i=this.catalog[this.locale][e.name]||{};t=i[e.requirements]}else t=this.formatMessage(this.catalog[this.locale][e.name],e.requirements);return t||this.catalog[this.locale].defaultMessage||this.catalog.en.defaultMessage},formatMessage:function(e,t){if("object"==typeof t){for(var i in t)e=this.formatMessage(e,t[i]);return e}return"string"==typeof e?e.replace(/%s/i,t):""},validators:{notblank:{validateString:function(e){return/\S/.test(e)},priority:2},required:{validateMultiple:function(e){return e.length>0},validateString:function(e){return/\S/.test(e)},priority:512},type:{validateString:function(e,t){var i=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],n=i.step,r=void 0===n?"any":n,s=i.base,a=void 0===s?0:s,o=c[t];if(!o)throw new Error("validator type `"+t+"` is not supported");if(!o.test(e))return!1;if("number"===t&&!/^any$/i.test(r||"")){var l=Number(e),u=Math.max(f(r),f(a));if(f(l)>u)return!1;var d=function(e){return Math.round(e*Math.pow(10,u))};if((d(l)-d(a))%d(r)!=0)return!1}return!0},requirementType:{"":"string",step:"string",base:"number"},priority:256},pattern:{validateString:function(e,t){return t.test(e)},requirementType:"regexp",priority:64},minlength:{validateString:function(e,t){return e.length>=t},requirementType:"integer",priority:30},maxlength:{validateString:function(e,t){return e.length<=t},requirementType:"integer",priority:30},length:{validateString:function(e,t,i){return e.length>=t&&e.length<=i},requirementType:["integer","integer"],priority:30},mincheck:{validateMultiple:function(e,t){return e.length>=t},requirementType:"integer",priority:30},maxcheck:{validateMultiple:function(e,t){return e.length<=t},requirementType:"integer",priority:30},check:{validateMultiple:function(e,t,i){return e.length>=t&&e.length<=i},requirementType:["integer","integer"],priority:30},min:v(function(e,t){return e>=t}),max:v(function(e,t){return e<=t}),range:v(function(e,t,i){return e>=t&&e<=i}),equalto:{validateString:function(t,i){var n=e(i);return n.length?t===n.val():t===i},priority:256}}};var y={},_=function k(e,t,i){for(var n=[],r=[],s=0;s<e.length;s++){for(var a=!1,o=0;o<t.length;o++)if(e[s].assert.name===t[o].assert.name){a=!0;break}a?r.push(e[s]):n.push(e[s])}return{kept:r,added:n,removed:i?[]:k(t,e,!0).added}};y.Form={_actualizeTriggers:function(){var e=this;this.$element.on("submit.Parsley",function(t){e.onSubmitValidate(t)}),this.$element.on("click.Parsley",a._SubmitSelector,function(t){e.onSubmitButton(t)}),!1!==this.options.uiEnabled&&this.element.setAttribute("novalidate","")},focus:function(){if(this._focusedField=null,!0===this.validationResult||"none"===this.options.focus)return null;for(var e=0;e<this.fields.length;e++){var t=this.fields[e];if(!0!==t.validationResult&&t.validationResult.length>0&&"undefined"==typeof t.options.noFocus&&(this._focusedField=t.$element,"first"===this.options.focus))break}return null===this._focusedField?null:this._focusedField.focus()},_destroyUI:function(){this.$element.off(".Parsley")}},y.Field={_reflowUI:function(){if(this._buildUI(),this._ui){var e=_(this.validationResult,this._ui.lastValidationResult);this._ui.lastValidationResult=this.validationResult,this._manageStatusClass(),this._manageErrorsMessages(e),this._actualizeTriggers(),!e.kept.length&&!e.added.length||this._failedOnce||(this._failedOnce=!0,this._actualizeTriggers())}},getErrorsMessages:function(){if(!0===this.validationResult)return[];for(var e=[],t=0;t<this.validationResult.length;t++)e.push(this.validationResult[t].errorMessage||this._getErrorMessage(this.validationResult[t].assert));return e},addError:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=t.message,n=t.assert,r=t.updateClass,s=void 0===r||r;this._buildUI(),this._addError(e,{message:i,assert:n}),s&&this._errorClass()},updateError:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=t.message,n=t.assert,r=t.updateClass,s=void 0===r||r;this._buildUI(),this._updateError(e,{message:i,assert:n}),s&&this._errorClass()},removeError:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],i=t.updateClass,n=void 0===i||i;this._buildUI(),this._removeError(e),n&&this._manageStatusClass()},_manageStatusClass:function(){this.hasConstraints()&&this.needsValidation()&&!0===this.validationResult?this._successClass():this.validationResult.length>0?this._errorClass():this._resetClass()},_manageErrorsMessages:function(t){if("undefined"==typeof this.options.errorsMessagesDisabled){if("undefined"!=typeof this.options.errorMessage)return t.added.length||t.kept.length?(this._insertErrorWrapper(),0===this._ui.$errorsWrapper.find(".parsley-custom-error-message").length&&this._ui.$errorsWrapper.append(e(this.options.errorTemplate).addClass("parsley-custom-error-message")),this._ui.$errorsWrapper.addClass("filled").find(".parsley-custom-error-message").html(this.options.errorMessage)):this._ui.$errorsWrapper.removeClass("filled").find(".parsley-custom-error-message").remove();for(var i=0;i<t.removed.length;i++)this._removeError(t.removed[i].assert.name);for(i=0;i<t.added.length;i++)this._addError(t.added[i].assert.name,{message:t.added[i].errorMessage,assert:t.added[i].assert});for(i=0;i<t.kept.length;i++)this._updateError(t.kept[i].assert.name,{message:t.kept[i].errorMessage,assert:t.kept[i].assert})}},_addError:function(t,i){var n=i.message,r=i.assert;this._insertErrorWrapper(),this._ui.$errorsWrapper.addClass("filled").append(e(this.options.errorTemplate).addClass("parsley-"+t).html(n||this._getErrorMessage(r)))},_updateError:function(e,t){var i=t.message,n=t.assert;this._ui.$errorsWrapper.addClass("filled").find(".parsley-"+e).html(i||this._getErrorMessage(n))},_removeError:function(e){this._ui.$errorsWrapper.removeClass("filled").find(".parsley-"+e).remove()},_getErrorMessage:function(e){var t=e.name+"Message";return"undefined"!=typeof this.options[t]?window.Parsley.formatMessage(this.options[t],e.requirements):window.Parsley.getErrorMessage(e)},_buildUI:function(){if(!this._ui&&!1!==this.options.uiEnabled){var t={};this.element.setAttribute(this.options.namespace+"id",this.__id__),t.$errorClassHandler=this._manageClassHandler(),t.errorsWrapperId="parsley-id-"+(this.options.multiple?"multiple-"+this.options.multiple:this.__id__),t.$errorsWrapper=e(this.options.errorsWrapper).attr("id",t.errorsWrapperId),t.lastValidationResult=[],t.validationInformationVisible=!1,this._ui=t}},_manageClassHandler:function(){if("string"==typeof this.options.classHandler)return 0===e(this.options.classHandler).length&&ParsleyUtils.warn("No elements found that match the selector `"+this.options.classHandler+"` set in options.classHandler or data-parsley-class-handler"),e(this.options.classHandler);if("function"==typeof this.options.classHandler)var t=this.options.classHandler.call(this,this);return"undefined"!=typeof t&&t.length?t:this._inputHolder()},_inputHolder:function(){return this.options.multiple&&"SELECT"!==this.element.nodeName?this.$element.parent():this.$element},_insertErrorWrapper:function(){var t;if(0!==this._ui.$errorsWrapper.parent().length)return this._ui.$errorsWrapper.parent();if("string"==typeof this.options.errorsContainer){if(e(this.options.errorsContainer).length)return e(this.options.errorsContainer).append(this._ui.$errorsWrapper);a.warn("The errors container `"+this.options.errorsContainer+"` does not exist in DOM")}else"function"==typeof this.options.errorsContainer&&(t=this.options.errorsContainer.call(this,this));return"undefined"!=typeof t&&t.length?t.append(this._ui.$errorsWrapper):this._inputHolder().after(this._ui.$errorsWrapper)},_actualizeTriggers:function(){var e,t=this,i=this._findRelated();i.off(".Parsley"),this._failedOnce?i.on(a.namespaceEvents(this.options.triggerAfterFailure,"Parsley"),function(){t._validateIfNeeded()}):(e=a.namespaceEvents(this.options.trigger,"Parsley"))&&i.on(e,function(e){t._validateIfNeeded(e)})},_validateIfNeeded:function(e){var t=this;e&&/key|input/.test(e.type)&&(!this._ui||!this._ui.validationInformationVisible)&&this.getValue().length<=this.options.validationThreshold||(this.options.debounce?(window.clearTimeout(this._debounced),this._debounced=window.setTimeout(function(){return t.validate()},this.options.debounce)):this.validate())},_resetUI:function(){this._failedOnce=!1,this._actualizeTriggers(),"undefined"!=typeof this._ui&&(this._ui.$errorsWrapper.removeClass("filled").children().remove(),this._resetClass(),this._ui.lastValidationResult=[],this._ui.validationInformationVisible=!1)},_destroyUI:function(){this._resetUI(),"undefined"!=typeof this._ui&&this._ui.$errorsWrapper.remove(),delete this._ui},_successClass:function(){this._ui.validationInformationVisible=!0,this._ui.$errorClassHandler.removeClass(this.options.errorClass).addClass(this.options.successClass)},_errorClass:function(){this._ui.validationInformationVisible=!0,this._ui.$errorClassHandler.removeClass(this.options.successClass).addClass(this.options.errorClass)},_resetClass:function(){this._ui.$errorClassHandler.removeClass(this.options.successClass).removeClass(this.options.errorClass)}};var w=function(t,i,n){this.__class__="Form",this.element=t,this.$element=e(t),this.domOptions=i,this.options=n,this.parent=window.Parsley,this.fields=[],this.validationResult=null},b={pending:null,resolved:!0,rejected:!1};w.prototype={onSubmitValidate:function(e){var t=this;if(!0!==e.parsley){var i=this._submitSource||this.$element.find(a._SubmitSelector)[0];if(this._submitSource=null,this.$element.find(".parsley-synthetic-submit-button").prop("disabled",!0),!i||null===i.getAttribute("formnovalidate")){window.Parsley._remoteCache={};var n=this.whenValidate({event:e});"resolved"===n.state()&&!1!==this._trigger("submit")||(e.stopImmediatePropagation(),e.preventDefault(),"pending"===n.state()&&n.done(function(){t._submit(i)}))}}},onSubmitButton:function(e){this._submitSource=e.currentTarget},_submit:function(t){if(!1!==this._trigger("submit")){if(t){var i=this.$element.find(".parsley-synthetic-submit-button").prop("disabled",!1);0===i.length&&(i=e('<input class="parsley-synthetic-submit-button" type="hidden">').appendTo(this.$element)),i.attr({name:t.getAttribute("name"),value:t.getAttribute("value")})}this.$element.trigger(_extends(e.Event("submit"),{parsley:!0}))}},validate:function(t){if(arguments.length>=1&&!e.isPlainObject(t)){a.warnOnce("Calling validate on a parsley form without passing arguments as an object is deprecated.");var i=_slice.call(arguments),n=i[0],r=i[1],s=i[2];t={group:n,force:r,event:s}}return b[this.whenValidate(t).state()]},whenValidate:function(){var t,i=this,n=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],r=n.group,s=n.force,o=n.event;this.submitEvent=o,o&&(this.submitEvent=_extends({},o,{preventDefault:function(){a.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`"),i.validationResult=!1}})),this.validationResult=!0,this._trigger("validate"),this._refreshFields();var l=this._withoutReactualizingFormOptions(function(){return e.map(i.fields,function(e){return e.whenValidate({force:s,group:r})})});return(t=a.all(l).done(function(){i._trigger("success")}).fail(function(){i.validationResult=!1,i.focus(),i._trigger("error")}).always(function(){i._trigger("validated")})).pipe.apply(t,_toConsumableArray(this._pipeAccordingToValidationResult()))},isValid:function(t){if(arguments.length>=1&&!e.isPlainObject(t)){a.warnOnce("Calling isValid on a parsley form without passing arguments as an object is deprecated.");var i=_slice.call(arguments),n=i[0],r=i[1];t={group:n,force:r}}return b[this.whenValid(t).state()]},whenValid:function(){var t=this,i=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=i.group,r=i.force;this._refreshFields();var s=this._withoutReactualizingFormOptions(function(){return e.map(t.fields,function(e){return e.whenValid({group:n,force:r})})});return a.all(s)},reset:function(){for(var e=0;e<this.fields.length;e++)this.fields[e].reset();this._trigger("reset")},destroy:function(){this._destroyUI();for(var e=0;e<this.fields.length;e++)this.fields[e].destroy();this.$element.removeData("Parsley"),this._trigger("destroy")},_refreshFields:function(){return this.actualizeOptions()._bindFields()},_bindFields:function(){var t=this,i=this.fields;return this.fields=[],this.fieldsMappedById={},this._withoutReactualizingFormOptions(function(){t.$element.find(t.options.inputs).not(t.options.excluded).each(function(e,i){var n=new window.Parsley.Factory(i,{},t);if(("Field"===n.__class__||"FieldMultiple"===n.__class__)&&!0!==n.options.excluded){var r=n.__class__+"-"+n.__id__;"undefined"==typeof t.fieldsMappedById[r]&&(t.fieldsMappedById[r]=n,t.fields.push(n))}}),e.each(a.difference(i,t.fields),function(e,t){t.reset()})}),this},_withoutReactualizingFormOptions:function(e){var t=this.actualizeOptions;this.actualizeOptions=function(){return this};var i=e();return this.actualizeOptions=t,i},_trigger:function(e){return this.trigger("form:"+e)}};var F=function(e,t,i,n,r){var s=window.Parsley._validatorRegistry.validators[t],a=new h(s);n=n||e.options[t+"Priority"]||a.priority,r=!0===r,_extends(this,{validator:a,name:t,requirements:i,priority:n,isDomConstraint:r}),this._parseRequirements(e.options)},C=function(e){var t=e[0].toUpperCase();return t+e.slice(1)};F.prototype={validate:function(e,t){var i;return(i=this.validator).validate.apply(i,[e].concat(_toConsumableArray(this.requirementList),[t]))},_parseRequirements:function(e){var t=this;this.requirementList=this.validator.parseRequirements(this.requirements,function(i){return e[t.name+C(i)]})}};var E=function(t,i,n,r){this.__class__="Field",this.element=t,this.$element=e(t),"undefined"!=typeof r&&(this.parent=r),this.options=n,this.domOptions=i,this.constraints=[],this.constraintsByName={},this.validationResult=!0,this._bindConstraints()},A={pending:null,resolved:!0,rejected:!1};E.prototype={validate:function(t){arguments.length>=1&&!e.isPlainObject(t)&&(a.warnOnce("Calling validate on a parsley field without passing arguments as an object is deprecated."),t={options:t});var i=this.whenValidate(t);if(!i)return!0;switch(i.state()){case"pending":return null;case"resolved":return!0;case"rejected":return this.validationResult}},whenValidate:function(){var e,t=this,i=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=i.force,r=i.group;if(this.refreshConstraints(),!r||this._isInGroup(r))return this.value=this.getValue(),this._trigger("validate"),(e=this.whenValid({force:n,value:this.value,_refreshed:!0}).always(function(){t._reflowUI()}).done(function(){t._trigger("success")}).fail(function(){t._trigger("error")}).always(function(){t._trigger("validated")})).pipe.apply(e,_toConsumableArray(this._pipeAccordingToValidationResult()))},hasConstraints:function(){return 0!==this.constraints.length},needsValidation:function(e){return"undefined"==typeof e&&(e=this.getValue()),!(!e.length&&!this._isRequired()&&"undefined"==typeof this.options.validateIfEmpty)},_isInGroup:function(t){return Array.isArray(this.options.group)?-1!==e.inArray(t,this.options.group):this.options.group===t},isValid:function(t){if(arguments.length>=1&&!e.isPlainObject(t)){a.warnOnce("Calling isValid on a parsley field without passing arguments as an object is deprecated.");var i=_slice.call(arguments),n=i[0],r=i[1];t={force:n,value:r}}var s=this.whenValid(t);return!s||A[s.state()]},whenValid:function(){var t=this,i=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=i.force,r=void 0!==n&&n,s=i.value,o=i.group,l=i._refreshed;if(l||this.refreshConstraints(),!o||this._isInGroup(o)){if(this.validationResult=!0,!this.hasConstraints())return e.when();if("undefined"!=typeof s&&null!==s||(s=this.getValue()),!this.needsValidation(s)&&!0!==r)return e.when();var u=this._getGroupedConstraints(),d=[];return e.each(u,function(i,n){var r=a.all(e.map(n,function(e){return t._validateConstraint(s,e)}));if(d.push(r),"rejected"===r.state())return!1}),a.all(d)}},_validateConstraint:function(t,i){var n=this,r=i.validate(t,this);return!1===r&&(r=e.Deferred().reject()),a.all([r]).fail(function(e){n.validationResult instanceof Array||(n.validationResult=[]),n.validationResult.push({assert:i,errorMessage:"string"==typeof e&&e})})},getValue:function(){var e;return e="function"==typeof this.options.value?this.options.value(this):"undefined"!=typeof this.options.value?this.options.value:this.$element.val(),"undefined"==typeof e||null===e?"":this._handleWhitespace(e)},reset:function(){return this._resetUI(),this._trigger("reset")},destroy:function(){this._destroyUI(),this.$element.removeData("Parsley"),this.$element.removeData("FieldMultiple"),this._trigger("destroy")},refreshConstraints:function(){return this.actualizeOptions()._bindConstraints()},addConstraint:function(e,t,i,n){if(window.Parsley._validatorRegistry.validators[e]){var r=new F(this,e,t,i,n);"undefined"!==this.constraintsByName[r.name]&&this.removeConstraint(r.name),this.constraints.push(r),this.constraintsByName[r.name]=r}return this},removeConstraint:function(e){for(var t=0;t<this.constraints.length;t++)if(e===this.constraints[t].name){this.constraints.splice(t,1);break}return delete this.constraintsByName[e],this},updateConstraint:function(e,t,i){return this.removeConstraint(e).addConstraint(e,t,i)},_bindConstraints:function(){for(var e=[],t={},i=0;i<this.constraints.length;i++)!1===this.constraints[i].isDomConstraint&&(e.push(this.constraints[i]),t[this.constraints[i].name]=this.constraints[i]);this.constraints=e,this.constraintsByName=t;for(var n in this.options)this.addConstraint(n,this.options[n],void 0,!0);return this._bindHtml5Constraints()},_bindHtml5Constraints:function(){null!==this.element.getAttribute("required")&&this.addConstraint("required",!0,void 0,!0),null!==this.element.getAttribute("pattern")&&this.addConstraint("pattern",this.element.getAttribute("pattern"),void 0,!0);var e=this.element.getAttribute("min"),t=this.element.getAttribute("max");null!==e&&null!==t?this.addConstraint("range",[e,t],void 0,!0):null!==e?this.addConstraint("min",e,void 0,!0):null!==t&&this.addConstraint("max",t,void 0,!0),null!==this.element.getAttribute("minlength")&&null!==this.element.getAttribute("maxlength")?this.addConstraint("length",[this.element.getAttribute("minlength"),this.element.getAttribute("maxlength")],void 0,!0):null!==this.element.getAttribute("minlength")?this.addConstraint("minlength",this.element.getAttribute("minlength"),void 0,!0):null!==this.element.getAttribute("maxlength")&&this.addConstraint("maxlength",this.element.getAttribute("maxlength"),void 0,!0);var i=this.element.type;return"number"===i?this.addConstraint("type",["number",{step:this.element.getAttribute("step")||"1",base:e||this.element.getAttribute("value")}],void 0,!0):/^(email|url|range|date)$/i.test(i)?this.addConstraint("type",i,void 0,!0):this},_isRequired:function(){return"undefined"!=typeof this.constraintsByName.required&&!1!==this.constraintsByName.required.requirements},_trigger:function(e){return this.trigger("field:"+e)},_handleWhitespace:function(e){return!0===this.options.trimValue&&a.warnOnce('data-parsley-trim-value="true" is deprecated, please use data-parsley-whitespace="trim"'),"squish"===this.options.whitespace&&(e=e.replace(/\s{2,}/g," ")),"trim"!==this.options.whitespace&&"squish"!==this.options.whitespace&&!0!==this.options.trimValue||(e=a.trimString(e)),e},_isDateInput:function(){var e=this.constraintsByName.type;return e&&"date"===e.requirements},_getGroupedConstraints:function(){if(!1===this.options.priorityEnabled)return[this.constraints];for(var e=[],t={},i=0;i<this.constraints.length;i++){var n=this.constraints[i].priority;t[n]||e.push(t[n]=[]),t[n].push(this.constraints[i])}return e.sort(function(e,t){return t[0].priority-e[0].priority}),e}};var x=E,$=function(){this.__class__="FieldMultiple"};$.prototype={addElement:function(e){return this.$elements.push(e),this},refreshConstraints:function(){var t;if(this.constraints=[],"SELECT"===this.element.nodeName)return this.actualizeOptions()._bindConstraints(),
this;for(var i=0;i<this.$elements.length;i++)if(e("html").has(this.$elements[i]).length){t=this.$elements[i].data("FieldMultiple").refreshConstraints().constraints;for(var n=0;n<t.length;n++)this.addConstraint(t[n].name,t[n].requirements,t[n].priority,t[n].isDomConstraint)}else this.$elements.splice(i,1);return this},getValue:function(){if("function"==typeof this.options.value)return this.options.value(this);if("undefined"!=typeof this.options.value)return this.options.value;if("INPUT"===this.element.nodeName){if("radio"===this.element.type)return this._findRelated().filter(":checked").val()||"";if("checkbox"===this.element.type){var t=[];return this._findRelated().filter(":checked").each(function(){t.push(e(this).val())}),t}}return"SELECT"===this.element.nodeName&&null===this.$element.val()?[]:this.$element.val()},_init:function(){return this.$elements=[this.$element],this}};var P=function(t,i,n){this.element=t,this.$element=e(t);var r=this.$element.data("Parsley");if(r)return"undefined"!=typeof n&&r.parent===window.Parsley&&(r.parent=n,r._resetOptions(r.options)),"object"==typeof i&&_extends(r.options,i),r;if(!this.$element.length)throw new Error("You must bind Parsley on an existing element.");if("undefined"!=typeof n&&"Form"!==n.__class__)throw new Error("Parent instance must be a Form instance");return this.parent=n||window.Parsley,this.init(i)};P.prototype={init:function(e){return this.__class__="Parsley",this.__version__="2.7.2",this.__id__=a.generateID(),this._resetOptions(e),"FORM"===this.element.nodeName||a.checkAttr(this.element,this.options.namespace,"validate")&&!this.$element.is(this.options.inputs)?this.bind("parsleyForm"):this.isMultiple()?this.handleMultiple():this.bind("parsleyField")},isMultiple:function(){return"radio"===this.element.type||"checkbox"===this.element.type||"SELECT"===this.element.nodeName&&null!==this.element.getAttribute("multiple")},handleMultiple:function(){var t,i,n=this;if(this.options.multiple=this.options.multiple||(t=this.element.getAttribute("name"))||this.element.getAttribute("id"),"SELECT"===this.element.nodeName&&null!==this.element.getAttribute("multiple"))return this.options.multiple=this.options.multiple||this.__id__,this.bind("parsleyFieldMultiple");if(!this.options.multiple)return a.warn("To be bound by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.",this.$element),this;this.options.multiple=this.options.multiple.replace(/(:|\.|\[|\]|\{|\}|\$)/g,""),t&&e('input[name="'+t+'"]').each(function(e,t){"radio"!==t.type&&"checkbox"!==t.type||t.setAttribute(n.options.namespace+"multiple",n.options.multiple)});for(var r=this._findRelated(),s=0;s<r.length;s++)if(i=e(r.get(s)).data("Parsley"),"undefined"!=typeof i){this.$element.data("FieldMultiple")||i.addElement(this.$element);break}return this.bind("parsleyField",!0),i||this.bind("parsleyFieldMultiple")},bind:function(t,i){var n;switch(t){case"parsleyForm":n=e.extend(new w(this.element,this.domOptions,this.options),new l,window.ParsleyExtend)._bindFields();break;case"parsleyField":n=e.extend(new x(this.element,this.domOptions,this.options,this.parent),new l,window.ParsleyExtend);break;case"parsleyFieldMultiple":n=e.extend(new x(this.element,this.domOptions,this.options,this.parent),new $,new l,window.ParsleyExtend)._init();break;default:throw new Error(t+"is not a supported Parsley type")}return this.options.multiple&&a.setAttr(this.element,this.options.namespace,"multiple",this.options.multiple),"undefined"!=typeof i?(this.$element.data("FieldMultiple",n),n):(this.$element.data("Parsley",n),n._actualizeTriggers(),n._trigger("init"),n)}};var V=e.fn.jquery.split(".");if(parseInt(V[0])<=1&&parseInt(V[1])<8)throw"The loaded version of jQuery is too old. Please upgrade to 1.8.x or better.";V.forEach||a.warn("Parsley requires ES5 to run properly. Please include https://github.com/es-shims/es5-shim");var O=_extends(new l,{element:document,$element:e(document),actualizeOptions:null,_resetOptions:null,Factory:P,version:"2.7.2"});_extends(x.prototype,y.Field,l.prototype),_extends(w.prototype,y.Form,l.prototype),_extends(P.prototype,l.prototype),e.fn.parsley=e.fn.psly=function(t){if(this.length>1){var i=[];return this.each(function(){i.push(e(this).parsley(t))}),i}return e(this).length?new P(this[0],t):void a.warn("You must bind Parsley on an existing element.")},"undefined"==typeof window.ParsleyExtend&&(window.ParsleyExtend={}),O.options=_extends(a.objectCreate(o),window.ParsleyConfig),window.ParsleyConfig=O.options,window.Parsley=window.psly=O,O.Utils=a,window.ParsleyUtils={},e.each(a,function(e,t){"function"==typeof t&&(window.ParsleyUtils[e]=function(){return a.warnOnce("Accessing `window.ParsleyUtils` is deprecated. Use `window.Parsley.Utils` instead."),a[e].apply(a,arguments)})});var M=window.Parsley._validatorRegistry=new p(window.ParsleyConfig.validators,window.ParsleyConfig.i18n);window.ParsleyValidator={},e.each("setLocale addCatalog addMessage addMessages getErrorMessage formatMessage addValidator updateValidator removeValidator".split(" "),function(e,t){window.Parsley[t]=function(){return M[t].apply(M,arguments)},window.ParsleyValidator[t]=function(){var e;return a.warnOnce("Accessing the method '"+t+"' through Validator is deprecated. Simply call 'window.Parsley."+t+"(...)'"),(e=window.Parsley)[t].apply(e,arguments)}}),window.Parsley.UI=y,window.ParsleyUI={removeError:function(e,t,i){var n=!0!==i;return a.warnOnce("Accessing UI is deprecated. Call 'removeError' on the instance directly. Please comment in issue 1073 as to your need to call this method."),e.removeError(t,{updateClass:n})},getErrorsMessages:function(e){return a.warnOnce("Accessing UI is deprecated. Call 'getErrorsMessages' on the instance directly."),e.getErrorsMessages()}},e.each("addError updateError".split(" "),function(e,t){window.ParsleyUI[t]=function(e,i,n,r,s){var o=!0!==s;return a.warnOnce("Accessing UI is deprecated. Call '"+t+"' on the instance directly. Please comment in issue 1073 as to your need to call this method."),e[t](i,{message:n,assert:r,updateClass:o})}}),!1!==window.ParsleyConfig.autoBind&&e(function(){e("[data-parsley-validate]").length&&e("[data-parsley-validate]").parsley()});var T=e({}),R=function(){a.warnOnce("Parsley's pubsub module is deprecated; use the 'on' and 'off' methods on parsley instances or window.Parsley")},D="parsley:";e.listen=function(e,n){var r;if(R(),"object"==typeof arguments[1]&&"function"==typeof arguments[2]&&(r=arguments[1],n=arguments[2]),"function"!=typeof n)throw new Error("Wrong parameters");window.Parsley.on(i(e),t(n,r))},e.listenTo=function(e,n,r){if(R(),!(e instanceof x||e instanceof w))throw new Error("Must give Parsley instance");if("string"!=typeof n||"function"!=typeof r)throw new Error("Wrong parameters");e.on(i(n),t(r))},e.unsubscribe=function(e,t){if(R(),"string"!=typeof e||"function"!=typeof t)throw new Error("Wrong arguments");window.Parsley.off(i(e),t.parsleyAdaptedCallback)},e.unsubscribeTo=function(e,t){if(R(),!(e instanceof x||e instanceof w))throw new Error("Must give Parsley instance");e.off(i(t))},e.unsubscribeAll=function(t){R(),window.Parsley.off(i(t)),e("form,input,textarea,select").each(function(){var n=e(this).data("Parsley");n&&n.off(i(t))})},e.emit=function(e,t){var n;R();var r=t instanceof x||t instanceof w,s=Array.prototype.slice.call(arguments,r?2:1);s.unshift(i(e)),r||(t=window.Parsley),(n=t).trigger.apply(n,_toConsumableArray(s))};e.extend(!0,O,{asyncValidators:{"default":{fn:function(e){return e.status>=200&&e.status<300},url:!1},reverse:{fn:function(e){return e.status<200||e.status>=300},url:!1}},addAsyncValidator:function(e,t,i,n){return O.asyncValidators[e]={fn:t,url:i||!1,options:n||{}},this}}),O.addValidator("remote",{requirementType:{"":"string",validator:"string",reverse:"boolean",options:"object"},validateString:function(t,i,n,r){var s,a,o={},l=n.validator||(!0===n.reverse?"reverse":"default");if("undefined"==typeof O.asyncValidators[l])throw new Error("Calling an undefined async validator: `"+l+"`");i=O.asyncValidators[l].url||i,i.indexOf("{value}")>-1?i=i.replace("{value}",encodeURIComponent(t)):o[r.element.getAttribute("name")||r.element.getAttribute("id")]=t;var u=e.extend(!0,n.options||{},O.asyncValidators[l].options);s=e.extend(!0,{},{url:i,data:o,type:"GET"},u),r.trigger("field:ajaxoptions",r,s),a=e.param(s),"undefined"==typeof O._remoteCache&&(O._remoteCache={});var d=O._remoteCache[a]=O._remoteCache[a]||e.ajax(s),h=function(){var t=O.asyncValidators[l].fn.call(r,d,i,n);return t||(t=e.Deferred().reject()),e.when(t)};return d.then(h,h)},priority:-1}),O.on("form:submit",function(){O._remoteCache={}}),l.prototype.addAsyncValidator=function(){return a.warnOnce("Accessing the method `addAsyncValidator` through an instance is deprecated. Simply call `Parsley.addAsyncValidator(...)`"),O.addAsyncValidator.apply(O,arguments)},O.addMessages("en",{defaultMessage:"This value seems to be invalid.",type:{email:"This value should be a valid email.",url:"This value should be a valid url.",number:"This value should be a valid number.",integer:"This value should be a valid integer.",digits:"This value should be digits.",alphanum:"This value should be alphanumeric."},notblank:"This value should not be blank.",required:"This value is required.",pattern:"This value seems to be invalid.",min:"This value should be greater than or equal to %s.",max:"This value should be lower than or equal to %s.",range:"This value should be between %s and %s.",minlength:"This value is too short. It should have %s characters or more.",maxlength:"This value is too long. It should have %s characters or fewer.",length:"This value length is invalid. It should be between %s and %s characters long.",mincheck:"You must select at least %s choices.",maxcheck:"You must select %s choices or fewer.",check:"You must select between %s and %s choices.",equalto:"This value should be the same."}),O.setLocale("en");var I=new n;I.install();var q=O;return q});
jQuery(document).ready(function(e){function a(e,a){l(e,a),e.find(a.container).first().show()}function n(a,n){if(n.tabs){var t=e("<div />",{"class":n.tabMenuClassName}).insertBefore(a.children(n.container).filter(":first"));a.children(n.container).each(function(i,r){var l=e("<button/>").html(e(this).children(n.header).html()).addClass(0==i?n.tabMenuItemActiveClassName:"").addClass("item"+i).addClass("btn btn-default").prop("type","button").on("click keypress",{container:a.children(n.container),fieldset:e(r)},function(){var t=e(this),i=t.parent().children().index(t);s(a,n,t,i)});n.tabIndex&&l.prop("tabindex",i),t.append(l)})}}function t(a,n){n.navigation&&a.children(n.container).each(function(t){var i=e("<div />").addClass("powermail_fieldwrap").addClass("powermail_tab_navigation").appendTo(e(this));t>0&&i.append(c(a,n)),t<a.children(n.container).length-1&&i.append(o(a,n))})}function i(a,n){e.fn.parsley&&"data-parsley-validate"===a.data("parsley-validate")&&a.parsley().subscribe("parsley:field:validated",function(){v(a,n),C(a,n)})}function r(a,n){n.openTabOnError&&e.fn.parsley&&e.listen("parsley:field:error",function(){setTimeout(function(){a.find("."+n.tabMenuClassName+" > ."+n.tabMenuItemErrorClassName+":first").click()},50)})}function s(a,n,t,i){$activeTab=b(a,n),$activeTab.removeClass(n.tabMenuItemActiveClassName),t.addClass(n.tabMenuItemActiveClassName),l(a,n),e(".powermail_fieldset",a).slice(i,i+1).show()}function l(e,a){e.children(a.container).hide()}function c(a,n){return e("<a />").prop("href","#").addClass("btn btn-warning").html("<").click(function(e){e.preventDefault(),u(a,n)})}function o(a,n){return e("<a />").prop("href","#").addClass("btn btn-primary pull-right").html(">").click(function(e){e.preventDefault(),d(a,n)})}function d(e,a){var n=m(e,a);$activeTab=b(e,a),$activeTab.removeClass(a.tabMenuItemActiveClassName).next().addClass(a.tabMenuItemActiveClassName),f(e,a,n+1)}function u(e,a){var n=m(e,a);$activeTab=b(e,a),$activeTab.removeClass(a.tabMenuItemActiveClassName).prev().addClass(a.tabMenuItemActiveClassName),f(e,a,n-1)}function f(e,a,n){l(e,a),e.find(".powermail_fieldset").slice(n,n+1).show()}function m(e,a){var n=p(e,a),t=n.index(b(e,a));return parseInt(t)}function p(e,a){return e.find("."+a.tabMenuClassName).children()}function b(e,a){var n=p(e,a);return n.filter("."+a.tabMenuItemActiveClassName)}function v(e,a){var n=p(e,a);n.removeClass(a.tabMenuItemErrorClassName)}function C(a,n){a.parsley().isValid()||a.find(".parsley-error").each(function(){var t=a.find(".powermail_fieldset").index(e(this).closest(".powermail_fieldset")),i=p(a,n),r=i.slice(t,t+1);r.addClass(n.tabMenuItemErrorClassName)})}e.fn.powermailTabs=function(e){"use strict";var s=jQuery(this);e=jQuery.extend({container:"fieldset",header:"legend",tabs:!0,navigation:!0,openTabOnError:!0,tabIndex:!0,tabMenuClassName:"btn-group",tabMenuItemActiveClassName:"btn-primary",tabMenuItemErrorClassName:"btn-danger"},e),a(s,e),n(s,e),t(s,e),i(s,e),r(s,e)}});
function PowermailForm(e){"use strict";this.initialize=function(){t(),a(),i(),r(),o(),n(),f(),l()};var t=function(){e.fn.powermailTabs&&e(".powermail_morestep").each(function(){e(this).powermailTabs()})},a=function(){e("form[data-powermail-ajax]").length&&p()},i=function(){if(e('*[data-powermail-location="prefill"]').length&&navigator.geolocation){e(this);navigator.geolocation.getCurrentPosition(function(t){var a=t.coords.latitude,i=t.coords.longitude,r=C()+"/index.php?eID=powermailEidGetLocation";jQuery.ajax({url:r,data:"lat="+a+"&lng="+i,cache:!1,success:function(t){t&&e('*[data-powermail-location="prefill"]').val(t)}})})}},r=function(){e.fn.datetimepicker&&e(".powermail_date").each(function(){var t=e(this);if("date"===t.prop("type")||"datetime-local"===t.prop("type")||"time"===t.prop("type")){if(!t.data("datepicker-force")){if(e(this).data("date-value")){var a=g(e(this).data("date-value"),e(this).data("datepicker-format"),t.prop("type"));null!==a&&e(this).val(a)}return}t.prop("type","text")}var i=!0,r=!0;"date"===t.data("datepicker-settings")?r=!1:"time"===t.data("datepicker-settings")&&(i=!1),t.datetimepicker({format:t.data("datepicker-format"),timepicker:r,datepicker:i,lang:"en",i18n:{en:{months:t.data("datepicker-months").split(","),dayOfWeek:t.data("datepicker-days").split(",")}}})})},o=function(){e(".powermail_all_type_password.powermail_all_value").html("********")},n=function(){e.fn.parsley&&e(".powermail_reset").on("click","",function(){e('form[data-parsley-validate="data-parsley-validate"]').parsley().reset()})},l=function(){window.Parsley&&(x(),b())},p=function(){var t,a=!1;e(document).on("submit","form[data-powermail-ajax]",function(i){var r=e(this),o=r.closest(".tx-powermail");r.data("powermail-ajax-uri")&&(t=r.data("powermail-ajax-uri"));var n=r.data("powermail-form");a||(e.ajax({type:"POST",url:r.prop("action"),data:new FormData(r.get(0)),contentType:!1,processData:!1,beforeSend:function(){s(r)},complete:function(){d(r),f(),c(o)},success:function(i){var o=e('*[data-powermail-form="'+n+'"]:first',i);o.length?(e('*[data-powermail-form="'+n+'"]:first').closest(".tx-powermail").html(o),e.fn.powermailTabs&&e(".powermail_morestep").powermailTabs(),e.fn.parsley&&e('form[data-parsley-validate="data-parsley-validate"]').parsley(),w()):(t?D(t):r.submit(),a=!0)}}),i.preventDefault())})},s=function(t){d(t),e(".powermail_submit",t).length?e(".powermail_submit",t).parent().append(y()):t.closest(".tx-powermail").append(y())},d=function(e){e.closest(".tx-powermail").find(".powermail_progressbar").remove()},c=function(t){var a=e.Event("submitted.powermail.form");t.trigger(a)},f=function(){e(".powermail_fieldwrap_file").find(".deleteAllFiles").each(function(){u(e(this).closest(".powermail_fieldwrap_file").find('input[type="file"]'))}),e(".deleteAllFiles").click(function(){m(e(this).closest(".powermail_fieldwrap_file").find('input[type="hidden"]')),e(this).closest("ul").fadeOut(function(){e(this).remove()})})},u=function(e){e.prop("disabled","disabled").addClass("hide").prop("type","hidden")},m=function(e){e.prop("disabled",!1).removeClass("hide").prop("type","file")},w=function(){e("img.powermail_captchaimage").each(function(){var t=h(e(this).prop("src"));e(this).prop("src",t+"?hash="+v(5))})},h=function(e){var t=e.split("?");return t[0]},v=function(e){for(var t="",a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",i=0;i<e;i++)t+=a.charAt(Math.floor(Math.random()*a.length));return t},g=function(e,t,a){var i=Date.parseDate(e,t);if(null===i)return null;var r=new Date(i),o=r.getFullYear()+"-";o+=("0"+(r.getMonth()+1)).slice(-2)+"-",o+=("0"+r.getDate()).slice(-2);var n=("0"+r.getHours()).slice(-2)+":"+("0"+r.getMinutes()).slice(-2),l=o+"T"+n;return"date"===a?o:"datetime-local"===a?l:"time"===a?n:null},y=function(){return e("<div />").addClass("powermail_progressbar").html(e("<div />").addClass("powermail_progress").html(e("<div />").addClass("powermail_progess_inner")))},_=function(e){for(var t=e.get(0),a=0,i=0;i<t.files.length;i++){var r=t.files[i];r.size>a&&(a=r.size)}return parseInt(a)},x=function(){window.Parsley.addValidator("powermailfilesize",function(t,a){if(a.indexOf(",")!==-1){var i=a.split(","),r=parseInt(i[0]),o=e('*[name="tx_powermail_pi1[field]['+i[1]+'][]"]');if(o.length&&_(o)>r)return!1}return!0},32).addMessage("en","powermailfilesize","Error")},b=function(){window.Parsley.addValidator("powermailfileextensions",function(t,a){var i=e('*[name="tx_powermail_pi1[field]['+a+'][]"]');return!i.length||k(j(t),i.prop("accept"))},32).addMessage("en","powermailfileextensions","Error")},k=function(e,t){return t.indexOf("."+e)!==-1},j=function(e){return e.split(".").pop().toLowerCase()},D=function(e){e.indexOf("http")!==-1?window.location=e:window.location.pathname=e},C=function(){var t;return t=e("base").length>0?jQuery("base").prop("href"):"https:"!=window.location.protocol?"http://"+window.location.hostname:"https://"+window.location.hostname}}jQuery(document).ready(function(e){"use strict";var t=new window.PowermailForm(e);t.initialize()});
/*! Picturefill - v2.1.0 - 2014-07-25
* http://scottjehl.github.io/picturefill
* Copyright (c) 2014 https://github.com/scottjehl/picturefill/blob/master/Authors.txt; Licensed MIT */
window.matchMedia||(window.matchMedia=function(){"use strict";var a=window.styleMedia||window.media;if(!a){var b=document.createElement("style"),c=document.getElementsByTagName("script")[0],d=null;b.type="text/css",b.id="matchmediajs-test",c.parentNode.insertBefore(b,c),d="getComputedStyle"in window&&window.getComputedStyle(b,null)||b.currentStyle,a={matchMedium:function(a){var c="@media "+a+"{ #matchmediajs-test { width: 1px; } }";return b.styleSheet?b.styleSheet.cssText=c:b.textContent=c,"1px"===d.width}}}return function(b){return{matches:a.matchMedium(b||"all"),media:b||"all"}}}()),function(a,b){"use strict";function c(a){var b,c,d,f,g,h=a||{};b=h.elements||e.getAllElements();for(var i=0,j=b.length;j>i;i++)if(c=b[i],d=c.parentNode,f=void 0,g=void 0,c[e.ns]||(c[e.ns]={}),h.reevaluate||!c[e.ns].evaluated){if("PICTURE"===d.nodeName.toUpperCase()){if(e.removeVideoShim(d),f=e.getMatch(c,d),f===!1)continue}else f=void 0;("PICTURE"===d.nodeName.toUpperCase()||c.srcset&&!e.srcsetSupported||!e.sizesSupported&&c.srcset&&c.srcset.indexOf("w")>-1)&&e.dodgeSrcset(c),f?(g=e.processSourceSet(f),e.applyBestCandidate(g,c)):(g=e.processSourceSet(c),(void 0===c.srcset||c[e.ns].srcset)&&e.applyBestCandidate(g,c)),c[e.ns].evaluated=!0}}function d(){c();var d=setInterval(function(){return c(),/^loaded|^i|^c/.test(b.readyState)?void clearInterval(d):void 0},250);if(a.addEventListener){var e;a.addEventListener("resize",function(){a._picturefillWorking||(a._picturefillWorking=!0,a.clearTimeout(e),e=a.setTimeout(function(){c({reevaluate:!0}),a._picturefillWorking=!1},60))},!1)}}if(a.HTMLPictureElement)return void(a.picturefill=function(){});b.createElement("picture");var e={};e.ns="picturefill",e.srcsetSupported="srcset"in b.createElement("img"),e.sizesSupported=a.HTMLImageElement.sizes,e.trim=function(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")},e.endsWith=function(a,b){return a.endsWith?a.endsWith(b):-1!==a.indexOf(b,a.length-b.length)},e.matchesMedia=function(b){return a.matchMedia&&a.matchMedia(b).matches},e.getDpr=function(){return a.devicePixelRatio||1},e.getWidthFromLength=function(a){return a=a&&(parseFloat(a)>0||a.indexOf("calc(")>-1)?a:"100vw",a=a.replace("vw","%"),e.lengthEl||(e.lengthEl=b.createElement("div"),b.documentElement.insertBefore(e.lengthEl,b.documentElement.firstChild)),e.lengthEl.style.cssText="position: absolute; left: 0; width: "+a+";",e.lengthEl.offsetWidth<=0&&(e.lengthEl.style.cssText="width: 100%;"),e.lengthEl.offsetWidth},e.types={},e.types["image/jpeg"]=!0,e.types["image/gif"]=!0,e.types["image/png"]=!0,e.types["image/svg+xml"]=b.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image","1.1"),e.types["image/webp"]=function(){var b=new a.Image,d="image/webp";b.onerror=function(){e.types[d]=!1,c()},b.onload=function(){e.types[d]=1===b.width,c()},b.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="},e.verifyTypeSupport=function(a){var b=a.getAttribute("type");return null===b||""===b?!0:"function"==typeof e.types[b]?(e.types[b](),"pending"):e.types[b]},e.parseSize=function(a){var b=/(\([^)]+\))?\s*(.+)/g.exec(a);return{media:b&&b[1],length:b&&b[2]}},e.findWidthFromSourceSize=function(a){for(var b,c=e.trim(a).split(/\s*,\s*/),d=0,f=c.length;f>d;d++){var g=c[d],h=e.parseSize(g),i=h.length,j=h.media;if(i&&(!j||e.matchesMedia(j))){b=i;break}}return e.getWidthFromLength(b)},e.parseSrcset=function(a){for(var b=[];""!==a;){a=a.replace(/^\s+/g,"");var c,d=a.search(/\s/g),e=null;if(-1!==d){c=a.slice(0,d);var f=c[c.length-1];if((","===f||""===c)&&(c=c.replace(/,+$/,""),e=""),a=a.slice(d+1),null===e){var g=a.indexOf(",");-1!==g?(e=a.slice(0,g),a=a.slice(g+1)):(e=a,a="")}}else c=a,a="";(c||e)&&b.push({url:c,descriptor:e})}return b},e.parseDescriptor=function(a,b){var c,d=b||"100vw",f=a&&a.replace(/(^\s+|\s+$)/g,""),g=e.findWidthFromSourceSize(d);if(f)for(var h=f.split(" "),i=h.length+1;i>=0;i--)if(void 0!==h[i]){var j=h[i],k=j&&j.slice(j.length-1);if("h"!==k&&"w"!==k||e.sizesSupported){if("x"===k){var l=j&&parseFloat(j,10);c=l&&!isNaN(l)?l:1}}else c=parseFloat(parseInt(j,10)/g)}return c||1},e.getCandidatesFromSourceSet=function(a,b){for(var c=e.parseSrcset(a),d=[],f=0,g=c.length;g>f;f++){var h=c[f];d.push({url:h.url,resolution:e.parseDescriptor(h.descriptor,b)})}return d},e.dodgeSrcset=function(a){a.srcset&&(a[e.ns].srcset=a.srcset,a.removeAttribute("srcset"))},e.processSourceSet=function(a){var b=a.getAttribute("srcset"),c=a.getAttribute("sizes"),d=[];return"IMG"===a.nodeName.toUpperCase()&&a[e.ns]&&a[e.ns].srcset&&(b=a[e.ns].srcset),b&&(d=e.getCandidatesFromSourceSet(b,c)),d},e.applyBestCandidate=function(a,b){var c,d,f;a.sort(e.ascendingSort),d=a.length,f=a[d-1];for(var g=0;d>g;g++)if(c=a[g],c.resolution>=e.getDpr()){f=c;break}f&&!e.endsWith(b.src,f.url)&&(b.src=f.url,b.currentSrc=b.src)},e.ascendingSort=function(a,b){return a.resolution-b.resolution},e.removeVideoShim=function(a){var b=a.getElementsByTagName("video");if(b.length){for(var c=b[0],d=c.getElementsByTagName("source");d.length;)a.insertBefore(d[0],c);c.parentNode.removeChild(c)}},e.getAllElements=function(){for(var a=[],c=b.getElementsByTagName("img"),d=0,f=c.length;f>d;d++){var g=c[d];("PICTURE"===g.parentNode.nodeName.toUpperCase()||null!==g.getAttribute("srcset")||g[e.ns]&&null!==g[e.ns].srcset)&&a.push(g)}return a},e.getMatch=function(a,b){for(var c,d=b.childNodes,f=0,g=d.length;g>f;f++){var h=d[f];if(1===h.nodeType){if(h===a)return c;if("SOURCE"===h.nodeName.toUpperCase()){null!==h.getAttribute("src")&&void 0!==typeof console&&console.warn("The `src` attribute is invalid on `picture` `source` element; instead, use `srcset`.");var i=h.getAttribute("media");if(h.getAttribute("srcset")&&(!i||e.matchesMedia(i))){var j=e.verifyTypeSupport(h);if(j===!0){c=h;break}if("pending"===j)return!1}}}}return c},d(),c._=e,"object"==typeof module&&"object"==typeof module.exports?module.exports=c:"function"==typeof define&&define.amd?define(function(){return c}):"object"==typeof a&&(a.picturefill=c)}(this,this.document);

/* HTML5 Placeholder jQuery Plugin - v2.1.2
 * Copyright (c)2015 Mathias Bynens
 * 2015-06-09
 */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof module&&module.exports?require("jquery"):jQuery)}(function(a){function b(b){var c={},d=/^jQuery\d+$/;return a.each(b.attributes,function(a,b){b.specified&&!d.test(b.name)&&(c[b.name]=b.value)}),c}function c(b,c){var d=this,f=a(d);if(d.value==f.attr("placeholder")&&f.hasClass(m.customClass))if(f.data("placeholder-password")){if(f=f.hide().nextAll('input[type="password"]:first').show().attr("id",f.removeAttr("id").data("placeholder-id")),b===!0)return f[0].value=c;f.focus()}else d.value="",f.removeClass(m.customClass),d==e()&&d.select()}function d(){var d,e=this,f=a(e),g=this.id;if(""===e.value){if("password"===e.type){if(!f.data("placeholder-textinput")){try{d=f.clone().prop({type:"text"})}catch(h){d=a("<input>").attr(a.extend(b(this),{type:"text"}))}d.removeAttr("name").data({"placeholder-password":f,"placeholder-id":g}).bind("focus.placeholder",c),f.data({"placeholder-textinput":d,"placeholder-id":g}).before(d)}f=f.removeAttr("id").hide().prevAll('input[type="text"]:first').attr("id",g).show()}f.addClass(m.customClass),f[0].value=f.attr("placeholder")}else f.removeClass(m.customClass)}function e(){try{return document.activeElement}catch(a){}}var f,g,h="[object OperaMini]"==Object.prototype.toString.call(window.operamini),i="placeholder"in document.createElement("input")&&!h,j="placeholder"in document.createElement("textarea")&&!h,k=a.valHooks,l=a.propHooks;if(i&&j)g=a.fn.placeholder=function(){return this},g.input=g.textarea=!0;else{var m={};g=a.fn.placeholder=function(b){var e={customClass:"placeholder"};m=a.extend({},e,b);var f=this;return f.filter((i?"textarea":":input")+"[placeholder]").not("."+m.customClass).bind({"focus.placeholder":c,"blur.placeholder":d}).data("placeholder-enabled",!0).trigger("blur.placeholder"),f},g.input=i,g.textarea=j,f={get:function(b){var c=a(b),d=c.data("placeholder-password");return d?d[0].value:c.data("placeholder-enabled")&&c.hasClass(m.customClass)?"":b.value},set:function(b,f){var g=a(b),h=g.data("placeholder-password");return h?h[0].value=f:g.data("placeholder-enabled")?(""===f?(b.value=f,b!=e()&&d.call(b)):g.hasClass(m.customClass)?c.call(b,!0,f)||(b.value=f):b.value=f,g):b.value=f}},i||(k.input=f,l.value=f),j||(k.textarea=f,l.value=f),a(function(){a(document).delegate("form","submit.placeholder",function(){var b=a("."+m.customClass,this).each(c);setTimeout(function(){b.each(d)},10)})}),a(window).bind("beforeunload.placeholder",function(){a("."+m.customClass).each(function(){this.value=""})})}});
/*! Idle Timer v1.0.1 2014-03-21 | https://github.com/thorst/jquery-idletimer | (c) 2014 Paul Irish | Licensed MIT */
!function(a){a.idleTimer=function(b,c){var d;"object"==typeof b?(d=b,b=null):"number"==typeof b&&(d={timeout:b},b=null),c=c||document,d=a.extend({idle:!1,timeout:3e4,events:"mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove"},d);var e=a(c),f=e.data("idleTimerObj")||{},g=function(b){var d=a.data(c,"idleTimerObj")||{};d.idle=!d.idle,d.olddate=+new Date;var e=a.Event((d.idle?"idle":"active")+".idleTimer");a(c).trigger(e,[c,a.extend({},d),b])},h=function(b){var d=a.data(c,"idleTimerObj")||{};if(null==d.remaining){if("mousemove"===b.type){if(b.pageX===d.pageX&&b.pageY===d.pageY)return;if("undefined"==typeof b.pageX&&"undefined"==typeof b.pageY)return;var e=+new Date-d.olddate;if(200>e)return}clearTimeout(d.tId),d.idle&&g(b),d.lastActive=+new Date,d.pageX=b.pageX,d.pageY=b.pageY,d.tId=setTimeout(g,d.timeout)}},i=function(){var b=a.data(c,"idleTimerObj")||{};b.idle=b.idleBackup,b.olddate=+new Date,b.lastActive=b.olddate,b.remaining=null,clearTimeout(b.tId),b.idle||(b.tId=setTimeout(g,b.timeout))},j=function(){var b=a.data(c,"idleTimerObj")||{};null==b.remaining&&(b.remaining=b.timeout-(+new Date-b.olddate),clearTimeout(b.tId))},k=function(){var b=a.data(c,"idleTimerObj")||{};null!=b.remaining&&(b.idle||(b.tId=setTimeout(g,b.remaining)),b.remaining=null)},l=function(){var b=a.data(c,"idleTimerObj")||{};clearTimeout(b.tId),e.removeData("idleTimerObj"),e.off("._idleTimer")},m=function(){var b=a.data(c,"idleTimerObj")||{};if(b.idle)return 0;if(null!=b.remaining)return b.remaining;var d=b.timeout-(+new Date-b.lastActive);return 0>d&&(d=0),d};if(null===b&&"undefined"!=typeof f.idle)return i(),e;if(null===b);else{if(null!==b&&"undefined"==typeof f.idle)return!1;if("destroy"===b)return l(),e;if("pause"===b)return j(),e;if("resume"===b)return k(),e;if("reset"===b)return i(),e;if("getRemainingTime"===b)return m();if("getElapsedTime"===b)return+new Date-f.olddate;if("getLastActiveTime"===b)return f.lastActive;if("isIdle"===b)return f.idle}return e.on(a.trim((d.events+" ").split(" ").join("._idleTimer ")),function(a){h(a)}),f=a.extend({},{olddate:+new Date,lastActive:+new Date,idle:d.idle,idleBackup:d.idle,timeout:d.timeout,remaining:null,tId:null,pageX:null,pageY:null}),f.idle||(f.tId=setTimeout(g,f.timeout)),a.data(c,"idleTimerObj",f),e},a.fn.idleTimer=function(b){return this[0]?a.idleTimer(b,this[0]):this}}(jQuery);

/*
 * Lazy Load - jQuery plugin for lazy loading images
 *
 * Copyright (c) 2007-2013 Mika Tuupola
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Project home:
 *   http://www.appelsiini.net/projects/lazyload
 *
 * Version:  1.9.3
 *
 */

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

    $.fn.lazyload = function(options) {
        var elements = this;
        var $container;
        var settings = {
            threshold       : 0,
            failure_limit   : 0,
            event           : "scroll",
            effect          : "show",
            container       : window,
            data_attribute  : "original",
            skip_invisible  : true,
            appear          : null,
            load            : null,
            placeholder     : "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC"
        };

        function update() {
            var counter = 0;

            elements.each(function() {
                var $this = $(this);
                if (settings.skip_invisible && !$this.is(":visible")) {
                    return;
                }
                if ($.abovethetop(this, settings) ||
                    $.leftofbegin(this, settings)) {
                        /* Nothing. */
                } else if (!$.belowthefold(this, settings) &&
                    !$.rightoffold(this, settings)) {
                        $this.trigger("appear");
                        /* if we found an image we'll load, reset the counter */
                        counter = 0;
                } else {
                    if (++counter > settings.failure_limit) {
                        return false;
                    }
                }
            });

        }

        if(options) {
            /* Maintain BC for a couple of versions. */
            if (undefined !== options.failurelimit) {
                options.failure_limit = options.failurelimit;
                delete options.failurelimit;
            }
            if (undefined !== options.effectspeed) {
                options.effect_speed = options.effectspeed;
                delete options.effectspeed;
            }

            $.extend(settings, options);
        }

        /* Cache container as jQuery as object. */
        $container = (settings.container === undefined ||
                      settings.container === window) ? $window : $(settings.container);

        /* Fire one scroll event per scroll. Not one scroll event per image. */
        if (0 === settings.event.indexOf("scroll")) {
            $container.bind(settings.event, function() {
                return update();
            });
        }

        this.each(function() {
            var self = this;
            var $self = $(self);

            self.loaded = false;

            /* If no src attribute given use data:uri. */
            if ($self.attr("src") === undefined || $self.attr("src") === false) {
                if ($self.is("img")) {
                    $self.attr("src", settings.placeholder);
                }
            }

            /* When appear is triggered load original image. */
            $self.one("appear", function() {
                if (!this.loaded) {
                    if (settings.appear) {
                        var elements_left = elements.length;
                        settings.appear.call(self, elements_left, settings);
                    }
                    $("<img />")
                        .bind("load", function() {

                            var original = $self.attr("data-" + settings.data_attribute);
                            $self.hide();
                            if ($self.is("img")) {
                                $self.attr("src", original);
                            } else {
                                $self.css("background-image", "url('" + original + "')");
                            }
                            $self[settings.effect](settings.effect_speed);

                            self.loaded = true;

                            /* Remove image from array so it is not looped next time. */
                            var temp = $.grep(elements, function(element) {
                                return !element.loaded;
                            });
                            elements = $(temp);

                            if (settings.load) {
                                var elements_left = elements.length;
                                settings.load.call(self, elements_left, settings);
                            }
                        })
                        .attr("src", $self.attr("data-" + settings.data_attribute));
                }
            });

            /* When wanted event is triggered load original image */
            /* by triggering appear.                              */
            if (0 !== settings.event.indexOf("scroll")) {
                $self.bind(settings.event, function() {
                    if (!self.loaded) {
                        $self.trigger("appear");
                    }
                });
            }
        });

        /* Check if something appears when window is resized. */
        $window.bind("resize", function() {
            update();
        });

        /* With IOS5 force loading images when navigating with back button. */
        /* Non optimal workaround. */
        if ((/(?:iphone|ipod|ipad).*os 5/gi).test(navigator.appVersion)) {
            $window.bind("pageshow", function(event) {
                if (event.originalEvent && event.originalEvent.persisted) {
                    elements.each(function() {
                        $(this).trigger("appear");
                    });
                }
            });
        }

        /* Force initial check if images should appear. */
        $(document).ready(function() {
            update();
        });

        return this;
    };

    /* Convenience methods in jQuery namespace.           */
    /* Use as  $.belowthefold(element, {threshold : 100, container : window}) */

    $.belowthefold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = (window.innerHeight ? window.innerHeight : $window.height()) + $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top + $(settings.container).height();
        }

        return fold <= $(element).offset().top - settings.threshold;
    };

    $.rightoffold = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.width() + $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left + $(settings.container).width();
        }

        return fold <= $(element).offset().left - settings.threshold;
    };

    $.abovethetop = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollTop();
        } else {
            fold = $(settings.container).offset().top;
        }

        return fold >= $(element).offset().top + settings.threshold  + $(element).height();
    };

    $.leftofbegin = function(element, settings) {
        var fold;

        if (settings.container === undefined || settings.container === window) {
            fold = $window.scrollLeft();
        } else {
            fold = $(settings.container).offset().left;
        }

        return fold >= $(element).offset().left + settings.threshold + $(element).width();
    };

    $.inviewport = function(element, settings) {
         return !$.rightoffold(element, settings) && !$.leftofbegin(element, settings) &&
                !$.belowthefold(element, settings) && !$.abovethetop(element, settings);
     };

    /* Custom selectors for your convenience.   */
    /* Use as $("img:below-the-fold").something() or */
    /* $("img").filter(":below-the-fold").something() which is faster */

    $.extend($.expr[":"], {
        "below-the-fold" : function(a) { return $.belowthefold(a, {threshold : 0}); },
        "above-the-top"  : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-screen": function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-screen" : function(a) { return !$.rightoffold(a, {threshold : 0}); },
        "in-viewport"    : function(a) { return $.inviewport(a, {threshold : 0}); },
        /* Maintain BC for couple of versions. */
        "above-the-fold" : function(a) { return !$.belowthefold(a, {threshold : 0}); },
        "right-of-fold"  : function(a) { return $.rightoffold(a, {threshold : 0}); },
        "left-of-fold"   : function(a) { return !$.rightoffold(a, {threshold : 0}); }
    });

})(jQuery, window, document);

/*jshint browser:true */
/*!
* FitVids 1.1
*
* Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
* Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - http://sam.zoy.org/wtfpl/
*
*/

;(function( $ ){

  'use strict';

  $.fn.fitVids = function( options ) {
    var settings = {
      customSelector: null,
      ignore: null
    };

    if(!document.getElementById('fit-vids-style')) {
      // appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js
      var head = document.head || document.getElementsByTagName('head')[0];
      var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';
      var div = document.createElement("div");
      div.innerHTML = '<p>x</p><style id="fit-vids-style">' + css + '</style>';
      head.appendChild(div.childNodes[1]);
    }

    if ( options ) {
      $.extend( settings, options );
    }

    return this.each(function(){
      var selectors = [
        'iframe[src*="player.vimeo.com"]',
        'iframe[src*="youtube.com"]',
        'iframe[src*="youtube-nocookie.com"]',
        'iframe[src*="kickstarter.com"][src*="video.html"]',
        'object',
        'embed'
      ];

      if (settings.customSelector) {
        selectors.push(settings.customSelector);
      }

      var ignoreList = '.fitvidsignore';

      if(settings.ignore) {
        ignoreList = ignoreList + ', ' + settings.ignore;
      }

      var $allVideos = $(this).find(selectors.join(','));
      $allVideos = $allVideos.not('object object'); // SwfObj conflict patch
      $allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video.

      $allVideos.each(function(count){
        var $this = $(this);
        if($this.parents(ignoreList).length > 0) {
          return; // Disable FitVids on this video.
        }
        if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
        if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width'))))
        {
          $this.attr('height', 9);
          $this.attr('width', 16);
        }
        var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
            width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
            aspectRatio = height / width;
        if(!$this.attr('id')){
          var videoID = 'fitvid' + count;
          $this.attr('id', videoID);
        }
        $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+'%');
        $this.removeAttr('height').removeAttr('width');
      });
    });
  };
// Works with either jQuery or Zepto
})( window.jQuery || window.Zepto );

/**
 * bxSlider v4.2.1d
 * Copyright 2013-2017 Steven Wanderski
 * Written while drinking Belgian ales and listening to jazz
 * Licensed under MIT (http://opensource.org/licenses/MIT)
 */

;(function($) {

  var defaults = {

    // GENERAL
    mode: 'horizontal',
    slideSelector: '',
    infiniteLoop: true,
    hideControlOnEnd: false,
    speed: 500,
    easing: null,
    slideMargin: 0,
    startSlide: 0,
    randomStart: false,
    captions: false,
    ticker: false,
    tickerHover: false,
    adaptiveHeight: false,
    adaptiveHeightSpeed: 500,
    video: false,
    useCSS: true,
    preloadImages: 'visible',
    responsive: true,
    slideZIndex: 50,
    wrapperClass: 'bx-wrapper',

    // TOUCH
    touchEnabled: true,
    swipeThreshold: 50,
    oneToOneTouch: true,
    preventDefaultSwipeX: true,
    preventDefaultSwipeY: false,

    // ACCESSIBILITY
    ariaLive: true,
    ariaHidden: true,

    // KEYBOARD
    keyboardEnabled: false,

    // PAGER
    pager: true,
    pagerType: 'full',
    pagerShortSeparator: ' / ',
    pagerSelector: null,
    buildPager: null,
    pagerCustom: null,

    // CONTROLS
    controls: true,
    nextText: 'Next',
    prevText: 'Prev',
    nextSelector: null,
    prevSelector: null,
    autoControls: false,
    startText: 'Start',
    stopText: 'Stop',
    autoControlsCombine: false,
    autoControlsSelector: null,

    // AUTO
    auto: false,
    pause: 4000,
    autoStart: true,
    autoDirection: 'next',
    stopAutoOnClick: false,
    autoHover: false,
    autoDelay: 0,
    autoSlideForOnePage: false,

    // CAROUSEL
    minSlides: 1,
    maxSlides: 1,
    moveSlides: 0,
    slideWidth: 0,
    shrinkItems: false,

    // CALLBACKS
    onSliderLoad: function() { return true; },
    onSlideBefore: function() { return true; },
    onSlideAfter: function() { return true; },
    onSlideNext: function() { return true; },
    onSlidePrev: function() { return true; },
    onSliderResize: function() { return true; },
	onAutoChange: function() { return true; } //calls when auto slides starts and stops
  };

  $.fn.bxSlider = function(options) {

    if (this.length === 0) {
      return this;
    }

    // support multiple elements
    if (this.length > 1) {
      this.each(function() {
        $(this).bxSlider(options);
      });
      return this;
    }

    // create a namespace to be used throughout the plugin
    var slider = {},
    // set a reference to our slider element
    el = this,
    // get the original window dimens (thanks a lot IE)
    windowWidth = $(window).width(),
    windowHeight = $(window).height();

    // Return if slider is already initialized
    if ($(el).data('bxSlider')) { return; }

    /**
     * ===================================================================================
     * = PRIVATE FUNCTIONS
     * ===================================================================================
     */

    /**
     * Initializes namespace settings to be used throughout plugin
     */
    var init = function() {
      // Return if slider is already initialized
      if ($(el).data('bxSlider')) { return; }
      // merge user-supplied options with the defaults
      slider.settings = $.extend({}, defaults, options);
      // parse slideWidth setting
      slider.settings.slideWidth = parseInt(slider.settings.slideWidth);
      // store the original children
      slider.children = el.children(slider.settings.slideSelector);
      // check if actual number of slides is less than minSlides / maxSlides
      if (slider.children.length < slider.settings.minSlides) { slider.settings.minSlides = slider.children.length; }
      if (slider.children.length < slider.settings.maxSlides) { slider.settings.maxSlides = slider.children.length; }
      // if random start, set the startSlide setting to random number
      if (slider.settings.randomStart) { slider.settings.startSlide = Math.floor(Math.random() * slider.children.length); }
      // store active slide information
      slider.active = { index: slider.settings.startSlide };
      // store if the slider is in carousel mode (displaying / moving multiple slides)
      slider.carousel = slider.settings.minSlides > 1 || slider.settings.maxSlides > 1;
      // if carousel, force preloadImages = 'all'
      if (slider.carousel) { slider.settings.preloadImages = 'all'; }
      // calculate the min / max width thresholds based on min / max number of slides
      // used to setup and update carousel slides dimensions
      slider.minThreshold = (slider.settings.minSlides * slider.settings.slideWidth) + ((slider.settings.minSlides - 1) * slider.settings.slideMargin);
      slider.maxThreshold = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin);
      // store the current state of the slider (if currently animating, working is true)
      slider.working = false;
      // initialize the controls object
      slider.controls = {};
      // initialize an auto interval
      slider.interval = null;
      // determine which property to use for transitions
      slider.animProp = slider.settings.mode === 'vertical' ? 'top' : 'left';
      // determine if hardware acceleration can be used
      slider.usingCSS = slider.settings.useCSS && slider.settings.mode !== 'fade' && (function() {
        // create our test div element
        var div = document.createElement('div'),
        // css transition properties
        props = ['WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'];
        // test for each property
        for (var i = 0; i < props.length; i++) {
          if (div.style[props[i]] !== undefined) {
            slider.cssPrefix = props[i].replace('Perspective', '').toLowerCase();
            slider.animProp = '-' + slider.cssPrefix + '-transform';
            return true;
          }
        }
        return false;
      }());
      // if vertical mode always make maxSlides and minSlides equal
      if (slider.settings.mode === 'vertical') { slider.settings.maxSlides = slider.settings.minSlides; }
      // save original style data
      el.data('origStyle', el.attr('style'));
      el.children(slider.settings.slideSelector).each(function() {
        $(this).data('origStyle', $(this).attr('style'));
      });

      // perform all DOM / CSS modifications
      setup();
    };

    /**
     * Performs all DOM and CSS modifications
     */
    var setup = function() {
      var preloadSelector = slider.children.eq(slider.settings.startSlide); // set the default preload selector (visible)

      // wrap el in a wrapper
      el.wrap('<div class="' + slider.settings.wrapperClass + '"><div class="bx-viewport"></div></div>');
      // store a namespace reference to .bx-viewport
      slider.viewport = el.parent();

      // add aria-live if the setting is enabled and ticker mode is disabled
      if (slider.settings.ariaLive && !slider.settings.ticker) {
        slider.viewport.attr('aria-live', 'polite');
      }
      // add a loading div to display while images are loading
      slider.loader = $('<div class="bx-loading" />');
      slider.viewport.prepend(slider.loader);
      // set el to a massive width, to hold any needed slides
      // also strip any margin and padding from el
      el.css({
        width: slider.settings.mode === 'horizontal' ? (slider.children.length * 1000 + 215) + '%' : 'auto',
        position: 'relative'
      });
      // if using CSS, add the easing property
      if (slider.usingCSS && slider.settings.easing) {
        el.css('-' + slider.cssPrefix + '-transition-timing-function', slider.settings.easing);
      // if not using CSS and no easing value was supplied, use the default JS animation easing (swing)
      } else if (!slider.settings.easing) {
        slider.settings.easing = 'swing';
      }
      // make modifications to the viewport (.bx-viewport)
      slider.viewport.css({
        width: '100%',
        overflow: 'hidden',
        position: 'relative'
      });
      slider.viewport.parent().css({
        maxWidth: getViewportMaxWidth()
      });
      // apply css to all slider children
      slider.children.css({
        // the float attribute is a reserved word in compressors like YUI compressor and need to be quoted #48
        'float': slider.settings.mode === 'horizontal' ? 'left' : 'none',
        listStyle: 'none',
        position: 'relative'
      });
      // apply the calculated width after the float is applied to prevent scrollbar interference
      slider.children.css('width', getSlideWidth());
      // if slideMargin is supplied, add the css
      if (slider.settings.mode === 'horizontal' && slider.settings.slideMargin > 0) { slider.children.css('marginRight', slider.settings.slideMargin); }
      if (slider.settings.mode === 'vertical' && slider.settings.slideMargin > 0) { slider.children.css('marginBottom', slider.settings.slideMargin); }
      // if "fade" mode, add positioning and z-index CSS
      if (slider.settings.mode === 'fade') {
        slider.children.css({
          position: 'absolute',
          zIndex: 0,
          display: 'none'
        });
        // prepare the z-index on the showing element
        slider.children.eq(slider.settings.startSlide).css({zIndex: slider.settings.slideZIndex, display: 'block'});
      }
      // create an element to contain all slider controls (pager, start / stop, etc)
      slider.controls.el = $('<div class="bx-controls" />');
      // if captions are requested, add them
      if (slider.settings.captions) { appendCaptions(); }
      // check if startSlide is last slide
      slider.active.last = slider.settings.startSlide === getPagerQty() - 1;
      // if video is true, set up the fitVids plugin
      if (slider.settings.video) { el.fitVids(); }
	  //preloadImages
	  if (slider.settings.preloadImages === 'none') {
		  preloadSelector = null;
	  }
      else if (slider.settings.preloadImages === 'all' || slider.settings.ticker) {
		  preloadSelector = slider.children;
	  }
      // only check for control addition if not in "ticker" mode
      if (!slider.settings.ticker) {
        // if controls are requested, add them
        if (slider.settings.controls) { appendControls(); }
        // if auto is true, and auto controls are requested, add them
        if (slider.settings.auto && slider.settings.autoControls) { appendControlsAuto(); }
        // if pager is requested, add it
        if (slider.settings.pager) { appendPager(); }
        // if any control option is requested, add the controls wrapper
        if (slider.settings.controls || slider.settings.autoControls || slider.settings.pager) { slider.viewport.after(slider.controls.el); }
      // if ticker mode, do not allow a pager
      } else {
        slider.settings.pager = false;
      }
	  if (preloadSelector === null) {
        start();
      } else {
        loadElements(preloadSelector, start);
      }
    };

    var loadElements = function(selector, callback) {
      var total = selector.find('img:not([src=""]), iframe').length,
      count = 0;
      if (total === 0) {
        callback();
        return;
      }
      selector.find('img:not([src=""]), iframe').each(function() {
        $(this).one('load error', function() {
          if (++count === total) { callback(); }
        }).each(function() {
          if (this.complete || this.src == '') { $(this).trigger('load'); }
        });
      });
    };

    /**
     * Start the slider
     */
    var start = function() {
      // if infinite loop, prepare additional slides
      if (slider.settings.infiniteLoop && slider.settings.mode !== 'fade' && !slider.settings.ticker) {
        var slice    = slider.settings.mode === 'vertical' ? slider.settings.minSlides : slider.settings.maxSlides,
        sliceAppend  = slider.children.slice(0, slice).clone(true).addClass('bx-clone'),
        slicePrepend = slider.children.slice(-slice).clone(true).addClass('bx-clone');
        if (slider.settings.ariaHidden) {
          sliceAppend.attr('aria-hidden', true);
          slicePrepend.attr('aria-hidden', true);
        }
        el.append(sliceAppend).prepend(slicePrepend);
      }
      // remove the loading DOM element
      slider.loader.remove();
      // set the left / top position of "el"
      setSlidePosition();
      // if "vertical" mode, always use adaptiveHeight to prevent odd behavior
      if (slider.settings.mode === 'vertical') { slider.settings.adaptiveHeight = true; }
      // set the viewport height
      slider.viewport.height(getViewportHeight());
      // make sure everything is positioned just right (same as a window resize)
      el.redrawSlider();
      // onSliderLoad callback
      slider.settings.onSliderLoad.call(el, slider.active.index);
      // slider has been fully initialized
      slider.initialized = true;
      // add the resize call to the window
      if (slider.settings.responsive) { $(window).on('resize', resizeWindow); }
      // if auto is true and has more than 1 page, start the show
      if (slider.settings.auto && slider.settings.autoStart && (getPagerQty() > 1 || slider.settings.autoSlideForOnePage)) { initAuto(); }
      // if ticker is true, start the ticker
      if (slider.settings.ticker) { initTicker(); }
      // if pager is requested, make the appropriate pager link active
      if (slider.settings.pager) { updatePagerActive(slider.settings.startSlide); }
      // check for any updates to the controls (like hideControlOnEnd updates)
      if (slider.settings.controls) { updateDirectionControls(); }
      // if touchEnabled is true, setup the touch events
      if (slider.settings.touchEnabled && !slider.settings.ticker) { initTouch(); }
      // if keyboardEnabled is true, setup the keyboard events
      if (slider.settings.keyboardEnabled && !slider.settings.ticker) {
        $(document).keydown(keyPress);
      }
    };

    /**
     * Returns the calculated height of the viewport, used to determine either adaptiveHeight or the maxHeight value
     */
    var getViewportHeight = function() {
      var height = 0;
      // first determine which children (slides) should be used in our height calculation
      var children = $();
      // if mode is not "vertical" and adaptiveHeight is false, include all children
      if (slider.settings.mode !== 'vertical' && !slider.settings.adaptiveHeight) {
        children = slider.children;
      } else {
        // if not carousel, return the single active child
        if (!slider.carousel) {
          children = slider.children.eq(slider.active.index);
        // if carousel, return a slice of children
        } else {
          // get the individual slide index
          var currentIndex = slider.settings.moveSlides === 1 ? slider.active.index : slider.active.index * getMoveBy();
          // add the current slide to the children
          children = slider.children.eq(currentIndex);
          // cycle through the remaining "showing" slides
          for (var i = 1; i <= slider.settings.maxSlides - 1; i++) {
            // if looped back to the start
            if (currentIndex + i >= slider.children.length) {
              children = children.add(slider.children.eq(i - 1));
            } else {
              children = children.add(slider.children.eq(currentIndex + i));
            }
          }
        }
      }
      // if "vertical" mode, calculate the sum of the heights of the children
      if (slider.settings.mode === 'vertical') {
        children.each(function(index) {
          height += $(this).outerHeight();
        });
        // add user-supplied margins
        if (slider.settings.slideMargin > 0) {
          height += slider.settings.slideMargin * (slider.settings.minSlides - 1);
        }
      // if not "vertical" mode, calculate the max height of the children
      } else {
        height = Math.max.apply(Math, children.map(function() {
          return $(this).outerHeight(false);
        }).get());
      }

      if (slider.viewport.css('box-sizing') === 'border-box') {
        height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom')) +
              parseFloat(slider.viewport.css('border-top-width')) + parseFloat(slider.viewport.css('border-bottom-width'));
      } else if (slider.viewport.css('box-sizing') === 'padding-box') {
        height += parseFloat(slider.viewport.css('padding-top')) + parseFloat(slider.viewport.css('padding-bottom'));
      }

      return height;
    };

    /**
     * Returns the calculated width to be used for the outer wrapper / viewport
     */
    var getViewportMaxWidth = function() {
      var width = '100%';
      if (slider.settings.slideWidth > 0) {
        if (slider.settings.mode === 'horizontal') {
          width = (slider.settings.maxSlides * slider.settings.slideWidth) + ((slider.settings.maxSlides - 1) * slider.settings.slideMargin);
        } else {
          width = slider.settings.slideWidth;
        }
      }
      return width;
    };

    /**
     * Returns the calculated width to be applied to each slide
     */
    var getSlideWidth = function() {
      var newElWidth = slider.settings.slideWidth, // start with any user-supplied slide width
      wrapWidth      = slider.viewport.width();    // get the current viewport width
      // if slide width was not supplied, or is larger than the viewport use the viewport width
      if (slider.settings.slideWidth === 0 ||
        (slider.settings.slideWidth > wrapWidth && !slider.carousel) ||
        slider.settings.mode === 'vertical') {
        newElWidth = wrapWidth;
      // if carousel, use the thresholds to determine the width
      } else if (slider.settings.maxSlides > 1 && slider.settings.mode === 'horizontal') {
        if (wrapWidth > slider.maxThreshold) {
          return newElWidth;
        } else if (wrapWidth < slider.minThreshold) {
          newElWidth = (wrapWidth - (slider.settings.slideMargin * (slider.settings.minSlides - 1))) / slider.settings.minSlides;
        } else if (slider.settings.shrinkItems) {
          newElWidth = Math.floor((wrapWidth + slider.settings.slideMargin) / (Math.ceil((wrapWidth + slider.settings.slideMargin) / (newElWidth + slider.settings.slideMargin))) - slider.settings.slideMargin);
        }
      }
      return newElWidth;
    };

    /**
     * Returns the number of slides currently visible in the viewport (includes partially visible slides)
     */
    var getNumberSlidesShowing = function() {
      var slidesShowing = 1,
      childWidth = null;
      if (slider.settings.mode === 'horizontal' && slider.settings.slideWidth > 0) {
        // if viewport is smaller than minThreshold, return minSlides
        if (slider.viewport.width() < slider.minThreshold) {
          slidesShowing = slider.settings.minSlides;
        // if viewport is larger than maxThreshold, return maxSlides
        } else if (slider.viewport.width() > slider.maxThreshold) {
          slidesShowing = slider.settings.maxSlides;
        // if viewport is between min / max thresholds, divide viewport width by first child width
        } else {
          childWidth = slider.children.first().width() + slider.settings.slideMargin;
          slidesShowing = Math.floor((slider.viewport.width() +
            slider.settings.slideMargin) / childWidth) || 1;
        }
      // if "vertical" mode, slides showing will always be minSlides
      } else if (slider.settings.mode === 'vertical') {
        slidesShowing = slider.settings.minSlides;
      }
      return slidesShowing;
    };

    /**
     * Returns the number of pages (one full viewport of slides is one "page")
     */
    var getPagerQty = function() {
      var pagerQty = 0,
      breakPoint = 0,
      counter = 0;
      // if moveSlides is specified by the user
      if (slider.settings.moveSlides > 0) {
        if (slider.settings.infiniteLoop) {
          pagerQty = Math.ceil(slider.children.length / getMoveBy());
        } else {
          // when breakpoint goes above children length, counter is the number of pages
          while (breakPoint < slider.children.length) {
            ++pagerQty;
            breakPoint = counter + getNumberSlidesShowing();
            counter += slider.settings.moveSlides <= getNumberSlidesShowing() ? slider.settings.moveSlides : getNumberSlidesShowing();
          }
		  return counter;
        }
      // if moveSlides is 0 (auto) divide children length by sides showing, then round up
      } else {
        pagerQty = Math.ceil(slider.children.length / getNumberSlidesShowing());
      }
      return pagerQty;
    };

    /**
     * Returns the number of individual slides by which to shift the slider
     */
    var getMoveBy = function() {
      // if moveSlides was set by the user and moveSlides is less than number of slides showing
      if (slider.settings.moveSlides > 0 && slider.settings.moveSlides <= getNumberSlidesShowing()) {
        return slider.settings.moveSlides;
      }
      // if moveSlides is 0 (auto)
      return getNumberSlidesShowing();
    };

    /**
     * Sets the slider's (el) left or top position
     */
    var setSlidePosition = function() {
      var position, lastChild, lastShowingIndex;
      // if last slide, not infinite loop, and number of children is larger than specified maxSlides
      if (slider.children.length > slider.settings.maxSlides && slider.active.last && !slider.settings.infiniteLoop) {
        if (slider.settings.mode === 'horizontal') {
          // get the last child's position
          lastChild = slider.children.last();
          position = lastChild.position();
          // set the left position
          setPositionProperty(-(position.left - (slider.viewport.width() - lastChild.outerWidth())), 'reset', 0);
        } else if (slider.settings.mode === 'vertical') {
          // get the last showing index's position
          lastShowingIndex = slider.children.length - slider.settings.minSlides;
          position = slider.children.eq(lastShowingIndex).position();
          // set the top position
          setPositionProperty(-position.top, 'reset', 0);
        }
      // if not last slide
      } else {
        // get the position of the first showing slide
        position = slider.children.eq(slider.active.index * getMoveBy()).position();
        // check for last slide
        if (slider.active.index === getPagerQty() - 1) { slider.active.last = true; }
        // set the respective position
        if (position !== undefined) {
          if (slider.settings.mode === 'horizontal') { setPositionProperty(-position.left, 'reset', 0); }
          else if (slider.settings.mode === 'vertical') { setPositionProperty(-position.top, 'reset', 0); }
        }
      }
    };

    /**
     * Sets the el's animating property position (which in turn will sometimes animate el).
     * If using CSS, sets the transform property. If not using CSS, sets the top / left property.
     *
     * @param value (int)
     *  - the animating property's value
     *
     * @param type (string) 'slide', 'reset', 'ticker'
     *  - the type of instance for which the function is being
     *
     * @param duration (int)
     *  - the amount of time (in ms) the transition should occupy
     *
     * @param params (array) optional
     *  - an optional parameter containing any variables that need to be passed in
     */
    var setPositionProperty = function(value, type, duration, params) {
      var animateObj, propValue;
      // use CSS transform
      if (slider.usingCSS) {
        // determine the translate3d value
        propValue = slider.settings.mode === 'vertical' ? 'translate3d(0, ' + value + 'px, 0)' : 'translate3d(' + value + 'px, 0, 0)';
        // add the CSS transition-duration
        el.css('-' + slider.cssPrefix + '-transition-duration', duration / 1000 + 's');
        if (type === 'slide') {
          // set the property value
          el.css(slider.animProp, propValue);
          if (duration !== 0) {
            // add a callback method - executes when CSS transition completes
            el.on('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) {
              //make sure it's the correct one
              if (!$(e.target).is(el)) { return; }
              // remove the callback
              el.off('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd');
              updateAfterSlideTransition();
            });
          } else { //duration = 0
            updateAfterSlideTransition();
          }
        } else if (type === 'reset') {
          el.css(slider.animProp, propValue);
        } else if (type === 'ticker') {
          // make the transition use 'linear'
          el.css('-' + slider.cssPrefix + '-transition-timing-function', 'linear');
          el.css(slider.animProp, propValue);
          if (duration !== 0) {
            el.on('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) {
              //make sure it's the correct one
              if (!$(e.target).is(el)) { return; }
              // remove the callback
              el.off('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd');
              // reset the position
              setPositionProperty(params.resetValue, 'reset', 0);
              // start the loop again
              tickerLoop();
            });
          } else { //duration = 0
            setPositionProperty(params.resetValue, 'reset', 0);
            tickerLoop();
          }
        }
      // use JS animate
      } else {
        animateObj = {};
        animateObj[slider.animProp] = value;
        if (type === 'slide') {
          el.animate(animateObj, duration, slider.settings.easing, function() {
            updateAfterSlideTransition();
          });
        } else if (type === 'reset') {
          el.css(slider.animProp, value);
        } else if (type === 'ticker') {
          el.animate(animateObj, duration, 'linear', function() {
            setPositionProperty(params.resetValue, 'reset', 0);
            // run the recursive loop after animation
            tickerLoop();
          });
        }
      }
    };

    /**
     * Populates the pager with proper amount of pages
     */
    var populatePager = function() {
      var pagerHtml = '',
      linkContent = '',
      pagerQty = getPagerQty();
      // loop through each pager item
      for (var i = 0; i < pagerQty; i++) {
        linkContent = '';
        // if a buildPager function is supplied, use it to get pager link value, else use index + 1
        if (slider.settings.buildPager && $.isFunction(slider.settings.buildPager) || slider.settings.pagerCustom) {
          linkContent = slider.settings.buildPager(i);
          slider.pagerEl.addClass('bx-custom-pager');
        } else {
          linkContent = i + 1;
          slider.pagerEl.addClass('bx-default-pager');
        }
        // var linkContent = slider.settings.buildPager && $.isFunction(slider.settings.buildPager) ? slider.settings.buildPager(i) : i + 1;
        // add the markup to the string
        pagerHtml += '<div class="bx-pager-item"><a href="" data-slide-index="' + i + '" class="bx-pager-link">' + linkContent + '</a></div>';
      }
      // populate the pager element with pager links
      slider.pagerEl.html(pagerHtml);
    };

    /**
     * Appends the pager to the controls element
     */
    var appendPager = function() {
      if (!slider.settings.pagerCustom) {
        // create the pager DOM element
        slider.pagerEl = $('<div class="bx-pager" />');
        // if a pager selector was supplied, populate it with the pager
        if (slider.settings.pagerSelector) {
          $(slider.settings.pagerSelector).html(slider.pagerEl);
        // if no pager selector was supplied, add it after the wrapper
        } else {
          slider.controls.el.addClass('bx-has-pager').append(slider.pagerEl);
        }
        // populate the pager
        populatePager();
      } else {
        slider.pagerEl = $(slider.settings.pagerCustom);
      }
      // assign the pager click binding
      slider.pagerEl.on('click touchend', 'a', clickPagerBind);
    };

    /**
     * Appends prev / next controls to the controls element
     */
    var appendControls = function() {
      slider.controls.next = $('<a class="bx-next" href="">' + slider.settings.nextText + '</a>');
      slider.controls.prev = $('<a class="bx-prev" href="">' + slider.settings.prevText + '</a>');
      // add click actions to the controls
      slider.controls.next.on('click touchend', clickNextBind);
      slider.controls.prev.on('click touchend', clickPrevBind);
      // if nextSelector was supplied, populate it
      if (slider.settings.nextSelector) {
        $(slider.settings.nextSelector).append(slider.controls.next);
      }
      // if prevSelector was supplied, populate it
      if (slider.settings.prevSelector) {
        $(slider.settings.prevSelector).append(slider.controls.prev);
      }
      // if no custom selectors were supplied
      if (!slider.settings.nextSelector && !slider.settings.prevSelector) {
        // add the controls to the DOM
        slider.controls.directionEl = $('<div class="bx-controls-direction" />');
        // add the control elements to the directionEl
        slider.controls.directionEl.append(slider.controls.prev).append(slider.controls.next);
        // slider.viewport.append(slider.controls.directionEl);
        slider.controls.el.addClass('bx-has-controls-direction').append(slider.controls.directionEl);
      }
    };

    /**
     * Appends start / stop auto controls to the controls element
     */
    var appendControlsAuto = function() {
      slider.controls.start = $('<div class="bx-controls-auto-item"><a class="bx-start" href="">' + slider.settings.startText + '</a></div>');
      slider.controls.stop = $('<div class="bx-controls-auto-item"><a class="bx-stop" href="">' + slider.settings.stopText + '</a></div>');
      // add the controls to the DOM
      slider.controls.autoEl = $('<div class="bx-controls-auto" />');
      // on click actions to the controls
      slider.controls.autoEl.on('click', '.bx-start', clickStartBind);
      slider.controls.autoEl.on('click', '.bx-stop', clickStopBind);
      // if autoControlsCombine, insert only the "start" control
      if (slider.settings.autoControlsCombine) {
        slider.controls.autoEl.append(slider.controls.start);
      // if autoControlsCombine is false, insert both controls
      } else {
        slider.controls.autoEl.append(slider.controls.start).append(slider.controls.stop);
      }
      // if auto controls selector was supplied, populate it with the controls
      if (slider.settings.autoControlsSelector) {
        $(slider.settings.autoControlsSelector).html(slider.controls.autoEl);
      // if auto controls selector was not supplied, add it after the wrapper
      } else {
        slider.controls.el.addClass('bx-has-controls-auto').append(slider.controls.autoEl);
      }
      // update the auto controls
      updateAutoControls(slider.settings.autoStart ? 'stop' : 'start');
    };

    /**
     * Appends image captions to the DOM
     */
    var appendCaptions = function() {
      // cycle through each child
      slider.children.each(function(index) {
        // get the image title attribute
        var title = $(this).find('img:first').attr('title');
        // append the caption
        if (title !== undefined && ('' + title).length) {
          $(this).append('<div class="bx-caption"><span>' + title + '</span></div>');
        }
      });
    };

    /**
     * Click next binding
     *
     * @param e (event)
     *  - DOM event object
     */
    var clickNextBind = function(e) {
      e.preventDefault();
      if (slider.controls.el.hasClass('disabled')) { return; }
      // if auto show is running, stop it
      if (slider.settings.auto && slider.settings.stopAutoOnClick) { el.stopAuto(); }
      el.goToNextSlide();
    };

    /**
     * Click prev binding
     *
     * @param e (event)
     *  - DOM event object
     */
    var clickPrevBind = function(e) {
      e.preventDefault();
      if (slider.controls.el.hasClass('disabled')) { return; }
      // if auto show is running, stop it
      if (slider.settings.auto && slider.settings.stopAutoOnClick) { el.stopAuto(); }
      el.goToPrevSlide();
    };

    /**
     * Click start binding
     *
     * @param e (event)
     *  - DOM event object
     */
    var clickStartBind = function(e) {
      el.startAuto();
      e.preventDefault();
    };

    /**
     * Click stop binding
     *
     * @param e (event)
     *  - DOM event object
     */
    var clickStopBind = function(e) {
      el.stopAuto();
      e.preventDefault();
    };

    /**
     * Click pager binding
     *
     * @param e (event)
     *  - DOM event object
     */
    var clickPagerBind = function(e) {
      var pagerLink, pagerIndex;
      e.preventDefault();
      if (slider.controls.el.hasClass('disabled')) {
        return;
      }
      // if auto show is running, stop it
      if (slider.settings.auto  && slider.settings.stopAutoOnClick) { el.stopAuto(); }
      pagerLink = $(e.currentTarget);
      if (pagerLink.attr('data-slide-index') !== undefined) {
        pagerIndex = parseInt(pagerLink.attr('data-slide-index'));
        // if clicked pager link is not active, continue with the goToSlide call
        if (pagerIndex !== slider.active.index) { el.goToSlide(pagerIndex); }
      }
    };

    /**
     * Updates the pager links with an active class
     *
     * @param slideIndex (int)
     *  - index of slide to make active
     */
    var updatePagerActive = function(slideIndex) {
      // if "short" pager type
      var len = slider.children.length; // nb of children
      if (slider.settings.pagerType === 'short') {
        if (slider.settings.maxSlides > 1) {
          len = Math.ceil(slider.children.length / slider.settings.maxSlides);
        }
        slider.pagerEl.html((slideIndex + 1) + slider.settings.pagerShortSeparator + len);
        return;
      }
      // remove all pager active classes
      slider.pagerEl.find('a').removeClass('active');
      // apply the active class for all pagers
      slider.pagerEl.each(function(i, el) { $(el).find('a').eq(slideIndex).addClass('active'); });
    };

    /**
     * Performs needed actions after a slide transition
     */
    var updateAfterSlideTransition = function() {
      // if infinite loop is true
      if (slider.settings.infiniteLoop) {
        var position = '';
        // first slide
        if (slider.active.index === 0) {
          // set the new position
          position = slider.children.eq(0).position();
        // carousel, last slide
        } else if (slider.active.index === getPagerQty() - 1 && slider.carousel) {
          position = slider.children.eq((getPagerQty() - 1) * getMoveBy()).position();
        // last slide
        } else if (slider.active.index === slider.children.length - 1) {
          position = slider.children.eq(slider.children.length - 1).position();
        }
        if (position) {
          if (slider.settings.mode === 'horizontal') { setPositionProperty(-position.left, 'reset', 0); }
          else if (slider.settings.mode === 'vertical') { setPositionProperty(-position.top, 'reset', 0); }
        }
      }
      // declare that the transition is complete
      slider.working = false;
      // onSlideAfter callback
      slider.settings.onSlideAfter.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index);
    };

    /**
     * Updates the auto controls state (either active, or combined switch)
     *
     * @param state (string) "start", "stop"
     *  - the new state of the auto show
     */
    var updateAutoControls = function(state) {
      // if autoControlsCombine is true, replace the current control with the new state
      if (slider.settings.autoControlsCombine) {
        slider.controls.autoEl.html(slider.controls[state]);
      // if autoControlsCombine is false, apply the "active" class to the appropriate control
      } else {
        slider.controls.autoEl.find('a').removeClass('active');
        slider.controls.autoEl.find('a:not(.bx-' + state + ')').addClass('active');
      }
    };

    /**
     * Updates the direction controls (checks if either should be hidden)
     */
    var updateDirectionControls = function() {
      if (getPagerQty() === 1) {
        slider.controls.prev.addClass('disabled');
        slider.controls.next.addClass('disabled');
      } else if (!slider.settings.infiniteLoop && slider.settings.hideControlOnEnd) {
        // if first slide
        if (slider.active.index === 0) {
          slider.controls.prev.addClass('disabled');
          slider.controls.next.removeClass('disabled');
        // if last slide
        } else if (slider.active.index === getPagerQty() - 1) {
          slider.controls.next.addClass('disabled');
          slider.controls.prev.removeClass('disabled');
        // if any slide in the middle
        } else {
          slider.controls.prev.removeClass('disabled');
          slider.controls.next.removeClass('disabled');
        }
      }
    };
	/* auto start and stop functions */
	var windowFocusHandler = function() { el.startAuto(); };
	var windowBlurHandler = function() { el.stopAuto(); };
    /**
     * Initializes the auto process
     */
    var initAuto = function() {
      // if autoDelay was supplied, launch the auto show using a setTimeout() call
      if (slider.settings.autoDelay > 0) {
        setTimeout(el.startAuto, slider.settings.autoDelay);
      // if autoDelay was not supplied, start the auto show normally
      } else {
        el.startAuto();

        //add focus and blur events to ensure its running if timeout gets paused
        $(window).focus(windowFocusHandler).blur(windowBlurHandler);
      }
      // if autoHover is requested
      if (slider.settings.autoHover) {
        // on el hover
        el.hover(function() {
          // if the auto show is currently playing (has an active interval)
          if (slider.interval) {
            // stop the auto show and pass true argument which will prevent control update
            el.stopAuto(true);
            // create a new autoPaused value which will be used by the relative "mouseout" event
            slider.autoPaused = true;
          }
        }, function() {
          // if the autoPaused value was created be the prior "mouseover" event
          if (slider.autoPaused) {
            // start the auto show and pass true argument which will prevent control update
            el.startAuto(true);
            // reset the autoPaused value
            slider.autoPaused = null;
          }
        });
      }
    };

    /**
     * Initializes the ticker process
     */
    var initTicker = function() {
      var startPosition = 0,
      position, transform, value, idx, ratio, property, newSpeed, totalDimens;
      // if autoDirection is "next", append a clone of the entire slider
      if (slider.settings.autoDirection === 'next') {
        el.append(slider.children.clone().addClass('bx-clone'));
      // if autoDirection is "prev", prepend a clone of the entire slider, and set the left position
      } else {
        el.prepend(slider.children.clone().addClass('bx-clone'));
        position = slider.children.first().position();
        startPosition = slider.settings.mode === 'horizontal' ? -position.left : -position.top;
      }
      setPositionProperty(startPosition, 'reset', 0);
      // do not allow controls in ticker mode
      slider.settings.pager = false;
      slider.settings.controls = false;
      slider.settings.autoControls = false;
      // if autoHover is requested
      if (slider.settings.tickerHover) {
        if (slider.usingCSS) {
          idx = slider.settings.mode === 'horizontal' ? 4 : 5;
          slider.viewport.hover(function() {
            transform = el.css('-' + slider.cssPrefix + '-transform');
            value = parseFloat(transform.split(',')[idx]);
            setPositionProperty(value, 'reset', 0);
          }, function() {
            totalDimens = 0;
            slider.children.each(function(index) {
              totalDimens += slider.settings.mode === 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true);
            });
            // calculate the speed ratio (used to determine the new speed to finish the paused animation)
            ratio = slider.settings.speed / totalDimens;
            // determine which property to use
            property = slider.settings.mode === 'horizontal' ? 'left' : 'top';
            // calculate the new speed
            newSpeed = ratio * (totalDimens - (Math.abs(parseInt(value))));
            tickerLoop(newSpeed);
          });
        } else {
          // on el hover
          slider.viewport.hover(function() {
            el.stop();
          }, function() {
            // calculate the total width of children (used to calculate the speed ratio)
            totalDimens = 0;
            slider.children.each(function(index) {
              totalDimens += slider.settings.mode === 'horizontal' ? $(this).outerWidth(true) : $(this).outerHeight(true);
            });
            // calculate the speed ratio (used to determine the new speed to finish the paused animation)
            ratio = slider.settings.speed / totalDimens;
            // determine which property to use
            property = slider.settings.mode === 'horizontal' ? 'left' : 'top';
            // calculate the new speed
            newSpeed = ratio * (totalDimens - (Math.abs(parseInt(el.css(property)))));
            tickerLoop(newSpeed);
          });
        }
      }
      // start the ticker loop
      tickerLoop();
    };

    /**
     * Runs a continuous loop, news ticker-style
     */
    var tickerLoop = function(resumeSpeed) {
      var speed = resumeSpeed ? resumeSpeed : slider.settings.speed,
      position = {left: 0, top: 0},
      reset = {left: 0, top: 0},
      animateProperty, resetValue, params;

      // if "next" animate left position to last child, then reset left to 0
      if (slider.settings.autoDirection === 'next') {
        position = el.find('.bx-clone').first().position();
      // if "prev" animate left position to 0, then reset left to first non-clone child
      } else {
        reset = slider.children.first().position();
      }
      animateProperty = slider.settings.mode === 'horizontal' ? -position.left : -position.top;
      resetValue = slider.settings.mode === 'horizontal' ? -reset.left : -reset.top;
      params = {resetValue: resetValue};
      setPositionProperty(animateProperty, 'ticker', speed, params);
    };

    /**
     * Check if el is on screen
     */
    var isOnScreen = function(el) {
      var win = $(window),
      viewport = {
        top: win.scrollTop(),
        left: win.scrollLeft()
      },
      bounds = el.offset();

      viewport.right = viewport.left + win.width();
      viewport.bottom = viewport.top + win.height();
      bounds.right = bounds.left + el.outerWidth();
      bounds.bottom = bounds.top + el.outerHeight();

      return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
    };

    /**
     * Initializes keyboard events
     */
    var keyPress = function(e) {
      var activeElementTag = document.activeElement.tagName.toLowerCase(),
      tagFilters = 'input|textarea',
      p = new RegExp(activeElementTag,['i']),
      result = p.exec(tagFilters);

      if (result == null && isOnScreen(el)) {
        if (e.keyCode === 39) {
          clickNextBind(e);
          return false;
        } else if (e.keyCode === 37) {
          clickPrevBind(e);
          return false;
        }
      }
    };

    /**
     * Initializes touch events
     */
    var initTouch = function() {
      // initialize object to contain all touch values
      slider.touch = {
        start: {x: 0, y: 0},
        end: {x: 0, y: 0}
      };
      slider.viewport.on('touchstart MSPointerDown pointerdown', onTouchStart);

      //for browsers that have implemented pointer events and fire a click after
      //every pointerup regardless of whether pointerup is on same screen location as pointerdown or not
      slider.viewport.on('click', '.bxslider a', function(e) {
        if (slider.viewport.hasClass('click-disabled')) {
          e.preventDefault();
          slider.viewport.removeClass('click-disabled');
        }
      });
    };

    /**
     * Event handler for "touchstart"
     *
     * @param e (event)
     *  - DOM event object
     */
    var onTouchStart = function(e) {
      // watch only for left mouse, touch contact and pen contact
      // touchstart event object doesn`t have button property
      if (e.type !== 'touchstart' && e.button !== 0) {
        return;
      }
      e.preventDefault();
      //disable slider controls while user is interacting with slides to avoid slider freeze that happens on touch devices when a slide swipe happens immediately after interacting with slider controls
      slider.controls.el.addClass('disabled');

      if (slider.working) {
        slider.controls.el.removeClass('disabled');
      } else {
        // record the original position when touch starts
        slider.touch.originalPos = el.position();
        var orig = e.originalEvent,
        touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig];
		var chromePointerEvents = typeof PointerEvent === 'function';
		if (chromePointerEvents) {
			if (orig.pointerId === undefined) {
				return;
			}
		}
        // record the starting touch x, y coordinates
        slider.touch.start.x = touchPoints[0].pageX;
        slider.touch.start.y = touchPoints[0].pageY;

        if (slider.viewport.get(0).setPointerCapture) {
          slider.pointerId = orig.pointerId;
          slider.viewport.get(0).setPointerCapture(slider.pointerId);
        }
        // store original event data for click fixation
        slider.originalClickTarget = orig.originalTarget || orig.target;
        slider.originalClickButton = orig.button;
        slider.originalClickButtons = orig.buttons;
        slider.originalEventType = orig.type;
        // at this moment we don`t know what it is click or swipe
        slider.hasMove = false;
        // on a "touchmove" event to the viewport
        slider.viewport.on('touchmove MSPointerMove pointermove', onTouchMove);
        // on a "touchend" event to the viewport
        slider.viewport.on('touchend MSPointerUp pointerup', onTouchEnd);
        slider.viewport.on('MSPointerCancel pointercancel', onPointerCancel);
      }
    };

    /**
     * Cancel Pointer for Windows Phone
     *
     * @param e (event)
     *  - DOM event object
     */
    var onPointerCancel = function(e) {
      e.preventDefault();
      /* onPointerCancel handler is needed to deal with situations when a touchend
      doesn't fire after a touchstart (this happens on windows phones only) */
      setPositionProperty(slider.touch.originalPos.left, 'reset', 0);

      //remove handlers
      slider.controls.el.removeClass('disabled');
      slider.viewport.off('MSPointerCancel pointercancel', onPointerCancel);
      slider.viewport.off('touchmove MSPointerMove pointermove', onTouchMove);
      slider.viewport.off('touchend MSPointerUp pointerup', onTouchEnd);
      if (slider.viewport.get(0).releasePointerCapture) {
        slider.viewport.get(0).releasePointerCapture(slider.pointerId);
      }
    };

    /**
     * Event handler for "touchmove"
     *
     * @param e (event)
     *  - DOM event object
     */
    var onTouchMove = function(e) {
      var orig = e.originalEvent,
      touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig],
      // if scrolling on y axis, do not prevent default
      xMovement = Math.abs(touchPoints[0].pageX - slider.touch.start.x),
      yMovement = Math.abs(touchPoints[0].pageY - slider.touch.start.y),
      value = 0,
      change = 0;
      // this is swipe
      slider.hasMove = true;

      // x axis swipe
      if ((xMovement * 3) > yMovement && slider.settings.preventDefaultSwipeX) {
        e.preventDefault();
      // y axis swipe
      } else if ((yMovement * 3) > xMovement && slider.settings.preventDefaultSwipeY) {
        e.preventDefault();
      }
      if (e.type !== 'touchmove') {
        e.preventDefault();
      }

      if (slider.settings.mode !== 'fade' && slider.settings.oneToOneTouch) {
        // if horizontal, drag along x axis
        if (slider.settings.mode === 'horizontal') {
          change = touchPoints[0].pageX - slider.touch.start.x;
          value = slider.touch.originalPos.left + change;
        // if vertical, drag along y axis
        } else {
          change = touchPoints[0].pageY - slider.touch.start.y;
          value = slider.touch.originalPos.top + change;
        }
        setPositionProperty(value, 'reset', 0);
      }
    };

    /**
     * Event handler for "touchend"
     *
     * @param e (event)
     *  - DOM event object
     */
    var onTouchEnd = function(e) {
      e.preventDefault();
      slider.viewport.off('touchmove MSPointerMove pointermove', onTouchMove);
      //enable slider controls as soon as user stops interacing with slides
      slider.controls.el.removeClass('disabled');
      var orig    = e.originalEvent,
      touchPoints = (typeof orig.changedTouches !== 'undefined') ? orig.changedTouches : [orig],
      value       = 0,
      distance    = 0;
      // record end x, y positions
      slider.touch.end.x = touchPoints[0].pageX;
      slider.touch.end.y = touchPoints[0].pageY;
      // if fade mode, check if absolute x distance clears the threshold
      if (slider.settings.mode === 'fade') {
        distance = Math.abs(slider.touch.start.x - slider.touch.end.x);
        if (distance >= slider.settings.swipeThreshold) {
          if (slider.touch.start.x > slider.touch.end.x) {
            el.goToNextSlide();
          } else {
            el.goToPrevSlide();
          }
          el.stopAuto();
        }
      // not fade mode
      } else {
        // calculate distance and el's animate property
        if (slider.settings.mode === 'horizontal') {
          distance = slider.touch.end.x - slider.touch.start.x;
          value = slider.touch.originalPos.left;
        } else {
          distance = slider.touch.end.y - slider.touch.start.y;
          value = slider.touch.originalPos.top;
        }
        // if not infinite loop and first / last slide, do not attempt a slide transition
        if (!slider.settings.infiniteLoop && ((slider.active.index === 0 && distance > 0) || (slider.active.last && distance < 0))) {
          setPositionProperty(value, 'reset', 200);
        } else {
          // check if distance clears threshold
          if (Math.abs(distance) >= slider.settings.swipeThreshold) {
            if (distance < 0) {
              el.goToNextSlide();
            } else {
              el.goToPrevSlide();
            }
            el.stopAuto();
          } else {
            // el.animate(property, 200);
            setPositionProperty(value, 'reset', 200);
          }
        }
      }
      slider.viewport.off('touchend MSPointerUp pointerup', onTouchEnd);

      if (slider.viewport.get(0).releasePointerCapture) {
        slider.viewport.get(0).releasePointerCapture(slider.pointerId);
      }
      // if slider had swipe with left mouse, touch contact and pen contact
      if (slider.hasMove === false && (slider.originalClickButton === 0 || slider.originalEventType === 'touchstart')) {
        // trigger click event (fix for Firefox59 and PointerEvent standard compatibility)
        $(slider.originalClickTarget).trigger({
          type: 'click',
          button: slider.originalClickButton,
          buttons: slider.originalClickButtons
        });
      }
    };

    /**
     * Window resize event callback
     */
    var resizeWindow = function(e) {
      // don't do anything if slider isn't initialized.
      if (!slider.initialized) { return; }
      // Delay if slider working.
      if (slider.working) {
        window.setTimeout(resizeWindow, 10);
      } else {
        // get the new window dimens (again, thank you IE)
        var windowWidthNew = $(window).width(),
        windowHeightNew = $(window).height();
        // make sure that it is a true window resize
        // *we must check this because our dinosaur friend IE fires a window resize event when certain DOM elements
        // are resized. Can you just die already?*
        if (windowWidth !== windowWidthNew || windowHeight !== windowHeightNew) {
          // set the new window dimens
          windowWidth = windowWidthNew;
          windowHeight = windowHeightNew;
          // update all dynamic elements
          el.redrawSlider();
          // Call user resize handler
          slider.settings.onSliderResize.call(el, slider.active.index);
        }
      }
    };

    /**
     * Adds an aria-hidden=true attribute to each element
     *
     * @param startVisibleIndex (int)
     *  - the first visible element's index
     */
    var applyAriaHiddenAttributes = function(startVisibleIndex) {
      var numberOfSlidesShowing = getNumberSlidesShowing();
      // only apply attributes if the setting is enabled and not in ticker mode
      if (slider.settings.ariaHidden && !slider.settings.ticker) {
        // add aria-hidden=true to all elements
        slider.children.attr('aria-hidden', 'true');
        // get the visible elements and change to aria-hidden=false
        slider.children.slice(startVisibleIndex, startVisibleIndex + numberOfSlidesShowing).attr('aria-hidden', 'false');
      }
    };

    /**
     * Returns index according to present page range
     *
     * @param slideOndex (int)
     *  - the desired slide index
     */
    var setSlideIndex = function(slideIndex) {
      if (slideIndex < 0) {
        if (slider.settings.infiniteLoop) {
          return getPagerQty() - 1;
        }else {
          //we don't go to undefined slides
          return slider.active.index;
        }
      // if slideIndex is greater than children length, set active index to 0 (this happens during infinite loop)
      } else if (slideIndex >= getPagerQty()) {
        if (slider.settings.infiniteLoop) {
          return 0;
        } else {
          //we don't move to undefined pages
          return slider.active.index;
        }
      // set active index to requested slide
      } else {
        return slideIndex;
      }
    };

    /**
     * ===================================================================================
     * = PUBLIC FUNCTIONS
     * ===================================================================================
     */

    /**
     * Performs slide transition to the specified slide
     *
     * @param slideIndex (int)
     *  - the destination slide's index (zero-based)
     *
     * @param direction (string)
     *  - INTERNAL USE ONLY - the direction of travel ("prev" / "next")
     */
    el.goToSlide = function(slideIndex, direction) {
      // onSlideBefore, onSlideNext, onSlidePrev callbacks
      // Allow transition canceling based on returned value
      var performTransition = true,
      moveBy = 0,
      position = {left: 0, top: 0},
      lastChild = null,
      lastShowingIndex, eq, value, requestEl;
      // store the old index
      slider.oldIndex = slider.active.index;
      //set new index
      slider.active.index = setSlideIndex(slideIndex);

      // if plugin is currently in motion, ignore request
      if (slider.working || slider.active.index === slider.oldIndex) { return; }
      // declare that plugin is in motion
      slider.working = true;

      performTransition = slider.settings.onSlideBefore.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index);

      // If transitions canceled, reset and return
      if (typeof (performTransition) !== 'undefined' && !performTransition) {
        slider.active.index = slider.oldIndex; // restore old index
        slider.working = false; // is not in motion
        return;
      }

      if (direction === 'next') {
        // Prevent canceling in future functions or lack there-of from negating previous commands to cancel
        if (!slider.settings.onSlideNext.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index)) {
          performTransition = false;
        }
      } else if (direction === 'prev') {
        // Prevent canceling in future functions or lack there-of from negating previous commands to cancel
        if (!slider.settings.onSlidePrev.call(el, slider.children.eq(slider.active.index), slider.oldIndex, slider.active.index)) {
          performTransition = false;
        }
      }

      // check if last slide
      slider.active.last = slider.active.index >= getPagerQty() - 1;
      // update the pager with active class
      if (slider.settings.pager || slider.settings.pagerCustom) { updatePagerActive(slider.active.index); }
      // // check for direction control update
      if (slider.settings.controls) { updateDirectionControls(); }
      // if slider is set to mode: "fade"
      if (slider.settings.mode === 'fade') {
        // if adaptiveHeight is true and next height is different from current height, animate to the new height
        if (slider.settings.adaptiveHeight && slider.viewport.height() !== getViewportHeight()) {
          slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed);
        }
        // fade out the visible child and reset its z-index value
        slider.children.filter(':visible').fadeOut(slider.settings.speed).css({zIndex: 0});
        // fade in the newly requested slide
        slider.children.eq(slider.active.index).css('zIndex', slider.settings.slideZIndex + 1).fadeIn(slider.settings.speed, function() {
          $(this).css('zIndex', slider.settings.slideZIndex);
          updateAfterSlideTransition();
        });
      // slider mode is not "fade"
      } else {
        // if adaptiveHeight is true and next height is different from current height, animate to the new height
        if (slider.settings.adaptiveHeight && slider.viewport.height() !== getViewportHeight()) {
          slider.viewport.animate({height: getViewportHeight()}, slider.settings.adaptiveHeightSpeed);
        }
        // if carousel and not infinite loop
        if (!slider.settings.infiniteLoop && slider.carousel && slider.active.last) {
          if (slider.settings.mode === 'horizontal') {
            // get the last child position
            lastChild = slider.children.eq(slider.children.length - 1);
            position = lastChild.position();
            // calculate the position of the last slide
            moveBy = slider.viewport.width() - lastChild.outerWidth();
          } else {
            // get last showing index position
            lastShowingIndex = slider.children.length - slider.settings.minSlides;
            position = slider.children.eq(lastShowingIndex).position();
          }
          // horizontal carousel, going previous while on first slide (infiniteLoop mode)
        } else if (slider.carousel && slider.active.last && direction === 'prev') {
          // get the last child position
          eq = slider.settings.moveSlides === 1 ? slider.settings.maxSlides - getMoveBy() : ((getPagerQty() - 1) * getMoveBy()) - (slider.children.length - slider.settings.maxSlides);
          lastChild = el.children('.bx-clone').eq(eq);
          position = lastChild.position();
        // if infinite loop and "Next" is clicked on the last slide
        } else if (direction === 'next' && slider.active.index === 0) {
          // get the last clone position
          position = el.find('> .bx-clone').eq(slider.settings.maxSlides).position();
          slider.active.last = false;
        // normal non-zero requests
        } else if (slideIndex >= 0) {
          //parseInt is applied to allow floats for slides/page
          requestEl = slideIndex * parseInt(getMoveBy());
          position = slider.children.eq(requestEl).position();
        }

        /* If the position doesn't exist
         * (e.g. if you destroy the slider on a next click),
         * it doesn't throw an error.
         */
        if (typeof (position) !== 'undefined') {
          value = slider.settings.mode === 'horizontal' ? -(position.left - moveBy) : -position.top;
          // plugin values to be animated
          setPositionProperty(value, 'slide', slider.settings.speed);
        }
        slider.working = false;
      }
      if (slider.settings.ariaHidden) { applyAriaHiddenAttributes(slider.active.index * getMoveBy()); }
    };

    /**
     * Transitions to the next slide in the show
     */
    el.goToNextSlide = function() {
      // if infiniteLoop is false and last page is showing, disregard call
      if (!slider.settings.infiniteLoop && slider.active.last) { return; }
	  if (slider.working === true){ return ;}
      var pagerIndex = parseInt(slider.active.index) + 1;
      el.goToSlide(pagerIndex, 'next');
    };

    /**
     * Transitions to the prev slide in the show
     */
    el.goToPrevSlide = function() {
      // if infiniteLoop is false and last page is showing, disregard call
      if (!slider.settings.infiniteLoop && slider.active.index === 0) { return; }
	  if (slider.working === true){ return ;}
      var pagerIndex = parseInt(slider.active.index) - 1;
      el.goToSlide(pagerIndex, 'prev');
    };

    /**
     * Starts the auto show
     *
     * @param preventControlUpdate (boolean)
     *  - if true, auto controls state will not be updated
     */
    el.startAuto = function(preventControlUpdate) {
      // if an interval already exists, disregard call
      if (slider.interval) { return; }
      // create an interval
      slider.interval = setInterval(function() {
        if (slider.settings.autoDirection === 'next') {
          el.goToNextSlide();
        } else {
          el.goToPrevSlide();
        }
      }, slider.settings.pause);
	  //allback for when the auto rotate status changes
	  slider.settings.onAutoChange.call(el, true);
      // if auto controls are displayed and preventControlUpdate is not true
      if (slider.settings.autoControls && preventControlUpdate !== true) { updateAutoControls('stop'); }
    };

    /**
     * Stops the auto show
     *
     * @param preventControlUpdate (boolean)
     *  - if true, auto controls state will not be updated
     */
    el.stopAuto = function(preventControlUpdate) {
      // if slider is auto paused, just clear that state
      if (slider.autoPaused) slider.autoPaused = false;
      // if no interval exists, disregard call
      if (!slider.interval) { return; }
      // clear the interval
      clearInterval(slider.interval);
      slider.interval = null;
	  //allback for when the auto rotate status changes
	  slider.settings.onAutoChange.call(el, false);
      // if auto controls are displayed and preventControlUpdate is not true
      if (slider.settings.autoControls && preventControlUpdate !== true) { updateAutoControls('start'); }
    };

    /**
     * Returns current slide index (zero-based)
     */
    el.getCurrentSlide = function() {
      return slider.active.index;
    };

    /**
     * Returns current slide element
     */
    el.getCurrentSlideElement = function() {
      return slider.children.eq(slider.active.index);
    };

    /**
     * Returns a slide element
     * @param index (int)
     *  - The index (zero-based) of the element you want returned.
     */
    el.getSlideElement = function(index) {
      return slider.children.eq(index);
    };

    /**
     * Returns number of slides in show
     */
    el.getSlideCount = function() {
      return slider.children.length;
    };

    /**
     * Return slider.working variable
     */
    el.isWorking = function() {
      return slider.working;
    };

    /**
     * Update all dynamic slider elements
     */
    el.redrawSlider = function() {
      // resize all children in ratio to new screen size
      slider.children.add(el.find('.bx-clone')).outerWidth(getSlideWidth());
      // adjust the height
      slider.viewport.css('height', getViewportHeight());
      // update the slide position
      if (!slider.settings.ticker) { setSlidePosition(); }
      // if active.last was true before the screen resize, we want
      // to keep it last no matter what screen size we end on
      if (slider.active.last) { slider.active.index = getPagerQty() - 1; }
      // if the active index (page) no longer exists due to the resize, simply set the index as last
      if (slider.active.index >= getPagerQty()) { slider.active.last = true; }
      // if a pager is being displayed and a custom pager is not being used, update it
      if (slider.settings.pager && !slider.settings.pagerCustom) {
        populatePager();
        updatePagerActive(slider.active.index);
      }
      if (slider.settings.ariaHidden) { applyAriaHiddenAttributes(slider.active.index * getMoveBy()); }
    };

    /**
     * Destroy the current instance of the slider (revert everything back to original state)
     */
    el.destroySlider = function() {
      // don't do anything if slider has already been destroyed
      if (!slider.initialized) { return; }
      slider.initialized = false;
      $('.bx-clone', this).remove();
      slider.children.each(function() {
        if ($(this).data('origStyle') !== undefined) {
          $(this).attr('style', $(this).data('origStyle'));
        } else {
          $(this).removeAttr('style');
        }
      });
      if ($(this).data('origStyle') !== undefined) {
        this.attr('style', $(this).data('origStyle'));
      } else {
        $(this).removeAttr('style');
      }
      $(this).unwrap().unwrap();
      if (slider.controls.el) { slider.controls.el.remove(); }
      if (slider.controls.next) { slider.controls.next.remove(); }
      if (slider.controls.prev) { slider.controls.prev.remove(); }
      if (slider.pagerEl && slider.settings.controls && !slider.settings.pagerCustom) { slider.pagerEl.remove(); }
      $('.bx-caption', this).remove();
      if (slider.controls.autoEl) { slider.controls.autoEl.remove(); }
      clearInterval(slider.interval);
      if (slider.settings.responsive) { $(window).off('resize', resizeWindow); }
      if (slider.settings.keyboardEnabled) { $(document).off('keydown', keyPress); }
      //remove self reference in data
      $(this).removeData('bxSlider');
	  // remove global window handlers
	  $(window).off('blur', windowBlurHandler).off('focus', windowFocusHandler);
    };

    /**
     * Reload the slider (revert all DOM changes, and re-initialize)
     */
    el.reloadSlider = function(settings) {
      if (settings !== undefined) { options = settings; }
      el.destroySlider();
      init();
      //store reference to self in order to access public functions later
      $(el).data('bxSlider', this);
    };

    init();

    $(el).data('bxSlider', this);

    // returns the current jQuery object
    return this;
  };

})(jQuery);

/*
     _ _      _       _
 ___| (_) ___| | __  (_)___
/ __| | |/ __| |/ /  | / __|
\__ \ | | (__|   < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
                   |__/

 Version: 1.8.1
  Author: Ken Wheeler
 Website: http://kenwheeler.github.io
    Docs: http://kenwheeler.github.io/slick
    Repo: http://github.com/kenwheeler/slick
  Issues: http://github.com/kenwheeler/slick/issues

 */
!function(i){"use strict";"function"==typeof define&&define.amd?define(["jquery"],i):"undefined"!=typeof exports?module.exports=i(require("jquery")):i(jQuery)}(function(i){"use strict";var e=window.Slick||{};(e=function(){var e=0;return function(t,o){var s,n=this;n.defaults={accessibility:!0,adaptiveHeight:!1,appendArrows:i(t),appendDots:i(t),arrows:!0,asNavFor:null,prevArrow:'<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',nextArrow:'<button class="slick-next" aria-label="Next" type="button">Next</button>',autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",customPaging:function(e,t){return i('<button type="button" />').text(t+1)},dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,focusOnChange:!1,infinite:!0,initialSlide:0,lazyLoad:"ondemand",mobileFirst:!1,pauseOnHover:!0,pauseOnFocus:!0,pauseOnDotsHover:!1,respondTo:"window",responsive:null,rows:1,rtl:!1,slide:"",slidesPerRow:1,slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,useTransform:!0,variableWidth:!1,vertical:!1,verticalSwiping:!1,waitForAnimate:!0,zIndex:1e3},n.initials={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,$dots:null,listWidth:null,listHeight:null,loadIndex:0,$nextArrow:null,$prevArrow:null,scrolling:!1,slideCount:null,slideWidth:null,$slideTrack:null,$slides:null,sliding:!1,slideOffset:0,swipeLeft:null,swiping:!1,$list:null,touchObject:{},transformsEnabled:!1,unslicked:!1},i.extend(n,n.initials),n.activeBreakpoint=null,n.animType=null,n.animProp=null,n.breakpoints=[],n.breakpointSettings=[],n.cssTransitions=!1,n.focussed=!1,n.interrupted=!1,n.hidden="hidden",n.paused=!0,n.positionProp=null,n.respondTo=null,n.rowCount=1,n.shouldClick=!0,n.$slider=i(t),n.$slidesCache=null,n.transformType=null,n.transitionType=null,n.visibilityChange="visibilitychange",n.windowWidth=0,n.windowTimer=null,s=i(t).data("slick")||{},n.options=i.extend({},n.defaults,o,s),n.currentSlide=n.options.initialSlide,n.originalSettings=n.options,void 0!==document.mozHidden?(n.hidden="mozHidden",n.visibilityChange="mozvisibilitychange"):void 0!==document.webkitHidden&&(n.hidden="webkitHidden",n.visibilityChange="webkitvisibilitychange"),n.autoPlay=i.proxy(n.autoPlay,n),n.autoPlayClear=i.proxy(n.autoPlayClear,n),n.autoPlayIterator=i.proxy(n.autoPlayIterator,n),n.changeSlide=i.proxy(n.changeSlide,n),n.clickHandler=i.proxy(n.clickHandler,n),n.selectHandler=i.proxy(n.selectHandler,n),n.setPosition=i.proxy(n.setPosition,n),n.swipeHandler=i.proxy(n.swipeHandler,n),n.dragHandler=i.proxy(n.dragHandler,n),n.keyHandler=i.proxy(n.keyHandler,n),n.instanceUid=e++,n.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/,n.registerBreakpoints(),n.init(!0)}}()).prototype.activateADA=function(){this.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})},e.prototype.addSlide=e.prototype.slickAdd=function(e,t,o){var s=this;if("boolean"==typeof t)o=t,t=null;else if(t<0||t>=s.slideCount)return!1;s.unload(),"number"==typeof t?0===t&&0===s.$slides.length?i(e).appendTo(s.$slideTrack):o?i(e).insertBefore(s.$slides.eq(t)):i(e).insertAfter(s.$slides.eq(t)):!0===o?i(e).prependTo(s.$slideTrack):i(e).appendTo(s.$slideTrack),s.$slides=s.$slideTrack.children(this.options.slide),s.$slideTrack.children(this.options.slide).detach(),s.$slideTrack.append(s.$slides),s.$slides.each(function(e,t){i(t).attr("data-slick-index",e)}),s.$slidesCache=s.$slides,s.reinit()},e.prototype.animateHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.animate({height:e},i.options.speed)}},e.prototype.animateSlide=function(e,t){var o={},s=this;s.animateHeight(),!0===s.options.rtl&&!1===s.options.vertical&&(e=-e),!1===s.transformsEnabled?!1===s.options.vertical?s.$slideTrack.animate({left:e},s.options.speed,s.options.easing,t):s.$slideTrack.animate({top:e},s.options.speed,s.options.easing,t):!1===s.cssTransitions?(!0===s.options.rtl&&(s.currentLeft=-s.currentLeft),i({animStart:s.currentLeft}).animate({animStart:e},{duration:s.options.speed,easing:s.options.easing,step:function(i){i=Math.ceil(i),!1===s.options.vertical?(o[s.animType]="translate("+i+"px, 0px)",s.$slideTrack.css(o)):(o[s.animType]="translate(0px,"+i+"px)",s.$slideTrack.css(o))},complete:function(){t&&t.call()}})):(s.applyTransition(),e=Math.ceil(e),!1===s.options.vertical?o[s.animType]="translate3d("+e+"px, 0px, 0px)":o[s.animType]="translate3d(0px,"+e+"px, 0px)",s.$slideTrack.css(o),t&&setTimeout(function(){s.disableTransition(),t.call()},s.options.speed))},e.prototype.getNavTarget=function(){var e=this,t=e.options.asNavFor;return t&&null!==t&&(t=i(t).not(e.$slider)),t},e.prototype.asNavFor=function(e){var t=this.getNavTarget();null!==t&&"object"==typeof t&&t.each(function(){var t=i(this).slick("getSlick");t.unslicked||t.slideHandler(e,!0)})},e.prototype.applyTransition=function(i){var e=this,t={};!1===e.options.fade?t[e.transitionType]=e.transformType+" "+e.options.speed+"ms "+e.options.cssEase:t[e.transitionType]="opacity "+e.options.speed+"ms "+e.options.cssEase,!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.autoPlay=function(){var i=this;i.autoPlayClear(),i.slideCount>i.options.slidesToShow&&(i.autoPlayTimer=setInterval(i.autoPlayIterator,i.options.autoplaySpeed))},e.prototype.autoPlayClear=function(){var i=this;i.autoPlayTimer&&clearInterval(i.autoPlayTimer)},e.prototype.autoPlayIterator=function(){var i=this,e=i.currentSlide+i.options.slidesToScroll;i.paused||i.interrupted||i.focussed||(!1===i.options.infinite&&(1===i.direction&&i.currentSlide+1===i.slideCount-1?i.direction=0:0===i.direction&&(e=i.currentSlide-i.options.slidesToScroll,i.currentSlide-1==0&&(i.direction=1))),i.slideHandler(e))},e.prototype.buildArrows=function(){var e=this;!0===e.options.arrows&&(e.$prevArrow=i(e.options.prevArrow).addClass("slick-arrow"),e.$nextArrow=i(e.options.nextArrow).addClass("slick-arrow"),e.slideCount>e.options.slidesToShow?(e.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex"),e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.prependTo(e.options.appendArrows),e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.appendTo(e.options.appendArrows),!0!==e.options.infinite&&e.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")):e.$prevArrow.add(e.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"}))},e.prototype.buildDots=function(){var e,t,o=this;if(!0===o.options.dots){for(o.$slider.addClass("slick-dotted"),t=i("<ul />").addClass(o.options.dotsClass),e=0;e<=o.getDotCount();e+=1)t.append(i("<li />").append(o.options.customPaging.call(this,o,e)));o.$dots=t.appendTo(o.options.appendDots),o.$dots.find("li").first().addClass("slick-active")}},e.prototype.buildOut=function(){var e=this;e.$slides=e.$slider.children(e.options.slide+":not(.slick-cloned)").addClass("slick-slide"),e.slideCount=e.$slides.length,e.$slides.each(function(e,t){i(t).attr("data-slick-index",e).data("originalStyling",i(t).attr("style")||"")}),e.$slider.addClass("slick-slider"),e.$slideTrack=0===e.slideCount?i('<div class="slick-track"/>').appendTo(e.$slider):e.$slides.wrapAll('<div class="slick-track"/>').parent(),e.$list=e.$slideTrack.wrap('<div class="slick-list"/>').parent(),e.$slideTrack.css("opacity",0),!0!==e.options.centerMode&&!0!==e.options.swipeToSlide||(e.options.slidesToScroll=1),i("img[data-lazy]",e.$slider).not("[src]").addClass("slick-loading"),e.setupInfinite(),e.buildArrows(),e.buildDots(),e.updateDots(),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),!0===e.options.draggable&&e.$list.addClass("draggable")},e.prototype.buildRows=function(){var i,e,t,o,s,n,r,l=this;if(o=document.createDocumentFragment(),n=l.$slider.children(),l.options.rows>1){for(r=l.options.slidesPerRow*l.options.rows,s=Math.ceil(n.length/r),i=0;i<s;i++){var d=document.createElement("div");for(e=0;e<l.options.rows;e++){var a=document.createElement("div");for(t=0;t<l.options.slidesPerRow;t++){var c=i*r+(e*l.options.slidesPerRow+t);n.get(c)&&a.appendChild(n.get(c))}d.appendChild(a)}o.appendChild(d)}l.$slider.empty().append(o),l.$slider.children().children().children().css({width:100/l.options.slidesPerRow+"%",display:"inline-block"})}},e.prototype.checkResponsive=function(e,t){var o,s,n,r=this,l=!1,d=r.$slider.width(),a=window.innerWidth||i(window).width();if("window"===r.respondTo?n=a:"slider"===r.respondTo?n=d:"min"===r.respondTo&&(n=Math.min(a,d)),r.options.responsive&&r.options.responsive.length&&null!==r.options.responsive){s=null;for(o in r.breakpoints)r.breakpoints.hasOwnProperty(o)&&(!1===r.originalSettings.mobileFirst?n<r.breakpoints[o]&&(s=r.breakpoints[o]):n>r.breakpoints[o]&&(s=r.breakpoints[o]));null!==s?null!==r.activeBreakpoint?(s!==r.activeBreakpoint||t)&&(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):(r.activeBreakpoint=s,"unslick"===r.breakpointSettings[s]?r.unslick(s):(r.options=i.extend({},r.originalSettings,r.breakpointSettings[s]),!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e)),l=s):null!==r.activeBreakpoint&&(r.activeBreakpoint=null,r.options=r.originalSettings,!0===e&&(r.currentSlide=r.options.initialSlide),r.refresh(e),l=s),e||!1===l||r.$slider.trigger("breakpoint",[r,l])}},e.prototype.changeSlide=function(e,t){var o,s,n,r=this,l=i(e.currentTarget);switch(l.is("a")&&e.preventDefault(),l.is("li")||(l=l.closest("li")),n=r.slideCount%r.options.slidesToScroll!=0,o=n?0:(r.slideCount-r.currentSlide)%r.options.slidesToScroll,e.data.message){case"previous":s=0===o?r.options.slidesToScroll:r.options.slidesToShow-o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide-s,!1,t);break;case"next":s=0===o?r.options.slidesToScroll:o,r.slideCount>r.options.slidesToShow&&r.slideHandler(r.currentSlide+s,!1,t);break;case"index":var d=0===e.data.index?0:e.data.index||l.index()*r.options.slidesToScroll;r.slideHandler(r.checkNavigable(d),!1,t),l.children().trigger("focus");break;default:return}},e.prototype.checkNavigable=function(i){var e,t;if(e=this.getNavigableIndexes(),t=0,i>e[e.length-1])i=e[e.length-1];else for(var o in e){if(i<e[o]){i=t;break}t=e[o]}return i},e.prototype.cleanUpEvents=function(){var e=this;e.options.dots&&null!==e.$dots&&(i("li",e.$dots).off("click.slick",e.changeSlide).off("mouseenter.slick",i.proxy(e.interrupt,e,!0)).off("mouseleave.slick",i.proxy(e.interrupt,e,!1)),!0===e.options.accessibility&&e.$dots.off("keydown.slick",e.keyHandler)),e.$slider.off("focus.slick blur.slick"),!0===e.options.arrows&&e.slideCount>e.options.slidesToShow&&(e.$prevArrow&&e.$prevArrow.off("click.slick",e.changeSlide),e.$nextArrow&&e.$nextArrow.off("click.slick",e.changeSlide),!0===e.options.accessibility&&(e.$prevArrow&&e.$prevArrow.off("keydown.slick",e.keyHandler),e.$nextArrow&&e.$nextArrow.off("keydown.slick",e.keyHandler))),e.$list.off("touchstart.slick mousedown.slick",e.swipeHandler),e.$list.off("touchmove.slick mousemove.slick",e.swipeHandler),e.$list.off("touchend.slick mouseup.slick",e.swipeHandler),e.$list.off("touchcancel.slick mouseleave.slick",e.swipeHandler),e.$list.off("click.slick",e.clickHandler),i(document).off(e.visibilityChange,e.visibility),e.cleanUpSlideEvents(),!0===e.options.accessibility&&e.$list.off("keydown.slick",e.keyHandler),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().off("click.slick",e.selectHandler),i(window).off("orientationchange.slick.slick-"+e.instanceUid,e.orientationChange),i(window).off("resize.slick.slick-"+e.instanceUid,e.resize),i("[draggable!=true]",e.$slideTrack).off("dragstart",e.preventDefault),i(window).off("load.slick.slick-"+e.instanceUid,e.setPosition)},e.prototype.cleanUpSlideEvents=function(){var e=this;e.$list.off("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.off("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.cleanUpRows=function(){var i,e=this;e.options.rows>1&&((i=e.$slides.children().children()).removeAttr("style"),e.$slider.empty().append(i))},e.prototype.clickHandler=function(i){!1===this.shouldClick&&(i.stopImmediatePropagation(),i.stopPropagation(),i.preventDefault())},e.prototype.destroy=function(e){var t=this;t.autoPlayClear(),t.touchObject={},t.cleanUpEvents(),i(".slick-cloned",t.$slider).detach(),t.$dots&&t.$dots.remove(),t.$prevArrow&&t.$prevArrow.length&&(t.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.prevArrow)&&t.$prevArrow.remove()),t.$nextArrow&&t.$nextArrow.length&&(t.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display",""),t.htmlExpr.test(t.options.nextArrow)&&t.$nextArrow.remove()),t.$slides&&(t.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){i(this).attr("style",i(this).data("originalStyling"))}),t.$slideTrack.children(this.options.slide).detach(),t.$slideTrack.detach(),t.$list.detach(),t.$slider.append(t.$slides)),t.cleanUpRows(),t.$slider.removeClass("slick-slider"),t.$slider.removeClass("slick-initialized"),t.$slider.removeClass("slick-dotted"),t.unslicked=!0,e||t.$slider.trigger("destroy",[t])},e.prototype.disableTransition=function(i){var e=this,t={};t[e.transitionType]="",!1===e.options.fade?e.$slideTrack.css(t):e.$slides.eq(i).css(t)},e.prototype.fadeSlide=function(i,e){var t=this;!1===t.cssTransitions?(t.$slides.eq(i).css({zIndex:t.options.zIndex}),t.$slides.eq(i).animate({opacity:1},t.options.speed,t.options.easing,e)):(t.applyTransition(i),t.$slides.eq(i).css({opacity:1,zIndex:t.options.zIndex}),e&&setTimeout(function(){t.disableTransition(i),e.call()},t.options.speed))},e.prototype.fadeSlideOut=function(i){var e=this;!1===e.cssTransitions?e.$slides.eq(i).animate({opacity:0,zIndex:e.options.zIndex-2},e.options.speed,e.options.easing):(e.applyTransition(i),e.$slides.eq(i).css({opacity:0,zIndex:e.options.zIndex-2}))},e.prototype.filterSlides=e.prototype.slickFilter=function(i){var e=this;null!==i&&(e.$slidesCache=e.$slides,e.unload(),e.$slideTrack.children(this.options.slide).detach(),e.$slidesCache.filter(i).appendTo(e.$slideTrack),e.reinit())},e.prototype.focusHandler=function(){var e=this;e.$slider.off("focus.slick blur.slick").on("focus.slick blur.slick","*",function(t){t.stopImmediatePropagation();var o=i(this);setTimeout(function(){e.options.pauseOnFocus&&(e.focussed=o.is(":focus"),e.autoPlay())},0)})},e.prototype.getCurrent=e.prototype.slickCurrentSlide=function(){return this.currentSlide},e.prototype.getDotCount=function(){var i=this,e=0,t=0,o=0;if(!0===i.options.infinite)if(i.slideCount<=i.options.slidesToShow)++o;else for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else if(!0===i.options.centerMode)o=i.slideCount;else if(i.options.asNavFor)for(;e<i.slideCount;)++o,e=t+i.options.slidesToScroll,t+=i.options.slidesToScroll<=i.options.slidesToShow?i.options.slidesToScroll:i.options.slidesToShow;else o=1+Math.ceil((i.slideCount-i.options.slidesToShow)/i.options.slidesToScroll);return o-1},e.prototype.getLeft=function(i){var e,t,o,s,n=this,r=0;return n.slideOffset=0,t=n.$slides.first().outerHeight(!0),!0===n.options.infinite?(n.slideCount>n.options.slidesToShow&&(n.slideOffset=n.slideWidth*n.options.slidesToShow*-1,s=-1,!0===n.options.vertical&&!0===n.options.centerMode&&(2===n.options.slidesToShow?s=-1.5:1===n.options.slidesToShow&&(s=-2)),r=t*n.options.slidesToShow*s),n.slideCount%n.options.slidesToScroll!=0&&i+n.options.slidesToScroll>n.slideCount&&n.slideCount>n.options.slidesToShow&&(i>n.slideCount?(n.slideOffset=(n.options.slidesToShow-(i-n.slideCount))*n.slideWidth*-1,r=(n.options.slidesToShow-(i-n.slideCount))*t*-1):(n.slideOffset=n.slideCount%n.options.slidesToScroll*n.slideWidth*-1,r=n.slideCount%n.options.slidesToScroll*t*-1))):i+n.options.slidesToShow>n.slideCount&&(n.slideOffset=(i+n.options.slidesToShow-n.slideCount)*n.slideWidth,r=(i+n.options.slidesToShow-n.slideCount)*t),n.slideCount<=n.options.slidesToShow&&(n.slideOffset=0,r=0),!0===n.options.centerMode&&n.slideCount<=n.options.slidesToShow?n.slideOffset=n.slideWidth*Math.floor(n.options.slidesToShow)/2-n.slideWidth*n.slideCount/2:!0===n.options.centerMode&&!0===n.options.infinite?n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)-n.slideWidth:!0===n.options.centerMode&&(n.slideOffset=0,n.slideOffset+=n.slideWidth*Math.floor(n.options.slidesToShow/2)),e=!1===n.options.vertical?i*n.slideWidth*-1+n.slideOffset:i*t*-1+r,!0===n.options.variableWidth&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,!0===n.options.centerMode&&(o=n.slideCount<=n.options.slidesToShow||!1===n.options.infinite?n.$slideTrack.children(".slick-slide").eq(i):n.$slideTrack.children(".slick-slide").eq(i+n.options.slidesToShow+1),e=!0===n.options.rtl?o[0]?-1*(n.$slideTrack.width()-o[0].offsetLeft-o.width()):0:o[0]?-1*o[0].offsetLeft:0,e+=(n.$list.width()-o.outerWidth())/2)),e},e.prototype.getOption=e.prototype.slickGetOption=function(i){return this.options[i]},e.prototype.getNavigableIndexes=function(){var i,e=this,t=0,o=0,s=[];for(!1===e.options.infinite?i=e.slideCount:(t=-1*e.options.slidesToScroll,o=-1*e.options.slidesToScroll,i=2*e.slideCount);t<i;)s.push(t),t=o+e.options.slidesToScroll,o+=e.options.slidesToScroll<=e.options.slidesToShow?e.options.slidesToScroll:e.options.slidesToShow;return s},e.prototype.getSlick=function(){return this},e.prototype.getSlideCount=function(){var e,t,o=this;return t=!0===o.options.centerMode?o.slideWidth*Math.floor(o.options.slidesToShow/2):0,!0===o.options.swipeToSlide?(o.$slideTrack.find(".slick-slide").each(function(s,n){if(n.offsetLeft-t+i(n).outerWidth()/2>-1*o.swipeLeft)return e=n,!1}),Math.abs(i(e).attr("data-slick-index")-o.currentSlide)||1):o.options.slidesToScroll},e.prototype.goTo=e.prototype.slickGoTo=function(i,e){this.changeSlide({data:{message:"index",index:parseInt(i)}},e)},e.prototype.init=function(e){var t=this;i(t.$slider).hasClass("slick-initialized")||(i(t.$slider).addClass("slick-initialized"),t.buildRows(),t.buildOut(),t.setProps(),t.startLoad(),t.loadSlider(),t.initializeEvents(),t.updateArrows(),t.updateDots(),t.checkResponsive(!0),t.focusHandler()),e&&t.$slider.trigger("init",[t]),!0===t.options.accessibility&&t.initADA(),t.options.autoplay&&(t.paused=!1,t.autoPlay())},e.prototype.initADA=function(){var e=this,t=Math.ceil(e.slideCount/e.options.slidesToShow),o=e.getNavigableIndexes().filter(function(i){return i>=0&&i<e.slideCount});e.$slides.add(e.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"}),null!==e.$dots&&(e.$slides.not(e.$slideTrack.find(".slick-cloned")).each(function(t){var s=o.indexOf(t);i(this).attr({role:"tabpanel",id:"slick-slide"+e.instanceUid+t,tabindex:-1}),-1!==s&&i(this).attr({"aria-describedby":"slick-slide-control"+e.instanceUid+s})}),e.$dots.attr("role","tablist").find("li").each(function(s){var n=o[s];i(this).attr({role:"presentation"}),i(this).find("button").first().attr({role:"tab",id:"slick-slide-control"+e.instanceUid+s,"aria-controls":"slick-slide"+e.instanceUid+n,"aria-label":s+1+" of "+t,"aria-selected":null,tabindex:"-1"})}).eq(e.currentSlide).find("button").attr({"aria-selected":"true",tabindex:"0"}).end());for(var s=e.currentSlide,n=s+e.options.slidesToShow;s<n;s++)e.$slides.eq(s).attr("tabindex",0);e.activateADA()},e.prototype.initArrowEvents=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.off("click.slick").on("click.slick",{message:"previous"},i.changeSlide),i.$nextArrow.off("click.slick").on("click.slick",{message:"next"},i.changeSlide),!0===i.options.accessibility&&(i.$prevArrow.on("keydown.slick",i.keyHandler),i.$nextArrow.on("keydown.slick",i.keyHandler)))},e.prototype.initDotEvents=function(){var e=this;!0===e.options.dots&&(i("li",e.$dots).on("click.slick",{message:"index"},e.changeSlide),!0===e.options.accessibility&&e.$dots.on("keydown.slick",e.keyHandler)),!0===e.options.dots&&!0===e.options.pauseOnDotsHover&&i("li",e.$dots).on("mouseenter.slick",i.proxy(e.interrupt,e,!0)).on("mouseleave.slick",i.proxy(e.interrupt,e,!1))},e.prototype.initSlideEvents=function(){var e=this;e.options.pauseOnHover&&(e.$list.on("mouseenter.slick",i.proxy(e.interrupt,e,!0)),e.$list.on("mouseleave.slick",i.proxy(e.interrupt,e,!1)))},e.prototype.initializeEvents=function(){var e=this;e.initArrowEvents(),e.initDotEvents(),e.initSlideEvents(),e.$list.on("touchstart.slick mousedown.slick",{action:"start"},e.swipeHandler),e.$list.on("touchmove.slick mousemove.slick",{action:"move"},e.swipeHandler),e.$list.on("touchend.slick mouseup.slick",{action:"end"},e.swipeHandler),e.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},e.swipeHandler),e.$list.on("click.slick",e.clickHandler),i(document).on(e.visibilityChange,i.proxy(e.visibility,e)),!0===e.options.accessibility&&e.$list.on("keydown.slick",e.keyHandler),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),i(window).on("orientationchange.slick.slick-"+e.instanceUid,i.proxy(e.orientationChange,e)),i(window).on("resize.slick.slick-"+e.instanceUid,i.proxy(e.resize,e)),i("[draggable!=true]",e.$slideTrack).on("dragstart",e.preventDefault),i(window).on("load.slick.slick-"+e.instanceUid,e.setPosition),i(e.setPosition)},e.prototype.initUI=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.show(),i.$nextArrow.show()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.show()},e.prototype.keyHandler=function(i){var e=this;i.target.tagName.match("TEXTAREA|INPUT|SELECT")||(37===i.keyCode&&!0===e.options.accessibility?e.changeSlide({data:{message:!0===e.options.rtl?"next":"previous"}}):39===i.keyCode&&!0===e.options.accessibility&&e.changeSlide({data:{message:!0===e.options.rtl?"previous":"next"}}))},e.prototype.lazyLoad=function(){function e(e){i("img[data-lazy]",e).each(function(){var e=i(this),t=i(this).attr("data-lazy"),o=i(this).attr("data-srcset"),s=i(this).attr("data-sizes")||n.$slider.attr("data-sizes"),r=document.createElement("img");r.onload=function(){e.animate({opacity:0},100,function(){o&&(e.attr("srcset",o),s&&e.attr("sizes",s)),e.attr("src",t).animate({opacity:1},200,function(){e.removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading")}),n.$slider.trigger("lazyLoaded",[n,e,t])})},r.onerror=function(){e.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),n.$slider.trigger("lazyLoadError",[n,e,t])},r.src=t})}var t,o,s,n=this;if(!0===n.options.centerMode?!0===n.options.infinite?s=(o=n.currentSlide+(n.options.slidesToShow/2+1))+n.options.slidesToShow+2:(o=Math.max(0,n.currentSlide-(n.options.slidesToShow/2+1)),s=n.options.slidesToShow/2+1+2+n.currentSlide):(o=n.options.infinite?n.options.slidesToShow+n.currentSlide:n.currentSlide,s=Math.ceil(o+n.options.slidesToShow),!0===n.options.fade&&(o>0&&o--,s<=n.slideCount&&s++)),t=n.$slider.find(".slick-slide").slice(o,s),"anticipated"===n.options.lazyLoad)for(var r=o-1,l=s,d=n.$slider.find(".slick-slide"),a=0;a<n.options.slidesToScroll;a++)r<0&&(r=n.slideCount-1),t=(t=t.add(d.eq(r))).add(d.eq(l)),r--,l++;e(t),n.slideCount<=n.options.slidesToShow?e(n.$slider.find(".slick-slide")):n.currentSlide>=n.slideCount-n.options.slidesToShow?e(n.$slider.find(".slick-cloned").slice(0,n.options.slidesToShow)):0===n.currentSlide&&e(n.$slider.find(".slick-cloned").slice(-1*n.options.slidesToShow))},e.prototype.loadSlider=function(){var i=this;i.setPosition(),i.$slideTrack.css({opacity:1}),i.$slider.removeClass("slick-loading"),i.initUI(),"progressive"===i.options.lazyLoad&&i.progressiveLazyLoad()},e.prototype.next=e.prototype.slickNext=function(){this.changeSlide({data:{message:"next"}})},e.prototype.orientationChange=function(){var i=this;i.checkResponsive(),i.setPosition()},e.prototype.pause=e.prototype.slickPause=function(){var i=this;i.autoPlayClear(),i.paused=!0},e.prototype.play=e.prototype.slickPlay=function(){var i=this;i.autoPlay(),i.options.autoplay=!0,i.paused=!1,i.focussed=!1,i.interrupted=!1},e.prototype.postSlide=function(e){var t=this;t.unslicked||(t.$slider.trigger("afterChange",[t,e]),t.animating=!1,t.slideCount>t.options.slidesToShow&&t.setPosition(),t.swipeLeft=null,t.options.autoplay&&t.autoPlay(),!0===t.options.accessibility&&(t.initADA(),t.options.focusOnChange&&i(t.$slides.get(t.currentSlide)).attr("tabindex",0).focus()))},e.prototype.prev=e.prototype.slickPrev=function(){this.changeSlide({data:{message:"previous"}})},e.prototype.preventDefault=function(i){i.preventDefault()},e.prototype.progressiveLazyLoad=function(e){e=e||1;var t,o,s,n,r,l=this,d=i("img[data-lazy]",l.$slider);d.length?(t=d.first(),o=t.attr("data-lazy"),s=t.attr("data-srcset"),n=t.attr("data-sizes")||l.$slider.attr("data-sizes"),(r=document.createElement("img")).onload=function(){s&&(t.attr("srcset",s),n&&t.attr("sizes",n)),t.attr("src",o).removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading"),!0===l.options.adaptiveHeight&&l.setPosition(),l.$slider.trigger("lazyLoaded",[l,t,o]),l.progressiveLazyLoad()},r.onerror=function(){e<3?setTimeout(function(){l.progressiveLazyLoad(e+1)},500):(t.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error"),l.$slider.trigger("lazyLoadError",[l,t,o]),l.progressiveLazyLoad())},r.src=o):l.$slider.trigger("allImagesLoaded",[l])},e.prototype.refresh=function(e){var t,o,s=this;o=s.slideCount-s.options.slidesToShow,!s.options.infinite&&s.currentSlide>o&&(s.currentSlide=o),s.slideCount<=s.options.slidesToShow&&(s.currentSlide=0),t=s.currentSlide,s.destroy(!0),i.extend(s,s.initials,{currentSlide:t}),s.init(),e||s.changeSlide({data:{message:"index",index:t}},!1)},e.prototype.registerBreakpoints=function(){var e,t,o,s=this,n=s.options.responsive||null;if("array"===i.type(n)&&n.length){s.respondTo=s.options.respondTo||"window";for(e in n)if(o=s.breakpoints.length-1,n.hasOwnProperty(e)){for(t=n[e].breakpoint;o>=0;)s.breakpoints[o]&&s.breakpoints[o]===t&&s.breakpoints.splice(o,1),o--;s.breakpoints.push(t),s.breakpointSettings[t]=n[e].settings}s.breakpoints.sort(function(i,e){return s.options.mobileFirst?i-e:e-i})}},e.prototype.reinit=function(){var e=this;e.$slides=e.$slideTrack.children(e.options.slide).addClass("slick-slide"),e.slideCount=e.$slides.length,e.currentSlide>=e.slideCount&&0!==e.currentSlide&&(e.currentSlide=e.currentSlide-e.options.slidesToScroll),e.slideCount<=e.options.slidesToShow&&(e.currentSlide=0),e.registerBreakpoints(),e.setProps(),e.setupInfinite(),e.buildArrows(),e.updateArrows(),e.initArrowEvents(),e.buildDots(),e.updateDots(),e.initDotEvents(),e.cleanUpSlideEvents(),e.initSlideEvents(),e.checkResponsive(!1,!0),!0===e.options.focusOnSelect&&i(e.$slideTrack).children().on("click.slick",e.selectHandler),e.setSlideClasses("number"==typeof e.currentSlide?e.currentSlide:0),e.setPosition(),e.focusHandler(),e.paused=!e.options.autoplay,e.autoPlay(),e.$slider.trigger("reInit",[e])},e.prototype.resize=function(){var e=this;i(window).width()!==e.windowWidth&&(clearTimeout(e.windowDelay),e.windowDelay=window.setTimeout(function(){e.windowWidth=i(window).width(),e.checkResponsive(),e.unslicked||e.setPosition()},50))},e.prototype.removeSlide=e.prototype.slickRemove=function(i,e,t){var o=this;if(i="boolean"==typeof i?!0===(e=i)?0:o.slideCount-1:!0===e?--i:i,o.slideCount<1||i<0||i>o.slideCount-1)return!1;o.unload(),!0===t?o.$slideTrack.children().remove():o.$slideTrack.children(this.options.slide).eq(i).remove(),o.$slides=o.$slideTrack.children(this.options.slide),o.$slideTrack.children(this.options.slide).detach(),o.$slideTrack.append(o.$slides),o.$slidesCache=o.$slides,o.reinit()},e.prototype.setCSS=function(i){var e,t,o=this,s={};!0===o.options.rtl&&(i=-i),e="left"==o.positionProp?Math.ceil(i)+"px":"0px",t="top"==o.positionProp?Math.ceil(i)+"px":"0px",s[o.positionProp]=i,!1===o.transformsEnabled?o.$slideTrack.css(s):(s={},!1===o.cssTransitions?(s[o.animType]="translate("+e+", "+t+")",o.$slideTrack.css(s)):(s[o.animType]="translate3d("+e+", "+t+", 0px)",o.$slideTrack.css(s)))},e.prototype.setDimensions=function(){var i=this;!1===i.options.vertical?!0===i.options.centerMode&&i.$list.css({padding:"0px "+i.options.centerPadding}):(i.$list.height(i.$slides.first().outerHeight(!0)*i.options.slidesToShow),!0===i.options.centerMode&&i.$list.css({padding:i.options.centerPadding+" 0px"})),i.listWidth=i.$list.width(),i.listHeight=i.$list.height(),!1===i.options.vertical&&!1===i.options.variableWidth?(i.slideWidth=Math.ceil(i.listWidth/i.options.slidesToShow),i.$slideTrack.width(Math.ceil(i.slideWidth*i.$slideTrack.children(".slick-slide").length))):!0===i.options.variableWidth?i.$slideTrack.width(5e3*i.slideCount):(i.slideWidth=Math.ceil(i.listWidth),i.$slideTrack.height(Math.ceil(i.$slides.first().outerHeight(!0)*i.$slideTrack.children(".slick-slide").length)));var e=i.$slides.first().outerWidth(!0)-i.$slides.first().width();!1===i.options.variableWidth&&i.$slideTrack.children(".slick-slide").width(i.slideWidth-e)},e.prototype.setFade=function(){var e,t=this;t.$slides.each(function(o,s){e=t.slideWidth*o*-1,!0===t.options.rtl?i(s).css({position:"relative",right:e,top:0,zIndex:t.options.zIndex-2,opacity:0}):i(s).css({position:"relative",left:e,top:0,zIndex:t.options.zIndex-2,opacity:0})}),t.$slides.eq(t.currentSlide).css({zIndex:t.options.zIndex-1,opacity:1})},e.prototype.setHeight=function(){var i=this;if(1===i.options.slidesToShow&&!0===i.options.adaptiveHeight&&!1===i.options.vertical){var e=i.$slides.eq(i.currentSlide).outerHeight(!0);i.$list.css("height",e)}},e.prototype.setOption=e.prototype.slickSetOption=function(){var e,t,o,s,n,r=this,l=!1;if("object"===i.type(arguments[0])?(o=arguments[0],l=arguments[1],n="multiple"):"string"===i.type(arguments[0])&&(o=arguments[0],s=arguments[1],l=arguments[2],"responsive"===arguments[0]&&"array"===i.type(arguments[1])?n="responsive":void 0!==arguments[1]&&(n="single")),"single"===n)r.options[o]=s;else if("multiple"===n)i.each(o,function(i,e){r.options[i]=e});else if("responsive"===n)for(t in s)if("array"!==i.type(r.options.responsive))r.options.responsive=[s[t]];else{for(e=r.options.responsive.length-1;e>=0;)r.options.responsive[e].breakpoint===s[t].breakpoint&&r.options.responsive.splice(e,1),e--;r.options.responsive.push(s[t])}l&&(r.unload(),r.reinit())},e.prototype.setPosition=function(){var i=this;i.setDimensions(),i.setHeight(),!1===i.options.fade?i.setCSS(i.getLeft(i.currentSlide)):i.setFade(),i.$slider.trigger("setPosition",[i])},e.prototype.setProps=function(){var i=this,e=document.body.style;i.positionProp=!0===i.options.vertical?"top":"left","top"===i.positionProp?i.$slider.addClass("slick-vertical"):i.$slider.removeClass("slick-vertical"),void 0===e.WebkitTransition&&void 0===e.MozTransition&&void 0===e.msTransition||!0===i.options.useCSS&&(i.cssTransitions=!0),i.options.fade&&("number"==typeof i.options.zIndex?i.options.zIndex<3&&(i.options.zIndex=3):i.options.zIndex=i.defaults.zIndex),void 0!==e.OTransform&&(i.animType="OTransform",i.transformType="-o-transform",i.transitionType="OTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.MozTransform&&(i.animType="MozTransform",i.transformType="-moz-transform",i.transitionType="MozTransition",void 0===e.perspectiveProperty&&void 0===e.MozPerspective&&(i.animType=!1)),void 0!==e.webkitTransform&&(i.animType="webkitTransform",i.transformType="-webkit-transform",i.transitionType="webkitTransition",void 0===e.perspectiveProperty&&void 0===e.webkitPerspective&&(i.animType=!1)),void 0!==e.msTransform&&(i.animType="msTransform",i.transformType="-ms-transform",i.transitionType="msTransition",void 0===e.msTransform&&(i.animType=!1)),void 0!==e.transform&&!1!==i.animType&&(i.animType="transform",i.transformType="transform",i.transitionType="transition"),i.transformsEnabled=i.options.useTransform&&null!==i.animType&&!1!==i.animType},e.prototype.setSlideClasses=function(i){var e,t,o,s,n=this;if(t=n.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true"),n.$slides.eq(i).addClass("slick-current"),!0===n.options.centerMode){var r=n.options.slidesToShow%2==0?1:0;e=Math.floor(n.options.slidesToShow/2),!0===n.options.infinite&&(i>=e&&i<=n.slideCount-1-e?n.$slides.slice(i-e+r,i+e+1).addClass("slick-active").attr("aria-hidden","false"):(o=n.options.slidesToShow+i,t.slice(o-e+1+r,o+e+2).addClass("slick-active").attr("aria-hidden","false")),0===i?t.eq(t.length-1-n.options.slidesToShow).addClass("slick-center"):i===n.slideCount-1&&t.eq(n.options.slidesToShow).addClass("slick-center")),n.$slides.eq(i).addClass("slick-center")}else i>=0&&i<=n.slideCount-n.options.slidesToShow?n.$slides.slice(i,i+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"):t.length<=n.options.slidesToShow?t.addClass("slick-active").attr("aria-hidden","false"):(s=n.slideCount%n.options.slidesToShow,o=!0===n.options.infinite?n.options.slidesToShow+i:i,n.options.slidesToShow==n.options.slidesToScroll&&n.slideCount-i<n.options.slidesToShow?t.slice(o-(n.options.slidesToShow-s),o+s).addClass("slick-active").attr("aria-hidden","false"):t.slice(o,o+n.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false"));"ondemand"!==n.options.lazyLoad&&"anticipated"!==n.options.lazyLoad||n.lazyLoad()},e.prototype.setupInfinite=function(){var e,t,o,s=this;if(!0===s.options.fade&&(s.options.centerMode=!1),!0===s.options.infinite&&!1===s.options.fade&&(t=null,s.slideCount>s.options.slidesToShow)){for(o=!0===s.options.centerMode?s.options.slidesToShow+1:s.options.slidesToShow,e=s.slideCount;e>s.slideCount-o;e-=1)t=e-1,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t-s.slideCount).prependTo(s.$slideTrack).addClass("slick-cloned");for(e=0;e<o+s.slideCount;e+=1)t=e,i(s.$slides[t]).clone(!0).attr("id","").attr("data-slick-index",t+s.slideCount).appendTo(s.$slideTrack).addClass("slick-cloned");s.$slideTrack.find(".slick-cloned").find("[id]").each(function(){i(this).attr("id","")})}},e.prototype.interrupt=function(i){var e=this;i||e.autoPlay(),e.interrupted=i},e.prototype.selectHandler=function(e){var t=this,o=i(e.target).is(".slick-slide")?i(e.target):i(e.target).parents(".slick-slide"),s=parseInt(o.attr("data-slick-index"));s||(s=0),t.slideCount<=t.options.slidesToShow?t.slideHandler(s,!1,!0):t.slideHandler(s)},e.prototype.slideHandler=function(i,e,t){var o,s,n,r,l,d=null,a=this;if(e=e||!1,!(!0===a.animating&&!0===a.options.waitForAnimate||!0===a.options.fade&&a.currentSlide===i))if(!1===e&&a.asNavFor(i),o=i,d=a.getLeft(o),r=a.getLeft(a.currentSlide),a.currentLeft=null===a.swipeLeft?r:a.swipeLeft,!1===a.options.infinite&&!1===a.options.centerMode&&(i<0||i>a.getDotCount()*a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else if(!1===a.options.infinite&&!0===a.options.centerMode&&(i<0||i>a.slideCount-a.options.slidesToScroll))!1===a.options.fade&&(o=a.currentSlide,!0!==t?a.animateSlide(r,function(){a.postSlide(o)}):a.postSlide(o));else{if(a.options.autoplay&&clearInterval(a.autoPlayTimer),s=o<0?a.slideCount%a.options.slidesToScroll!=0?a.slideCount-a.slideCount%a.options.slidesToScroll:a.slideCount+o:o>=a.slideCount?a.slideCount%a.options.slidesToScroll!=0?0:o-a.slideCount:o,a.animating=!0,a.$slider.trigger("beforeChange",[a,a.currentSlide,s]),n=a.currentSlide,a.currentSlide=s,a.setSlideClasses(a.currentSlide),a.options.asNavFor&&(l=(l=a.getNavTarget()).slick("getSlick")).slideCount<=l.options.slidesToShow&&l.setSlideClasses(a.currentSlide),a.updateDots(),a.updateArrows(),!0===a.options.fade)return!0!==t?(a.fadeSlideOut(n),a.fadeSlide(s,function(){a.postSlide(s)})):a.postSlide(s),void a.animateHeight();!0!==t?a.animateSlide(d,function(){a.postSlide(s)}):a.postSlide(s)}},e.prototype.startLoad=function(){var i=this;!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&(i.$prevArrow.hide(),i.$nextArrow.hide()),!0===i.options.dots&&i.slideCount>i.options.slidesToShow&&i.$dots.hide(),i.$slider.addClass("slick-loading")},e.prototype.swipeDirection=function(){var i,e,t,o,s=this;return i=s.touchObject.startX-s.touchObject.curX,e=s.touchObject.startY-s.touchObject.curY,t=Math.atan2(e,i),(o=Math.round(180*t/Math.PI))<0&&(o=360-Math.abs(o)),o<=45&&o>=0?!1===s.options.rtl?"left":"right":o<=360&&o>=315?!1===s.options.rtl?"left":"right":o>=135&&o<=225?!1===s.options.rtl?"right":"left":!0===s.options.verticalSwiping?o>=35&&o<=135?"down":"up":"vertical"},e.prototype.swipeEnd=function(i){var e,t,o=this;if(o.dragging=!1,o.swiping=!1,o.scrolling)return o.scrolling=!1,!1;if(o.interrupted=!1,o.shouldClick=!(o.touchObject.swipeLength>10),void 0===o.touchObject.curX)return!1;if(!0===o.touchObject.edgeHit&&o.$slider.trigger("edge",[o,o.swipeDirection()]),o.touchObject.swipeLength>=o.touchObject.minSwipe){switch(t=o.swipeDirection()){case"left":case"down":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide+o.getSlideCount()):o.currentSlide+o.getSlideCount(),o.currentDirection=0;break;case"right":case"up":e=o.options.swipeToSlide?o.checkNavigable(o.currentSlide-o.getSlideCount()):o.currentSlide-o.getSlideCount(),o.currentDirection=1}"vertical"!=t&&(o.slideHandler(e),o.touchObject={},o.$slider.trigger("swipe",[o,t]))}else o.touchObject.startX!==o.touchObject.curX&&(o.slideHandler(o.currentSlide),o.touchObject={})},e.prototype.swipeHandler=function(i){var e=this;if(!(!1===e.options.swipe||"ontouchend"in document&&!1===e.options.swipe||!1===e.options.draggable&&-1!==i.type.indexOf("mouse")))switch(e.touchObject.fingerCount=i.originalEvent&&void 0!==i.originalEvent.touches?i.originalEvent.touches.length:1,e.touchObject.minSwipe=e.listWidth/e.options.touchThreshold,!0===e.options.verticalSwiping&&(e.touchObject.minSwipe=e.listHeight/e.options.touchThreshold),i.data.action){case"start":e.swipeStart(i);break;case"move":e.swipeMove(i);break;case"end":e.swipeEnd(i)}},e.prototype.swipeMove=function(i){var e,t,o,s,n,r,l=this;return n=void 0!==i.originalEvent?i.originalEvent.touches:null,!(!l.dragging||l.scrolling||n&&1!==n.length)&&(e=l.getLeft(l.currentSlide),l.touchObject.curX=void 0!==n?n[0].pageX:i.clientX,l.touchObject.curY=void 0!==n?n[0].pageY:i.clientY,l.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(l.touchObject.curX-l.touchObject.startX,2))),r=Math.round(Math.sqrt(Math.pow(l.touchObject.curY-l.touchObject.startY,2))),!l.options.verticalSwiping&&!l.swiping&&r>4?(l.scrolling=!0,!1):(!0===l.options.verticalSwiping&&(l.touchObject.swipeLength=r),t=l.swipeDirection(),void 0!==i.originalEvent&&l.touchObject.swipeLength>4&&(l.swiping=!0,i.preventDefault()),s=(!1===l.options.rtl?1:-1)*(l.touchObject.curX>l.touchObject.startX?1:-1),!0===l.options.verticalSwiping&&(s=l.touchObject.curY>l.touchObject.startY?1:-1),o=l.touchObject.swipeLength,l.touchObject.edgeHit=!1,!1===l.options.infinite&&(0===l.currentSlide&&"right"===t||l.currentSlide>=l.getDotCount()&&"left"===t)&&(o=l.touchObject.swipeLength*l.options.edgeFriction,l.touchObject.edgeHit=!0),!1===l.options.vertical?l.swipeLeft=e+o*s:l.swipeLeft=e+o*(l.$list.height()/l.listWidth)*s,!0===l.options.verticalSwiping&&(l.swipeLeft=e+o*s),!0!==l.options.fade&&!1!==l.options.touchMove&&(!0===l.animating?(l.swipeLeft=null,!1):void l.setCSS(l.swipeLeft))))},e.prototype.swipeStart=function(i){var e,t=this;if(t.interrupted=!0,1!==t.touchObject.fingerCount||t.slideCount<=t.options.slidesToShow)return t.touchObject={},!1;void 0!==i.originalEvent&&void 0!==i.originalEvent.touches&&(e=i.originalEvent.touches[0]),t.touchObject.startX=t.touchObject.curX=void 0!==e?e.pageX:i.clientX,t.touchObject.startY=t.touchObject.curY=void 0!==e?e.pageY:i.clientY,t.dragging=!0},e.prototype.unfilterSlides=e.prototype.slickUnfilter=function(){var i=this;null!==i.$slidesCache&&(i.unload(),i.$slideTrack.children(this.options.slide).detach(),i.$slidesCache.appendTo(i.$slideTrack),i.reinit())},e.prototype.unload=function(){var e=this;i(".slick-cloned",e.$slider).remove(),e.$dots&&e.$dots.remove(),e.$prevArrow&&e.htmlExpr.test(e.options.prevArrow)&&e.$prevArrow.remove(),e.$nextArrow&&e.htmlExpr.test(e.options.nextArrow)&&e.$nextArrow.remove(),e.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")},e.prototype.unslick=function(i){var e=this;e.$slider.trigger("unslick",[e,i]),e.destroy()},e.prototype.updateArrows=function(){var i=this;Math.floor(i.options.slidesToShow/2),!0===i.options.arrows&&i.slideCount>i.options.slidesToShow&&!i.options.infinite&&(i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false"),0===i.currentSlide?(i.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-i.options.slidesToShow&&!1===i.options.centerMode?(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")):i.currentSlide>=i.slideCount-1&&!0===i.options.centerMode&&(i.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true"),i.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")))},e.prototype.updateDots=function(){var i=this;null!==i.$dots&&(i.$dots.find("li").removeClass("slick-active").end(),i.$dots.find("li").eq(Math.floor(i.currentSlide/i.options.slidesToScroll)).addClass("slick-active"))},e.prototype.visibility=function(){var i=this;i.options.autoplay&&(document[i.hidden]?i.interrupted=!0:i.interrupted=!1)},i.fn.slick=function(){var i,t,o=this,s=arguments[0],n=Array.prototype.slice.call(arguments,1),r=o.length;for(i=0;i<r;i++)if("object"==typeof s||void 0===s?o[i].slick=new e(o[i],s):t=o[i].slick[s].apply(o[i].slick,n),void 0!==t)return t;return o}});
/**
 * Lightbox v2.7.1
 * by Lokesh Dhakar - http://lokeshdhakar.com/projects/lightbox2/
 *
 * @license http://creativecommons.org/licenses/by/2.5/
 * - Free for use in both personal and commercial projects
 * - Attribution requires leaving author name, author link, and the license info intact
 */
(function(){var a=jQuery,b=function(){function a(){this.fadeDuration=500,this.fitImagesInViewport=!0,this.resizeDuration=700,this.positionFromTop=50,this.showImageNumberLabel=!0,this.alwaysShowNavOnTouchDevices=!1,this.wrapAround=!1}return a.prototype.albumLabel=function(a,b){return"Image "+a+" of "+b},a}(),c=function(){function b(a){this.options=a,this.album=[],this.currentImageIndex=void 0,this.init()}return b.prototype.init=function(){this.enable(),this.build()},b.prototype.enable=function(){var b=this;a("body").on("click","a[rel^=lightbox], area[rel^=lightbox], a[data-lightbox], area[data-lightbox]",function(c){return b.start(a(c.currentTarget)),!1})},b.prototype.build=function(){var b=this;a("<div id='lightboxOverlay' class='lightboxOverlay'></div><div id='lightbox' class='lightbox'><div class='lb-outerContainer'><div class='lb-container'><img class='lb-image' src='' /><div class='lb-nav'><a class='lb-prev' href='' ></a><a class='lb-next' href='' ></a></div><div class='lb-loader'><a class='lb-cancel'></a></div></div></div><div class='lb-dataContainer'><div class='lb-data'><div class='lb-details'><span class='lb-caption'></span><span class='lb-number'></span></div><div class='lb-closeContainer'><a class='lb-close'></a></div></div></div></div>").appendTo(a("body")),this.$lightbox=a("#lightbox"),this.$overlay=a("#lightboxOverlay"),this.$outerContainer=this.$lightbox.find(".lb-outerContainer"),this.$container=this.$lightbox.find(".lb-container"),this.containerTopPadding=parseInt(this.$container.css("padding-top"),10),this.containerRightPadding=parseInt(this.$container.css("padding-right"),10),this.containerBottomPadding=parseInt(this.$container.css("padding-bottom"),10),this.containerLeftPadding=parseInt(this.$container.css("padding-left"),10),this.$overlay.hide().on("click",function(){return b.end(),!1}),this.$lightbox.hide().on("click",function(c){return"lightbox"===a(c.target).attr("id")&&b.end(),!1}),this.$outerContainer.on("click",function(c){return"lightbox"===a(c.target).attr("id")&&b.end(),!1}),this.$lightbox.find(".lb-prev").on("click",function(){return b.changeImage(0===b.currentImageIndex?b.album.length-1:b.currentImageIndex-1),!1}),this.$lightbox.find(".lb-next").on("click",function(){return b.changeImage(b.currentImageIndex===b.album.length-1?0:b.currentImageIndex+1),!1}),this.$lightbox.find(".lb-loader, .lb-close").on("click",function(){return b.end(),!1})},b.prototype.start=function(b){function c(a){d.album.push({link:a.attr("href"),title:a.attr("data-title")||a.attr("title")})}var d=this,e=a(window);e.on("resize",a.proxy(this.sizeOverlay,this)),a("select, object, embed").css({visibility:"hidden"}),this.sizeOverlay(),this.album=[];var f,g=0,h=b.attr("data-lightbox");if(h){f=a(b.prop("tagName")+'[data-lightbox="'+h+'"]');for(var i=0;i<f.length;i=++i)c(a(f[i])),f[i]===b[0]&&(g=i)}else if("lightbox"===b.attr("rel"))c(b);else{f=a(b.prop("tagName")+'[rel="'+b.attr("rel")+'"]');for(var j=0;j<f.length;j=++j)c(a(f[j])),f[j]===b[0]&&(g=j)}var k=e.scrollTop()+this.options.positionFromTop,l=e.scrollLeft();this.$lightbox.css({top:k+"px",left:l+"px"}).fadeIn(this.options.fadeDuration),this.changeImage(g)},b.prototype.changeImage=function(b){var c=this;this.disableKeyboardNav();var d=this.$lightbox.find(".lb-image");this.$overlay.fadeIn(this.options.fadeDuration),a(".lb-loader").fadeIn("slow"),this.$lightbox.find(".lb-image, .lb-nav, .lb-prev, .lb-next, .lb-dataContainer, .lb-numbers, .lb-caption").hide(),this.$outerContainer.addClass("animating");var e=new Image;e.onload=function(){var f,g,h,i,j,k,l;d.attr("src",c.album[b].link),f=a(e),d.width(e.width),d.height(e.height),c.options.fitImagesInViewport&&(l=a(window).width(),k=a(window).height(),j=l-c.containerLeftPadding-c.containerRightPadding-20,i=k-c.containerTopPadding-c.containerBottomPadding-120,(e.width>j||e.height>i)&&(e.width/j>e.height/i?(h=j,g=parseInt(e.height/(e.width/h),10),d.width(h),d.height(g)):(g=i,h=parseInt(e.width/(e.height/g),10),d.width(h),d.height(g)))),c.sizeContainer(d.width(),d.height())},e.src=this.album[b].link,this.currentImageIndex=b},b.prototype.sizeOverlay=function(){this.$overlay.width(a(window).width()).height(a(document).height())},b.prototype.sizeContainer=function(a,b){function c(){d.$lightbox.find(".lb-dataContainer").width(g),d.$lightbox.find(".lb-prevLink").height(h),d.$lightbox.find(".lb-nextLink").height(h),d.showImage()}var d=this,e=this.$outerContainer.outerWidth(),f=this.$outerContainer.outerHeight(),g=a+this.containerLeftPadding+this.containerRightPadding,h=b+this.containerTopPadding+this.containerBottomPadding;e!==g||f!==h?this.$outerContainer.animate({width:g,height:h},this.options.resizeDuration,"swing",function(){c()}):c()},b.prototype.showImage=function(){this.$lightbox.find(".lb-loader").hide(),this.$lightbox.find(".lb-image").fadeIn("slow"),this.updateNav(),this.updateDetails(),this.preloadNeighboringImages(),this.enableKeyboardNav()},b.prototype.updateNav=function(){var a=!1;try{document.createEvent("TouchEvent"),a=this.options.alwaysShowNavOnTouchDevices?!0:!1}catch(b){}this.$lightbox.find(".lb-nav").show(),this.album.length>1&&(this.options.wrapAround?(a&&this.$lightbox.find(".lb-prev, .lb-next").css("opacity","1"),this.$lightbox.find(".lb-prev, .lb-next").show()):(this.currentImageIndex>0&&(this.$lightbox.find(".lb-prev").show(),a&&this.$lightbox.find(".lb-prev").css("opacity","1")),this.currentImageIndex<this.album.length-1&&(this.$lightbox.find(".lb-next").show(),a&&this.$lightbox.find(".lb-next").css("opacity","1"))))},b.prototype.updateDetails=function(){var b=this;"undefined"!=typeof this.album[this.currentImageIndex].title&&""!==this.album[this.currentImageIndex].title&&this.$lightbox.find(".lb-caption").html(this.album[this.currentImageIndex].title).fadeIn("fast").find("a").on("click",function(){location.href=a(this).attr("href")}),this.album.length>1&&this.options.showImageNumberLabel?this.$lightbox.find(".lb-number").text(this.options.albumLabel(this.currentImageIndex+1,this.album.length)).fadeIn("fast"):this.$lightbox.find(".lb-number").hide(),this.$outerContainer.removeClass("animating"),this.$lightbox.find(".lb-dataContainer").fadeIn(this.options.resizeDuration,function(){return b.sizeOverlay()})},b.prototype.preloadNeighboringImages=function(){if(this.album.length>this.currentImageIndex+1){var a=new Image;a.src=this.album[this.currentImageIndex+1].link}if(this.currentImageIndex>0){var b=new Image;b.src=this.album[this.currentImageIndex-1].link}},b.prototype.enableKeyboardNav=function(){a(document).on("keyup.keyboard",a.proxy(this.keyboardAction,this))},b.prototype.disableKeyboardNav=function(){a(document).off(".keyboard")},b.prototype.keyboardAction=function(a){var b=27,c=37,d=39,e=a.keyCode,f=String.fromCharCode(e).toLowerCase();e===b||f.match(/x|o|c/)?this.end():"p"===f||e===c?0!==this.currentImageIndex?this.changeImage(this.currentImageIndex-1):this.options.wrapAround&&this.album.length>1&&this.changeImage(this.album.length-1):("n"===f||e===d)&&(this.currentImageIndex!==this.album.length-1?this.changeImage(this.currentImageIndex+1):this.options.wrapAround&&this.album.length>1&&this.changeImage(0))},b.prototype.end=function(){this.disableKeyboardNav(),a(window).off("resize",this.sizeOverlay),this.$lightbox.fadeOut(this.options.fadeDuration),this.$overlay.fadeOut(this.options.fadeDuration),a("select, object, embed").css({visibility:"visible"})},b}();a(function(){{var a=new b;new c(a)}})}).call(this);
//# sourceMappingURL=lightbox.min.map
/*!
 * 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));
// Easy Responsive Tabs Plugin
// Author: Samson.Onna <Email : samson3d@gmail.com>
(function ($) {
    $.fn.extend({
        easyResponsiveTabs: function (options) {
            //Set the default values, use comma to separate the settings, example:
            var defaults = {
                type: 'default', //default, vertical, accordion;
                width: 'auto',
                fit: true,
                closed: false,
                activate: function(){}
            }
            //Variables
            var options = $.extend(defaults, options);
            var opt = options, jtype = opt.type, jfit = opt.fit, jwidth = opt.width, vtabs = 'vertical', accord = 'accordion';
            var hash = window.location.hash;
            var historyApi = !!(window.history && history.replaceState);

            //Events
            $(this).bind('tabactivate', function(e, currentTab) {
                if(typeof options.activate === 'function') {
                    options.activate.call(currentTab, e)
                }
            });

            //Main function
            this.each(function () {
                var $respTabs = $(this);
                var $respTabsList = $respTabs.find('ul.resp-tabs-list');
                var respTabsId = $respTabs.attr('id');
                $respTabs.find('ul.resp-tabs-list li').addClass('resp-tab-item');
                $respTabs.css({
                    'display': 'block',
                    'width': jwidth
                });

                $respTabs.find('.resp-tabs-container > div').addClass('resp-tab-content');
                jtab_options();
                //Properties Function
                function jtab_options() {
                    if (jtype == vtabs) {
                        $respTabs.addClass('resp-vtabs');
                    }
                    if (jfit == true) {
                        $respTabs.css({ width: '100%', margin: '0px' });
                    }
                    if (jtype == accord) {
                        $respTabs.addClass('resp-easy-accordion');
                        $respTabs.find('.resp-tabs-list').css('display', 'none');
                    }
                }

                //Assigning the h2 markup to accordion title
                var $tabItemh2;
                $respTabs.find('.resp-tab-content').before("<h3 class='resp-accordion' role='tab'><span class='resp-arrow'></span></h3>");

                var itemCount = 0;
                $respTabs.find('.resp-accordion').each(function () {
                    $tabItemh2 = $(this);
                    var $tabItem = $respTabs.find('.resp-tab-item:eq(' + itemCount + ')');
                    var $accItem = $respTabs.find('.resp-accordion:eq(' + itemCount + ')');
                    $accItem.append($tabItem.text());
                    $accItem.data($tabItem.data());
                    $tabItemh2.attr('aria-controls', 'tab_item-' + (itemCount));
                    itemCount++;
                });

                //Assigning the 'aria-controls' to Tab items
                var count = 0,
                    $tabContent;
                $respTabs.find('.resp-tab-item').each(function () {
                    $tabItem = $(this);
                    $tabItem.attr('aria-controls', 'tab_item-' + (count));
                    $tabItem.attr('role', 'tab');

                    //Assigning the 'aria-labelledby' attr to tab-content
                    var tabcount = 0;
                    $respTabs.find('.resp-tab-content').each(function () {
                        $tabContent = $(this);
                        $tabContent.attr('aria-labelledby', 'tab_item-' + (tabcount));
                        tabcount++;
                    });
                    count++;
                });

                // Show correct content area
                var tabNum = 0;
                if(hash!='') {
                    var matches = hash.match(new RegExp(respTabsId+"([0-9]+)"));
                    if (matches!==null && matches.length===2) {
                        tabNum = parseInt(matches[1],10)-1;
                        if (tabNum > count) {
                            tabNum = 0;
                        }
                    }
                }

                //Active correct tab
                $($respTabs.find('.resp-tab-item')[tabNum]).addClass('resp-tab-active');

                //keep closed if option = 'closed' or option is 'accordion' and the element is in accordion mode
                if(options.closed !== true && !(options.closed === 'accordion' && !$respTabsList.is(':visible')) && !(options.closed === 'tabs' && $respTabsList.is(':visible'))) {
                    $($respTabs.find('.resp-accordion')[tabNum]).addClass('resp-tab-active');
                    $($respTabs.find('.resp-tab-content')[tabNum]).addClass('resp-tab-content-active').attr('style', 'display:block');
                }
                //assign proper classes for when tabs mode is activated before making a selection in accordion mode
                else {
                    $($respTabs.find('.resp-tab-content')[tabNum]).addClass('resp-tab-content-active resp-accordion-closed')
                }

                //Tab Click action function
                $respTabs.find("[role=tab]").each(function () {

                    var $currentTab = $(this);
                    $currentTab.click(function () {

                        var $currentTab = $(this);
                        var $tabAria = $currentTab.attr('aria-controls');

                        if ($currentTab.hasClass('resp-accordion') && $currentTab.hasClass('resp-tab-active')) {
                            $respTabs.find('.resp-tab-content-active').slideUp('', function () { $(this).addClass('resp-accordion-closed'); });
                            $currentTab.removeClass('resp-tab-active');
                            return false;
                        }
                        if (!$currentTab.hasClass('resp-tab-active') && $currentTab.hasClass('resp-accordion')) {
                            $respTabs.find('.resp-tab-active').removeClass('resp-tab-active');
                            $respTabs.find('.resp-tab-content-active').slideUp().removeClass('resp-tab-content-active resp-accordion-closed');
                            $respTabs.find("[aria-controls=" + $tabAria + "]").addClass('resp-tab-active');

                            $respTabs.find('.resp-tab-content[aria-labelledby = ' + $tabAria + ']').slideDown().addClass('resp-tab-content-active');
                        } else {
                            $respTabs.find('.resp-tab-active').removeClass('resp-tab-active');
                            $respTabs.find('.resp-tab-content-active').removeAttr('style').removeClass('resp-tab-content-active').removeClass('resp-accordion-closed');
                            $respTabs.find("[aria-controls=" + $tabAria + "]").addClass('resp-tab-active');
                            $respTabs.find('.resp-tab-content[aria-labelledby = ' + $tabAria + ']').addClass('resp-tab-content-active').attr('style', 'display:block');
                        }
                        //Trigger tab activation event
                        $currentTab.trigger('tabactivate', $currentTab);

                        //Update Browser History
                        if(historyApi) {
                            var currentHash = window.location.hash;
                            var newHash = respTabsId+(parseInt($tabAria.substring(9),10)+1).toString();
                            if (currentHash!="") {
                                var re = new RegExp(respTabsId+"[0-9]+");
                                if (currentHash.match(re)!=null) {
                                    newHash = currentHash.replace(re,newHash);
                                }
                                else {
                                    newHash = currentHash+"|"+newHash;
                                }
                            }
                            else {
                                newHash = '#'+newHash;
                            }

                            //history.replaceState(null,null,newHash);
                        }
                    });

                });

                //Window resize function
                $(window).resize(function () {
                    $respTabs.find('.resp-accordion-closed').removeAttr('style');
                });
            });
        }
    });
})(jQuery);


/* == malihu jquery custom scrollbar plugin == Version: 3.0.5, License: MIT License (MIT) */
/*!function(e,t,o){!function(t){var a="function"==typeof define&&define.amd,n="https:"==o.location.protocol?"https:":"http:",r="cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.11/jquery.mousewheel.min.js";a||e.event.special.mousewheel||e("head").append(decodeURI("%3Cscript src="+n+"//"+r+"%3E%3C/script%3E")),t()}(function(){var a="mCustomScrollbar",n="mCS",r=".mCustomScrollbar",i={setWidth:!1,setHeight:!1,setTop:0,setLeft:0,axis:"y",scrollbarPosition:"inside",scrollInertia:950,autoDraggerLength:!0,autoHideScrollbar:!1,autoExpandScrollbar:!1,alwaysShowScrollbar:0,snapAmount:null,snapOffset:0,mouseWheel:{enable:!0,scrollAmount:"auto",axis:"y",preventDefault:!1,deltaFactor:"auto",normalizeDelta:!1,invert:!1,disableOver:["select","option","keygen","datalist","textarea"]},scrollButtons:{enable:!1,scrollType:"stepless",scrollAmount:"auto"},keyboard:{enable:!0,scrollType:"stepless",scrollAmount:"auto"},contentTouchScroll:25,advanced:{autoExpandHorizontalScroll:!1,autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']",updateOnContentResize:!0,updateOnImageLoad:!0,updateOnSelectorChange:!1,releaseDraggableSelectors:!1},theme:"light",callbacks:{onInit:!1,onScrollStart:!1,onScroll:!1,onTotalScroll:!1,onTotalScrollBack:!1,whileScrolling:!1,onTotalScrollOffset:0,onTotalScrollBackOffset:0,alwaysTriggerOffsets:!0,onOverflowY:!1,onOverflowX:!1,onOverflowYNone:!1,onOverflowXNone:!1},live:!1,liveSelector:null},l=0,s={},c=function(e){s[e]&&(clearTimeout(s[e]),h._delete.call(null,s[e]))},d=t.attachEvent&&!t.addEventListener?1:0,u=!1,f={init:function(t){var t=e.extend(!0,{},i,t),o=h._selector.call(this);if(t.live){var a=t.liveSelector||this.selector||r,d=e(a);if("off"===t.live)return void c(a);s[a]=setTimeout(function(){d.mCustomScrollbar(t),"once"===t.live&&d.length&&c(a)},500)}else c(a);return t.setWidth=t.set_width?t.set_width:t.setWidth,t.setHeight=t.set_height?t.set_height:t.setHeight,t.axis=t.horizontalScroll?"x":h._findAxis.call(null,t.axis),t.scrollInertia=t.scrollInertia>0&&t.scrollInertia<17?17:t.scrollInertia,"object"!=typeof t.mouseWheel&&1==t.mouseWheel&&(t.mouseWheel={enable:!0,scrollAmount:"auto",axis:"y",preventDefault:!1,deltaFactor:"auto",normalizeDelta:!1,invert:!1}),t.mouseWheel.scrollAmount=t.mouseWheelPixels?t.mouseWheelPixels:t.mouseWheel.scrollAmount,t.mouseWheel.normalizeDelta=t.advanced.normalizeMouseWheelDelta?t.advanced.normalizeMouseWheelDelta:t.mouseWheel.normalizeDelta,t.scrollButtons.scrollType=h._findScrollButtonsType.call(null,t.scrollButtons.scrollType),h._theme.call(null,t),e(o).each(function(){var o=e(this);if(!o.data(n)){o.data(n,{idx:++l,opt:t,scrollRatio:{y:null,x:null},overflowed:null,contentReset:{y:null,x:null},bindEvents:!1,tweenRunning:!1,sequential:{},langDir:o.css("direction"),cbOffsets:null,trigger:null});var a=o.data(n).opt,r=o.data("mcs-axis"),i=o.data("mcs-scrollbar-position"),s=o.data("mcs-theme");r&&(a.axis=r),i&&(a.scrollbarPosition=i),s&&(a.theme=s,h._theme.call(null,a)),h._pluginMarkup.call(this),f.update.call(null,o)}})},update:function(t){var o=t||h._selector.call(this);return e(o).each(function(){var t=e(this);if(t.data(n)){var o=t.data(n),a=o.opt,r=e("#mCSB_"+o.idx+"_container"),i=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")];if(!r.length)return;o.tweenRunning&&h._stop.call(null,t),t.hasClass("mCS_disabled")&&t.removeClass("mCS_disabled"),t.hasClass("mCS_destroyed")&&t.removeClass("mCS_destroyed"),h._maxHeight.call(this),h._expandContentHorizontally.call(this),"y"===a.axis||a.advanced.autoExpandHorizontalScroll||r.css("width",h._contentWidth(r.children())),o.overflowed=h._overflowed.call(this),h._scrollbarVisibility.call(this),a.autoDraggerLength&&h._setDraggerLength.call(this),h._scrollRatio.call(this),h._bindEvents.call(this);var l=[Math.abs(r[0].offsetTop),Math.abs(r[0].offsetLeft)];"x"!==a.axis&&(o.overflowed[0]?i[0].height()>i[0].parent().height()?h._resetContentPosition.call(this):(h._scrollTo.call(this,t,l[0].toString(),{dir:"y",dur:0,overwrite:"none"}),o.contentReset.y=null):(h._resetContentPosition.call(this),"y"===a.axis?h._unbindEvents.call(this):"yx"===a.axis&&o.overflowed[1]&&h._scrollTo.call(this,t,l[1].toString(),{dir:"x",dur:0,overwrite:"none"}))),"y"!==a.axis&&(o.overflowed[1]?i[1].width()>i[1].parent().width()?h._resetContentPosition.call(this):(h._scrollTo.call(this,t,l[1].toString(),{dir:"x",dur:0,overwrite:"none"}),o.contentReset.x=null):(h._resetContentPosition.call(this),"x"===a.axis?h._unbindEvents.call(this):"yx"===a.axis&&o.overflowed[0]&&h._scrollTo.call(this,t,l[0].toString(),{dir:"y",dur:0,overwrite:"none"}))),h._autoUpdate.call(this)}})},scrollTo:function(t,o){if("undefined"!=typeof t&&null!=t){var a=h._selector.call(this);return e(a).each(function(){var a=e(this);if(a.data(n)){var r=a.data(n),i=r.opt,l={trigger:"external",scrollInertia:i.scrollInertia,scrollEasing:"mcsEaseInOut",moveDragger:!1,timeout:60,callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},s=e.extend(!0,{},l,o),c=h._arr.call(this,t),d=s.scrollInertia>0&&s.scrollInertia<17?17:s.scrollInertia;c[0]=h._to.call(this,c[0],"y"),c[1]=h._to.call(this,c[1],"x"),s.moveDragger&&(c[0]*=r.scrollRatio.y,c[1]*=r.scrollRatio.x),s.dur=d,setTimeout(function(){null!==c[0]&&"undefined"!=typeof c[0]&&"x"!==i.axis&&r.overflowed[0]&&(s.dir="y",s.overwrite="all",h._scrollTo.call(this,a,c[0].toString(),s)),null!==c[1]&&"undefined"!=typeof c[1]&&"y"!==i.axis&&r.overflowed[1]&&(s.dir="x",s.overwrite="none",h._scrollTo.call(this,a,c[1].toString(),s))},s.timeout)}})}},stop:function(){var t=h._selector.call(this);return e(t).each(function(){var t=e(this);t.data(n)&&h._stop.call(null,t)})},disable:function(t){var o=h._selector.call(this);return e(o).each(function(){var o=e(this);if(o.data(n)){{var a=o.data(n);a.opt}h._autoUpdate.call(this,"remove"),h._unbindEvents.call(this),t&&h._resetContentPosition.call(this),h._scrollbarVisibility.call(this,!0),o.addClass("mCS_disabled")}})},destroy:function(){var t=h._selector.call(this);return e(t).each(function(){var o=e(this);if(o.data(n)){var r=o.data(n),i=r.opt,l=e("#mCSB_"+r.idx),s=e("#mCSB_"+r.idx+"_container"),d=e(".mCSB_"+r.idx+"_scrollbar");i.live&&c(t),h._autoUpdate.call(this,"remove"),h._unbindEvents.call(this),h._resetContentPosition.call(this),o.removeData(n),h._delete.call(null,this.mcs),d.remove(),l.replaceWith(s.contents()),o.removeClass(a+" _"+n+"_"+r.idx+" mCS-autoHide mCS-dir-rtl mCS_no_scrollbar mCS_disabled").addClass("mCS_destroyed")}})}},h={_selector:function(){return"object"!=typeof e(this)||e(this).length<1?r:this},_theme:function(t){var o=["rounded","rounded-dark","rounded-dots","rounded-dots-dark"],a=["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"],n=["minimal","minimal-dark"],r=["minimal","minimal-dark"],i=["minimal","minimal-dark"];t.autoDraggerLength=e.inArray(t.theme,o)>-1?!1:t.autoDraggerLength,t.autoExpandScrollbar=e.inArray(t.theme,a)>-1?!1:t.autoExpandScrollbar,t.scrollButtons.enable=e.inArray(t.theme,n)>-1?!1:t.scrollButtons.enable,t.autoHideScrollbar=e.inArray(t.theme,r)>-1?!0:t.autoHideScrollbar,t.scrollbarPosition=e.inArray(t.theme,i)>-1?"outside":t.scrollbarPosition},_findAxis:function(e){return"yx"===e||"xy"===e||"auto"===e?"yx":"x"===e||"horizontal"===e?"x":"y"},_findScrollButtonsType:function(e){return"stepped"===e||"pixels"===e||"step"===e||"click"===e?"stepped":"stepless"},_pluginMarkup:function(){var t=e(this),o=t.data(n),r=o.opt,i=r.autoExpandScrollbar?" mCSB_scrollTools_onDrag_expand":"",l=["<div id='mCSB_"+o.idx+"_scrollbar_vertical' class='mCSB_scrollTools mCSB_"+o.idx+"_scrollbar mCS-"+r.theme+" mCSB_scrollTools_vertical"+i+"'><div class='mCSB_draggerContainer'><div id='mCSB_"+o.idx+"_dragger_vertical' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>","<div id='mCSB_"+o.idx+"_scrollbar_horizontal' class='mCSB_scrollTools mCSB_"+o.idx+"_scrollbar mCS-"+r.theme+" mCSB_scrollTools_horizontal"+i+"'><div class='mCSB_draggerContainer'><div id='mCSB_"+o.idx+"_dragger_horizontal' class='mCSB_dragger' style='position:absolute;' oncontextmenu='return false;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>"],s="yx"===r.axis?"mCSB_vertical_horizontal":"x"===r.axis?"mCSB_horizontal":"mCSB_vertical",c="yx"===r.axis?l[0]+l[1]:"x"===r.axis?l[1]:l[0],d="yx"===r.axis?"<div id='mCSB_"+o.idx+"_container_wrapper' class='mCSB_container_wrapper' />":"",u=r.autoHideScrollbar?" mCS-autoHide":"",f="x"!==r.axis&&"rtl"===o.langDir?" mCS-dir-rtl":"";r.setWidth&&t.css("width",r.setWidth),r.setHeight&&t.css("height",r.setHeight),r.setLeft="y"!==r.axis&&"rtl"===o.langDir?"989999px":r.setLeft,t.addClass(a+" _"+n+"_"+o.idx+u+f).wrapInner("<div id='mCSB_"+o.idx+"' class='mCustomScrollBox mCS-"+r.theme+" "+s+"'><div id='mCSB_"+o.idx+"_container' class='mCSB_container' style='position:relative; top:"+r.setTop+"; left:"+r.setLeft+";' dir="+o.langDir+" /></div>");var _=e("#mCSB_"+o.idx),m=e("#mCSB_"+o.idx+"_container");"y"===r.axis||r.advanced.autoExpandHorizontalScroll||m.css("width",h._contentWidth(m.children())),"outside"===r.scrollbarPosition?("static"===t.css("position")&&t.css("position","relative"),t.css("overflow","visible"),_.addClass("mCSB_outside").after(c)):(_.addClass("mCSB_inside").append(c),m.wrap(d)),h._scrollButtons.call(this);var p=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")];p[0].css("min-height",p[0].height()),p[1].css("min-width",p[1].width())},_contentWidth:function(t){return Math.max.apply(Math,t.map(function(){return e(this).outerWidth(!0)}).get())},_expandContentHorizontally:function(){var t=e(this),o=t.data(n),a=o.opt,r=e("#mCSB_"+o.idx+"_container");a.advanced.autoExpandHorizontalScroll&&"y"!==a.axis&&r.css({position:"absolute",width:"auto"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:Math.ceil(r[0].getBoundingClientRect().right+.4)-Math.floor(r[0].getBoundingClientRect().left),position:"relative"}).unwrap()},_scrollButtons:function(){var t=e(this),o=t.data(n),a=o.opt,r=e(".mCSB_"+o.idx+"_scrollbar:first"),i=["<a href='#' class='mCSB_buttonUp' oncontextmenu='return false;' />","<a href='#' class='mCSB_buttonDown' oncontextmenu='return false;' />","<a href='#' class='mCSB_buttonLeft' oncontextmenu='return false;' />","<a href='#' class='mCSB_buttonRight' oncontextmenu='return false;' />"],l=["x"===a.axis?i[2]:i[0],"x"===a.axis?i[3]:i[1],i[2],i[3]];a.scrollButtons.enable&&r.prepend(l[0]).append(l[1]).next(".mCSB_scrollTools").prepend(l[2]).append(l[3])},_maxHeight:function(){var t=e(this),o=t.data(n),a=(o.opt,e("#mCSB_"+o.idx)),r=t.css("max-height"),i=-1!==r.indexOf("%"),l=t.css("box-sizing");if("none"!==r){var s=i?t.parent().height()*parseInt(r)/100:parseInt(r);"border-box"===l&&(s-=t.innerHeight()-t.height()+(t.outerHeight()-t.innerHeight())),a.css("max-height",Math.round(s))}},_setDraggerLength:function(){var t=e(this),o=t.data(n),a=e("#mCSB_"+o.idx),r=e("#mCSB_"+o.idx+"_container"),i=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[a.height()/r.outerHeight(!1),a.width()/r.outerWidth(!1)],s=[parseInt(i[0].css("min-height")),Math.round(l[0]*i[0].parent().height()),parseInt(i[1].css("min-width")),Math.round(l[1]*i[1].parent().width())],c=d&&s[1]<s[0]?s[0]:s[1],u=d&&s[3]<s[2]?s[2]:s[3];i[0].css({height:c,"max-height":i[0].parent().height()-10}).find(".mCSB_dragger_bar").css({"line-height":s[0]+"px"}),i[1].css({width:u,"max-width":i[1].parent().width()-10})},_scrollRatio:function(){var t=e(this),o=t.data(n),a=e("#mCSB_"+o.idx),r=e("#mCSB_"+o.idx+"_container"),i=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[r.outerHeight(!1)-a.height(),r.outerWidth(!1)-a.width()],s=[l[0]/(i[0].parent().height()-i[0].height()),l[1]/(i[1].parent().width()-i[1].width())];o.scrollRatio={y:s[0],x:s[1]}},_onDragClasses:function(e,t,o){var a=o?"mCSB_dragger_onDrag_expanded":"",n=["mCSB_dragger_onDrag","mCSB_scrollTools_onDrag"],r=e.closest(".mCSB_scrollTools");"active"===t?(e.toggleClass(n[0]+" "+a),r.toggleClass(n[1]),e[0]._draggable=e[0]._draggable?0:1):e[0]._draggable||("hide"===t?(e.removeClass(n[0]),r.removeClass(n[1])):(e.addClass(n[0]),r.addClass(n[1])))},_overflowed:function(){var t=e(this),o=t.data(n),a=e("#mCSB_"+o.idx),r=e("#mCSB_"+o.idx+"_container"),i=null==o.overflowed?r.height():r.outerHeight(!1),l=null==o.overflowed?r.width():r.outerWidth(!1);return[i>a.height(),l>a.width()]},_resetContentPosition:function(){var t=e(this),o=t.data(n),a=o.opt,r=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),l=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")];if(h._stop(t),("x"!==a.axis&&!o.overflowed[0]||"y"===a.axis&&o.overflowed[0])&&(l[0].add(i).css("top",0),h._scrollTo(t,"_resetY")),"y"!==a.axis&&!o.overflowed[1]||"x"===a.axis&&o.overflowed[1]){var s=dx=0;"rtl"===o.langDir&&(s=r.width()-i.outerWidth(!1),dx=Math.abs(s/o.scrollRatio.x)),i.css("left",s),l[1].css("left",dx),h._scrollTo(t,"_resetX")}},_bindEvents:function(){function t(){i=setTimeout(function(){e.event.special.mousewheel?(clearTimeout(i),h._mousewheel.call(o[0])):t()},1e3)}var o=e(this),a=o.data(n),r=a.opt;if(!a.bindEvents){if(h._draggable.call(this),r.contentTouchScroll&&h._contentDraggable.call(this),r.mouseWheel.enable){var i;t()}h._draggerRail.call(this),h._wrapperScroll.call(this),r.advanced.autoScrollOnFocus&&h._focus.call(this),r.scrollButtons.enable&&h._buttons.call(this),r.keyboard.enable&&h._keyboard.call(this),a.bindEvents=!0}},_unbindEvents:function(){var t=e(this),a=t.data(n),r=a.opt,i=n+"_"+a.idx,l=".mCSB_"+a.idx+"_scrollbar",s=e("#mCSB_"+a.idx+",#mCSB_"+a.idx+"_container,#mCSB_"+a.idx+"_container_wrapper,"+l+" .mCSB_draggerContainer,#mCSB_"+a.idx+"_dragger_vertical,#mCSB_"+a.idx+"_dragger_horizontal,"+l+">a"),c=e("#mCSB_"+a.idx+"_container");r.advanced.releaseDraggableSelectors&&s.add(e(r.advanced.releaseDraggableSelectors)),a.bindEvents&&(e(o).unbind("."+i),s.each(function(){e(this).unbind("."+i)}),clearTimeout(t[0]._focusTimeout),h._delete.call(null,t[0]._focusTimeout),clearTimeout(a.sequential.step),h._delete.call(null,a.sequential.step),clearTimeout(c[0].onCompleteTimeout),h._delete.call(null,c[0].onCompleteTimeout),a.bindEvents=!1)},_scrollbarVisibility:function(t){var o=e(this),a=o.data(n),r=a.opt,i=e("#mCSB_"+a.idx+"_container_wrapper"),l=i.length?i:e("#mCSB_"+a.idx+"_container"),s=[e("#mCSB_"+a.idx+"_scrollbar_vertical"),e("#mCSB_"+a.idx+"_scrollbar_horizontal")],c=[s[0].find(".mCSB_dragger"),s[1].find(".mCSB_dragger")];"x"!==r.axis&&(a.overflowed[0]&&!t?(s[0].add(c[0]).add(s[0].children("a")).css("display","block"),l.removeClass("mCS_no_scrollbar_y mCS_y_hidden")):(r.alwaysShowScrollbar?(2!==r.alwaysShowScrollbar&&c[0].add(s[0].children("a")).css("display","none"),l.removeClass("mCS_y_hidden")):(s[0].css("display","none"),l.addClass("mCS_y_hidden")),l.addClass("mCS_no_scrollbar_y"))),"y"!==r.axis&&(a.overflowed[1]&&!t?(s[1].add(c[1]).add(s[1].children("a")).css("display","block"),l.removeClass("mCS_no_scrollbar_x mCS_x_hidden")):(r.alwaysShowScrollbar?(2!==r.alwaysShowScrollbar&&c[1].add(s[1].children("a")).css("display","none"),l.removeClass("mCS_x_hidden")):(s[1].css("display","none"),l.addClass("mCS_x_hidden")),l.addClass("mCS_no_scrollbar_x"))),a.overflowed[0]||a.overflowed[1]?o.removeClass("mCS_no_scrollbar"):o.addClass("mCS_no_scrollbar")},_coordinates:function(e){var t=e.type;switch(t){case"pointerdown":case"MSPointerDown":case"pointermove":case"MSPointerMove":case"pointerup":case"MSPointerUp":return[e.originalEvent.pageY,e.originalEvent.pageX,!1];case"touchstart":case"touchmove":case"touchend":var o=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0],a=e.originalEvent.touches.length||e.originalEvent.changedTouches.length;return[o.pageY,o.pageX,a>1];default:return[e.pageY,e.pageX,!1]}},_draggable:function(){function t(e){var t=p.find("iframe");if(t.length){var o=e?"auto":"none";t.css("pointer-events",o)}}function a(e,t,o,a){if(p[0].idleTimer=f.scrollInertia<233?250:0,r.attr("id")===m[1])var n="x",i=(r[0].offsetLeft-t+a)*c.scrollRatio.x;else var n="y",i=(r[0].offsetTop-e+o)*c.scrollRatio.y;h._scrollTo(s,i.toString(),{dir:n,drag:!0})}var r,i,l,s=e(this),c=s.data(n),f=c.opt,_=n+"_"+c.idx,m=["mCSB_"+c.idx+"_dragger_vertical","mCSB_"+c.idx+"_dragger_horizontal"],p=e("#mCSB_"+c.idx+"_container"),g=e("#"+m[0]+",#"+m[1]),v=f.advanced.releaseDraggableSelectors?g.add(e(f.advanced.releaseDraggableSelectors)):g;g.bind("mousedown."+_+" touchstart."+_+" pointerdown."+_+" MSPointerDown."+_,function(a){if(a.stopImmediatePropagation(),a.preventDefault(),h._mouseBtnLeft(a)){u=!0,d&&(o.onselectstart=function(){return!1}),t(!1),h._stop(s),r=e(this);var n=r.offset(),c=h._coordinates(a)[0]-n.top,_=h._coordinates(a)[1]-n.left,m=r.height()+n.top,p=r.width()+n.left;m>c&&c>0&&p>_&&_>0&&(i=c,l=_),h._onDragClasses(r,"active",f.autoExpandScrollbar)}}).bind("touchmove."+_,function(e){e.stopImmediatePropagation(),e.preventDefault();var t=r.offset(),o=h._coordinates(e)[0]-t.top,n=h._coordinates(e)[1]-t.left;a(i,l,o,n)}),e(o).bind("mousemove."+_+" pointermove."+_+" MSPointerMove."+_,function(e){if(r){var t=r.offset(),o=h._coordinates(e)[0]-t.top,n=h._coordinates(e)[1]-t.left;if(i===o)return;a(i,l,o,n)}}).add(v).bind("mouseup."+_+" touchend."+_+" pointerup."+_+" MSPointerUp."+_,function(){r&&(h._onDragClasses(r,"active",f.autoExpandScrollbar),r=null),u=!1,d&&(o.onselectstart=null),t(!0)})},_contentDraggable:function(){function t(e,t){var o=[1.5*t,2*t,t/1.5,t/2];return e>90?t>4?o[0]:o[3]:e>60?t>3?o[3]:o[2]:e>30?t>8?o[1]:t>6?o[0]:t>4?t:o[2]:t>8?t:o[3]}function o(e,t,o,a,n,r){e&&h._scrollTo(g,e.toString(),{dur:t,scrollEasing:o,dir:a,overwrite:n,drag:r})}var a,r,i,l,s,c,d,f,_,m,p,g=e(this),v=g.data(n),x=v.opt,S=n+"_"+v.idx,C=e("#mCSB_"+v.idx),b=e("#mCSB_"+v.idx+"_container"),w=[e("#mCSB_"+v.idx+"_dragger_vertical"),e("#mCSB_"+v.idx+"_dragger_horizontal")],y=[],B=[],T=0,M="yx"===x.axis?"none":"all",k=[];b.bind("touchstart."+S+" pointerdown."+S+" MSPointerDown."+S,function(e){if(h._pointerTouch(e)&&!u&&!h._coordinates(e)[2]){var t=b.offset();a=h._coordinates(e)[0]-t.top,r=h._coordinates(e)[1]-t.left,k=[h._coordinates(e)[0],h._coordinates(e)[1]]}}).bind("touchmove."+S+" pointermove."+S+" MSPointerMove."+S,function(e){if(h._pointerTouch(e)&&!u&&!h._coordinates(e)[2]){e.stopImmediatePropagation(),c=h._getTime();var t=C.offset(),n=h._coordinates(e)[0]-t.top,i=h._coordinates(e)[1]-t.left,l="mcsLinearOut";if(y.push(n),B.push(i),k[2]=Math.abs(h._coordinates(e)[0]-k[0]),k[3]=Math.abs(h._coordinates(e)[1]-k[1]),v.overflowed[0])var s=w[0].parent().height()-w[0].height(),d=a-n>0&&n-a>-(s*v.scrollRatio.y)&&(2*k[3]<k[2]||"yx"===x.axis);if(v.overflowed[1])var f=w[1].parent().width()-w[1].width(),_=r-i>0&&i-r>-(f*v.scrollRatio.x)&&(2*k[2]<k[3]||"yx"===x.axis);(d||_)&&e.preventDefault(),m="yx"===x.axis?[a-n,r-i]:"x"===x.axis?[null,r-i]:[a-n,null],b[0].idleTimer=250,v.overflowed[0]&&o(m[0],T,l,"y","all",!0),v.overflowed[1]&&o(m[1],T,l,"x",M,!0)}}),C.bind("touchstart."+S+" pointerdown."+S+" MSPointerDown."+S,function(e){if(h._pointerTouch(e)&&!u&&!h._coordinates(e)[2]){e.stopImmediatePropagation(),h._stop(g),s=h._getTime();var t=C.offset();i=h._coordinates(e)[0]-t.top,l=h._coordinates(e)[1]-t.left,y=[],B=[]}}).bind("touchend."+S+" pointerup."+S+" MSPointerUp."+S,function(e){if(h._pointerTouch(e)&&!u&&!h._coordinates(e)[2]){e.stopImmediatePropagation(),d=h._getTime();var a=C.offset(),n=h._coordinates(e)[0]-a.top,r=h._coordinates(e)[1]-a.left;if(!(d-c>30)){_=1e3/(d-s);var g="mcsEaseOut",S=2.5>_,w=S?[y[y.length-2],B[B.length-2]]:[0,0];f=S?[n-w[0],r-w[1]]:[n-i,r-l];var T=[Math.abs(f[0]),Math.abs(f[1])];_=S?[Math.abs(f[0]/4),Math.abs(f[1]/4)]:[_,_];var k=[Math.abs(b[0].offsetTop)-f[0]*t(T[0]/_[0],_[0]),Math.abs(b[0].offsetLeft)-f[1]*t(T[1]/_[1],_[1])];m="yx"===x.axis?[k[0],k[1]]:"x"===x.axis?[null,k[1]]:[k[0],null],p=[4*T[0]+x.scrollInertia,4*T[1]+x.scrollInertia];var O=parseInt(x.contentTouchScroll)||0;m[0]=T[0]>O?m[0]:0,m[1]=T[1]>O?m[1]:0,v.overflowed[0]&&o(m[0],p[0],g,"y",M,!1),v.overflowed[1]&&o(m[1],p[1],g,"x",M,!1)}}})},_mousewheel:function(){function t(e){var t=null;try{var o=e.contentDocument||e.contentWindow.document;t=o.body.innerHTML}catch(a){}return null!==t}var o=e(this),a=o.data(n);if(a){var r=a.opt,i=n+"_"+a.idx,l=e("#mCSB_"+a.idx),s=[e("#mCSB_"+a.idx+"_dragger_vertical"),e("#mCSB_"+a.idx+"_dragger_horizontal")],c=e("#mCSB_"+a.idx+"_container").find("iframe"),u=l;c.length&&c.each(function(){var o=this;t(o)&&(u=u.add(e(o).contents().find("body")))}),u.bind("mousewheel."+i,function(t,n){if(h._stop(o),!h._disableMousewheel(o,t.target)){var i="auto"!==r.mouseWheel.deltaFactor?parseInt(r.mouseWheel.deltaFactor):d&&t.deltaFactor<100?100:t.deltaFactor||100;if("x"===r.axis||"x"===r.mouseWheel.axis)var c="x",u=[Math.round(i*a.scrollRatio.x),parseInt(r.mouseWheel.scrollAmount)],f="auto"!==r.mouseWheel.scrollAmount?u[1]:u[0]>=l.width()?.9*l.width():u[0],_=Math.abs(e("#mCSB_"+a.idx+"_container")[0].offsetLeft),m=s[1][0].offsetLeft,p=s[1].parent().width()-s[1].width(),g=t.deltaX||t.deltaY||n;else var c="y",u=[Math.round(i*a.scrollRatio.y),parseInt(r.mouseWheel.scrollAmount)],f="auto"!==r.mouseWheel.scrollAmount?u[1]:u[0]>=l.height()?.9*l.height():u[0],_=Math.abs(e("#mCSB_"+a.idx+"_container")[0].offsetTop),m=s[0][0].offsetTop,p=s[0].parent().height()-s[0].height(),g=t.deltaY||n;"y"===c&&!a.overflowed[0]||"x"===c&&!a.overflowed[1]||(r.mouseWheel.invert&&(g=-g),r.mouseWheel.normalizeDelta&&(g=0>g?-1:1),(g>0&&0!==m||0>g&&m!==p||r.mouseWheel.preventDefault)&&(t.stopImmediatePropagation(),t.preventDefault()),h._scrollTo(o,(_-g*f).toString(),{dir:c}))}})}},_disableMousewheel:function(t,o){var a=o.nodeName.toLowerCase(),r=t.data(n).opt.mouseWheel.disableOver,i=["select","textarea"];return e.inArray(a,r)>-1&&!(e.inArray(a,i)>-1&&!e(o).is(":focus"))},_draggerRail:function(){var t=e(this),o=t.data(n),a=n+"_"+o.idx,r=e("#mCSB_"+o.idx+"_container"),i=r.parent(),l=e(".mCSB_"+o.idx+"_scrollbar .mCSB_draggerContainer");l.bind("touchstart."+a+" pointerdown."+a+" MSPointerDown."+a,function(){u=!0}).bind("touchend."+a+" pointerup."+a+" MSPointerUp."+a,function(){u=!1}).bind("click."+a,function(a){if(e(a.target).hasClass("mCSB_draggerContainer")||e(a.target).hasClass("mCSB_draggerRail")){h._stop(t);var n=e(this),l=n.find(".mCSB_dragger");if(n.parent(".mCSB_scrollTools_horizontal").length>0){if(!o.overflowed[1])return;var s="x",c=a.pageX>l.offset().left?-1:1,d=Math.abs(r[0].offsetLeft)-.9*c*i.width()}else{if(!o.overflowed[0])return;var s="y",c=a.pageY>l.offset().top?-1:1,d=Math.abs(r[0].offsetTop)-.9*c*i.height()}h._scrollTo(t,d.toString(),{dir:s,scrollEasing:"mcsEaseInOut"})}})},_focus:function(){var t=e(this),a=t.data(n),r=a.opt,i=n+"_"+a.idx,l=e("#mCSB_"+a.idx+"_container"),s=l.parent();l.bind("focusin."+i,function(){var a=e(o.activeElement),n=l.find(".mCustomScrollBox").length,i=0;a.is(r.advanced.autoScrollOnFocus)&&(h._stop(t),clearTimeout(t[0]._focusTimeout),t[0]._focusTimer=n?(i+17)*n:0,t[0]._focusTimeout=setTimeout(function(){var e=[a.offset().top-l.offset().top,a.offset().left-l.offset().left],o=[l[0].offsetTop,l[0].offsetLeft],n=[o[0]+e[0]>=0&&o[0]+e[0]<s.height()-a.outerHeight(!1),o[1]+e[1]>=0&&o[0]+e[1]<s.width()-a.outerWidth(!1)],c="yx"!==r.axis||n[0]||n[1]?"all":"none";"x"===r.axis||n[0]||h._scrollTo(t,e[0].toString(),{dir:"y",scrollEasing:"mcsEaseInOut",overwrite:c,dur:i}),"y"===r.axis||n[1]||h._scrollTo(t,e[1].toString(),{dir:"x",scrollEasing:"mcsEaseInOut",overwrite:c,dur:i})},t[0]._focusTimer))})},_wrapperScroll:function(){var t=e(this),o=t.data(n),a=n+"_"+o.idx,r=e("#mCSB_"+o.idx+"_container").parent();r.bind("scroll."+a,function(){(0!==r.scrollTop()||0!==r.scrollLeft())&&e(".mCSB_"+o.idx+"_scrollbar").css("visibility","hidden")})},_buttons:function(){var t=e(this),o=t.data(n),a=o.opt,r=o.sequential,i=n+"_"+o.idx,l=(e("#mCSB_"+o.idx+"_container"),".mCSB_"+o.idx+"_scrollbar"),s=e(l+">a");s.bind("mousedown."+i+" touchstart."+i+" pointerdown."+i+" MSPointerDown."+i+" mouseup."+i+" touchend."+i+" pointerup."+i+" MSPointerUp."+i+" mouseout."+i+" pointerout."+i+" MSPointerOut."+i+" click."+i,function(n){function i(e,o){r.scrollAmount=a.snapAmount||a.scrollButtons.scrollAmount,h._sequentialScroll.call(this,t,e,o)}if(n.preventDefault(),h._mouseBtnLeft(n)){var l=e(this).attr("class");switch(r.type=a.scrollButtons.scrollType,n.type){case"mousedown":case"touchstart":case"pointerdown":case"MSPointerDown":if("stepped"===r.type)return;u=!0,o.tweenRunning=!1,i("on",l);break;case"mouseup":case"touchend":case"pointerup":case"MSPointerUp":case"mouseout":case"pointerout":case"MSPointerOut":if("stepped"===r.type)return;u=!1,r.dir&&i("off",l);break;case"click":if("stepped"!==r.type||o.tweenRunning)return;i("on",l)}}})},_keyboard:function(){var t=e(this),a=t.data(n),r=a.opt,i=a.sequential,l=n+"_"+a.idx,s=e("#mCSB_"+a.idx),c=e("#mCSB_"+a.idx+"_container"),d=c.parent(),u="input,textarea,select,datalist,keygen,[contenteditable='true']";s.attr("tabindex","0").bind("blur."+l+" keydown."+l+" keyup."+l,function(n){function l(e,o){i.type=r.keyboard.scrollType,i.scrollAmount=r.snapAmount||r.keyboard.scrollAmount,"stepped"===i.type&&a.tweenRunning||h._sequentialScroll.call(this,t,e,o)}switch(n.type){case"blur":a.tweenRunning&&i.dir&&l("off",null);break;case"keydown":case"keyup":var s=n.keyCode?n.keyCode:n.which,f="on";if("x"!==r.axis&&(38===s||40===s)||"y"!==r.axis&&(37===s||39===s)){if((38===s||40===s)&&!a.overflowed[0]||(37===s||39===s)&&!a.overflowed[1])return;"keyup"===n.type&&(f="off"),e(o.activeElement).is(u)||(n.preventDefault(),n.stopImmediatePropagation(),l(f,s))}else if(33===s||34===s){if((a.overflowed[0]||a.overflowed[1])&&(n.preventDefault(),n.stopImmediatePropagation()),"keyup"===n.type){h._stop(t);var _=34===s?-1:1;if("x"===r.axis||"yx"===r.axis&&a.overflowed[1]&&!a.overflowed[0])var m="x",p=Math.abs(c[0].offsetLeft)-.9*_*d.width();else var m="y",p=Math.abs(c[0].offsetTop)-.9*_*d.height();h._scrollTo(t,p.toString(),{dir:m,scrollEasing:"mcsEaseInOut"})}}else if((35===s||36===s)&&!e(o.activeElement).is(u)&&((a.overflowed[0]||a.overflowed[1])&&(n.preventDefault(),n.stopImmediatePropagation()),"keyup"===n.type)){if("x"===r.axis||"yx"===r.axis&&a.overflowed[1]&&!a.overflowed[0])var m="x",p=35===s?Math.abs(d.width()-c.outerWidth(!1)):0;else var m="y",p=35===s?Math.abs(d.height()-c.outerHeight(!1)):0;h._scrollTo(t,p.toString(),{dir:m,scrollEasing:"mcsEaseInOut"})}}})},_sequentialScroll:function(t,o,a){function r(e){var o="stepped"!==c.type,a=e?o?s.scrollInertia/1.5:s.scrollInertia:1e3/60,n=e?o?7.5:40:2.5,i=[Math.abs(d[0].offsetTop),Math.abs(d[0].offsetLeft)],u=[l.scrollRatio.y>10?10:l.scrollRatio.y,l.scrollRatio.x>10?10:l.scrollRatio.x],f="x"===c.dir[0]?i[1]+c.dir[1]*u[1]*n:i[0]+c.dir[1]*u[0]*n,_="x"===c.dir[0]?i[1]+c.dir[1]*parseInt(c.scrollAmount):i[0]+c.dir[1]*parseInt(c.scrollAmount),m="auto"!==c.scrollAmount?_:f,p=e?o?"mcsLinearOut":"mcsEaseInOut":"mcsLinear",g=e?!0:!1;return e&&17>a&&(m="x"===c.dir[0]?i[1]:i[0]),h._scrollTo(t,m.toString(),{dir:c.dir[0],scrollEasing:p,dur:a,onComplete:g}),e?void(c.dir=!1):(clearTimeout(c.step),void(c.step=setTimeout(function(){r()},a)))}function i(){clearTimeout(c.step),h._stop(t)}var l=t.data(n),s=l.opt,c=l.sequential,d=e("#mCSB_"+l.idx+"_container"),u="stepped"===c.type?!0:!1;switch(o){case"on":if(c.dir=["mCSB_buttonRight"===a||"mCSB_buttonLeft"===a||39===a||37===a?"x":"y","mCSB_buttonUp"===a||"mCSB_buttonLeft"===a||38===a||37===a?-1:1],h._stop(t),h._isNumeric(a)&&"stepped"===c.type)return;r(u);break;case"off":i(),(u||l.tweenRunning&&c.dir)&&r(!0)}},_arr:function(t){var o=e(this).data(n).opt,a=[];return"function"==typeof t&&(t=t()),t instanceof Array?a=t.length>1?[t[0],t[1]]:"x"===o.axis?[null,t[0]]:[t[0],null]:(a[0]=t.y?t.y:t.x||"x"===o.axis?null:t,a[1]=t.x?t.x:t.y||"y"===o.axis?null:t),"function"==typeof a[0]&&(a[0]=a[0]()),"function"==typeof a[1]&&(a[1]=a[1]()),a},_to:function(t,o){if(null!=t&&"undefined"!=typeof t){var a=e(this),r=a.data(n),i=r.opt,l=e("#mCSB_"+r.idx+"_container"),s=l.parent(),c=typeof t;o||(o="x"===i.axis?"x":"y");var d="x"===o?l.outerWidth(!1):l.outerHeight(!1),u="x"===o?l.offset().left:l.offset().top,_="x"===o?l[0].offsetLeft:l[0].offsetTop,m="x"===o?"left":"top";switch(c){case"function":return t();case"object":if(t.nodeType)var p="x"===o?e(t).offset().left:e(t).offset().top;else if(t.jquery){if(!t.length)return;var p="x"===o?t.offset().left:t.offset().top}return p-u;case"string":case"number":if(h._isNumeric.call(null,t))return Math.abs(t);if(-1!==t.indexOf("%"))return Math.abs(d*parseInt(t)/100);if(-1!==t.indexOf("-="))return Math.abs(_-parseInt(t.split("-=")[1]));if(-1!==t.indexOf("+=")){var g=_+parseInt(t.split("+=")[1]);return g>=0?0:Math.abs(g)}if(-1!==t.indexOf("px")&&h._isNumeric.call(null,t.split("px")[0]))return Math.abs(t.split("px")[0]);if("top"===t||"left"===t)return 0;if("bottom"===t)return Math.abs(s.height()-l.outerHeight(!1));if("right"===t)return Math.abs(s.width()-l.outerWidth(!1));if("first"===t||"last"===t){var v=l.find(":"+t),p="x"===o?e(v).offset().left:e(v).offset().top;return p-u}if(e(t).length){var p="x"===o?e(t).offset().left:e(t).offset().top;return p-u}return l.css(m,t),void f.update.call(null,a[0])}}},_autoUpdate:function(t){function o(){clearTimeout(u[0].autoUpdate),u[0].autoUpdate=setTimeout(function(){return d.advanced.updateOnSelectorChange&&(_=i(),_!==S)?(l(),void(S=_)):(d.advanced.updateOnContentResize&&(m=[u.outerHeight(!1),u.outerWidth(!1),g.height(),g.width(),x()[0],x()[1]],(m[0]!==C[0]||m[1]!==C[1]||m[2]!==C[2]||m[3]!==C[3]||m[4]!==C[4]||m[5]!==C[5])&&(l(),C=m)),d.advanced.updateOnImageLoad&&(p=a(),p!==b&&(u.find("img").each(function(){r(this.src)}),b=p)),void((d.advanced.updateOnSelectorChange||d.advanced.updateOnContentResize||d.advanced.updateOnImageLoad)&&o()))},60)}function a(){var e=0;return d.advanced.updateOnImageLoad&&(e=u.find("img").length),e}function r(e){function t(e,t){return function(){return t.apply(e,arguments)}}function o(){this.onload=null,l()}var a=new Image;a.onload=t(a,o),a.src=e}function i(){d.advanced.updateOnSelectorChange===!0&&(d.advanced.updateOnSelectorChange="*");var t=0,o=u.find(d.advanced.updateOnSelectorChange);return d.advanced.updateOnSelectorChange&&o.length>0&&o.each(function(){t+=e(this).height()+e(this).width()}),t}function l(){clearTimeout(u[0].autoUpdate),f.update.call(null,s[0])}var s=e(this),c=s.data(n),d=c.opt,u=e("#mCSB_"+c.idx+"_container");if(t)return clearTimeout(u[0].autoUpdate),void h._delete.call(null,u[0].autoUpdate);var _,m,p,g=u.parent(),v=[e("#mCSB_"+c.idx+"_scrollbar_vertical"),e("#mCSB_"+c.idx+"_scrollbar_horizontal")],x=function(){return[v[0].is(":visible")?v[0].outerHeight(!0):0,v[1].is(":visible")?v[1].outerWidth(!0):0]},S=i(),C=[u.outerHeight(!1),u.outerWidth(!1),g.height(),g.width(),x()[0],x()[1]],b=a();o()},_snapAmount:function(e,t,o){return Math.round(e/t)*t-o},_stop:function(t){var o=t.data(n),a=e("#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal");a.each(function(){h._stopTween.call(this)})},_scrollTo:function(t,o,a){function r(e){return s&&c.callbacks[e]&&"function"==typeof c.callbacks[e]}function i(){return[c.callbacks.alwaysTriggerOffsets||S>=C[0]+w,c.callbacks.alwaysTriggerOffsets||-y>=S]}function l(){var e=[_[0].offsetTop,_[0].offsetLeft],o=[v[0].offsetTop,v[0].offsetLeft],n=[_.outerHeight(!1),_.outerWidth(!1)],r=[f.height(),f.width()];t[0].mcs={content:_,top:e[0],left:e[1],draggerTop:o[0],draggerLeft:o[1],topPct:Math.round(100*Math.abs(e[0])/(Math.abs(n[0])-r[0])),leftPct:Math.round(100*Math.abs(e[1])/(Math.abs(n[1])-r[1])),direction:a.dir}}var s=t.data(n),c=s.opt,d={trigger:"internal",dir:"y",scrollEasing:"mcsEaseOut",drag:!1,dur:c.scrollInertia,overwrite:"all",callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},a=e.extend(d,a),u=[a.dur,a.drag?0:a.dur],f=e("#mCSB_"+s.idx),_=e("#mCSB_"+s.idx+"_container"),m=_.parent(),p=c.callbacks.onTotalScrollOffset?h._arr.call(t,c.callbacks.onTotalScrollOffset):[0,0],g=c.callbacks.onTotalScrollBackOffset?h._arr.call(t,c.callbacks.onTotalScrollBackOffset):[0,0];
if(s.trigger=a.trigger,(0!==m.scrollTop()||0!==m.scrollLeft())&&(e(".mCSB_"+s.idx+"_scrollbar").css("visibility","visible"),m.scrollTop(0).scrollLeft(0)),"_resetY"!==o||s.contentReset.y||(r("onOverflowYNone")&&c.callbacks.onOverflowYNone.call(t[0]),s.contentReset.y=1),"_resetX"!==o||s.contentReset.x||(r("onOverflowXNone")&&c.callbacks.onOverflowXNone.call(t[0]),s.contentReset.x=1),"_resetY"!==o&&"_resetX"!==o){switch(!s.contentReset.y&&t[0].mcs||!s.overflowed[0]||(r("onOverflowY")&&c.callbacks.onOverflowY.call(t[0]),s.contentReset.x=null),!s.contentReset.x&&t[0].mcs||!s.overflowed[1]||(r("onOverflowX")&&c.callbacks.onOverflowX.call(t[0]),s.contentReset.x=null),c.snapAmount&&(o=h._snapAmount(o,c.snapAmount,c.snapOffset)),a.dir){case"x":var v=e("#mCSB_"+s.idx+"_dragger_horizontal"),x="left",S=_[0].offsetLeft,C=[f.width()-_.outerWidth(!1),v.parent().width()-v.width()],b=[o,0===o?0:o/s.scrollRatio.x],w=p[1],y=g[1],B=w>0?w/s.scrollRatio.x:0,T=y>0?y/s.scrollRatio.x:0;break;case"y":var v=e("#mCSB_"+s.idx+"_dragger_vertical"),x="top",S=_[0].offsetTop,C=[f.height()-_.outerHeight(!1),v.parent().height()-v.height()],b=[o,0===o?0:o/s.scrollRatio.y],w=p[0],y=g[0],B=w>0?w/s.scrollRatio.y:0,T=y>0?y/s.scrollRatio.y:0}b[1]<0||0===b[0]&&0===b[1]?b=[0,0]:b[1]>=C[1]?b=[C[0],C[1]]:b[0]=-b[0],t[0].mcs||(l(),r("onInit")&&c.callbacks.onInit.call(t[0])),clearTimeout(_[0].onCompleteTimeout),(s.tweenRunning||!(0===S&&b[0]>=0||S===C[0]&&b[0]<=C[0]))&&(h._tweenTo.call(null,v[0],x,Math.round(b[1]),u[1],a.scrollEasing),h._tweenTo.call(null,_[0],x,Math.round(b[0]),u[0],a.scrollEasing,a.overwrite,{onStart:function(){a.callbacks&&a.onStart&&!s.tweenRunning&&(r("onScrollStart")&&(l(),c.callbacks.onScrollStart.call(t[0])),s.tweenRunning=!0,h._onDragClasses(v),s.cbOffsets=i())},onUpdate:function(){a.callbacks&&a.onUpdate&&r("whileScrolling")&&(l(),c.callbacks.whileScrolling.call(t[0]))},onComplete:function(){if(a.callbacks&&a.onComplete){"yx"===c.axis&&clearTimeout(_[0].onCompleteTimeout);var e=_[0].idleTimer||0;_[0].onCompleteTimeout=setTimeout(function(){r("onScroll")&&(l(),c.callbacks.onScroll.call(t[0])),r("onTotalScroll")&&b[1]>=C[1]-B&&s.cbOffsets[0]&&(l(),c.callbacks.onTotalScroll.call(t[0])),r("onTotalScrollBack")&&b[1]<=T&&s.cbOffsets[1]&&(l(),c.callbacks.onTotalScrollBack.call(t[0])),s.tweenRunning=!1,_[0].idleTimer=0,h._onDragClasses(v,"hide")},e)}}}))}},_tweenTo:function(e,o,a,n,r,i,l){function s(){w.stop||(S||p.call(),S=h._getTime()-x,c(),S>=w.time&&(w.time=S>w.time?S+_-(S-w.time):S+_-1,w.time<S+1&&(w.time=S+1)),w.time<n?w.id=m(s):v.call())}function c(){n>0?(w.currVal=f(w.time,C,y,n,r),b[o]=Math.round(w.currVal)+"px"):b[o]=a+"px",g.call()}function d(){_=1e3/60,w.time=S+_,m=t.requestAnimationFrame?t.requestAnimationFrame:function(e){return c(),setTimeout(e,.01)},w.id=m(s)}function u(){null!=w.id&&(t.requestAnimationFrame?t.cancelAnimationFrame(w.id):clearTimeout(w.id),w.id=null)}function f(e,t,o,a,n){switch(n){case"linear":case"mcsLinear":return o*e/a+t;case"mcsLinearOut":return e/=a,e--,o*Math.sqrt(1-e*e)+t;case"easeInOutSmooth":return e/=a/2,1>e?o/2*e*e+t:(e--,-o/2*(e*(e-2)-1)+t);case"easeInOutStrong":return e/=a/2,1>e?o/2*Math.pow(2,10*(e-1))+t:(e--,o/2*(-Math.pow(2,-10*e)+2)+t);case"easeInOut":case"mcsEaseInOut":return e/=a/2,1>e?o/2*e*e*e+t:(e-=2,o/2*(e*e*e+2)+t);case"easeOutSmooth":return e/=a,e--,-o*(e*e*e*e-1)+t;case"easeOutStrong":return o*(-Math.pow(2,-10*e/a)+1)+t;case"easeOut":case"mcsEaseOut":default:var r=(e/=a)*e,i=r*e;return t+o*(.499999999999997*i*r+-2.5*r*r+5.5*i+-6.5*r+4*e)}}e._malihuTween||(e._malihuTween={top:{},left:{}});var _,m,l=l||{},p=l.onStart||function(){},g=l.onUpdate||function(){},v=l.onComplete||function(){},x=h._getTime(),S=0,C=e.offsetTop,b=e.style,w=e._malihuTween[o];"left"===o&&(C=e.offsetLeft);var y=a-C;w.stop=0,"none"!==i&&u(),d()},_getTime:function(){return t.performance&&t.performance.now?t.performance.now():t.performance&&t.performance.webkitNow?t.performance.webkitNow():Date.now?Date.now():(new Date).getTime()},_stopTween:function(){var e=this;e._malihuTween||(e._malihuTween={top:{},left:{}}),e._malihuTween.top.id&&(t.requestAnimationFrame?t.cancelAnimationFrame(e._malihuTween.top.id):clearTimeout(e._malihuTween.top.id),e._malihuTween.top.id=null,e._malihuTween.top.stop=1),e._malihuTween.left.id&&(t.requestAnimationFrame?t.cancelAnimationFrame(e._malihuTween.left.id):clearTimeout(e._malihuTween.left.id),e._malihuTween.left.id=null,e._malihuTween.left.stop=1)},_delete:function(e){try{delete e}catch(t){e=null}},_mouseBtnLeft:function(e){return!(e.which&&1!==e.which)},_pointerTouch:function(e){var t=e.originalEvent.pointerType;return!(t&&"touch"!==t&&2!==t)},_isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)}};e.fn[a]=function(t){return f[t]?f[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):f.init.apply(this,arguments)},e[a]=function(t){return f[t]?f[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):f.init.apply(this,arguments)},e[a].defaults=i,t[a]=!0,e(t).load(function(){e(r)[a]()})})}(jQuery,window,document);*/

/* == malihu jquery custom scrollbar plugin == Version: 3.1.5, License: MIT License (MIT) */
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"undefined"!=typeof module&&module.exports?module.exports=e:e(jQuery,window,document)}(function(e){!function(t){var o="function"==typeof define&&define.amd,a="undefined"!=typeof module&&module.exports,n="https:"==document.location.protocol?"https:":"http:",i="cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js";o||(a?require("jquery-mousewheel")(e):e.event.special.mousewheel||e("head").append(decodeURI("%3Cscript src="+n+"//"+i+"%3E%3C/script%3E"))),t()}(function(){var t,o="mCustomScrollbar",a="mCS",n=".mCustomScrollbar",i={setTop:0,setLeft:0,axis:"y",scrollbarPosition:"inside",scrollInertia:950,autoDraggerLength:!0,alwaysShowScrollbar:0,snapOffset:0,mouseWheel:{enable:!0,scrollAmount:"auto",axis:"y",deltaFactor:"auto",disableOver:["select","option","keygen","datalist","textarea"]},scrollButtons:{scrollType:"stepless",scrollAmount:"auto"},keyboard:{enable:!0,scrollType:"stepless",scrollAmount:"auto"},contentTouchScroll:25,documentTouchScroll:!0,advanced:{autoScrollOnFocus:"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']",updateOnContentResize:!0,updateOnImageLoad:"auto",autoUpdateTimeout:60},theme:"light",callbacks:{onTotalScrollOffset:0,onTotalScrollBackOffset:0,alwaysTriggerOffsets:!0}},r=0,l={},s=window.attachEvent&&!window.addEventListener?1:0,c=!1,d=["mCSB_dragger_onDrag","mCSB_scrollTools_onDrag","mCS_img_loaded","mCS_disabled","mCS_destroyed","mCS_no_scrollbar","mCS-autoHide","mCS-dir-rtl","mCS_no_scrollbar_y","mCS_no_scrollbar_x","mCS_y_hidden","mCS_x_hidden","mCSB_draggerContainer","mCSB_buttonUp","mCSB_buttonDown","mCSB_buttonLeft","mCSB_buttonRight"],u={init:function(t){var t=e.extend(!0,{},i,t),o=f.call(this);if(t.live){var s=t.liveSelector||this.selector||n,c=e(s);if("off"===t.live)return void m(s);l[s]=setTimeout(function(){c.mCustomScrollbar(t),"once"===t.live&&c.length&&m(s)},500)}else m(s);return t.setWidth=t.set_width?t.set_width:t.setWidth,t.setHeight=t.set_height?t.set_height:t.setHeight,t.axis=t.horizontalScroll?"x":p(t.axis),t.scrollInertia=t.scrollInertia>0&&t.scrollInertia<17?17:t.scrollInertia,"object"!=typeof t.mouseWheel&&1==t.mouseWheel&&(t.mouseWheel={enable:!0,scrollAmount:"auto",axis:"y",preventDefault:!1,deltaFactor:"auto",normalizeDelta:!1,invert:!1}),t.mouseWheel.scrollAmount=t.mouseWheelPixels?t.mouseWheelPixels:t.mouseWheel.scrollAmount,t.mouseWheel.normalizeDelta=t.advanced.normalizeMouseWheelDelta?t.advanced.normalizeMouseWheelDelta:t.mouseWheel.normalizeDelta,t.scrollButtons.scrollType=g(t.scrollButtons.scrollType),h(t),e(o).each(function(){var o=e(this);if(!o.data(a)){o.data(a,{idx:++r,opt:t,scrollRatio:{y:null,x:null},overflowed:null,contentReset:{y:null,x:null},bindEvents:!1,tweenRunning:!1,sequential:{},langDir:o.css("direction"),cbOffsets:null,trigger:null,poll:{size:{o:0,n:0},img:{o:0,n:0},change:{o:0,n:0}}});var n=o.data(a),i=n.opt,l=o.data("mcs-axis"),s=o.data("mcs-scrollbar-position"),c=o.data("mcs-theme");l&&(i.axis=l),s&&(i.scrollbarPosition=s),c&&(i.theme=c,h(i)),v.call(this),n&&i.callbacks.onCreate&&"function"==typeof i.callbacks.onCreate&&i.callbacks.onCreate.call(this),e("#mCSB_"+n.idx+"_container img:not(."+d[2]+")").addClass(d[2]),u.update.call(null,o)}})},update:function(t,o){var n=t||f.call(this);return e(n).each(function(){var t=e(this);if(t.data(a)){var n=t.data(a),i=n.opt,r=e("#mCSB_"+n.idx+"_container"),l=e("#mCSB_"+n.idx),s=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];if(!r.length)return;n.tweenRunning&&Q(t),o&&n&&i.callbacks.onBeforeUpdate&&"function"==typeof i.callbacks.onBeforeUpdate&&i.callbacks.onBeforeUpdate.call(this),t.hasClass(d[3])&&t.removeClass(d[3]),t.hasClass(d[4])&&t.removeClass(d[4]),l.css("max-height","none"),l.height()!==t.height()&&l.css("max-height",t.height()),_.call(this),"y"===i.axis||i.advanced.autoExpandHorizontalScroll||r.css("width",x(r)),n.overflowed=y.call(this),M.call(this),i.autoDraggerLength&&S.call(this),b.call(this),T.call(this);var c=[Math.abs(r[0].offsetTop),Math.abs(r[0].offsetLeft)];"x"!==i.axis&&(n.overflowed[0]?s[0].height()>s[0].parent().height()?B.call(this):(G(t,c[0].toString(),{dir:"y",dur:0,overwrite:"none"}),n.contentReset.y=null):(B.call(this),"y"===i.axis?k.call(this):"yx"===i.axis&&n.overflowed[1]&&G(t,c[1].toString(),{dir:"x",dur:0,overwrite:"none"}))),"y"!==i.axis&&(n.overflowed[1]?s[1].width()>s[1].parent().width()?B.call(this):(G(t,c[1].toString(),{dir:"x",dur:0,overwrite:"none"}),n.contentReset.x=null):(B.call(this),"x"===i.axis?k.call(this):"yx"===i.axis&&n.overflowed[0]&&G(t,c[0].toString(),{dir:"y",dur:0,overwrite:"none"}))),o&&n&&(2===o&&i.callbacks.onImageLoad&&"function"==typeof i.callbacks.onImageLoad?i.callbacks.onImageLoad.call(this):3===o&&i.callbacks.onSelectorChange&&"function"==typeof i.callbacks.onSelectorChange?i.callbacks.onSelectorChange.call(this):i.callbacks.onUpdate&&"function"==typeof i.callbacks.onUpdate&&i.callbacks.onUpdate.call(this)),N.call(this)}})},scrollTo:function(t,o){if("undefined"!=typeof t&&null!=t){var n=f.call(this);return e(n).each(function(){var n=e(this);if(n.data(a)){var i=n.data(a),r=i.opt,l={trigger:"external",scrollInertia:r.scrollInertia,scrollEasing:"mcsEaseInOut",moveDragger:!1,timeout:60,callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},s=e.extend(!0,{},l,o),c=Y.call(this,t),d=s.scrollInertia>0&&s.scrollInertia<17?17:s.scrollInertia;c[0]=X.call(this,c[0],"y"),c[1]=X.call(this,c[1],"x"),s.moveDragger&&(c[0]*=i.scrollRatio.y,c[1]*=i.scrollRatio.x),s.dur=ne()?0:d,setTimeout(function(){null!==c[0]&&"undefined"!=typeof c[0]&&"x"!==r.axis&&i.overflowed[0]&&(s.dir="y",s.overwrite="all",G(n,c[0].toString(),s)),null!==c[1]&&"undefined"!=typeof c[1]&&"y"!==r.axis&&i.overflowed[1]&&(s.dir="x",s.overwrite="none",G(n,c[1].toString(),s))},s.timeout)}})}},stop:function(){var t=f.call(this);return e(t).each(function(){var t=e(this);t.data(a)&&Q(t)})},disable:function(t){var o=f.call(this);return e(o).each(function(){var o=e(this);if(o.data(a)){o.data(a);N.call(this,"remove"),k.call(this),t&&B.call(this),M.call(this,!0),o.addClass(d[3])}})},destroy:function(){var t=f.call(this);return e(t).each(function(){var n=e(this);if(n.data(a)){var i=n.data(a),r=i.opt,l=e("#mCSB_"+i.idx),s=e("#mCSB_"+i.idx+"_container"),c=e(".mCSB_"+i.idx+"_scrollbar");r.live&&m(r.liveSelector||e(t).selector),N.call(this,"remove"),k.call(this),B.call(this),n.removeData(a),$(this,"mcs"),c.remove(),s.find("img."+d[2]).removeClass(d[2]),l.replaceWith(s.contents()),n.removeClass(o+" _"+a+"_"+i.idx+" "+d[6]+" "+d[7]+" "+d[5]+" "+d[3]).addClass(d[4])}})}},f=function(){return"object"!=typeof e(this)||e(this).length<1?n:this},h=function(t){var o=["rounded","rounded-dark","rounded-dots","rounded-dots-dark"],a=["rounded-dots","rounded-dots-dark","3d","3d-dark","3d-thick","3d-thick-dark","inset","inset-dark","inset-2","inset-2-dark","inset-3","inset-3-dark"],n=["minimal","minimal-dark"],i=["minimal","minimal-dark"],r=["minimal","minimal-dark"];t.autoDraggerLength=e.inArray(t.theme,o)>-1?!1:t.autoDraggerLength,t.autoExpandScrollbar=e.inArray(t.theme,a)>-1?!1:t.autoExpandScrollbar,t.scrollButtons.enable=e.inArray(t.theme,n)>-1?!1:t.scrollButtons.enable,t.autoHideScrollbar=e.inArray(t.theme,i)>-1?!0:t.autoHideScrollbar,t.scrollbarPosition=e.inArray(t.theme,r)>-1?"outside":t.scrollbarPosition},m=function(e){l[e]&&(clearTimeout(l[e]),$(l,e))},p=function(e){return"yx"===e||"xy"===e||"auto"===e?"yx":"x"===e||"horizontal"===e?"x":"y"},g=function(e){return"stepped"===e||"pixels"===e||"step"===e||"click"===e?"stepped":"stepless"},v=function(){var t=e(this),n=t.data(a),i=n.opt,r=i.autoExpandScrollbar?" "+d[1]+"_expand":"",l=["<div id='mCSB_"+n.idx+"_scrollbar_vertical' class='mCSB_scrollTools mCSB_"+n.idx+"_scrollbar mCS-"+i.theme+" mCSB_scrollTools_vertical"+r+"'><div class='"+d[12]+"'><div id='mCSB_"+n.idx+"_dragger_vertical' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>","<div id='mCSB_"+n.idx+"_scrollbar_horizontal' class='mCSB_scrollTools mCSB_"+n.idx+"_scrollbar mCS-"+i.theme+" mCSB_scrollTools_horizontal"+r+"'><div class='"+d[12]+"'><div id='mCSB_"+n.idx+"_dragger_horizontal' class='mCSB_dragger' style='position:absolute;'><div class='mCSB_dragger_bar' /></div><div class='mCSB_draggerRail' /></div></div>"],s="yx"===i.axis?"mCSB_vertical_horizontal":"x"===i.axis?"mCSB_horizontal":"mCSB_vertical",c="yx"===i.axis?l[0]+l[1]:"x"===i.axis?l[1]:l[0],u="yx"===i.axis?"<div id='mCSB_"+n.idx+"_container_wrapper' class='mCSB_container_wrapper' />":"",f=i.autoHideScrollbar?" "+d[6]:"",h="x"!==i.axis&&"rtl"===n.langDir?" "+d[7]:"";i.setWidth&&t.css("width",i.setWidth),i.setHeight&&t.css("height",i.setHeight),i.setLeft="y"!==i.axis&&"rtl"===n.langDir?"989999px":i.setLeft,t.addClass(o+" _"+a+"_"+n.idx+f+h).wrapInner("<div id='mCSB_"+n.idx+"' class='mCustomScrollBox mCS-"+i.theme+" "+s+"'><div id='mCSB_"+n.idx+"_container' class='mCSB_container' style='position:relative; top:"+i.setTop+"; left:"+i.setLeft+";' dir='"+n.langDir+"' /></div>");var m=e("#mCSB_"+n.idx),p=e("#mCSB_"+n.idx+"_container");"y"===i.axis||i.advanced.autoExpandHorizontalScroll||p.css("width",x(p)),"outside"===i.scrollbarPosition?("static"===t.css("position")&&t.css("position","relative"),t.css("overflow","visible"),m.addClass("mCSB_outside").after(c)):(m.addClass("mCSB_inside").append(c),p.wrap(u)),w.call(this);var g=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")];g[0].css("min-height",g[0].height()),g[1].css("min-width",g[1].width())},x=function(t){var o=[t[0].scrollWidth,Math.max.apply(Math,t.children().map(function(){return e(this).outerWidth(!0)}).get())],a=t.parent().width();return o[0]>a?o[0]:o[1]>a?o[1]:"100%"},_=function(){var t=e(this),o=t.data(a),n=o.opt,i=e("#mCSB_"+o.idx+"_container");if(n.advanced.autoExpandHorizontalScroll&&"y"!==n.axis){i.css({width:"auto","min-width":0,"overflow-x":"scroll"});var r=Math.ceil(i[0].scrollWidth);3===n.advanced.autoExpandHorizontalScroll||2!==n.advanced.autoExpandHorizontalScroll&&r>i.parent().width()?i.css({width:r,"min-width":"100%","overflow-x":"inherit"}):i.css({"overflow-x":"inherit",position:"absolute"}).wrap("<div class='mCSB_h_wrapper' style='position:relative; left:0; width:999999px;' />").css({width:Math.ceil(i[0].getBoundingClientRect().right+.4)-Math.floor(i[0].getBoundingClientRect().left),"min-width":"100%",position:"relative"}).unwrap()}},w=function(){var t=e(this),o=t.data(a),n=o.opt,i=e(".mCSB_"+o.idx+"_scrollbar:first"),r=oe(n.scrollButtons.tabindex)?"tabindex='"+n.scrollButtons.tabindex+"'":"",l=["<a href='#' class='"+d[13]+"' "+r+" />","<a href='#' class='"+d[14]+"' "+r+" />","<a href='#' class='"+d[15]+"' "+r+" />","<a href='#' class='"+d[16]+"' "+r+" />"],s=["x"===n.axis?l[2]:l[0],"x"===n.axis?l[3]:l[1],l[2],l[3]];n.scrollButtons.enable&&i.prepend(s[0]).append(s[1]).next(".mCSB_scrollTools").prepend(s[2]).append(s[3])},S=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[n.height()/i.outerHeight(!1),n.width()/i.outerWidth(!1)],c=[parseInt(r[0].css("min-height")),Math.round(l[0]*r[0].parent().height()),parseInt(r[1].css("min-width")),Math.round(l[1]*r[1].parent().width())],d=s&&c[1]<c[0]?c[0]:c[1],u=s&&c[3]<c[2]?c[2]:c[3];r[0].css({height:d,"max-height":r[0].parent().height()-10}).find(".mCSB_dragger_bar").css({"line-height":c[0]+"px"}),r[1].css({width:u,"max-width":r[1].parent().width()-10})},b=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")],l=[i.outerHeight(!1)-n.height(),i.outerWidth(!1)-n.width()],s=[l[0]/(r[0].parent().height()-r[0].height()),l[1]/(r[1].parent().width()-r[1].width())];o.scrollRatio={y:s[0],x:s[1]}},C=function(e,t,o){var a=o?d[0]+"_expanded":"",n=e.closest(".mCSB_scrollTools");"active"===t?(e.toggleClass(d[0]+" "+a),n.toggleClass(d[1]),e[0]._draggable=e[0]._draggable?0:1):e[0]._draggable||("hide"===t?(e.removeClass(d[0]),n.removeClass(d[1])):(e.addClass(d[0]),n.addClass(d[1])))},y=function(){var t=e(this),o=t.data(a),n=e("#mCSB_"+o.idx),i=e("#mCSB_"+o.idx+"_container"),r=null==o.overflowed?i.height():i.outerHeight(!1),l=null==o.overflowed?i.width():i.outerWidth(!1),s=i[0].scrollHeight,c=i[0].scrollWidth;return s>r&&(r=s),c>l&&(l=c),[r>n.height(),l>n.width()]},B=function(){var t=e(this),o=t.data(a),n=o.opt,i=e("#mCSB_"+o.idx),r=e("#mCSB_"+o.idx+"_container"),l=[e("#mCSB_"+o.idx+"_dragger_vertical"),e("#mCSB_"+o.idx+"_dragger_horizontal")];if(Q(t),("x"!==n.axis&&!o.overflowed[0]||"y"===n.axis&&o.overflowed[0])&&(l[0].add(r).css("top",0),G(t,"_resetY")),"y"!==n.axis&&!o.overflowed[1]||"x"===n.axis&&o.overflowed[1]){var s=dx=0;"rtl"===o.langDir&&(s=i.width()-r.outerWidth(!1),dx=Math.abs(s/o.scrollRatio.x)),r.css("left",s),l[1].css("left",dx),G(t,"_resetX")}},T=function(){function t(){r=setTimeout(function(){e.event.special.mousewheel?(clearTimeout(r),W.call(o[0])):t()},100)}var o=e(this),n=o.data(a),i=n.opt;if(!n.bindEvents){if(I.call(this),i.contentTouchScroll&&D.call(this),E.call(this),i.mouseWheel.enable){var r;t()}P.call(this),U.call(this),i.advanced.autoScrollOnFocus&&H.call(this),i.scrollButtons.enable&&F.call(this),i.keyboard.enable&&q.call(this),n.bindEvents=!0}},k=function(){var t=e(this),o=t.data(a),n=o.opt,i=a+"_"+o.idx,r=".mCSB_"+o.idx+"_scrollbar",l=e("#mCSB_"+o.idx+",#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,"+r+" ."+d[12]+",#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal,"+r+">a"),s=e("#mCSB_"+o.idx+"_container");n.advanced.releaseDraggableSelectors&&l.add(e(n.advanced.releaseDraggableSelectors)),n.advanced.extraDraggableSelectors&&l.add(e(n.advanced.extraDraggableSelectors)),o.bindEvents&&(e(document).add(e(!A()||top.document)).unbind("."+i),l.each(function(){e(this).unbind("."+i)}),clearTimeout(t[0]._focusTimeout),$(t[0],"_focusTimeout"),clearTimeout(o.sequential.step),$(o.sequential,"step"),clearTimeout(s[0].onCompleteTimeout),$(s[0],"onCompleteTimeout"),o.bindEvents=!1)},M=function(t){var o=e(this),n=o.data(a),i=n.opt,r=e("#mCSB_"+n.idx+"_container_wrapper"),l=r.length?r:e("#mCSB_"+n.idx+"_container"),s=[e("#mCSB_"+n.idx+"_scrollbar_vertical"),e("#mCSB_"+n.idx+"_scrollbar_horizontal")],c=[s[0].find(".mCSB_dragger"),s[1].find(".mCSB_dragger")];"x"!==i.axis&&(n.overflowed[0]&&!t?(s[0].add(c[0]).add(s[0].children("a")).css("display","block"),l.removeClass(d[8]+" "+d[10])):(i.alwaysShowScrollbar?(2!==i.alwaysShowScrollbar&&c[0].css("display","none"),l.removeClass(d[10])):(s[0].css("display","none"),l.addClass(d[10])),l.addClass(d[8]))),"y"!==i.axis&&(n.overflowed[1]&&!t?(s[1].add(c[1]).add(s[1].children("a")).css("display","block"),l.removeClass(d[9]+" "+d[11])):(i.alwaysShowScrollbar?(2!==i.alwaysShowScrollbar&&c[1].css("display","none"),l.removeClass(d[11])):(s[1].css("display","none"),l.addClass(d[11])),l.addClass(d[9]))),n.overflowed[0]||n.overflowed[1]?o.removeClass(d[5]):o.addClass(d[5])},O=function(t){var o=t.type,a=t.target.ownerDocument!==document&&null!==frameElement?[e(frameElement).offset().top,e(frameElement).offset().left]:null,n=A()&&t.target.ownerDocument!==top.document&&null!==frameElement?[e(t.view.frameElement).offset().top,e(t.view.frameElement).offset().left]:[0,0];switch(o){case"pointerdown":case"MSPointerDown":case"pointermove":case"MSPointerMove":case"pointerup":case"MSPointerUp":return a?[t.originalEvent.pageY-a[0]+n[0],t.originalEvent.pageX-a[1]+n[1],!1]:[t.originalEvent.pageY,t.originalEvent.pageX,!1];case"touchstart":case"touchmove":case"touchend":var i=t.originalEvent.touches[0]||t.originalEvent.changedTouches[0],r=t.originalEvent.touches.length||t.originalEvent.changedTouches.length;return t.target.ownerDocument!==document?[i.screenY,i.screenX,r>1]:[i.pageY,i.pageX,r>1];default:return a?[t.pageY-a[0]+n[0],t.pageX-a[1]+n[1],!1]:[t.pageY,t.pageX,!1]}},I=function(){function t(e,t,a,n){if(h[0].idleTimer=d.scrollInertia<233?250:0,o.attr("id")===f[1])var i="x",s=(o[0].offsetLeft-t+n)*l.scrollRatio.x;else var i="y",s=(o[0].offsetTop-e+a)*l.scrollRatio.y;G(r,s.toString(),{dir:i,drag:!0})}var o,n,i,r=e(this),l=r.data(a),d=l.opt,u=a+"_"+l.idx,f=["mCSB_"+l.idx+"_dragger_vertical","mCSB_"+l.idx+"_dragger_horizontal"],h=e("#mCSB_"+l.idx+"_container"),m=e("#"+f[0]+",#"+f[1]),p=d.advanced.releaseDraggableSelectors?m.add(e(d.advanced.releaseDraggableSelectors)):m,g=d.advanced.extraDraggableSelectors?e(!A()||top.document).add(e(d.advanced.extraDraggableSelectors)):e(!A()||top.document);m.bind("contextmenu."+u,function(e){e.preventDefault()}).bind("mousedown."+u+" touchstart."+u+" pointerdown."+u+" MSPointerDown."+u,function(t){if(t.stopImmediatePropagation(),t.preventDefault(),ee(t)){c=!0,s&&(document.onselectstart=function(){return!1}),L.call(h,!1),Q(r),o=e(this);var a=o.offset(),l=O(t)[0]-a.top,u=O(t)[1]-a.left,f=o.height()+a.top,m=o.width()+a.left;f>l&&l>0&&m>u&&u>0&&(n=l,i=u),C(o,"active",d.autoExpandScrollbar)}}).bind("touchmove."+u,function(e){e.stopImmediatePropagation(),e.preventDefault();var a=o.offset(),r=O(e)[0]-a.top,l=O(e)[1]-a.left;t(n,i,r,l)}),e(document).add(g).bind("mousemove."+u+" pointermove."+u+" MSPointerMove."+u,function(e){if(o){var a=o.offset(),r=O(e)[0]-a.top,l=O(e)[1]-a.left;if(n===r&&i===l)return;t(n,i,r,l)}}).add(p).bind("mouseup."+u+" touchend."+u+" pointerup."+u+" MSPointerUp."+u,function(){o&&(C(o,"active",d.autoExpandScrollbar),o=null),c=!1,s&&(document.onselectstart=null),L.call(h,!0)})},D=function(){function o(e){if(!te(e)||c||O(e)[2])return void(t=0);t=1,b=0,C=0,d=1,y.removeClass("mCS_touch_action");var o=I.offset();u=O(e)[0]-o.top,f=O(e)[1]-o.left,z=[O(e)[0],O(e)[1]]}function n(e){if(te(e)&&!c&&!O(e)[2]&&(T.documentTouchScroll||e.preventDefault(),e.stopImmediatePropagation(),(!C||b)&&d)){g=K();var t=M.offset(),o=O(e)[0]-t.top,a=O(e)[1]-t.left,n="mcsLinearOut";if(E.push(o),W.push(a),z[2]=Math.abs(O(e)[0]-z[0]),z[3]=Math.abs(O(e)[1]-z[1]),B.overflowed[0])var i=D[0].parent().height()-D[0].height(),r=u-o>0&&o-u>-(i*B.scrollRatio.y)&&(2*z[3]<z[2]||"yx"===T.axis);if(B.overflowed[1])var l=D[1].parent().width()-D[1].width(),h=f-a>0&&a-f>-(l*B.scrollRatio.x)&&(2*z[2]<z[3]||"yx"===T.axis);r||h?(U||e.preventDefault(),b=1):(C=1,y.addClass("mCS_touch_action")),U&&e.preventDefault(),w="yx"===T.axis?[u-o,f-a]:"x"===T.axis?[null,f-a]:[u-o,null],I[0].idleTimer=250,B.overflowed[0]&&s(w[0],R,n,"y","all",!0),B.overflowed[1]&&s(w[1],R,n,"x",L,!0)}}function i(e){if(!te(e)||c||O(e)[2])return void(t=0);t=1,e.stopImmediatePropagation(),Q(y),p=K();var o=M.offset();h=O(e)[0]-o.top,m=O(e)[1]-o.left,E=[],W=[]}function r(e){if(te(e)&&!c&&!O(e)[2]){d=0,e.stopImmediatePropagation(),b=0,C=0,v=K();var t=M.offset(),o=O(e)[0]-t.top,a=O(e)[1]-t.left;if(!(v-g>30)){_=1e3/(v-p);var n="mcsEaseOut",i=2.5>_,r=i?[E[E.length-2],W[W.length-2]]:[0,0];x=i?[o-r[0],a-r[1]]:[o-h,a-m];var u=[Math.abs(x[0]),Math.abs(x[1])];_=i?[Math.abs(x[0]/4),Math.abs(x[1]/4)]:[_,_];var f=[Math.abs(I[0].offsetTop)-x[0]*l(u[0]/_[0],_[0]),Math.abs(I[0].offsetLeft)-x[1]*l(u[1]/_[1],_[1])];w="yx"===T.axis?[f[0],f[1]]:"x"===T.axis?[null,f[1]]:[f[0],null],S=[4*u[0]+T.scrollInertia,4*u[1]+T.scrollInertia];var y=parseInt(T.contentTouchScroll)||0;w[0]=u[0]>y?w[0]:0,w[1]=u[1]>y?w[1]:0,B.overflowed[0]&&s(w[0],S[0],n,"y",L,!1),B.overflowed[1]&&s(w[1],S[1],n,"x",L,!1)}}}function l(e,t){var o=[1.5*t,2*t,t/1.5,t/2];return e>90?t>4?o[0]:o[3]:e>60?t>3?o[3]:o[2]:e>30?t>8?o[1]:t>6?o[0]:t>4?t:o[2]:t>8?t:o[3]}function s(e,t,o,a,n,i){e&&G(y,e.toString(),{dur:t,scrollEasing:o,dir:a,overwrite:n,drag:i})}var d,u,f,h,m,p,g,v,x,_,w,S,b,C,y=e(this),B=y.data(a),T=B.opt,k=a+"_"+B.idx,M=e("#mCSB_"+B.idx),I=e("#mCSB_"+B.idx+"_container"),D=[e("#mCSB_"+B.idx+"_dragger_vertical"),e("#mCSB_"+B.idx+"_dragger_horizontal")],E=[],W=[],R=0,L="yx"===T.axis?"none":"all",z=[],P=I.find("iframe"),H=["touchstart."+k+" pointerdown."+k+" MSPointerDown."+k,"touchmove."+k+" pointermove."+k+" MSPointerMove."+k,"touchend."+k+" pointerup."+k+" MSPointerUp."+k],U=void 0!==document.body.style.touchAction&&""!==document.body.style.touchAction;I.bind(H[0],function(e){o(e)}).bind(H[1],function(e){n(e)}),M.bind(H[0],function(e){i(e)}).bind(H[2],function(e){r(e)}),P.length&&P.each(function(){e(this).bind("load",function(){A(this)&&e(this.contentDocument||this.contentWindow.document).bind(H[0],function(e){o(e),i(e)}).bind(H[1],function(e){n(e)}).bind(H[2],function(e){r(e)})})})},E=function(){function o(){return window.getSelection?window.getSelection().toString():document.selection&&"Control"!=document.selection.type?document.selection.createRange().text:0}function n(e,t,o){d.type=o&&i?"stepped":"stepless",d.scrollAmount=10,j(r,e,t,"mcsLinearOut",o?60:null)}var i,r=e(this),l=r.data(a),s=l.opt,d=l.sequential,u=a+"_"+l.idx,f=e("#mCSB_"+l.idx+"_container"),h=f.parent();f.bind("mousedown."+u,function(){t||i||(i=1,c=!0)}).add(document).bind("mousemove."+u,function(e){if(!t&&i&&o()){var a=f.offset(),r=O(e)[0]-a.top+f[0].offsetTop,c=O(e)[1]-a.left+f[0].offsetLeft;r>0&&r<h.height()&&c>0&&c<h.width()?d.step&&n("off",null,"stepped"):("x"!==s.axis&&l.overflowed[0]&&(0>r?n("on",38):r>h.height()&&n("on",40)),"y"!==s.axis&&l.overflowed[1]&&(0>c?n("on",37):c>h.width()&&n("on",39)))}}).bind("mouseup."+u+" dragend."+u,function(){t||(i&&(i=0,n("off",null)),c=!1)})},W=function(){function t(t,a){if(Q(o),!z(o,t.target)){var r="auto"!==i.mouseWheel.deltaFactor?parseInt(i.mouseWheel.deltaFactor):s&&t.deltaFactor<100?100:t.deltaFactor||100,d=i.scrollInertia;if("x"===i.axis||"x"===i.mouseWheel.axis)var u="x",f=[Math.round(r*n.scrollRatio.x),parseInt(i.mouseWheel.scrollAmount)],h="auto"!==i.mouseWheel.scrollAmount?f[1]:f[0]>=l.width()?.9*l.width():f[0],m=Math.abs(e("#mCSB_"+n.idx+"_container")[0].offsetLeft),p=c[1][0].offsetLeft,g=c[1].parent().width()-c[1].width(),v="y"===i.mouseWheel.axis?t.deltaY||a:t.deltaX;else var u="y",f=[Math.round(r*n.scrollRatio.y),parseInt(i.mouseWheel.scrollAmount)],h="auto"!==i.mouseWheel.scrollAmount?f[1]:f[0]>=l.height()?.9*l.height():f[0],m=Math.abs(e("#mCSB_"+n.idx+"_container")[0].offsetTop),p=c[0][0].offsetTop,g=c[0].parent().height()-c[0].height(),v=t.deltaY||a;"y"===u&&!n.overflowed[0]||"x"===u&&!n.overflowed[1]||((i.mouseWheel.invert||t.webkitDirectionInvertedFromDevice)&&(v=-v),i.mouseWheel.normalizeDelta&&(v=0>v?-1:1),(v>0&&0!==p||0>v&&p!==g||i.mouseWheel.preventDefault)&&(t.stopImmediatePropagation(),t.preventDefault()),t.deltaFactor<5&&!i.mouseWheel.normalizeDelta&&(h=t.deltaFactor,d=17),G(o,(m-v*h).toString(),{dir:u,dur:d}))}}if(e(this).data(a)){var o=e(this),n=o.data(a),i=n.opt,r=a+"_"+n.idx,l=e("#mCSB_"+n.idx),c=[e("#mCSB_"+n.idx+"_dragger_vertical"),e("#mCSB_"+n.idx+"_dragger_horizontal")],d=e("#mCSB_"+n.idx+"_container").find("iframe");d.length&&d.each(function(){e(this).bind("load",function(){A(this)&&e(this.contentDocument||this.contentWindow.document).bind("mousewheel."+r,function(e,o){t(e,o)})})}),l.bind("mousewheel."+r,function(e,o){t(e,o)})}},R=new Object,A=function(t){var o=!1,a=!1,n=null;if(void 0===t?a="#empty":void 0!==e(t).attr("id")&&(a=e(t).attr("id")),a!==!1&&void 0!==R[a])return R[a];if(t){try{var i=t.contentDocument||t.contentWindow.document;n=i.body.innerHTML}catch(r){}o=null!==n}else{try{var i=top.document;n=i.body.innerHTML}catch(r){}o=null!==n}return a!==!1&&(R[a]=o),o},L=function(e){var t=this.find("iframe");if(t.length){var o=e?"auto":"none";t.css("pointer-events",o)}},z=function(t,o){var n=o.nodeName.toLowerCase(),i=t.data(a).opt.mouseWheel.disableOver,r=["select","textarea"];return e.inArray(n,i)>-1&&!(e.inArray(n,r)>-1&&!e(o).is(":focus"))},P=function(){var t,o=e(this),n=o.data(a),i=a+"_"+n.idx,r=e("#mCSB_"+n.idx+"_container"),l=r.parent(),s=e(".mCSB_"+n.idx+"_scrollbar ."+d[12]);s.bind("mousedown."+i+" touchstart."+i+" pointerdown."+i+" MSPointerDown."+i,function(o){c=!0,e(o.target).hasClass("mCSB_dragger")||(t=1)}).bind("touchend."+i+" pointerup."+i+" MSPointerUp."+i,function(){c=!1}).bind("click."+i,function(a){if(t&&(t=0,e(a.target).hasClass(d[12])||e(a.target).hasClass("mCSB_draggerRail"))){Q(o);var i=e(this),s=i.find(".mCSB_dragger");if(i.parent(".mCSB_scrollTools_horizontal").length>0){if(!n.overflowed[1])return;var c="x",u=a.pageX>s.offset().left?-1:1,f=Math.abs(r[0].offsetLeft)-u*(.9*l.width())}else{if(!n.overflowed[0])return;var c="y",u=a.pageY>s.offset().top?-1:1,f=Math.abs(r[0].offsetTop)-u*(.9*l.height())}G(o,f.toString(),{dir:c,scrollEasing:"mcsEaseInOut"})}})},H=function(){var t=e(this),o=t.data(a),n=o.opt,i=a+"_"+o.idx,r=e("#mCSB_"+o.idx+"_container"),l=r.parent();r.bind("focusin."+i,function(){var o=e(document.activeElement),a=r.find(".mCustomScrollBox").length,i=0;o.is(n.advanced.autoScrollOnFocus)&&(Q(t),clearTimeout(t[0]._focusTimeout),t[0]._focusTimer=a?(i+17)*a:0,t[0]._focusTimeout=setTimeout(function(){var e=[ae(o)[0],ae(o)[1]],a=[r[0].offsetTop,r[0].offsetLeft],s=[a[0]+e[0]>=0&&a[0]+e[0]<l.height()-o.outerHeight(!1),a[1]+e[1]>=0&&a[0]+e[1]<l.width()-o.outerWidth(!1)],c="yx"!==n.axis||s[0]||s[1]?"all":"none";"x"===n.axis||s[0]||G(t,e[0].toString(),{dir:"y",scrollEasing:"mcsEaseInOut",overwrite:c,dur:i}),"y"===n.axis||s[1]||G(t,e[1].toString(),{dir:"x",scrollEasing:"mcsEaseInOut",overwrite:c,dur:i})},t[0]._focusTimer))})},U=function(){var t=e(this),o=t.data(a),n=a+"_"+o.idx,i=e("#mCSB_"+o.idx+"_container").parent();i.bind("scroll."+n,function(){0===i.scrollTop()&&0===i.scrollLeft()||e(".mCSB_"+o.idx+"_scrollbar").css("visibility","hidden")})},F=function(){var t=e(this),o=t.data(a),n=o.opt,i=o.sequential,r=a+"_"+o.idx,l=".mCSB_"+o.idx+"_scrollbar",s=e(l+">a");s.bind("contextmenu."+r,function(e){e.preventDefault()}).bind("mousedown."+r+" touchstart."+r+" pointerdown."+r+" MSPointerDown."+r+" mouseup."+r+" touchend."+r+" pointerup."+r+" MSPointerUp."+r+" mouseout."+r+" pointerout."+r+" MSPointerOut."+r+" click."+r,function(a){function r(e,o){i.scrollAmount=n.scrollButtons.scrollAmount,j(t,e,o)}if(a.preventDefault(),ee(a)){var l=e(this).attr("class");switch(i.type=n.scrollButtons.scrollType,a.type){case"mousedown":case"touchstart":case"pointerdown":case"MSPointerDown":if("stepped"===i.type)return;c=!0,o.tweenRunning=!1,r("on",l);break;case"mouseup":case"touchend":case"pointerup":case"MSPointerUp":case"mouseout":case"pointerout":case"MSPointerOut":if("stepped"===i.type)return;c=!1,i.dir&&r("off",l);break;case"click":if("stepped"!==i.type||o.tweenRunning)return;r("on",l)}}})},q=function(){function t(t){function a(e,t){r.type=i.keyboard.scrollType,r.scrollAmount=i.keyboard.scrollAmount,"stepped"===r.type&&n.tweenRunning||j(o,e,t)}switch(t.type){case"blur":n.tweenRunning&&r.dir&&a("off",null);break;case"keydown":case"keyup":var l=t.keyCode?t.keyCode:t.which,s="on";if("x"!==i.axis&&(38===l||40===l)||"y"!==i.axis&&(37===l||39===l)){if((38===l||40===l)&&!n.overflowed[0]||(37===l||39===l)&&!n.overflowed[1])return;"keyup"===t.type&&(s="off"),e(document.activeElement).is(u)||(t.preventDefault(),t.stopImmediatePropagation(),a(s,l))}else if(33===l||34===l){if((n.overflowed[0]||n.overflowed[1])&&(t.preventDefault(),t.stopImmediatePropagation()),"keyup"===t.type){Q(o);var f=34===l?-1:1;if("x"===i.axis||"yx"===i.axis&&n.overflowed[1]&&!n.overflowed[0])var h="x",m=Math.abs(c[0].offsetLeft)-f*(.9*d.width());else var h="y",m=Math.abs(c[0].offsetTop)-f*(.9*d.height());G(o,m.toString(),{dir:h,scrollEasing:"mcsEaseInOut"})}}else if((35===l||36===l)&&!e(document.activeElement).is(u)&&((n.overflowed[0]||n.overflowed[1])&&(t.preventDefault(),t.stopImmediatePropagation()),"keyup"===t.type)){if("x"===i.axis||"yx"===i.axis&&n.overflowed[1]&&!n.overflowed[0])var h="x",m=35===l?Math.abs(d.width()-c.outerWidth(!1)):0;else var h="y",m=35===l?Math.abs(d.height()-c.outerHeight(!1)):0;G(o,m.toString(),{dir:h,scrollEasing:"mcsEaseInOut"})}}}var o=e(this),n=o.data(a),i=n.opt,r=n.sequential,l=a+"_"+n.idx,s=e("#mCSB_"+n.idx),c=e("#mCSB_"+n.idx+"_container"),d=c.parent(),u="input,textarea,select,datalist,keygen,[contenteditable='true']",f=c.find("iframe"),h=["blur."+l+" keydown."+l+" keyup."+l];f.length&&f.each(function(){e(this).bind("load",function(){A(this)&&e(this.contentDocument||this.contentWindow.document).bind(h[0],function(e){t(e)})})}),s.attr("tabindex","0").bind(h[0],function(e){t(e)})},j=function(t,o,n,i,r){function l(e){u.snapAmount&&(f.scrollAmount=u.snapAmount instanceof Array?"x"===f.dir[0]?u.snapAmount[1]:u.snapAmount[0]:u.snapAmount);var o="stepped"!==f.type,a=r?r:e?o?p/1.5:g:1e3/60,n=e?o?7.5:40:2.5,s=[Math.abs(h[0].offsetTop),Math.abs(h[0].offsetLeft)],d=[c.scrollRatio.y>10?10:c.scrollRatio.y,c.scrollRatio.x>10?10:c.scrollRatio.x],m="x"===f.dir[0]?s[1]+f.dir[1]*(d[1]*n):s[0]+f.dir[1]*(d[0]*n),v="x"===f.dir[0]?s[1]+f.dir[1]*parseInt(f.scrollAmount):s[0]+f.dir[1]*parseInt(f.scrollAmount),x="auto"!==f.scrollAmount?v:m,_=i?i:e?o?"mcsLinearOut":"mcsEaseInOut":"mcsLinear",w=!!e;return e&&17>a&&(x="x"===f.dir[0]?s[1]:s[0]),G(t,x.toString(),{dir:f.dir[0],scrollEasing:_,dur:a,onComplete:w}),e?void(f.dir=!1):(clearTimeout(f.step),void(f.step=setTimeout(function(){l()},a)))}function s(){clearTimeout(f.step),$(f,"step"),Q(t)}var c=t.data(a),u=c.opt,f=c.sequential,h=e("#mCSB_"+c.idx+"_container"),m="stepped"===f.type,p=u.scrollInertia<26?26:u.scrollInertia,g=u.scrollInertia<1?17:u.scrollInertia;switch(o){case"on":if(f.dir=[n===d[16]||n===d[15]||39===n||37===n?"x":"y",n===d[13]||n===d[15]||38===n||37===n?-1:1],Q(t),oe(n)&&"stepped"===f.type)return;l(m);break;case"off":s(),(m||c.tweenRunning&&f.dir)&&l(!0)}},Y=function(t){var o=e(this).data(a).opt,n=[];return"function"==typeof t&&(t=t()),t instanceof Array?n=t.length>1?[t[0],t[1]]:"x"===o.axis?[null,t[0]]:[t[0],null]:(n[0]=t.y?t.y:t.x||"x"===o.axis?null:t,n[1]=t.x?t.x:t.y||"y"===o.axis?null:t),"function"==typeof n[0]&&(n[0]=n[0]()),"function"==typeof n[1]&&(n[1]=n[1]()),n},X=function(t,o){if(null!=t&&"undefined"!=typeof t){var n=e(this),i=n.data(a),r=i.opt,l=e("#mCSB_"+i.idx+"_container"),s=l.parent(),c=typeof t;o||(o="x"===r.axis?"x":"y");var d="x"===o?l.outerWidth(!1)-s.width():l.outerHeight(!1)-s.height(),f="x"===o?l[0].offsetLeft:l[0].offsetTop,h="x"===o?"left":"top";switch(c){case"function":return t();case"object":var m=t.jquery?t:e(t);if(!m.length)return;return"x"===o?ae(m)[1]:ae(m)[0];case"string":case"number":if(oe(t))return Math.abs(t);if(-1!==t.indexOf("%"))return Math.abs(d*parseInt(t)/100);if(-1!==t.indexOf("-="))return Math.abs(f-parseInt(t.split("-=")[1]));if(-1!==t.indexOf("+=")){var p=f+parseInt(t.split("+=")[1]);return p>=0?0:Math.abs(p)}if(-1!==t.indexOf("px")&&oe(t.split("px")[0]))return Math.abs(t.split("px")[0]);if("top"===t||"left"===t)return 0;if("bottom"===t)return Math.abs(s.height()-l.outerHeight(!1));if("right"===t)return Math.abs(s.width()-l.outerWidth(!1));if("first"===t||"last"===t){var m=l.find(":"+t);return"x"===o?ae(m)[1]:ae(m)[0]}return e(t).length?"x"===o?ae(e(t))[1]:ae(e(t))[0]:(l.css(h,t),void u.update.call(null,n[0]))}}},N=function(t){function o(){return clearTimeout(f[0].autoUpdate),0===l.parents("html").length?void(l=null):void(f[0].autoUpdate=setTimeout(function(){return c.advanced.updateOnSelectorChange&&(s.poll.change.n=i(),s.poll.change.n!==s.poll.change.o)?(s.poll.change.o=s.poll.change.n,void r(3)):c.advanced.updateOnContentResize&&(s.poll.size.n=l[0].scrollHeight+l[0].scrollWidth+f[0].offsetHeight+l[0].offsetHeight+l[0].offsetWidth,s.poll.size.n!==s.poll.size.o)?(s.poll.size.o=s.poll.size.n,void r(1)):!c.advanced.updateOnImageLoad||"auto"===c.advanced.updateOnImageLoad&&"y"===c.axis||(s.poll.img.n=f.find("img").length,s.poll.img.n===s.poll.img.o)?void((c.advanced.updateOnSelectorChange||c.advanced.updateOnContentResize||c.advanced.updateOnImageLoad)&&o()):(s.poll.img.o=s.poll.img.n,void f.find("img").each(function(){n(this)}))},c.advanced.autoUpdateTimeout))}function n(t){function o(e,t){return function(){
return t.apply(e,arguments)}}function a(){this.onload=null,e(t).addClass(d[2]),r(2)}if(e(t).hasClass(d[2]))return void r();var n=new Image;n.onload=o(n,a),n.src=t.src}function i(){c.advanced.updateOnSelectorChange===!0&&(c.advanced.updateOnSelectorChange="*");var e=0,t=f.find(c.advanced.updateOnSelectorChange);return c.advanced.updateOnSelectorChange&&t.length>0&&t.each(function(){e+=this.offsetHeight+this.offsetWidth}),e}function r(e){clearTimeout(f[0].autoUpdate),u.update.call(null,l[0],e)}var l=e(this),s=l.data(a),c=s.opt,f=e("#mCSB_"+s.idx+"_container");return t?(clearTimeout(f[0].autoUpdate),void $(f[0],"autoUpdate")):void o()},V=function(e,t,o){return Math.round(e/t)*t-o},Q=function(t){var o=t.data(a),n=e("#mCSB_"+o.idx+"_container,#mCSB_"+o.idx+"_container_wrapper,#mCSB_"+o.idx+"_dragger_vertical,#mCSB_"+o.idx+"_dragger_horizontal");n.each(function(){Z.call(this)})},G=function(t,o,n){function i(e){return s&&c.callbacks[e]&&"function"==typeof c.callbacks[e]}function r(){return[c.callbacks.alwaysTriggerOffsets||w>=S[0]+y,c.callbacks.alwaysTriggerOffsets||-B>=w]}function l(){var e=[h[0].offsetTop,h[0].offsetLeft],o=[x[0].offsetTop,x[0].offsetLeft],a=[h.outerHeight(!1),h.outerWidth(!1)],i=[f.height(),f.width()];t[0].mcs={content:h,top:e[0],left:e[1],draggerTop:o[0],draggerLeft:o[1],topPct:Math.round(100*Math.abs(e[0])/(Math.abs(a[0])-i[0])),leftPct:Math.round(100*Math.abs(e[1])/(Math.abs(a[1])-i[1])),direction:n.dir}}var s=t.data(a),c=s.opt,d={trigger:"internal",dir:"y",scrollEasing:"mcsEaseOut",drag:!1,dur:c.scrollInertia,overwrite:"all",callbacks:!0,onStart:!0,onUpdate:!0,onComplete:!0},n=e.extend(d,n),u=[n.dur,n.drag?0:n.dur],f=e("#mCSB_"+s.idx),h=e("#mCSB_"+s.idx+"_container"),m=h.parent(),p=c.callbacks.onTotalScrollOffset?Y.call(t,c.callbacks.onTotalScrollOffset):[0,0],g=c.callbacks.onTotalScrollBackOffset?Y.call(t,c.callbacks.onTotalScrollBackOffset):[0,0];if(s.trigger=n.trigger,0===m.scrollTop()&&0===m.scrollLeft()||(e(".mCSB_"+s.idx+"_scrollbar").css("visibility","visible"),m.scrollTop(0).scrollLeft(0)),"_resetY"!==o||s.contentReset.y||(i("onOverflowYNone")&&c.callbacks.onOverflowYNone.call(t[0]),s.contentReset.y=1),"_resetX"!==o||s.contentReset.x||(i("onOverflowXNone")&&c.callbacks.onOverflowXNone.call(t[0]),s.contentReset.x=1),"_resetY"!==o&&"_resetX"!==o){if(!s.contentReset.y&&t[0].mcs||!s.overflowed[0]||(i("onOverflowY")&&c.callbacks.onOverflowY.call(t[0]),s.contentReset.x=null),!s.contentReset.x&&t[0].mcs||!s.overflowed[1]||(i("onOverflowX")&&c.callbacks.onOverflowX.call(t[0]),s.contentReset.x=null),c.snapAmount){var v=c.snapAmount instanceof Array?"x"===n.dir?c.snapAmount[1]:c.snapAmount[0]:c.snapAmount;o=V(o,v,c.snapOffset)}switch(n.dir){case"x":var x=e("#mCSB_"+s.idx+"_dragger_horizontal"),_="left",w=h[0].offsetLeft,S=[f.width()-h.outerWidth(!1),x.parent().width()-x.width()],b=[o,0===o?0:o/s.scrollRatio.x],y=p[1],B=g[1],T=y>0?y/s.scrollRatio.x:0,k=B>0?B/s.scrollRatio.x:0;break;case"y":var x=e("#mCSB_"+s.idx+"_dragger_vertical"),_="top",w=h[0].offsetTop,S=[f.height()-h.outerHeight(!1),x.parent().height()-x.height()],b=[o,0===o?0:o/s.scrollRatio.y],y=p[0],B=g[0],T=y>0?y/s.scrollRatio.y:0,k=B>0?B/s.scrollRatio.y:0}b[1]<0||0===b[0]&&0===b[1]?b=[0,0]:b[1]>=S[1]?b=[S[0],S[1]]:b[0]=-b[0],t[0].mcs||(l(),i("onInit")&&c.callbacks.onInit.call(t[0])),clearTimeout(h[0].onCompleteTimeout),J(x[0],_,Math.round(b[1]),u[1],n.scrollEasing),!s.tweenRunning&&(0===w&&b[0]>=0||w===S[0]&&b[0]<=S[0])||J(h[0],_,Math.round(b[0]),u[0],n.scrollEasing,n.overwrite,{onStart:function(){n.callbacks&&n.onStart&&!s.tweenRunning&&(i("onScrollStart")&&(l(),c.callbacks.onScrollStart.call(t[0])),s.tweenRunning=!0,C(x),s.cbOffsets=r())},onUpdate:function(){n.callbacks&&n.onUpdate&&i("whileScrolling")&&(l(),c.callbacks.whileScrolling.call(t[0]))},onComplete:function(){if(n.callbacks&&n.onComplete){"yx"===c.axis&&clearTimeout(h[0].onCompleteTimeout);var e=h[0].idleTimer||0;h[0].onCompleteTimeout=setTimeout(function(){i("onScroll")&&(l(),c.callbacks.onScroll.call(t[0])),i("onTotalScroll")&&b[1]>=S[1]-T&&s.cbOffsets[0]&&(l(),c.callbacks.onTotalScroll.call(t[0])),i("onTotalScrollBack")&&b[1]<=k&&s.cbOffsets[1]&&(l(),c.callbacks.onTotalScrollBack.call(t[0])),s.tweenRunning=!1,h[0].idleTimer=0,C(x,"hide")},e)}}})}},J=function(e,t,o,a,n,i,r){function l(){S.stop||(x||m.call(),x=K()-v,s(),x>=S.time&&(S.time=x>S.time?x+f-(x-S.time):x+f-1,S.time<x+1&&(S.time=x+1)),S.time<a?S.id=h(l):g.call())}function s(){a>0?(S.currVal=u(S.time,_,b,a,n),w[t]=Math.round(S.currVal)+"px"):w[t]=o+"px",p.call()}function c(){f=1e3/60,S.time=x+f,h=window.requestAnimationFrame?window.requestAnimationFrame:function(e){return s(),setTimeout(e,.01)},S.id=h(l)}function d(){null!=S.id&&(window.requestAnimationFrame?window.cancelAnimationFrame(S.id):clearTimeout(S.id),S.id=null)}function u(e,t,o,a,n){switch(n){case"linear":case"mcsLinear":return o*e/a+t;case"mcsLinearOut":return e/=a,e--,o*Math.sqrt(1-e*e)+t;case"easeInOutSmooth":return e/=a/2,1>e?o/2*e*e+t:(e--,-o/2*(e*(e-2)-1)+t);case"easeInOutStrong":return e/=a/2,1>e?o/2*Math.pow(2,10*(e-1))+t:(e--,o/2*(-Math.pow(2,-10*e)+2)+t);case"easeInOut":case"mcsEaseInOut":return e/=a/2,1>e?o/2*e*e*e+t:(e-=2,o/2*(e*e*e+2)+t);case"easeOutSmooth":return e/=a,e--,-o*(e*e*e*e-1)+t;case"easeOutStrong":return o*(-Math.pow(2,-10*e/a)+1)+t;case"easeOut":case"mcsEaseOut":default:var i=(e/=a)*e,r=i*e;return t+o*(.499999999999997*r*i+-2.5*i*i+5.5*r+-6.5*i+4*e)}}e._mTween||(e._mTween={top:{},left:{}});var f,h,r=r||{},m=r.onStart||function(){},p=r.onUpdate||function(){},g=r.onComplete||function(){},v=K(),x=0,_=e.offsetTop,w=e.style,S=e._mTween[t];"left"===t&&(_=e.offsetLeft);var b=o-_;S.stop=0,"none"!==i&&d(),c()},K=function(){return window.performance&&window.performance.now?window.performance.now():window.performance&&window.performance.webkitNow?window.performance.webkitNow():Date.now?Date.now():(new Date).getTime()},Z=function(){var e=this;e._mTween||(e._mTween={top:{},left:{}});for(var t=["top","left"],o=0;o<t.length;o++){var a=t[o];e._mTween[a].id&&(window.requestAnimationFrame?window.cancelAnimationFrame(e._mTween[a].id):clearTimeout(e._mTween[a].id),e._mTween[a].id=null,e._mTween[a].stop=1)}},$=function(e,t){try{delete e[t]}catch(o){e[t]=null}},ee=function(e){return!(e.which&&1!==e.which)},te=function(e){var t=e.originalEvent.pointerType;return!(t&&"touch"!==t&&2!==t)},oe=function(e){return!isNaN(parseFloat(e))&&isFinite(e)},ae=function(e){var t=e.parents(".mCSB_container");return[e.offset().top-t.offset().top,e.offset().left-t.offset().left]},ne=function(){function e(){var e=["webkit","moz","ms","o"];if("hidden"in document)return"hidden";for(var t=0;t<e.length;t++)if(e[t]+"Hidden"in document)return e[t]+"Hidden";return null}var t=e();return t?document[t]:!1};e.fn[o]=function(t){return u[t]?u[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):u.init.apply(this,arguments)},e[o]=function(t){return u[t]?u[t].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof t&&t?void e.error("Method "+t+" does not exist"):u.init.apply(this,arguments)},e[o].defaults=i,window[o]=!0,e(window).bind("load",function(){e(n)[o](),e.extend(e.expr[":"],{mcsInView:e.expr[":"].mcsInView||function(t){var o,a,n=e(t),i=n.parents(".mCSB_container");if(i.length)return o=i.parent(),a=[i[0].offsetTop,i[0].offsetLeft],a[0]+ae(n)[0]>=0&&a[0]+ae(n)[0]<o.height()-n.outerHeight(!1)&&a[1]+ae(n)[1]>=0&&a[1]+ae(n)[1]<o.width()-n.outerWidth(!1)},mcsInSight:e.expr[":"].mcsInSight||function(t,o,a){var n,i,r,l,s=e(t),c=s.parents(".mCSB_container"),d="exact"===a[3]?[[1,0],[1,0]]:[[.9,.1],[.6,.4]];if(c.length)return n=[s.outerHeight(!1),s.outerWidth(!1)],r=[c[0].offsetTop+ae(s)[0],c[0].offsetLeft+ae(s)[1]],i=[c.parent()[0].offsetHeight,c.parent()[0].offsetWidth],l=[n[0]<i[0]?d[0]:d[1],n[1]<i[1]?d[0]:d[1]],r[0]-i[0]*l[0][0]<0&&r[0]+n[0]-i[0]*l[0][1]>=0&&r[1]-i[1]*l[1][0]<0&&r[1]+n[1]-i[1]*l[1][1]>=0},mcsOverflow:e.expr[":"].mcsOverflow||function(t){var o=e(t).data(a);if(o)return o.overflowed[0]||o.overflowed[1]}})})})});
!function(a){"use strict";function b(a,b,c){for(a=String(a);a.length<b;)a=String(c)+a;return a}function c(a,b,c){return a>c?c:b>a?b:a}function d(a,b,c,d){for(;a>c;)a-=d;for(;b>a;)a+=d;return a}function e(a){return a.preventDefault(),!1}function f(){window.console&&window.console.log&&window.console.log.apply(window.console,arguments)}function g(a,b,c){c&&a.bind(b+"."+m,c)}function h(a){a.unbind("."+m)}function i(a){var b,c,d="string"==typeof a.source?[a.source]:a.source,e=0,f=[],g=function(){e+=1,"function"==typeof a.progress&&a.progress({loaded:e,total:d.length,percent:Math.round(e/d.length*100)}),e===f.length&&"function"==typeof a.complete&&a.complete(f)};for(b=0;b<d.length;b+=1)c=new Image,f.push(c),c.onload=c.onabort=c.onerror=g,c.src=d[b]}function j(a,b){var c,d,e=(b||a).width,g=(b||a).height;if(e*g>1048576){if(c=document.createElement("canvas"),!c||!c.getContext||!c.getContext("2d"))return!1;c.width=c.height=1,d=c.getContext("2d"),d.fillStyle="FF00FF",d.fillRect(0,0,1,1),d.drawImage(a,-e+1,0);try{var h=d.getImageData(0,0,1,1).data;return 255===h[0]&&0===h[1]&&255===h[2]}catch(i){return f(i.message,i.stack),!1}}return!1}function k(a){var b=new Image;return b.src=a.src,{width:b.width,height:b.height}}var l={};window.SpriteSpin=l;var m="spritespin";l.namespace=m;var n=["mousedown","mousemove","mouseup","mouseenter","mouseover","mouseleave","dblclick","touchstart","touchmove","touchend","touchcancel","selectstart","gesturestart","gesturechange","gestureend"],o=["dragstart"];l.mods={},l.defaults={source:void 0,width:void 0,height:void 0,frames:void 0,framesX:void 0,lanes:1,module:"360",behavior:"drag",renderer:"canvas",lane:0,frame:0,frameTime:40,animate:!0,reverse:!1,loop:!0,stopFrame:0,wrap:!0,wrapLane:!1,sense:1,senseLane:void 0,orientation:"horizontal",onInit:void 0,onProgress:void 0,onLoad:void 0,onFrame:void 0,onDraw:void 0},l.sourceArray=function(a,c){var d=0,e=0,f=0,g=0,h=c.digits||2;c.frame&&(d=c.frame[0],e=c.frame[1]),c.lane&&(f=c.lane[0],g=c.lane[1]);var i,j,k,l=[];for(i=f;g>=i;i+=1)for(j=d;e>=j;j+=1)k=a.replace("{lane}",b(i,h,0)),k=k.replace("{frame}",b(j,h,0)),l.push(k);return l},l.measureSource=function(a){var b=a.images[0],c=k(b);if(1===a.images.length){if(a.sourceWidth=c.width,a.sourceHeight=c.height,j(b,c)&&(a.sourceWidth/=2,a.sourceHeight/=2),a.framesX=a.framesX||a.frames,!a.frameWidth||!a.frameHeight)if(a.framesX){a.frameWidth=Math.floor(a.sourceWidth/a.framesX);var d=Math.ceil(a.frames*a.lanes/a.framesX);a.frameHeight=Math.floor(a.sourceHeight/d)}else a.frameWidth=c.width,a.frameHeight=c.height}else a.sourceWidth=a.frameWidth=c.width,a.sourceHeight=a.frameHeight=c.height,j(b,c)&&(a.sourceWidth=a.frameWidth=c.width/2,a.sourceHeight=a.frameHeight=c.height/2),a.frames=a.frames||a.images.length},l.resetInput=function(a){a.startX=a.startY=void 0,a.currentX=a.currentY=void 0,a.oldX=a.oldY=void 0,a.dX=a.dY=a.dW=0,a.ddX=a.ddY=a.ddW=0},l.updateInput=function(a,b){void 0===a.touches&&void 0!==a.originalEvent&&(a.touches=a.originalEvent.touches),b.oldX=b.currentX,b.oldY=b.currentY,void 0!==a.touches&&a.touches.length>0?(b.currentX=a.touches[0].clientX,b.currentY=a.touches[0].clientY):(b.currentX=a.clientX,b.currentY=a.clientY),(void 0===b.startX||void 0===b.startY)&&(b.startX=b.currentX,b.startY=b.currentY,b.clickframe=b.frame,b.clicklane=b.lane),b.dX=b.currentX-b.startX,b.dY=b.currentY-b.startY,b.ddX=b.currentX-b.oldX,b.ddY=b.currentY-b.oldY,b.ndX=b.dX/b.width,b.ndY=b.dY/b.height,b.nddX=b.ddX/b.width,b.nddY=b.ddY/b.height},l.updateFrame=function(a,b,e){void 0!==b?a.frame=Number(b):a.animation&&(a.frame+=a.reverse?-1:1),a.animation?(a.frame=d(a.frame,0,a.frames-1,a.frames),a.loop||a.frame!==a.stopFrame||(a.animate=!1,l.stopAnimation(a))):a.frame=a.wrap?d(a.frame,0,a.frames-1,a.frames):c(a.frame,0,a.frames-1),void 0!==e&&(a.lane=e,a.lane=c(a.lane,0,a.lanes-1)),a.target.trigger("onFrame",a),a.target.trigger("onDraw",a)},l.stopAnimation=function(a){a.animation&&(window.clearInterval(a.animation),a.animation=null)},l.setAnimation=function(a){l.stopAnimation(a),a.animate&&(a.animation=window.setInterval(function(){try{l.updateFrame(a)}catch(b){}},a.frameTime))},l.setModules=function(b){var c,d,e;for(c=0;c<b.mods.length;c+=1)d=b.mods[c],"string"==typeof d&&(e=l.mods[d],e?b.mods[c]=e:a.error("No module found with name "+d))},l.setLayout=function(a){a.target.attr("unselectable","on").css({"-ms-user-select":"none","-moz-user-select":"none","-khtml-user-select":"none","-webkit-user-select":"none","user-select":"none"});var b=Math.floor(a.width||a.frameWidth||a.target.innerWidth()),c=Math.floor(a.height||a.frameHeight||a.target.innerHeight());a.target.css({width:b,height:c,position:"relative",overflow:"hidden"});var d={width:"100%",height:"100%",top:0,left:0,bottom:0,right:0,position:"absolute"};a.stage.css(d).hide(),a.canvas&&(a.canvas[0].width=b,a.canvas[0].height=c,a.canvas.css(d).hide())},l.setEvents=function(a){var b,c,d,f=a.target;for(h(f),c=0;c<o.length;c+=1)g(f,o[c],e);for(b=0;b<a.mods.length;b+=1){for(d=a.mods[b],c=0;c<n.length;c+=1)g(f,n[c],d[n[c]]);g(f,"onInit",d.onInit),g(f,"onLoad",d.onLoad),g(f,"onFrame",d.onFrame),g(f,"onDraw",d.onDraw)}g(f,"onLoad",function(a,b){l.setAnimation(b)}),g(f,"onInit",a.onInit),g(f,"onProgress",a.onProgress),g(f,"onLoad",a.onLoad),g(f,"onFrame",a.onFrame),g(f,"onDraw",a.onDraw)},l.boot=function(a){l.setModules(a),l.setLayout(a),l.setEvents(a),a.target.addClass("loading").trigger("onInit",a),i({source:a.source,progress:function(b){a.target.trigger("onProgress",b)},complete:function(b){a.images=b,l.measureSource(a),a.stage.show(),a.target.removeClass("loading").trigger("onLoad",a).trigger("onFrame",a).trigger("onDraw",a)}})},l.create=function(b){var c=b.target,d=c.data(m);if(d)a.extend(d,b);else{if(d=a.extend({},l.defaults,b),d.source=d.source||[],c.find("img").each(function(){d.source.push(a(this).attr("src"))}),c.empty().addClass("spritespin-instance").append("<div class='spritespin-stage'></div>"),"canvas"===d.renderer){var e=a("<canvas class='spritespin-canvas'></canvas>")[0];e.getContext&&e.getContext("2d")?(d.canvas=a(e),d.context=e.getContext("2d"),c.append(d.canvas),c.addClass("with-canvas")):d.renderer="image"}d.target=c,d.stage=c.find(".spritespin-stage"),c.data(m,d)}"string"==typeof d.source&&(d.source=[d.source]),(d.behavior||d.module)&&(d.mods=[],d.behavior&&d.mods.push(d.behavior),d.module&&d.mods.push(d.module),delete d.behavior,delete d.module),l.boot(d)},l.destroy=function(a){a&&(l.stopAnimation(a),h(a.target),a.target.removeData(m))},l.registerModule=function(b,c){return l.mods[b]&&a.error("Module name is already taken: "+b),c=c||{},l.mods[b]=c,c},l.Api=function(a){this.data=a},l.extendApi=function(b){var c,d=l.Api.prototype;for(c in b)b.hasOwnProperty(c)&&(d[c]?a.error("API method is already defined: "+c):d[c]=b[c]);return d},a.fn.spritespin=function(b){return"data"===b?this.data(m):"api"===b?new l.Api(this.data(m)):"destroy"===b?a(this).each(function(){l.destroy(a(this).data(m))}):"object"==typeof b?(b.target=b.target||a(this),l.create(b),b.target):a.error("Invalid call to spritespin")}}(window.jQuery||window.Zepto||window.$),function(){"use strict";var a=window.SpriteSpin;a.extendApi({isPlaying:function(){return null!==this.data.animation},isLooping:function(){return this.data.loop},toggleAnimation:function(){this.data.animate=!this.data.animate,a.setAnimation(this.data)},stopAnimation:function(){this.data.animate=!1,a.setAnimation(this.data)},startAnimation:function(){this.data.animate=!0,a.setAnimation(this.data)},loop:function(b){return this.data.loop=b,a.setAnimation(this.data),this},currentFrame:function(){return this.data.frame},updateFrame:function(b){return a.updateFrame(this.data,b),this},skipFrames:function(b){var c=this.data;return a.updateFrame(c,c.frame+(c.reverse?-b:+b)),this},nextFrame:function(){return this.skipFrames(1)},prevFrame:function(){return this.skipFrames(-1)},playTo:function(b,c){var d=this.data;if(c=c||{},c.force||d.frame!==b){if(c.nearest){var e=b-d.frame,f=b>d.frame?e-d.frames:e+d.frames,g=Math.abs(e)<Math.abs(f)?e:f;d.reverse=0>g}return d.animate=!0,d.loop=!1,d.stopFrame=b,a.setAnimation(d),this}}})}(window.jQuery||window.Zepto||window.$),function(a,b){"use strict";function c(c){var d=a(this),e=d.data("spritespin");b.updateInput(c,e);var f,g;"horizontal"===e.orientation?(f=e.target.innerWidth()/2,g=e.currentX-e.target.offset().left):(f=e.target.innerHeight()/2,g=e.currentY-e.target.offset().top),g>f?d.spritespin("next"):d.spritespin("prev")}b.registerModule("click",{mouseup:c,touchend:c})}(window.jQuery||window.Zepto||window.$,window.SpriteSpin),function(a,b){"use strict";function c(c){var d=a(this).spritespin("data");b.updateInput(c,d),d.dragging=!0}function d(){var c=a(this),d=c.spritespin("data");b.resetInput(d),d.dragging=!1}function e(c){var d,e,f,g,h=a(this),i=h.spritespin("data");if(i.dragging){b.updateInput(c,i);var j=0;j="number"==typeof i.orientation?(Number(i.orientation)||0)*Math.PI/180:"horizontal"===i.orientation?0:Math.PI/2;var k=Math.sin(j),l=Math.cos(j),m=i.ndX*l-i.ndY*k,n=i.ndX*k+i.ndY*l;d=m*i.frames*i.sense,e=n*i.lanes*(i.senseLane||i.sense),g=Math.floor(i.clickframe+d),f=Math.floor(i.clicklane+e),b.updateFrame(i,g,f),i.animate=!1,b.stopAnimation(i),("horizontal"===i.orientation&&i.dX<i.dY||"vertical"===i.orientation&&i.dX<i.dY)&&c.preventDefault()}}b.registerModule("drag",{mousedown:c,mousemove:e,mouseup:d,mouseleave:d,touchstart:c,touchmove:e,touchend:d,touchcancel:d}),b.registerModule("move",{mousemove:function(a){c.call(this,a),e.call(this,a)},mouseleave:d,touchstart:c,touchmove:e,touchend:d,touchcancel:d})}(window.jQuery||window.Zepto||window.$,window.SpriteSpin),function(a,b){"use strict";function c(c){var d=a(this),e=d.spritespin("data");b.updateInput(c,e),e.dragging=!0,d.spritespin("api").startAnimation()}function d(){var c=a(this),d=c.spritespin("data");b.resetInput(d),d.dragging=!1,c.spritespin("api").stopAnimation()}function e(c){var d=a(this),e=d.spritespin("data");if(e.dragging){b.updateInput(c,e);var f,g;"horizontal"===e.orientation?(f=e.target.innerWidth()/2,g=(e.currentX-e.target.offset().left-f)/f):(f=e.height/2,g=(e.currentY-e.target.offset().top-f)/f),e.reverse=0>g,g=0>g?-g:g,e.frameTime=80*(1-g)+20,("horizontal"===e.orientation&&e.dX<e.dY||"vertical"===e.orientation&&e.dX<e.dY)&&c.preventDefault()}}b.registerModule("hold",{mousedown:c,mousemove:e,mouseup:d,mouseleave:d,touchstart:c,touchmove:e,touchend:d,touchcancel:d,onFrame:function(){a(this).spritespin("api").startAnimation()}})}(window.jQuery||window.Zepto||window.$,window.SpriteSpin),function(a,b){"use strict";function c(c){var d=a(this),e=d.spritespin("data");b.updateInput(c,e),e.dragging=!0}function d(){var c=a(this),d=c.spritespin("data");d.dragging=!1,b.resetInput(d)}function e(c){var d=a(this),e=d.spritespin("data");if(e.dragging){b.updateInput(c,e);var f,g,h=e.frame,i=e.snap||.25;"horizontal"===e.orientation?(f=e.dX,g=e.target.innerWidth()*i):(f=e.dY,g=e.target.innerHeight()*i),f>g?(h=e.frame-1,e.dragging=!1):-g>f&&(h=e.frame+1,e.dragging=!1),d.spritespin("update",h),d.spritespin("animate",!1),("horizontal"===e.orientation&&e.dX<e.dY||"vertical"===e.orientation&&e.dX<e.dY)&&c.preventDefault()}}b.registerModule("swipe",{mousedown:c,mousemove:e,mouseup:d,mouseleave:d,touchstart:c,touchmove:e,touchend:d,touchcancel:d})}(window.jQuery||window.Zepto||window.$,window.SpriteSpin),function(a,b){"use strict";function c(b){var c=b.lane*b.frames+b.frame,d=b.frameWidth*(c%b.framesX),f=b.frameHeight*e(c/b.framesX);return"canvas"===b.renderer?(b.context.clearRect(0,0,b.width,b.height),b.context.drawImage(b.images[0],d,f,b.frameWidth,b.frameHeight,0,0,b.width,b.height),void 0):(d=-e(d*b.scaleWidth),f=-e(f*b.scaleHeight),"background"===b.renderer?b.stage.css({"background-image":["url('",b.source[0],"')"].join(""),"background-position":[d,"px ",f,"px"].join("")}):a(b.images).css({top:f,left:d}),void 0)}function d(b){var c=b.lane*b.frames+b.frame;"canvas"===b.renderer?(b.context.clearRect(0,0,b.width,b.height),b.context.drawImage(b.images[c],0,0,b.width,b.height)):"background"===b.renderer?b.stage.css({"background-image":["url('",b.source[c],"')"].join(""),"background-position":[0,"px ",0,"px"].join("")}):(a(b.images).hide(),a(b.images[c]).show())}var e=Math.floor;b.registerModule("360",{onLoad:function(b,c){var d,f;if(c.scaleWidth=c.width/c.frameWidth,c.scaleHeight=c.height/c.frameHeight,c.sourceIsSprite=1===c.images.length,c.stage.empty().css({"background-image":"none"}).show(),"canvas"===c.renderer)c.context.clearRect(0,0,c.width,c.height),c.canvas.show();else if("background"===c.renderer){c.sourceIsSprite?(d=e(c.sourceWidth*c.scaleWidth),f=e(c.sourceHeight*c.scaleHeight)):(d=e(c.frameWidth*c.scaleWidth),f=e(c.frameHeight*c.scaleHeight));var g=[d,"px ",f,"px"].join("");c.stage.css({"background-repeat":"no-repeat","-webkit-background-size":g,"-moz-background-size":g,"-o-background-size":g,"background-size":g})}else"image"===c.renderer&&(c.sourceIsSprite?(d=e(c.sourceWidth*c.scaleWidth),f=e(c.sourceHeight*c.scaleHeight)):d=f="100%",a(c.images).appendTo(c.stage).css({width:d,height:f,position:"absolute"}))},onDraw:function(a,b){b.sourceIsSprite?c(b):d(b)}})}(window.jQuery||window.Zepto||window.$,window.SpriteSpin),function(a){"use strict";var b=window.SpriteSpin.mods.gallery={};b.onLoad=function(b,c){c.images=[],c.offsets=[],c.stage.empty(),c.speed=500,c.opacity=.25,c.oldFrame=0;var d,e=0;for(d=0;d<c.source.length;d+=1){var f=a("<img src='"+c.source[d]+"'/>");c.stage.append(f),c.images.push(f),c.offsets.push(-e+(c.width-f[0].width)/2),e+=f[0].width,f.css({opacity:.25})}c.stage.css({width:e}),c.images[c.oldFrame].animate({opacity:1},c.speed)},b.onDraw=function(a,b){b.oldFrame!==b.frame&&b.offsets?(b.stage.stop(!0,!1),b.stage.animate({left:b.offsets[b.frame]},b.speed),b.images[b.oldFrame].animate({opacity:b.opacity},b.speed),b.oldFrame=b.frame,b.images[b.oldFrame].animate({opacity:1},b.speed)):b.stage.css({left:b.offsets[b.frame]+b.dX})},b.resetInput=function(a,b){b.onDrag||b.stage.animate({left:b.offsets[b.frame]})}}(window.jQuery||window.Zepto||window.$),function(a,b){"use strict";var c=Math.floor;b.registerModule("panorama",{onLoad:function(a,b){b.stage.empty().show(),b.frames=b.sourceWidth,"horizontal"===b.orientation?(b.scale=b.height/b.sourceHeight,b.frames=b.sourceWidth):(b.scale=b.width/b.sourceWidth,b.frames=b.sourceHeight);var d=c(b.sourceWidth*b.scale),e=c(b.sourceHeight*b.scale),f=[d,"px ",e,"px"].join("");b.stage.css({"background-image":["url('",b.source[0],"')"].join(""),"background-repeat":"repeat-both","-webkit-background-size":f,"-moz-background-size":f,"-o-background-size":f,"background-size":f})},onDraw:function(a,b){var d=0,e=0;"horizontal"===b.orientation?d=-c(b.frame%b.frames*b.scale):e=-c(b.frame%b.frames*b.scale),b.stage.css({"background-position":[d,"px ",e,"px"].join("")})}})}(window.jQuery||window.Zepto||window.$,window.SpriteSpin);
/*!
 * Bootstrap v3.3.7 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under the MIT license
 */

if (typeof jQuery === 'undefined') {
  throw new Error('Bootstrap\'s JavaScript requires jQuery')
}

+function ($) {
  'use strict';
  var version = $.fn.jquery.split(' ')[0].split('.')
  if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) {
    throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4')
  }
}(jQuery);

/* ========================================================================
 * Bootstrap: transition.js v3.3.7
 * http://getbootstrap.com/javascript/#transitions
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
  // ============================================================

  function transitionEnd() {
    var el = document.createElement('bootstrap')

    var transEndEventNames = {
      WebkitTransition : 'webkitTransitionEnd',
      MozTransition    : 'transitionend',
      OTransition      : 'oTransitionEnd otransitionend',
      transition       : 'transitionend'
    }

    for (var name in transEndEventNames) {
      if (el.style[name] !== undefined) {
        return { end: transEndEventNames[name] }
      }
    }

    return false // explicit for ie8 (  ._.)
  }

  // http://blog.alexmaccaw.com/css-transitions
  $.fn.emulateTransitionEnd = function (duration) {
    var called = false
    var $el = this
    $(this).one('bsTransitionEnd', function () { called = true })
    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
    setTimeout(callback, duration)
    return this
  }

  $(function () {
    $.support.transition = transitionEnd()

    if (!$.support.transition) return

    $.event.special.bsTransitionEnd = {
      bindType: $.support.transition.end,
      delegateType: $.support.transition.end,
      handle: function (e) {
        if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
      }
    }
  })

}(jQuery);

/* ========================================================================
 * Bootstrap: alert.js v3.3.7
 * http://getbootstrap.com/javascript/#alerts
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // ALERT CLASS DEFINITION
  // ======================

  var dismiss = '[data-dismiss="alert"]'
  var Alert   = function (el) {
    $(el).on('click', dismiss, this.close)
  }

  Alert.VERSION = '3.3.7'

  Alert.TRANSITION_DURATION = 150

  Alert.prototype.close = function (e) {
    var $this    = $(this)
    var selector = $this.attr('data-target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    var $parent = $(selector === '#' ? [] : selector)

    if (e) e.preventDefault()

    if (!$parent.length) {
      $parent = $this.closest('.alert')
    }

    $parent.trigger(e = $.Event('close.bs.alert'))

    if (e.isDefaultPrevented()) return

    $parent.removeClass('in')

    function removeElement() {
      // detach from parent, fire event then clean up data
      $parent.detach().trigger('closed.bs.alert').remove()
    }

    $.support.transition && $parent.hasClass('fade') ?
      $parent
        .one('bsTransitionEnd', removeElement)
        .emulateTransitionEnd(Alert.TRANSITION_DURATION) :
      removeElement()
  }


  // ALERT PLUGIN DEFINITION
  // =======================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bs.alert')

      if (!data) $this.data('bs.alert', (data = new Alert(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  var old = $.fn.alert

  $.fn.alert             = Plugin
  $.fn.alert.Constructor = Alert


  // ALERT NO CONFLICT
  // =================

  $.fn.alert.noConflict = function () {
    $.fn.alert = old
    return this
  }


  // ALERT DATA-API
  // ==============

  $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)

}(jQuery);

/* ========================================================================
 * Bootstrap: button.js v3.3.7
 * http://getbootstrap.com/javascript/#buttons
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // BUTTON PUBLIC CLASS DEFINITION
  // ==============================

  var Button = function (element, options) {
    this.$element  = $(element)
    this.options   = $.extend({}, Button.DEFAULTS, options)
    this.isLoading = false
  }

  Button.VERSION  = '3.3.7'

  Button.DEFAULTS = {
    loadingText: 'loading...'
  }

  Button.prototype.setState = function (state) {
    var d    = 'disabled'
    var $el  = this.$element
    var val  = $el.is('input') ? 'val' : 'html'
    var data = $el.data()

    state += 'Text'

    if (data.resetText == null) $el.data('resetText', $el[val]())

    // push to event loop to allow forms to submit
    setTimeout($.proxy(function () {
      $el[val](data[state] == null ? this.options[state] : data[state])

      if (state == 'loadingText') {
        this.isLoading = true
        $el.addClass(d).attr(d, d).prop(d, true)
      } else if (this.isLoading) {
        this.isLoading = false
        $el.removeClass(d).removeAttr(d).prop(d, false)
      }
    }, this), 0)
  }

  Button.prototype.toggle = function () {
    var changed = true
    var $parent = this.$element.closest('[data-toggle="buttons"]')

    if ($parent.length) {
      var $input = this.$element.find('input')
      if ($input.prop('type') == 'radio') {
        if ($input.prop('checked')) changed = false
        $parent.find('.active').removeClass('active')
        this.$element.addClass('active')
      } else if ($input.prop('type') == 'checkbox') {
        if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
        this.$element.toggleClass('active')
      }
      $input.prop('checked', this.$element.hasClass('active'))
      if (changed) $input.trigger('change')
    } else {
      this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      this.$element.toggleClass('active')
    }
  }


  // BUTTON PLUGIN DEFINITION
  // ========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.button')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.button', (data = new Button(this, options)))

      if (option == 'toggle') data.toggle()
      else if (option) data.setState(option)
    })
  }

  var old = $.fn.button

  $.fn.button             = Plugin
  $.fn.button.Constructor = Button


  // BUTTON NO CONFLICT
  // ==================

  $.fn.button.noConflict = function () {
    $.fn.button = old
    return this
  }


  // BUTTON DATA-API
  // ===============

  $(document)
    .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
      var $btn = $(e.target).closest('.btn')
      Plugin.call($btn, 'toggle')
      if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
        // Prevent double click on radios, and the double selections (so cancellation) on checkboxes
        e.preventDefault()
        // The target component still receive the focus
        if ($btn.is('input,button')) $btn.trigger('focus')
        else $btn.find('input:visible,button:visible').first().trigger('focus')
      }
    })
    .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
      $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
    })

}(jQuery);

/* ========================================================================
 * Bootstrap: carousel.js v3.3.7
 * http://getbootstrap.com/javascript/#carousel
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // CAROUSEL CLASS DEFINITION
  // =========================

  var Carousel = function (element, options) {
    this.$element    = $(element)
    this.$indicators = this.$element.find('.carousel-indicators')
    this.options     = options
    this.paused      = null
    this.sliding     = null
    this.interval    = null
    this.$active     = null
    this.$items      = null

    this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))

    this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
      .on('mouseenter.bs.carousel', $.proxy(this.pause, this))
      .on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
  }

  Carousel.VERSION  = '3.3.7'

  Carousel.TRANSITION_DURATION = 600

  Carousel.DEFAULTS = {
    interval: 5000,
    pause: 'hover',
    wrap: true,
    keyboard: true
  }

  Carousel.prototype.keydown = function (e) {
    if (/input|textarea/i.test(e.target.tagName)) return
    switch (e.which) {
      case 37: this.prev(); break
      case 39: this.next(); break
      default: return
    }

    e.preventDefault()
  }

  Carousel.prototype.cycle = function (e) {
    e || (this.paused = false)

    this.interval && clearInterval(this.interval)

    this.options.interval
      && !this.paused
      && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))

    return this
  }

  Carousel.prototype.getItemIndex = function (item) {
    this.$items = item.parent().children('.item')
    return this.$items.index(item || this.$active)
  }

  Carousel.prototype.getItemForDirection = function (direction, active) {
    var activeIndex = this.getItemIndex(active)
    var willWrap = (direction == 'prev' && activeIndex === 0)
                || (direction == 'next' && activeIndex == (this.$items.length - 1))
    if (willWrap && !this.options.wrap) return active
    var delta = direction == 'prev' ? -1 : 1
    var itemIndex = (activeIndex + delta) % this.$items.length
    return this.$items.eq(itemIndex)
  }

  Carousel.prototype.to = function (pos) {
    var that        = this
    var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))

    if (pos > (this.$items.length - 1) || pos < 0) return

    if (this.sliding)       return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
    if (activeIndex == pos) return this.pause().cycle()

    return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
  }

  Carousel.prototype.pause = function (e) {
    e || (this.paused = true)

    if (this.$element.find('.next, .prev').length && $.support.transition) {
      this.$element.trigger($.support.transition.end)
      this.cycle(true)
    }

    this.interval = clearInterval(this.interval)

    return this
  }

  Carousel.prototype.next = function () {
    if (this.sliding) return
    return this.slide('next')
  }

  Carousel.prototype.prev = function () {
    if (this.sliding) return
    return this.slide('prev')
  }

  Carousel.prototype.slide = function (type, next) {
    var $active   = this.$element.find('.item.active')
    var $next     = next || this.getItemForDirection(type, $active)
    var isCycling = this.interval
    var direction = type == 'next' ? 'left' : 'right'
    var that      = this

    if ($next.hasClass('active')) return (this.sliding = false)

    var relatedTarget = $next[0]
    var slideEvent = $.Event('slide.bs.carousel', {
      relatedTarget: relatedTarget,
      direction: direction
    })
    this.$element.trigger(slideEvent)
    if (slideEvent.isDefaultPrevented()) return

    this.sliding = true

    isCycling && this.pause()

    if (this.$indicators.length) {
      this.$indicators.find('.active').removeClass('active')
      var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
      $nextIndicator && $nextIndicator.addClass('active')
    }

    var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
    if ($.support.transition && this.$element.hasClass('slide')) {
      $next.addClass(type)
      $next[0].offsetWidth // force reflow
      $active.addClass(direction)
      $next.addClass(direction)
      $active
        .one('bsTransitionEnd', function () {
          $next.removeClass([type, direction].join(' ')).addClass('active')
          $active.removeClass(['active', direction].join(' '))
          that.sliding = false
          setTimeout(function () {
            that.$element.trigger(slidEvent)
          }, 0)
        })
        .emulateTransitionEnd(Carousel.TRANSITION_DURATION)
    } else {
      $active.removeClass('active')
      $next.addClass('active')
      this.sliding = false
      this.$element.trigger(slidEvent)
    }

    isCycling && this.cycle()

    return this
  }


  // CAROUSEL PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.carousel')
      var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
      var action  = typeof option == 'string' ? option : options.slide

      if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
      if (typeof option == 'number') data.to(option)
      else if (action) data[action]()
      else if (options.interval) data.pause().cycle()
    })
  }

  var old = $.fn.carousel

  $.fn.carousel             = Plugin
  $.fn.carousel.Constructor = Carousel


  // CAROUSEL NO CONFLICT
  // ====================

  $.fn.carousel.noConflict = function () {
    $.fn.carousel = old
    return this
  }


  // CAROUSEL DATA-API
  // =================

  var clickHandler = function (e) {
    var href
    var $this   = $(this)
    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
    if (!$target.hasClass('carousel')) return
    var options = $.extend({}, $target.data(), $this.data())
    var slideIndex = $this.attr('data-slide-to')
    if (slideIndex) options.interval = false

    Plugin.call($target, options)

    if (slideIndex) {
      $target.data('bs.carousel').to(slideIndex)
    }

    e.preventDefault()
  }

  $(document)
    .on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
    .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)

  $(window).on('load', function () {
    $('[data-ride="carousel"]').each(function () {
      var $carousel = $(this)
      Plugin.call($carousel, $carousel.data())
    })
  })

}(jQuery);

/* ========================================================================
 * Bootstrap: collapse.js v3.3.7
 * http://getbootstrap.com/javascript/#collapse
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */

/* jshint latedef: false */

+function ($) {
  'use strict';

  // COLLAPSE PUBLIC CLASS DEFINITION
  // ================================

  var Collapse = function (element, options) {
    this.$element      = $(element)
    this.options       = $.extend({}, Collapse.DEFAULTS, options)
    this.$trigger      = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
                           '[data-toggle="collapse"][data-target="#' + element.id + '"]')
    this.transitioning = null

    if (this.options.parent) {
      this.$parent = this.getParent()
    } else {
      this.addAriaAndCollapsedClass(this.$element, this.$trigger)
    }

    if (this.options.toggle) this.toggle()
  }

  Collapse.VERSION  = '3.3.7'

  Collapse.TRANSITION_DURATION = 350

  Collapse.DEFAULTS = {
    toggle: true
  }

  Collapse.prototype.dimension = function () {
    var hasWidth = this.$element.hasClass('width')
    return hasWidth ? 'width' : 'height'
  }

  Collapse.prototype.show = function () {
    if (this.transitioning || this.$element.hasClass('in')) return

    var activesData
    var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')

    if (actives && actives.length) {
      activesData = actives.data('bs.collapse')
      if (activesData && activesData.transitioning) return
    }

    var startEvent = $.Event('show.bs.collapse')
    this.$element.trigger(startEvent)
    if (startEvent.isDefaultPrevented()) return

    if (actives && actives.length) {
      Plugin.call(actives, 'hide')
      activesData || actives.data('bs.collapse', null)
    }

    var dimension = this.dimension()

    this.$element
      .removeClass('collapse')
      .addClass('collapsing')[dimension](0)
      .attr('aria-expanded', true)

    this.$trigger
      .removeClass('collapsed')
      .attr('aria-expanded', true)

    this.transitioning = 1

    var complete = function () {
      this.$element
        .removeClass('collapsing')
        .addClass('collapse in')[dimension]('')
      this.transitioning = 0
      this.$element
        .trigger('shown.bs.collapse')
    }

    if (!$.support.transition) return complete.call(this)

    var scrollSize = $.camelCase(['scroll', dimension].join('-'))

    this.$element
      .one('bsTransitionEnd', $.proxy(complete, this))
      .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
  }

  Collapse.prototype.hide = function () {
    if (this.transitioning || !this.$element.hasClass('in')) return

    var startEvent = $.Event('hide.bs.collapse')
    this.$element.trigger(startEvent)
    if (startEvent.isDefaultPrevented()) return

    var dimension = this.dimension()

    this.$element[dimension](this.$element[dimension]())[0].offsetHeight

    this.$element
      .addClass('collapsing')
      .removeClass('collapse in')
      .attr('aria-expanded', false)

    this.$trigger
      .addClass('collapsed')
      .attr('aria-expanded', false)

    this.transitioning = 1

    var complete = function () {
      this.transitioning = 0
      this.$element
        .removeClass('collapsing')
        .addClass('collapse')
        .trigger('hidden.bs.collapse')
    }

    if (!$.support.transition) return complete.call(this)

    this.$element
      [dimension](0)
      .one('bsTransitionEnd', $.proxy(complete, this))
      .emulateTransitionEnd(Collapse.TRANSITION_DURATION)
  }

  Collapse.prototype.toggle = function () {
    this[this.$element.hasClass('in') ? 'hide' : 'show']()
  }

  Collapse.prototype.getParent = function () {
    return $(this.options.parent)
      .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
      .each($.proxy(function (i, element) {
        var $element = $(element)
        this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
      }, this))
      .end()
  }

  Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
    var isOpen = $element.hasClass('in')

    $element.attr('aria-expanded', isOpen)
    $trigger
      .toggleClass('collapsed', !isOpen)
      .attr('aria-expanded', isOpen)
  }

  function getTargetFromTrigger($trigger) {
    var href
    var target = $trigger.attr('data-target')
      || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7

    return $(target)
  }


  // COLLAPSE PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.collapse')
      var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)

      if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
      if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.collapse

  $.fn.collapse             = Plugin
  $.fn.collapse.Constructor = Collapse


  // COLLAPSE NO CONFLICT
  // ====================

  $.fn.collapse.noConflict = function () {
    $.fn.collapse = old
    return this
  }


  // COLLAPSE DATA-API
  // =================

  $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
    var $this   = $(this)

    if (!$this.attr('data-target')) e.preventDefault()

    var $target = getTargetFromTrigger($this)
    var data    = $target.data('bs.collapse')
    var option  = data ? 'toggle' : $this.data()

    Plugin.call($target, option)
  })

}(jQuery);

/* ========================================================================
 * Bootstrap: dropdown.js v3.3.7
 * http://getbootstrap.com/javascript/#dropdowns
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // DROPDOWN CLASS DEFINITION
  // =========================

  var backdrop = '.dropdown-backdrop'
  var toggle   = '[data-toggle="dropdown"]'
  var Dropdown = function (element) {
    $(element).on('click.bs.dropdown', this.toggle)
  }

  Dropdown.VERSION = '3.3.7'

  function getParent($this) {
    var selector = $this.attr('data-target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    var $parent = selector && $(selector)

    return $parent && $parent.length ? $parent : $this.parent()
  }

  function clearMenus(e) {
    if (e && e.which === 3) return
    $(backdrop).remove()
    $(toggle).each(function () {
      var $this         = $(this)
      var $parent       = getParent($this)
      var relatedTarget = { relatedTarget: this }

      if (!$parent.hasClass('open')) return

      if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return

      $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))

      if (e.isDefaultPrevented()) return

      $this.attr('aria-expanded', 'false')
      $parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
    })
  }

  Dropdown.prototype.toggle = function (e) {
    var $this = $(this)

    if ($this.is('.disabled, :disabled')) return

    var $parent  = getParent($this)
    var isActive = $parent.hasClass('open')

    clearMenus()

    if (!isActive) {
      if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
        // if mobile we use a backdrop because click events don't delegate
        $(document.createElement('div'))
          .addClass('dropdown-backdrop')
          .insertAfter($(this))
          .on('click', clearMenus)
      }

      var relatedTarget = { relatedTarget: this }
      $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))

      if (e.isDefaultPrevented()) return

      $this
        .trigger('focus')
        .attr('aria-expanded', 'true')

      $parent
        .toggleClass('open')
        .trigger($.Event('shown.bs.dropdown', relatedTarget))
    }

    return false
  }

  Dropdown.prototype.keydown = function (e) {
    if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return

    var $this = $(this)

    e.preventDefault()
    e.stopPropagation()

    if ($this.is('.disabled, :disabled')) return

    var $parent  = getParent($this)
    var isActive = $parent.hasClass('open')

    if (!isActive && e.which != 27 || isActive && e.which == 27) {
      if (e.which == 27) $parent.find(toggle).trigger('focus')
      return $this.trigger('click')
    }

    var desc = ' li:not(.disabled):visible a'
    var $items = $parent.find('.dropdown-menu' + desc)

    if (!$items.length) return

    var index = $items.index(e.target)

    if (e.which == 38 && index > 0)                 index--         // up
    if (e.which == 40 && index < $items.length - 1) index++         // down
    if (!~index)                                    index = 0

    $items.eq(index).trigger('focus')
  }


  // DROPDOWN PLUGIN DEFINITION
  // ==========================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bs.dropdown')

      if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  var old = $.fn.dropdown

  $.fn.dropdown             = Plugin
  $.fn.dropdown.Constructor = Dropdown


  // DROPDOWN NO CONFLICT
  // ====================

  $.fn.dropdown.noConflict = function () {
    $.fn.dropdown = old
    return this
  }


  // APPLY TO STANDARD DROPDOWN ELEMENTS
  // ===================================

  $(document)
    .on('click.bs.dropdown.data-api', clearMenus)
    .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
    .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
    .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
    .on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)

}(jQuery);

/* ========================================================================
 * Bootstrap: modal.js v3.3.7
 * http://getbootstrap.com/javascript/#modals
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // MODAL CLASS DEFINITION
  // ======================

  var Modal = function (element, options) {
    this.options             = options
    this.$body               = $(document.body)
    this.$element            = $(element)
    this.$dialog             = this.$element.find('.modal-dialog')
    this.$backdrop           = null
    this.isShown             = null
    this.originalBodyPad     = null
    this.scrollbarWidth      = 0
    this.ignoreBackdropClick = false

    if (this.options.remote) {
      this.$element
        .find('.modal-content')
        .load(this.options.remote, $.proxy(function () {
          this.$element.trigger('loaded.bs.modal')
        }, this))
    }
  }

  Modal.VERSION  = '3.3.7'

  Modal.TRANSITION_DURATION = 300
  Modal.BACKDROP_TRANSITION_DURATION = 150

  Modal.DEFAULTS = {
    backdrop: true,
    keyboard: true,
    show: true
  }

  Modal.prototype.toggle = function (_relatedTarget) {
    return this.isShown ? this.hide() : this.show(_relatedTarget)
  }

  Modal.prototype.show = function (_relatedTarget) {
    var that = this
    var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })

    this.$element.trigger(e)

    if (this.isShown || e.isDefaultPrevented()) return

    this.isShown = true

    this.checkScrollbar()
    this.setScrollbar()
    this.$body.addClass('modal-open')

    this.escape()
    this.resize()

    this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))

    this.$dialog.on('mousedown.dismiss.bs.modal', function () {
      that.$element.one('mouseup.dismiss.bs.modal', function (e) {
        if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
      })
    })

    this.backdrop(function () {
      var transition = $.support.transition && that.$element.hasClass('fade')

      if (!that.$element.parent().length) {
        that.$element.appendTo(that.$body) // don't move modals dom position
      }

      that.$element
        .show()
        .scrollTop(0)

      that.adjustDialog()

      if (transition) {
        that.$element[0].offsetWidth // force reflow
      }

      that.$element.addClass('in')

      that.enforceFocus()

      var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })

      transition ?
        that.$dialog // wait for modal to slide in
          .one('bsTransitionEnd', function () {
            that.$element.trigger('focus').trigger(e)
          })
          .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
        that.$element.trigger('focus').trigger(e)
    })
  }

  Modal.prototype.hide = function (e) {
    if (e) e.preventDefault()

    e = $.Event('hide.bs.modal')

    this.$element.trigger(e)

    if (!this.isShown || e.isDefaultPrevented()) return

    this.isShown = false

    this.escape()
    this.resize()

    $(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')

    $.support.transition && this.$element.hasClass('fade') ?
      this.$element
        .one('bsTransitionEnd', $.proxy(this.hideModal, this))
        .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
      this.hideModal()
  }

  Modal.prototype.enforceFocus = function () {
    $(document)
      .off('focusin.bs.modal') // guard against infinite focus loop
      .on('focusin.bs.modal', $.proxy(function (e) {
        if (document !== e.target &&
            this.$element[0] !== e.target &&
            !this.$element.has(e.target).length) {
          this.$element.trigger('focus')
        }
      }, this))
  }

  Modal.prototype.escape = function () {
    if (this.isShown && this.options.keyboard) {
      this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
        e.which == 27 && this.hide()
      }, this))
    } else if (!this.isShown) {
      this.$element.off('keydown.dismiss.bs.modal')
    }
  }

  Modal.prototype.resize = function () {
    if (this.isShown) {
      $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
    } else {
      $(window).off('resize.bs.modal')
    }
  }

  Modal.prototype.hideModal = function () {
    var that = this
    this.$element.hide()
    this.backdrop(function () {
      that.$body.removeClass('modal-open')
      that.resetAdjustments()
      that.resetScrollbar()
      that.$element.trigger('hidden.bs.modal')
    })
  }

  Modal.prototype.removeBackdrop = function () {
    this.$backdrop && this.$backdrop.remove()
    this.$backdrop = null
  }

  Modal.prototype.backdrop = function (callback) {
    var that = this
    var animate = this.$element.hasClass('fade') ? 'fade' : ''

    if (this.isShown && this.options.backdrop) {
      var doAnimate = $.support.transition && animate

      this.$backdrop = $(document.createElement('div'))
        .addClass('modal-backdrop ' + animate)
        .appendTo(this.$body)

      this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
        if (this.ignoreBackdropClick) {
          this.ignoreBackdropClick = false
          return
        }
        if (e.target !== e.currentTarget) return
        this.options.backdrop == 'static'
          ? this.$element[0].focus()
          : this.hide()
      }, this))

      if (doAnimate) this.$backdrop[0].offsetWidth // force reflow

      this.$backdrop.addClass('in')

      if (!callback) return

      doAnimate ?
        this.$backdrop
          .one('bsTransitionEnd', callback)
          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
        callback()

    } else if (!this.isShown && this.$backdrop) {
      this.$backdrop.removeClass('in')

      var callbackRemove = function () {
        that.removeBackdrop()
        callback && callback()
      }
      $.support.transition && this.$element.hasClass('fade') ?
        this.$backdrop
          .one('bsTransitionEnd', callbackRemove)
          .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
        callbackRemove()

    } else if (callback) {
      callback()
    }
  }

  // these following methods are used to handle overflowing modals

  Modal.prototype.handleUpdate = function () {
    this.adjustDialog()
  }

  Modal.prototype.adjustDialog = function () {
    var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight

    this.$element.css({
      paddingLeft:  !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
      paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
    })
  }

  Modal.prototype.resetAdjustments = function () {
    this.$element.css({
      paddingLeft: '',
      paddingRight: ''
    })
  }

  Modal.prototype.checkScrollbar = function () {
    var fullWindowWidth = window.innerWidth
    if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
      var documentElementRect = document.documentElement.getBoundingClientRect()
      fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
    }
    this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
    this.scrollbarWidth = this.measureScrollbar()
  }

  Modal.prototype.setScrollbar = function () {
    var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
    this.originalBodyPad = document.body.style.paddingRight || ''
    if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
  }

  Modal.prototype.resetScrollbar = function () {
    this.$body.css('padding-right', this.originalBodyPad)
  }

  Modal.prototype.measureScrollbar = function () { // thx walsh
    var scrollDiv = document.createElement('div')
    scrollDiv.className = 'modal-scrollbar-measure'
    this.$body.append(scrollDiv)
    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
    this.$body[0].removeChild(scrollDiv)
    return scrollbarWidth
  }


  // MODAL PLUGIN DEFINITION
  // =======================

  function Plugin(option, _relatedTarget) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.modal')
      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)

      if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
      if (typeof option == 'string') data[option](_relatedTarget)
      else if (options.show) data.show(_relatedTarget)
    })
  }

  var old = $.fn.modal

  $.fn.modal             = Plugin
  $.fn.modal.Constructor = Modal


  // MODAL NO CONFLICT
  // =================

  $.fn.modal.noConflict = function () {
    $.fn.modal = old
    return this
  }


  // MODAL DATA-API
  // ==============

  $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
    var $this   = $(this)
    var href    = $this.attr('href')
    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
    var option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())

    if ($this.is('a')) e.preventDefault()

    $target.one('show.bs.modal', function (showEvent) {
      if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
      $target.one('hidden.bs.modal', function () {
        $this.is(':visible') && $this.trigger('focus')
      })
    })
    Plugin.call($target, option, this)
  })

}(jQuery);

/* ========================================================================
 * Bootstrap: tooltip.js v3.3.7
 * http://getbootstrap.com/javascript/#tooltip
 * Inspired by the original jQuery.tipsy by Jason Frame
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // TOOLTIP PUBLIC CLASS DEFINITION
  // ===============================

  var Tooltip = function (element, options) {
    this.type       = null
    this.options    = null
    this.enabled    = null
    this.timeout    = null
    this.hoverState = null
    this.$element   = null
    this.inState    = null

    this.init('tooltip', element, options)
  }

  Tooltip.VERSION  = '3.3.7'

  Tooltip.TRANSITION_DURATION = 150

  Tooltip.DEFAULTS = {
    animation: true,
    placement: 'top',
    selector: false,
    template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
    trigger: 'hover focus',
    title: '',
    delay: 0,
    html: false,
    container: false,
    viewport: {
      selector: 'body',
      padding: 0
    }
  }

  Tooltip.prototype.init = function (type, element, options) {
    this.enabled   = true
    this.type      = type
    this.$element  = $(element)
    this.options   = this.getOptions(options)
    this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
    this.inState   = { click: false, hover: false, focus: false }

    if (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!')
    }

    var triggers = this.options.trigger.split(' ')

    for (var i = triggers.length; i--;) {
      var trigger = triggers[i]

      if (trigger == 'click') {
        this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
      } else if (trigger != 'manual') {
        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin'
        var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'

        this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
        this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
      }
    }

    this.options.selector ?
      (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
      this.fixTitle()
  }

  Tooltip.prototype.getDefaults = function () {
    return Tooltip.DEFAULTS
  }

  Tooltip.prototype.getOptions = function (options) {
    options = $.extend({}, this.getDefaults(), this.$element.data(), options)

    if (options.delay && typeof options.delay == 'number') {
      options.delay = {
        show: options.delay,
        hide: options.delay
      }
    }

    return options
  }

  Tooltip.prototype.getDelegateOptions = function () {
    var options  = {}
    var defaults = this.getDefaults()

    this._options && $.each(this._options, function (key, value) {
      if (defaults[key] != value) options[key] = value
    })

    return options
  }

  Tooltip.prototype.enter = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget).data('bs.' + this.type)

    if (!self) {
      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
      $(obj.currentTarget).data('bs.' + this.type, self)
    }

    if (obj instanceof $.Event) {
      self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
    }

    if (self.tip().hasClass('in') || self.hoverState == 'in') {
      self.hoverState = 'in'
      return
    }

    clearTimeout(self.timeout)

    self.hoverState = 'in'

    if (!self.options.delay || !self.options.delay.show) return self.show()

    self.timeout = setTimeout(function () {
      if (self.hoverState == 'in') self.show()
    }, self.options.delay.show)
  }

  Tooltip.prototype.isInStateTrue = function () {
    for (var key in this.inState) {
      if (this.inState[key]) return true
    }

    return false
  }

  Tooltip.prototype.leave = function (obj) {
    var self = obj instanceof this.constructor ?
      obj : $(obj.currentTarget).data('bs.' + this.type)

    if (!self) {
      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
      $(obj.currentTarget).data('bs.' + this.type, self)
    }

    if (obj instanceof $.Event) {
      self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
    }

    if (self.isInStateTrue()) return

    clearTimeout(self.timeout)

    self.hoverState = 'out'

    if (!self.options.delay || !self.options.delay.hide) return self.hide()

    self.timeout = setTimeout(function () {
      if (self.hoverState == 'out') self.hide()
    }, self.options.delay.hide)
  }

  Tooltip.prototype.show = function () {
    var e = $.Event('show.bs.' + this.type)

    if (this.hasContent() && this.enabled) {
      this.$element.trigger(e)

      var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
      if (e.isDefaultPrevented() || !inDom) return
      var that = this

      var $tip = this.tip()

      var tipId = this.getUID(this.type)

      this.setContent()
      $tip.attr('id', tipId)
      this.$element.attr('aria-describedby', tipId)

      if (this.options.animation) $tip.addClass('fade')

      var placement = typeof this.options.placement == 'function' ?
        this.options.placement.call(this, $tip[0], this.$element[0]) :
        this.options.placement

      var autoToken = /\s?auto?\s?/i
      var autoPlace = autoToken.test(placement)
      if (autoPlace) placement = placement.replace(autoToken, '') || 'top'

      $tip
        .detach()
        .css({ top: 0, left: 0, display: 'block' })
        .addClass(placement)
        .data('bs.' + this.type, this)

      this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
      this.$element.trigger('inserted.bs.' + this.type)

      var pos          = this.getPosition()
      var actualWidth  = $tip[0].offsetWidth
      var actualHeight = $tip[0].offsetHeight

      if (autoPlace) {
        var orgPlacement = placement
        var viewportDim = this.getPosition(this.$viewport)

        placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top'    :
                    placement == 'top'    && pos.top    - actualHeight < viewportDim.top    ? 'bottom' :
                    placement == 'right'  && pos.right  + actualWidth  > viewportDim.width  ? 'left'   :
                    placement == 'left'   && pos.left   - actualWidth  < viewportDim.left   ? 'right'  :
                    placement

        $tip
          .removeClass(orgPlacement)
          .addClass(placement)
      }

      var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)

      this.applyPlacement(calculatedOffset, placement)

      var complete = function () {
        var prevHoverState = that.hoverState
        that.$element.trigger('shown.bs.' + that.type)
        that.hoverState = null

        if (prevHoverState == 'out') that.leave(that)
      }

      $.support.transition && this.$tip.hasClass('fade') ?
        $tip
          .one('bsTransitionEnd', complete)
          .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
        complete()
    }
  }

  Tooltip.prototype.applyPlacement = function (offset, placement) {
    var $tip   = this.tip()
    var width  = $tip[0].offsetWidth
    var height = $tip[0].offsetHeight

    // manually read margins because getBoundingClientRect includes difference
    var marginTop = parseInt($tip.css('margin-top'), 10)
    var marginLeft = parseInt($tip.css('margin-left'), 10)

    // we must check for NaN for ie 8/9
    if (isNaN(marginTop))  marginTop  = 0
    if (isNaN(marginLeft)) marginLeft = 0

    offset.top  += marginTop
    offset.left += marginLeft

    // $.fn.offset doesn't round pixel values
    // so we use setOffset directly with our own function B-0
    $.offset.setOffset($tip[0], $.extend({
      using: function (props) {
        $tip.css({
          top: Math.round(props.top),
          left: Math.round(props.left)
        })
      }
    }, offset), 0)

    $tip.addClass('in')

    // check to see if placing tip in new offset caused the tip to resize itself
    var actualWidth  = $tip[0].offsetWidth
    var actualHeight = $tip[0].offsetHeight

    if (placement == 'top' && actualHeight != height) {
      offset.top = offset.top + height - actualHeight
    }

    var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)

    if (delta.left) offset.left += delta.left
    else offset.top += delta.top

    var isVertical          = /top|bottom/.test(placement)
    var arrowDelta          = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
    var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'

    $tip.offset(offset)
    this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
  }

  Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
    this.arrow()
      .css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
      .css(isVertical ? 'top' : 'left', '')
  }

  Tooltip.prototype.setContent = function () {
    var $tip  = this.tip()
    var title = this.getTitle()

    $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
    $tip.removeClass('fade in top bottom left right')
  }

  Tooltip.prototype.hide = function (callback) {
    var that = this
    var $tip = $(this.$tip)
    var e    = $.Event('hide.bs.' + this.type)

    function complete() {
      if (that.hoverState != 'in') $tip.detach()
      if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
        that.$element
          .removeAttr('aria-describedby')
          .trigger('hidden.bs.' + that.type)
      }
      callback && callback()
    }

    this.$element.trigger(e)

    if (e.isDefaultPrevented()) return

    $tip.removeClass('in')

    $.support.transition && $tip.hasClass('fade') ?
      $tip
        .one('bsTransitionEnd', complete)
        .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
      complete()

    this.hoverState = null

    return this
  }

  Tooltip.prototype.fixTitle = function () {
    var $e = this.$element
    if ($e.attr('title') || typeof $e.attr('data-original-title') != 'string') {
      $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
    }
  }

  Tooltip.prototype.hasContent = function () {
    return this.getTitle()
  }

  Tooltip.prototype.getPosition = function ($element) {
    $element   = $element || this.$element

    var el     = $element[0]
    var isBody = el.tagName == 'BODY'

    var elRect    = el.getBoundingClientRect()
    if (elRect.width == null) {
      // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
      elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
    }
    var isSvg = window.SVGElement && el instanceof window.SVGElement
    // Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
    // See https://github.com/twbs/bootstrap/issues/20280
    var elOffset  = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
    var scroll    = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
    var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null

    return $.extend({}, elRect, scroll, outerDims, elOffset)
  }

  Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2 } :
           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
           placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }

  }

  Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
    var delta = { top: 0, left: 0 }
    if (!this.$viewport) return delta

    var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
    var viewportDimensions = this.getPosition(this.$viewport)

    if (/right|left/.test(placement)) {
      var topEdgeOffset    = pos.top - viewportPadding - viewportDimensions.scroll
      var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
      if (topEdgeOffset < viewportDimensions.top) { // top overflow
        delta.top = viewportDimensions.top - topEdgeOffset
      } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
        delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
      }
    } else {
      var leftEdgeOffset  = pos.left - viewportPadding
      var rightEdgeOffset = pos.left + viewportPadding + actualWidth
      if (leftEdgeOffset < viewportDimensions.left) { // left overflow
        delta.left = viewportDimensions.left - leftEdgeOffset
      } else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
        delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
      }
    }

    return delta
  }

  Tooltip.prototype.getTitle = function () {
    var title
    var $e = this.$element
    var o  = this.options

    title = $e.attr('data-original-title')
      || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)

    return title
  }

  Tooltip.prototype.getUID = function (prefix) {
    do prefix += ~~(Math.random() * 1000000)
    while (document.getElementById(prefix))
    return prefix
  }

  Tooltip.prototype.tip = function () {
    if (!this.$tip) {
      this.$tip = $(this.options.template)
      if (this.$tip.length != 1) {
        throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
      }
    }
    return this.$tip
  }

  Tooltip.prototype.arrow = function () {
    return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
  }

  Tooltip.prototype.enable = function () {
    this.enabled = true
  }

  Tooltip.prototype.disable = function () {
    this.enabled = false
  }

  Tooltip.prototype.toggleEnabled = function () {
    this.enabled = !this.enabled
  }

  Tooltip.prototype.toggle = function (e) {
    var self = this
    if (e) {
      self = $(e.currentTarget).data('bs.' + this.type)
      if (!self) {
        self = new this.constructor(e.currentTarget, this.getDelegateOptions())
        $(e.currentTarget).data('bs.' + this.type, self)
      }
    }

    if (e) {
      self.inState.click = !self.inState.click
      if (self.isInStateTrue()) self.enter(self)
      else self.leave(self)
    } else {
      self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
    }
  }

  Tooltip.prototype.destroy = function () {
    var that = this
    clearTimeout(this.timeout)
    this.hide(function () {
      that.$element.off('.' + that.type).removeData('bs.' + that.type)
      if (that.$tip) {
        that.$tip.detach()
      }
      that.$tip = null
      that.$arrow = null
      that.$viewport = null
      that.$element = null
    })
  }


  // TOOLTIP PLUGIN DEFINITION
  // =========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.tooltip')
      var options = typeof option == 'object' && option

      if (!data && /destroy|hide/.test(option)) return
      if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.tooltip

  $.fn.tooltip             = Plugin
  $.fn.tooltip.Constructor = Tooltip


  // TOOLTIP NO CONFLICT
  // ===================

  $.fn.tooltip.noConflict = function () {
    $.fn.tooltip = old
    return this
  }

}(jQuery);

/* ========================================================================
 * Bootstrap: popover.js v3.3.7
 * http://getbootstrap.com/javascript/#popovers
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // POPOVER PUBLIC CLASS DEFINITION
  // ===============================

  var Popover = function (element, options) {
    this.init('popover', element, options)
  }

  if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')

  Popover.VERSION  = '3.3.7'

  Popover.DEFAULTS = $.extend({}, $.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>'
  })


  // NOTE: POPOVER EXTENDS tooltip.js
  // ================================

  Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)

  Popover.prototype.constructor = Popover

  Popover.prototype.getDefaults = function () {
    return Popover.DEFAULTS
  }

  Popover.prototype.setContent = function () {
    var $tip    = this.tip()
    var title   = this.getTitle()
    var content = this.getContent()

    $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
    $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
      this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
    ](content)

    $tip.removeClass('fade top bottom left right in')

    // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
    // this manually by checking the contents.
    if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
  }

  Popover.prototype.hasContent = function () {
    return this.getTitle() || this.getContent()
  }

  Popover.prototype.getContent = function () {
    var $e = this.$element
    var o  = this.options

    return $e.attr('data-content')
      || (typeof o.content == 'function' ?
            o.content.call($e[0]) :
            o.content)
  }

  Popover.prototype.arrow = function () {
    return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
  }


  // POPOVER PLUGIN DEFINITION
  // =========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.popover')
      var options = typeof option == 'object' && option

      if (!data && /destroy|hide/.test(option)) return
      if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.popover

  $.fn.popover             = Plugin
  $.fn.popover.Constructor = Popover


  // POPOVER NO CONFLICT
  // ===================

  $.fn.popover.noConflict = function () {
    $.fn.popover = old
    return this
  }

}(jQuery);

/* ========================================================================
 * Bootstrap: scrollspy.js v3.3.7
 * http://getbootstrap.com/javascript/#scrollspy
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // SCROLLSPY CLASS DEFINITION
  // ==========================

  function ScrollSpy(element, options) {
    this.$body          = $(document.body)
    this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
    this.options        = $.extend({}, ScrollSpy.DEFAULTS, options)
    this.selector       = (this.options.target || '') + ' .nav li > a'
    this.offsets        = []
    this.targets        = []
    this.activeTarget   = null
    this.scrollHeight   = 0

    this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
    this.refresh()
    this.process()
  }

  ScrollSpy.VERSION  = '3.3.7'

  ScrollSpy.DEFAULTS = {
    offset: 10
  }

  ScrollSpy.prototype.getScrollHeight = function () {
    return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
  }

  ScrollSpy.prototype.refresh = function () {
    var that          = this
    var offsetMethod  = 'offset'
    var offsetBase    = 0

    this.offsets      = []
    this.targets      = []
    this.scrollHeight = this.getScrollHeight()

    if (!$.isWindow(this.$scrollElement[0])) {
      offsetMethod = 'position'
      offsetBase   = this.$scrollElement.scrollTop()
    }

    this.$body
      .find(this.selector)
      .map(function () {
        var $el   = $(this)
        var href  = $el.data('target') || $el.attr('href')
        var $href = /^#./.test(href) && $(href)

        return ($href
          && $href.length
          && $href.is(':visible')
          && [[$href[offsetMethod]().top + offsetBase, href]]) || null
      })
      .sort(function (a, b) { return a[0] - b[0] })
      .each(function () {
        that.offsets.push(this[0])
        that.targets.push(this[1])
      })
  }

  ScrollSpy.prototype.process = function () {
    var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset
    var scrollHeight = this.getScrollHeight()
    var maxScroll    = this.options.offset + scrollHeight - this.$scrollElement.height()
    var offsets      = this.offsets
    var targets      = this.targets
    var activeTarget = this.activeTarget
    var i

    if (this.scrollHeight != scrollHeight) {
      this.refresh()
    }

    if (scrollTop >= maxScroll) {
      return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
    }

    if (activeTarget && scrollTop < offsets[0]) {
      this.activeTarget = null
      return this.clear()
    }

    for (i = offsets.length; i--;) {
      activeTarget != targets[i]
        && scrollTop >= offsets[i]
        && (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
        && this.activate(targets[i])
    }
  }

  ScrollSpy.prototype.activate = function (target) {
    this.activeTarget = target

    this.clear()

    var selector = this.selector +
      '[data-target="' + target + '"],' +
      this.selector + '[href="' + target + '"]'

    var active = $(selector)
      .parents('li')
      .addClass('active')

    if (active.parent('.dropdown-menu').length) {
      active = active
        .closest('li.dropdown')
        .addClass('active')
    }

    active.trigger('activate.bs.scrollspy')
  }

  ScrollSpy.prototype.clear = function () {
    $(this.selector)
      .parentsUntil(this.options.target, '.active')
      .removeClass('active')
  }


  // SCROLLSPY PLUGIN DEFINITION
  // ===========================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.scrollspy')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.scrollspy

  $.fn.scrollspy             = Plugin
  $.fn.scrollspy.Constructor = ScrollSpy


  // SCROLLSPY NO CONFLICT
  // =====================

  $.fn.scrollspy.noConflict = function () {
    $.fn.scrollspy = old
    return this
  }


  // SCROLLSPY DATA-API
  // ==================

  $(window).on('load.bs.scrollspy.data-api', function () {
    $('[data-spy="scroll"]').each(function () {
      var $spy = $(this)
      Plugin.call($spy, $spy.data())
    })
  })

}(jQuery);

/* ========================================================================
 * Bootstrap: tab.js v3.3.7
 * http://getbootstrap.com/javascript/#tabs
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // TAB CLASS DEFINITION
  // ====================

  var Tab = function (element) {
    // jscs:disable requireDollarBeforejQueryAssignment
    this.element = $(element)
    // jscs:enable requireDollarBeforejQueryAssignment
  }

  Tab.VERSION = '3.3.7'

  Tab.TRANSITION_DURATION = 150

  Tab.prototype.show = function () {
    var $this    = this.element
    var $ul      = $this.closest('ul:not(.dropdown-menu)')
    var selector = $this.data('target')

    if (!selector) {
      selector = $this.attr('href')
      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    if ($this.parent('li').hasClass('active')) return

    var $previous = $ul.find('.active:last a')
    var hideEvent = $.Event('hide.bs.tab', {
      relatedTarget: $this[0]
    })
    var showEvent = $.Event('show.bs.tab', {
      relatedTarget: $previous[0]
    })

    $previous.trigger(hideEvent)
    $this.trigger(showEvent)

    if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return

    var $target = $(selector)

    this.activate($this.closest('li'), $ul)
    this.activate($target, $target.parent(), function () {
      $previous.trigger({
        type: 'hidden.bs.tab',
        relatedTarget: $this[0]
      })
      $this.trigger({
        type: 'shown.bs.tab',
        relatedTarget: $previous[0]
      })
    })
  }

  Tab.prototype.activate = function (element, container, callback) {
    var $active    = container.find('> .active')
    var transition = callback
      && $.support.transition
      && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)

    function next() {
      $active
        .removeClass('active')
        .find('> .dropdown-menu > .active')
          .removeClass('active')
        .end()
        .find('[data-toggle="tab"]')
          .attr('aria-expanded', false)

      element
        .addClass('active')
        .find('[data-toggle="tab"]')
          .attr('aria-expanded', true)

      if (transition) {
        element[0].offsetWidth // reflow for transition
        element.addClass('in')
      } else {
        element.removeClass('fade')
      }

      if (element.parent('.dropdown-menu').length) {
        element
          .closest('li.dropdown')
            .addClass('active')
          .end()
          .find('[data-toggle="tab"]')
            .attr('aria-expanded', true)
      }

      callback && callback()
    }

    $active.length && transition ?
      $active
        .one('bsTransitionEnd', next)
        .emulateTransitionEnd(Tab.TRANSITION_DURATION) :
      next()

    $active.removeClass('in')
  }


  // TAB PLUGIN DEFINITION
  // =====================

  function Plugin(option) {
    return this.each(function () {
      var $this = $(this)
      var data  = $this.data('bs.tab')

      if (!data) $this.data('bs.tab', (data = new Tab(this)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.tab

  $.fn.tab             = Plugin
  $.fn.tab.Constructor = Tab


  // TAB NO CONFLICT
  // ===============

  $.fn.tab.noConflict = function () {
    $.fn.tab = old
    return this
  }


  // TAB DATA-API
  // ============

  var clickHandler = function (e) {
    e.preventDefault()
    Plugin.call($(this), 'show')
  }

  $(document)
    .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
    .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)

}(jQuery);

/* ========================================================================
 * Bootstrap: affix.js v3.3.7
 * http://getbootstrap.com/javascript/#affix
 * ========================================================================
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */


+function ($) {
  'use strict';

  // AFFIX CLASS DEFINITION
  // ======================

  var Affix = function (element, options) {
    this.options = $.extend({}, Affix.DEFAULTS, options)

    this.$target = $(this.options.target)
      .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
      .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))

    this.$element     = $(element)
    this.affixed      = null
    this.unpin        = null
    this.pinnedOffset = null

    this.checkPosition()
  }

  Affix.VERSION  = '3.3.7'

  Affix.RESET    = 'affix affix-top affix-bottom'

  Affix.DEFAULTS = {
    offset: 0,
    target: window
  }

  Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
    var scrollTop    = this.$target.scrollTop()
    var position     = this.$element.offset()
    var targetHeight = this.$target.height()

    if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false

    if (this.affixed == 'bottom') {
      if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
      return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
    }

    var initializing   = this.affixed == null
    var colliderTop    = initializing ? scrollTop : position.top
    var colliderHeight = initializing ? targetHeight : height

    if (offsetTop != null && scrollTop <= offsetTop) return 'top'
    if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'

    return false
  }

  Affix.prototype.getPinnedOffset = function () {
    if (this.pinnedOffset) return this.pinnedOffset
    this.$element.removeClass(Affix.RESET).addClass('affix')
    var scrollTop = this.$target.scrollTop()
    var position  = this.$element.offset()
    return (this.pinnedOffset = position.top - scrollTop)
  }

  Affix.prototype.checkPositionWithEventLoop = function () {
    setTimeout($.proxy(this.checkPosition, this), 1)
  }

  Affix.prototype.checkPosition = function () {
    if (!this.$element.is(':visible')) return

    var height       = this.$element.height()
    var offset       = this.options.offset
    var offsetTop    = offset.top
    var offsetBottom = offset.bottom
    var scrollHeight = Math.max($(document).height(), $(document.body).height())

    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
    if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)

    var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)

    if (this.affixed != affix) {
      if (this.unpin != null) this.$element.css('top', '')

      var affixType = 'affix' + (affix ? '-' + affix : '')
      var e         = $.Event(affixType + '.bs.affix')

      this.$element.trigger(e)

      if (e.isDefaultPrevented()) return

      this.affixed = affix
      this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null

      this.$element
        .removeClass(Affix.RESET)
        .addClass(affixType)
        .trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
    }

    if (affix == 'bottom') {
      this.$element.offset({
        top: scrollHeight - height - offsetBottom
      })
    }
  }


  // AFFIX PLUGIN DEFINITION
  // =======================

  function Plugin(option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.affix')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.affix

  $.fn.affix             = Plugin
  $.fn.affix.Constructor = Affix


  // AFFIX NO CONFLICT
  // =================

  $.fn.affix.noConflict = function () {
    $.fn.affix = old
    return this
  }


  // AFFIX DATA-API
  // ==============

  $(window).on('load', function () {
    $('[data-spy="affix"]').each(function () {
      var $spy = $(this)
      var data = $spy.data()

      data.offset = data.offset || {}

      if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
      if (data.offsetTop    != null) data.offset.top    = data.offsetTop

      Plugin.call($spy, data)
    })
  })

}(jQuery);

/*! jQuery UI - v1.12.0 - 2016-08-16
* http://jqueryui.com
* Includes: widget.js, position.js, jquery-1-7.js, keycode.js, unique-id.js, widgets/autocomplete.js, widgets/menu.js, widgets/mouse.js, widgets/slider.js, effect.js, effects/effect-blind.js, effects/effect-bounce.js, effects/effect-clip.js, effects/effect-drop.js, effects/effect-explode.js, effects/effect-fade.js, effects/effect-fold.js, effects/effect-highlight.js, effects/effect-puff.js, effects/effect-pulsate.js, effects/effect-scale.js, effects/effect-shake.js, effects/effect-size.js, effects/effect-slide.js, effects/effect-transfer.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */

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

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

		// Browser globals
		factory( jQuery );
	}
}(function( $ ) {

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

var version = $.ui.version = "1.12.0";


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

//>>label: Widget
//>>group: Core
//>>description: Provides a factory for creating stateful widgets with a common API.
//>>docs: http://api.jqueryui.com/jQuery.widget/
//>>demos: http://jqueryui.com/widget/



var widgetUuid = 0;
var widgetSlice = Array.prototype.slice;

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

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

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

$.widget = function( name, base, prototype ) {
	var existingConstructor, constructor, basePrototype;

	// ProxiedPrototype allows the provided prototype to remain unmodified
	// so that it can be used as a mixin for multiple widgets (#8876)
	var proxiedPrototype = {};

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

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

	if ( $.isArray( prototype ) ) {
		prototype = $.extend.apply( null, [ {} ].concat( prototype ) );
	}

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

	$[ namespace ] = $[ namespace ] || {};
	existingConstructor = $[ namespace ][ name ];
	constructor = $[ namespace ][ name ] = function( options, element ) {

		// Allow instantiation without "new" keyword
		if ( !this._createWidget ) {
			return new constructor( options, element );
		}

		// Allow instantiation without initializing for simple inheritance
		// must use "new" keyword (the code above always passes args)
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	// Extend with the existing constructor to carry over any static properties
	$.extend( constructor, existingConstructor, {
		version: prototype.version,

		// Copy the object used to create the prototype in case we need to
		// redefine the widget later
		_proto: $.extend( {}, prototype ),

		// Track widgets that inherit from this widget in case this widget is
		// redefined after a widget inherits from it
		_childConstructors: []
	} );

	basePrototype = new base();

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

			function _superApply( args ) {
				return base.prototype[ prop ].apply( this, args );
			}

			return function() {
				var __super = this._super;
				var __superApply = this._superApply;
				var returnValue;

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

				returnValue = value.apply( this, arguments );

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

				return returnValue;
			};
		} )();
	} );
	constructor.prototype = $.widget.extend( basePrototype, {

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

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

			// Redefine the child widget using the same prototype that was
			// originally used, but inherit from the new version of the base
			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor,
				child._proto );
		} );

		// Remove the list of existing child constructors from the old constructor
		// so the old child constructors can be garbage collected
		delete existingConstructor._childConstructors;
	} else {
		base._childConstructors.push( constructor );
	}

	$.widget.bridge( name, constructor );

	return constructor;
};

$.widget.extend = function( target ) {
	var input = widgetSlice.call( arguments, 1 );
	var inputIndex = 0;
	var inputLength = input.length;
	var key;
	var value;

	for ( ; inputIndex < inputLength; inputIndex++ ) {
		for ( key in input[ inputIndex ] ) {
			value = input[ inputIndex ][ key ];
			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {

				// Clone objects
				if ( $.isPlainObject( value ) ) {
					target[ key ] = $.isPlainObject( target[ key ] ) ?
						$.widget.extend( {}, target[ key ], value ) :

						// Don't extend strings, arrays, etc. with objects
						$.widget.extend( {}, value );

				// Copy everything else by reference
				} else {
					target[ key ] = value;
				}
			}
		}
	}
	return target;
};

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

		if ( isMethodCall ) {
			this.each( function() {
				var methodValue;
				var instance = $.data( this, fullName );

				if ( options === "instance" ) {
					returnValue = instance;
					return false;
				}

				if ( !instance ) {
					return $.error( "cannot call methods on " + name +
						" prior to initialization; " +
						"attempted to call method '" + options + "'" );
				}

				if ( !$.isFunction( instance[ options ] ) || options.charAt( 0 ) === "_" ) {
					return $.error( "no such method '" + options + "' for " + name +
						" widget instance" );
				}

				methodValue = instance[ options ].apply( instance, args );

				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue && methodValue.jquery ?
						returnValue.pushStack( methodValue.get() ) :
						methodValue;
					return false;
				}
			} );
		} else {

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

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

		return returnValue;
	};
};

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

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

	options: {
		classes: {},
		disabled: false,

		// Callbacks
		create: null
	},

	_createWidget: function( options, element ) {
		element = $( element || this.defaultElement || this )[ 0 ];
		this.element = $( element );
		this.uuid = widgetUuid++;
		this.eventNamespace = "." + this.widgetName + this.uuid;

		this.bindings = $();
		this.hoverable = $();
		this.focusable = $();
		this.classesElementLookup = {};

		if ( element !== this ) {
			$.data( element, this.widgetFullName, this );
			this._on( true, this.element, {
				remove: function( event ) {
					if ( event.target === element ) {
						this.destroy();
					}
				}
			} );
			this.document = $( element.style ?

				// Element within the document
				element.ownerDocument :

				// Element is window or document
				element.document || element );
			this.window = $( this.document[ 0 ].defaultView || this.document[ 0 ].parentWindow );
		}

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

		this._create();

		if ( this.options.disabled ) {
			this._setOptionDisabled( this.options.disabled );
		}

		this._trigger( "create", null, this._getCreateEventData() );
		this._init();
	},

	_getCreateOptions: function() {
		return {};
	},

	_getCreateEventData: $.noop,

	_create: $.noop,

	_init: $.noop,

	destroy: function() {
		var that = this;

		this._destroy();
		$.each( this.classesElementLookup, function( key, value ) {
			that._removeClass( value, key );
		} );

		// We can probably remove the unbind calls in 2.0
		// all event bindings should go through this._on()
		this.element
			.off( this.eventNamespace )
			.removeData( this.widgetFullName );
		this.widget()
			.off( this.eventNamespace )
			.removeAttr( "aria-disabled" );

		// Clean up events and states
		this.bindings.off( this.eventNamespace );
	},

	_destroy: $.noop,

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

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

		if ( arguments.length === 0 ) {

			// Don't return a reference to the internal hash
			return $.widget.extend( {}, this.options );
		}

		if ( typeof key === "string" ) {

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

		this._setOptions( options );

		return this;
	},

	_setOptions: function( options ) {
		var key;

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

		return this;
	},

	_setOption: function( key, value ) {
		if ( key === "classes" ) {
			this._setOptionClasses( value );
		}

		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this._setOptionDisabled( value );
		}

		return this;
	},

	_setOptionClasses: function( value ) {
		var classKey, elements, currentElements;

		for ( classKey in value ) {
			currentElements = this.classesElementLookup[ classKey ];
			if ( value[ classKey ] === this.options.classes[ classKey ] ||
					!currentElements ||
					!currentElements.length ) {
				continue;
			}

			// We are doing this to create a new jQuery object because the _removeClass() call
			// on the next line is going to destroy the reference to the current elements being
			// tracked. We need to save a copy of this collection so that we can add the new classes
			// below.
			elements = $( currentElements.get() );
			this._removeClass( currentElements, classKey );

			// We don't use _addClass() here, because that uses this.options.classes
			// for generating the string of classes. We want to use the value passed in from
			// _setOption(), this is the new value of the classes option which was passed to
			// _setOption(). We pass this value directly to _classes().
			elements.addClass( this._classes( {
				element: elements,
				keys: classKey,
				classes: value,
				add: true
			} ) );
		}
	},

	_setOptionDisabled: function( value ) {
		this._toggleClass( this.widget(), this.widgetFullName + "-disabled", null, !!value );

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

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

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

	_classes: function( options ) {
		var full = [];
		var that = this;

		options = $.extend( {
			element: this.element,
			classes: this.options.classes || {}
		}, options );

		function processClassString( classes, checkOption ) {
			var current, i;
			for ( i = 0; i < classes.length; i++ ) {
				current = that.classesElementLookup[ classes[ i ] ] || $();
				if ( options.add ) {
					current = $( $.unique( current.get().concat( options.element.get() ) ) );
				} else {
					current = $( current.not( options.element ).get() );
				}
				that.classesElementLookup[ classes[ i ] ] = current;
				full.push( classes[ i ] );
				if ( checkOption && options.classes[ classes[ i ] ] ) {
					full.push( options.classes[ classes[ i ] ] );
				}
			}
		}

		if ( options.keys ) {
			processClassString( options.keys.match( /\S+/g ) || [], true );
		}
		if ( options.extra ) {
			processClassString( options.extra.match( /\S+/g ) || [] );
		}

		return full.join( " " );
	},

	_removeClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, false );
	},

	_addClass: function( element, keys, extra ) {
		return this._toggleClass( element, keys, extra, true );
	},

	_toggleClass: function( element, keys, extra, add ) {
		add = ( typeof add === "boolean" ) ? add : extra;
		var shift = ( typeof element === "string" || element === null ),
			options = {
				extra: shift ? keys : extra,
				keys: shift ? element : keys,
				element: shift ? this.element : element,
				add: add
			};
		options.element.toggleClass( this._classes( options ), add );
		return this;
	},

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

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

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

		$.each( handlers, function( event, handler ) {
			function handlerProxy() {

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

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

			var match = event.match( /^([\w:-]*)\s*(.*)$/ );
			var eventName = match[ 1 ] + instance.eventNamespace;
			var selector = match[ 2 ];

			if ( selector ) {
				delegateElement.on( eventName, selector, handlerProxy );
			} else {
				element.on( eventName, handlerProxy );
			}
		} );
	},

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

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

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

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

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

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

		data = data || {};
		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();

		// The original event may come from any element
		// so we need to reset the target on the new event
		event.target = this.element[ 0 ];

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

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

$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
		if ( typeof options === "string" ) {
			options = { effect: options };
		}

		var hasOptions;
		var effectName = !options ?
			method :
			options === true || typeof options === "number" ?
				defaultEffect :
				options.effect || defaultEffect;

		options = options || {};
		if ( typeof options === "number" ) {
			options = { duration: options };
		}

		hasOptions = !$.isEmptyObject( options );
		options.complete = callback;

		if ( options.delay ) {
			element.delay( options.delay );
		}

		if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) {
			element[ method ]( options );
		} else if ( effectName !== method && element[ effectName ] ) {
			element[ effectName ]( options.duration, options.easing, callback );
		} else {
			element.queue( function( next ) {
				$( this )[ method ]();
				if ( callback ) {
					callback.call( element[ 0 ] );
				}
				next();
			} );
		}
	};
} );

var widget = $.widget;


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

//>>label: Position
//>>group: Core
//>>description: Positions elements relative to other elements.
//>>docs: http://api.jqueryui.com/position/
//>>demos: http://jqueryui.com/position/


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

// Support: IE <=9 only
supportsOffsetFractions = function() {
	var element = $( "<div>" )
			.css( "position", "absolute" )
			.appendTo( "body" )
			.offset( {
				top: 1.5,
				left: 1.5
			} ),
		support = element.offset().top === 1.5;

	element.remove();

	supportsOffsetFractions = function() {
		return support;
	};

	return support;
};

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

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

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

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

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

		w2 = innerDiv.offsetWidth;

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

		div.remove();

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

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

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

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

	dimensions = getDimensions( target );
	if ( target[ 0 ].preventDefault ) {

		// Force left top to allow flipping
		options.at = "left top";
	}
	targetWidth = dimensions.width;
	targetHeight = dimensions.height;
	targetOffset = dimensions.offset;

	// Clone to reuse original targetOffset later
	basePosition = $.extend( {}, targetOffset );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		if ( options.using ) {

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

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

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

			// Element is wider than within
			if ( data.collisionWidth > outerWidth ) {

				// Element is initially over the left side of within
				if ( overLeft > 0 && overRight <= 0 ) {
					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth -
						withinOffset;
					position.left += overLeft - newOverRight;

				// Element is initially over right side of within
				} else if ( overRight > 0 && overLeft <= 0 ) {
					position.left = withinOffset;

				// Element is initially over both left and right sides of within
				} else {
					if ( overLeft > overRight ) {
						position.left = withinOffset + outerWidth - data.collisionWidth;
					} else {
						position.left = withinOffset;
					}
				}

			// Too far left -> align with left edge
			} else if ( overLeft > 0 ) {
				position.left += overLeft;

			// Too far right -> align with right edge
			} else if ( overRight > 0 ) {
				position.left -= overRight;

			// Adjust based on position and margin
			} else {
				position.left = max( position.left - collisionPosLeft, position.left );
			}
		},
		top: function( position, data ) {
			var within = data.within,
				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
				outerHeight = data.within.height,
				collisionPosTop = position.top - data.collisionPosition.marginTop,
				overTop = withinOffset - collisionPosTop,
				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
				newOverBottom;

			// Element is taller than within
			if ( data.collisionHeight > outerHeight ) {

				// Element is initially over the top of within
				if ( overTop > 0 && overBottom <= 0 ) {
					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight -
						withinOffset;
					position.top += overTop - newOverBottom;

				// Element is initially over bottom of within
				} else if ( overBottom > 0 && overTop <= 0 ) {
					position.top = withinOffset;

				// Element is initially over both top and bottom of within
				} else {
					if ( overTop > overBottom ) {
						position.top = withinOffset + outerHeight - data.collisionHeight;
					} else {
						position.top = withinOffset;
					}
				}

			// Too far up -> align with top
			} else if ( overTop > 0 ) {
				position.top += overTop;

			// Too far down -> align with bottom edge
			} else if ( overBottom > 0 ) {
				position.top -= overBottom;

			// Adjust based on position and margin
			} else {
				position.top = max( position.top - collisionPosTop, position.top );
			}
		}
	},
	flip: {
		left: function( position, data ) {
			var within = data.within,
				withinOffset = within.offset.left + within.scrollLeft,
				outerWidth = within.width,
				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
				overLeft = collisionPosLeft - offsetLeft,
				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
				myOffset = data.my[ 0 ] === "left" ?
					-data.elemWidth :
					data.my[ 0 ] === "right" ?
						data.elemWidth :
						0,
				atOffset = data.at[ 0 ] === "left" ?
					data.targetWidth :
					data.at[ 0 ] === "right" ?
						-data.targetWidth :
						0,
				offset = -2 * data.offset[ 0 ],
				newOverRight,
				newOverLeft;

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

} )();

var position = $.ui.position;


/*!
 * jQuery UI Support for jQuery core 1.7.x 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 */

//>>label: jQuery 1.7 Support
//>>group: Core
//>>description: Support version 1.7.x of jQuery core



// Support: jQuery 1.7 only
// Not a great way to check versions, but since we only support 1.7+ and only
// need to detect <1.8, this is a simple check that should suffice. Checking
// for "1.7." would be a bit safer, but the version string is 1.7, not 1.7.0
// and we'll never reach 1.70.0 (if we do, we certainly won't be supporting
// 1.7 anymore). See #11197 for why we're not using feature detection.
if ( $.fn.jquery.substring( 0, 3 ) === "1.7" ) {

	// Setters for .innerWidth(), .innerHeight(), .outerWidth(), .outerHeight()
	// Unlike jQuery Core 1.8+, these only support numeric values to set the
	// dimensions in pixels
	$.each( [ "Width", "Height" ], function( i, name ) {
		var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
			type = name.toLowerCase(),
			orig = {
				innerWidth: $.fn.innerWidth,
				innerHeight: $.fn.innerHeight,
				outerWidth: $.fn.outerWidth,
				outerHeight: $.fn.outerHeight
			};

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

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

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

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

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

	$.fn.addBack = function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	};
}

;
/*!
 * jQuery UI Keycode 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/


var keycode = $.ui.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
};


/*!
 * jQuery UI Unique ID 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: uniqueId
//>>group: Core
//>>description: Functions to generate and remove uniqueId's
//>>docs: http://api.jqueryui.com/uniqueId/



var uniqueId = $.fn.extend( {
	uniqueId: ( function() {
		var uuid = 0;

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

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



var safeActiveElement = $.ui.safeActiveElement = function( document ) {
	var activeElement;

	// Support: IE 9 only
	// IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe>
	try {
		activeElement = document.activeElement;
	} catch ( error ) {
		activeElement = document.body;
	}

	// Support: IE 9 - 11 only
	// IE may return null instead of an element
	// Interestingly, this only seems to occur when NOT in an iframe
	if ( !activeElement ) {
		activeElement = document.body;
	}

	// Support: IE 11 only
	// IE11 returns a seemingly empty object in some cases when accessing
	// document.activeElement from an <iframe>
	if ( !activeElement.nodeName ) {
		activeElement = document.body;
	}

	return activeElement;
};


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

//>>label: Menu
//>>group: Widgets
//>>description: Creates nestable menus.
//>>docs: http://api.jqueryui.com/menu/
//>>demos: http://jqueryui.com/menu/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/menu.css
//>>css.theme: ../../themes/base/theme.css



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

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

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

		// Flag used to prevent firing of the click handler
		// as the event bubbles up through nested menus
		this.mouseHandled = false;
		this.element
			.uniqueId()
			.attr( {
				role: this.options.role,
				tabIndex: 0
			} );

		this._addClass( "ui-menu", "ui-widget ui-widget-content" );
		this._on( {

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

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

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

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

						// If the active item is on the top level, let it stay active.
						// Otherwise, blur the active item since it is no longer visible.
						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
							clearTimeout( this.timer );
						}
					}
				}
			},
			"mouseenter .ui-menu-item": function( event ) {

				// Ignore mouse events while typeahead is active, see #10458.
				// Prevents focusing the wrong item when typeahead causes a scroll while the mouse
				// is over an item in the menu
				if ( this.previousFilter ) {
					return;
				}

				var actualTarget = $( event.target ).closest( ".ui-menu-item" ),
					target = $( event.currentTarget );

				// Ignore bubbled events on parent items, see #11641
				if ( actualTarget[ 0 ] !== target[ 0 ] ) {
					return;
				}

				// Remove ui-state-active class from siblings of the newly focused menu item
				// to avoid a jump caused by adjacent elements both having a class with a border
				this._removeClass( target.siblings().children( ".ui-state-active" ),
					null, "ui-state-active" );
				this.focus( event, target );
			},
			mouseleave: "collapseAll",
			"mouseleave .ui-menu": "collapseAll",
			focus: function( event, keepActiveItem ) {

				// If there's already an active item, keep it active
				// If not, activate the first item
				var item = this.active || this.element.find( this.options.items ).eq( 0 );

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

		this.refresh();

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

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

	_destroy: function() {
		var items = this.element.find( ".ui-menu-item" )
				.removeAttr( "role aria-disabled" ),
			submenus = items.children( ".ui-menu-item-wrapper" )
				.removeUniqueId()
				.removeAttr( "tabIndex role aria-haspopup" );

		// Destroy (sub)menus
		this.element
			.removeAttr( "aria-activedescendant" )
			.find( ".ui-menu" ).addBack()
				.removeAttr( "role aria-labelledby aria-expanded aria-hidden aria-disabled " +
					"tabIndex" )
				.removeUniqueId()
				.show();

		submenus.children().each( function() {
			var elem = $( this );
			if ( elem.data( "ui-menu-submenu-caret" ) ) {
				elem.remove();
			}
		} );
	},

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

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

			clearTimeout( this.filterTimer );

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

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

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

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

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

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

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

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

		// Initialize nested menus
		newSubmenus = submenus.filter( ":not(.ui-menu)" )
			.hide()
			.attr( {
				role: this.options.role,
				"aria-hidden": "true",
				"aria-expanded": "false"
			} )
			.each( function() {
				var menu = $( this ),
					item = menu.prev(),
					submenuCaret = $( "<span>" ).data( "ui-menu-submenu-caret", true );

				that._addClass( submenuCaret, "ui-menu-icon", "ui-icon " + icon );
				item
					.attr( "aria-haspopup", "true" )
					.prepend( submenuCaret );
				menu.attr( "aria-labelledby", item.attr( "id" ) );
			} );

		this._addClass( newSubmenus, "ui-menu", "ui-widget ui-widget-content ui-front" );

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

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

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

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

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

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

	_setOption: function( key, value ) {
		if ( key === "icons" ) {
			var icons = this.element.find( ".ui-menu-icon" );
			this._removeClass( icons, null, this.options.icons.submenu )
				._addClass( icons, null, value.submenu );
		}
		this._super( key, value );
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this.element.attr( "aria-disabled", String( value ) );
		this._toggleClass( null, "ui-state-disabled", !!value );
	},

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

		this._scrollIntoView( item );

		this.active = item.first();

		focused = this.active.children( ".ui-menu-item-wrapper" );
		this._addClass( focused, null, "ui-state-active" );

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

		// Highlight active parent menu item, if any
		activeParent = this.active
			.parent()
				.closest( ".ui-menu-item" )
					.children( ".ui-menu-item-wrapper" );
		this._addClass( activeParent, null, "ui-state-active" );

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

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

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

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

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

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

		if ( !this.active ) {
			return;
		}

		this._removeClass( this.active.children( ".ui-menu-item-wrapper" ),
			null, "ui-state-active" );

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

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

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

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

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

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

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

	collapseAll: function( event, all ) {
		clearTimeout( this.timer );
		this.timer = this._delay( function() {

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

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

			this._close( currentMenu );

			this.blur( event );

			// Work around active item staying active after menu is blurred
			this._removeClass( currentMenu.find( ".ui-state-active" ), null, "ui-state-active" );

			this.activeMenu = currentMenu;
		}, this.delay );
	},

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

		startMenu.find( ".ui-menu" )
			.hide()
			.attr( "aria-hidden", "true" )
			.attr( "aria-expanded", "false" );
	},

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

	_isDivider: function( item ) {

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

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

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

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

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

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

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

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

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

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

		this.focus( event, next );
	},

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

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

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

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

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

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

	select: function( event ) {

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

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

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

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


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

//>>label: Autocomplete
//>>group: Widgets
//>>description: Lists suggested words as the user is typing.
//>>docs: http://api.jqueryui.com/autocomplete/
//>>demos: http://jqueryui.com/autocomplete/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/autocomplete.css
//>>css.theme: ../../themes/base/theme.css



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

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

	requestIndex: 0,
	pending: 0,

	_create: function() {

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

		// Textareas are always multi-line
		// Inputs are always single-line, even if inside a contentEditable element
		// IE also treats inputs as contentEditable
		// All other element types are determined by whether or not they're contentEditable
		this.isMultiLine = isTextarea || !isInput && this._isContentEditable( this.element );

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

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

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

				suppressKeyPress = false;
				suppressInput = false;
				suppressKeyPressRepeat = false;
				var keyCode = $.ui.keyCode;
				switch ( event.keyCode ) {
				case keyCode.PAGE_UP:
					suppressKeyPress = true;
					this._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					suppressKeyPress = true;
					this._move( "nextPage", event );
					break;
				case keyCode.UP:
					suppressKeyPress = true;
					this._keyEvent( "previous", event );
					break;
				case keyCode.DOWN:
					suppressKeyPress = true;
					this._keyEvent( "next", event );
					break;
				case keyCode.ENTER:

					// when menu is open and has focus
					if ( this.menu.active ) {

						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
						this.menu.select( event );
					}
					break;
				case keyCode.TAB:
					if ( this.menu.active ) {
						this.menu.select( event );
					}
					break;
				case keyCode.ESCAPE:
					if ( this.menu.element.is( ":visible" ) ) {
						if ( !this.isMultiLine ) {
							this._value( this.term );
						}
						this.close( event );

						// Different browsers have different default behavior for escape
						// Single press can mean undo or clear
						// Double press in IE means clear the whole form
						event.preventDefault();
					}
					break;
				default:
					suppressKeyPressRepeat = true;

					// search timeout should be triggered before the input value is changed
					this._searchTimeout( event );
					break;
				}
			},
			keypress: function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
						event.preventDefault();
					}
					return;
				}
				if ( suppressKeyPressRepeat ) {
					return;
				}

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

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

		this._initSource();
		this.menu = $( "<ul>" )
			.appendTo( this._appendTo() )
			.menu( {

				// disable ARIA support, the live region takes care of that
				role: null
			} )
			.hide()
			.menu( "instance" );

		this._addClass( this.menu.element, "ui-autocomplete", "ui-front" );
		this._on( this.menu.element, {
			mousedown: function( event ) {

				// prevent moving focus out of the text field
				event.preventDefault();

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

					// Support: IE 8 only
					// Right clicking a menu item or selecting text from the menu items will
					// result in focus moving out of the input. However, we've already received
					// and ignored the blur event because of the cancelBlur flag set above. So
					// we restore focus to ensure that the menu closes properly based on the user's
					// next actions.
					if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
						this.element.trigger( "focus" );
					}
				} );
			},
			menufocus: function( event, ui ) {
				var label, item;

				// support: Firefox
				// Prevent accidental activation of menu items in Firefox (#7024 #9118)
				if ( this.isNewMenu ) {
					this.isNewMenu = false;
					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
						this.menu.blur();

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

						return;
					}
				}

				item = ui.item.data( "ui-autocomplete-item" );
				if ( false !== this._trigger( "focus", event, { item: item } ) ) {

					// use value to match what will end up in the input, if it was a key event
					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
						this._value( item.value );
					}
				}

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

				// Only trigger when focus was lost (click on menu)
				if ( this.element[ 0 ] !== $.ui.safeActiveElement( this.document[ 0 ] ) ) {
					this.element.trigger( "focus" );
					this.previous = previous;

					// #6109 - IE triggers two focus events and the second
					// is asynchronous, so we need to reset the previous
					// term synchronously and asynchronously :-(
					this._delay( function() {
						this.previous = previous;
						this.selectedItem = item;
					} );
				}

				if ( false !== this._trigger( "select", event, { item: item } ) ) {
					this._value( item.value );
				}

				// reset the term after the select event
				// this allows custom select handling to work properly
				this.term = this._value();

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

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

		this._addClass( this.liveRegion, null, "ui-helper-hidden-accessible" );

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

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

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

	_isEventTargetInWidget: function( event ) {
		var menuElement = this.menu.element[ 0 ];

		return event.target === this.element[ 0 ] ||
			event.target === menuElement ||
			$.contains( menuElement, event.target );
	},

	_closeOnClickOutside: function( event ) {
		if ( !this._isEventTargetInWidget( event ) ) {
			this.close();
		}
	},

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

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

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

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

		return element;
	},

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

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

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

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

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

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

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

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

		return this._search( value );
	},

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

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

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

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

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

	__response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {

			// use ._close() instead of .close() so we don't cancel future searches
			this._close();
		}
	},

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

	_close: function( event ) {

		// Remove the handler that closes the menu on outside clicks
		this._off( this.document, "mousedown" );

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

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

	_normalize: function( items ) {

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

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

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

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

		// Listen for interactions outside of the widget (#6642)
		this._on( this.document, {
			mousedown: "_closeOnClickOutside"
		} );
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(

			// Firefox wraps long text (possibly a rounding bug)
			// so we add 1px to avoid the wrapping (#7513)
			ul.width( "" ).outerWidth() + 1,
			this.element.outerWidth()
		) );
	},

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

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

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

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

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

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

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

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

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

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

	// Support: Chrome <=50
	// We should be able to just use this.element.prop( "isContentEditable" )
	// but hidden elements always report false in Chrome.
	// https://code.google.com/p/chromium/issues/detail?id=313082
	_isContentEditable: function( element ) {
		if ( !element.length ) {
			return false;
		}

		var editable = element.prop( "contentEditable" );

		if ( editable === "inherit" ) {
		  return this._isContentEditable( element.parent() );
		}

		return editable === "true";
	}
} );

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

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

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

var widgetsAutocomplete = $.ui.autocomplete;




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

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

//>>label: Mouse
//>>group: Widgets
//>>description: Abstracts mouse-based interactions to assist in creating certain widgets.
//>>docs: http://api.jqueryui.com/mouse/



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

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

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

		this.started = false;
	},

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

	_mouseDown: function( event ) {

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

		this._mouseMoved = false;

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

		this._mouseDownEvent = event;

		var that = this,
			btnIsLeft = ( event.which === 1 ),

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

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

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

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

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

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

		event.preventDefault();

		mouseHandled = true;
		return true;
	},

	_mouseMove: function( event ) {

		// Only check for mouseups outside the document if you've moved inside the document
		// at least once. This prevents the firing of mouseup in the case of IE<9, which will
		// fire a mousemove event if content is placed under the cursor. See #7778
		// Support: IE <9
		if ( this._mouseMoved ) {

			// IE mouseup check - mouseup happened when mouse was out of window
			if ( $.ui.ie && ( !document.documentMode || document.documentMode < 9 ) &&
					!event.button ) {
				return this._mouseUp( event );

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

				// Support: Safari <=8 - 9
				// Safari sets which to 0 if you press any of the following keys
				// during a drag (#14461)
				if ( event.originalEvent.altKey || event.originalEvent.ctrlKey ||
						event.originalEvent.metaKey || event.originalEvent.shiftKey ) {
					this.ignoreMissingWhich = true;
				} else if ( !this.ignoreMissingWhich ) {
					return this._mouseUp( event );
				}
			}
		}

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

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

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

		return !this._mouseStarted;
	},

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

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

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

			this._mouseStop( event );
		}

		if ( this._mouseDelayTimer ) {
			clearTimeout( this._mouseDelayTimer );
			delete this._mouseDelayTimer;
		}

		this.ignoreMissingWhich = false;
		mouseHandled = false;
		event.preventDefault();
	},

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

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

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


/*!
 * jQuery UI Slider 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Slider
//>>group: Widgets
//>>description: Displays a flexible slider with ranges and accessibility via keyboard.
//>>docs: http://api.jqueryui.com/slider/
//>>demos: http://jqueryui.com/slider/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/slider.css
//>>css.theme: ../../themes/base/theme.css



var widgetsSlider = $.widget( "ui.slider", $.ui.mouse, {
	version: "1.12.0",
	widgetEventPrefix: "slide",

	options: {
		animate: false,
		classes: {
			"ui-slider": "ui-corner-all",
			"ui-slider-handle": "ui-corner-all",

			// Note: ui-widget-header isn't the most fittingly semantic framework class for this
			// element, but worked best visually with a variety of themes
			"ui-slider-range": "ui-corner-all ui-widget-header"
		},
		distance: 0,
		max: 100,
		min: 0,
		orientation: "horizontal",
		range: false,
		step: 1,
		value: 0,
		values: null,

		// Callbacks
		change: null,
		slide: null,
		start: null,
		stop: null
	},

	// Number of pages in a slider
	// (how many times can you page up/down to go through the whole range)
	numPages: 5,

	_create: function() {
		this._keySliding = false;
		this._mouseSliding = false;
		this._animateOff = true;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();
		this._calculateNewMax();

		this._addClass( "ui-slider ui-slider-" + this.orientation,
			"ui-widget ui-widget-content" );

		this._refresh();

		this._animateOff = false;
	},

	_refresh: function() {
		this._createRange();
		this._createHandles();
		this._setupEvents();
		this._refreshValue();
	},

	_createHandles: function() {
		var i, handleCount,
			options = this.options,
			existingHandles = this.element.find( ".ui-slider-handle" ),
			handle = "<span tabindex='0'></span>",
			handles = [];

		handleCount = ( options.values && options.values.length ) || 1;

		if ( existingHandles.length > handleCount ) {
			existingHandles.slice( handleCount ).remove();
			existingHandles = existingHandles.slice( 0, handleCount );
		}

		for ( i = existingHandles.length; i < handleCount; i++ ) {
			handles.push( handle );
		}

		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );

		this._addClass( this.handles, "ui-slider-handle", "ui-state-default" );

		this.handle = this.handles.eq( 0 );

		this.handles.each( function( i ) {
			$( this ).data( "ui-slider-handle-index", i );
		} );
	},

	_createRange: function() {
		var options = this.options;

		if ( options.range ) {
			if ( options.range === true ) {
				if ( !options.values ) {
					options.values = [ this._valueMin(), this._valueMin() ];
				} else if ( options.values.length && options.values.length !== 2 ) {
					options.values = [ options.values[ 0 ], options.values[ 0 ] ];
				} else if ( $.isArray( options.values ) ) {
					options.values = options.values.slice( 0 );
				}
			}

			if ( !this.range || !this.range.length ) {
				this.range = $( "<div>" )
					.appendTo( this.element );

				this._addClass( this.range, "ui-slider-range" );
			} else {
				this._removeClass( this.range, "ui-slider-range-min ui-slider-range-max" );

				// Handle range switching from true to min/max
				this.range.css( {
					"left": "",
					"bottom": ""
				} );
			}
			if ( options.range === "min" || options.range === "max" ) {
				this._addClass( this.range, "ui-slider-range-" + options.range );
			}
		} else {
			if ( this.range ) {
				this.range.remove();
			}
			this.range = null;
		}
	},

	_setupEvents: function() {
		this._off( this.handles );
		this._on( this.handles, this._handleEvents );
		this._hoverable( this.handles );
		this._focusable( this.handles );
	},

	_destroy: function() {
		this.handles.remove();
		if ( this.range ) {
			this.range.remove();
		}

		this._mouseDestroy();
	},

	_mouseCapture: function( event ) {
		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
			that = this,
			o = this.options;

		if ( o.disabled ) {
			return false;
		}

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		position = { x: event.pageX, y: event.pageY };
		normValue = this._normValueFromMouse( position );
		distance = this._valueMax() - this._valueMin() + 1;
		this.handles.each( function( i ) {
			var thisDistance = Math.abs( normValue - that.values( i ) );
			if ( ( distance > thisDistance ) ||
				( distance === thisDistance &&
					( i === that._lastChangedValue || that.values( i ) === o.min ) ) ) {
				distance = thisDistance;
				closestHandle = $( this );
				index = i;
			}
		} );

		allowed = this._start( event, index );
		if ( allowed === false ) {
			return false;
		}
		this._mouseSliding = true;

		this._handleIndex = index;

		this._addClass( closestHandle, null, "ui-state-active" );
		closestHandle.trigger( "focus" );

		offset = closestHandle.offset();
		mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" );
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
			top: event.pageY - offset.top -
				( closestHandle.height() / 2 ) -
				( parseInt( closestHandle.css( "borderTopWidth" ), 10 ) || 0 ) -
				( parseInt( closestHandle.css( "borderBottomWidth" ), 10 ) || 0 ) +
				( parseInt( closestHandle.css( "marginTop" ), 10 ) || 0 )
		};

		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
			this._slide( event, index, normValue );
		}
		this._animateOff = true;
		return true;
	},

	_mouseStart: function() {
		return true;
	},

	_mouseDrag: function( event ) {
		var position = { x: event.pageX, y: event.pageY },
			normValue = this._normValueFromMouse( position );

		this._slide( event, this._handleIndex, normValue );

		return false;
	},

	_mouseStop: function( event ) {
		this._removeClass( this.handles, null, "ui-state-active" );
		this._mouseSliding = false;

		this._stop( event, this._handleIndex );
		this._change( event, this._handleIndex );

		this._handleIndex = null;
		this._clickOffset = null;
		this._animateOff = false;

		return false;
	},

	_detectOrientation: function() {
		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
	},

	_normValueFromMouse: function( position ) {
		var pixelTotal,
			pixelMouse,
			percentMouse,
			valueTotal,
			valueMouse;

		if ( this.orientation === "horizontal" ) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left -
				( this._clickOffset ? this._clickOffset.left : 0 );
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top -
				( this._clickOffset ? this._clickOffset.top : 0 );
		}

		percentMouse = ( pixelMouse / pixelTotal );
		if ( percentMouse > 1 ) {
			percentMouse = 1;
		}
		if ( percentMouse < 0 ) {
			percentMouse = 0;
		}
		if ( this.orientation === "vertical" ) {
			percentMouse = 1 - percentMouse;
		}

		valueTotal = this._valueMax() - this._valueMin();
		valueMouse = this._valueMin() + percentMouse * valueTotal;

		return this._trimAlignValue( valueMouse );
	},

	_uiHash: function( index, value, values ) {
		var uiHash = {
			handle: this.handles[ index ],
			handleIndex: index,
			value: value !== undefined ? value : this.value()
		};

		if ( this._hasMultipleValues() ) {
			uiHash.value = value !== undefined ? value : this.values( index );
			uiHash.values = values || this.values();
		}

		return uiHash;
	},

	_hasMultipleValues: function() {
		return this.options.values && this.options.values.length;
	},

	_start: function( event, index ) {
		return this._trigger( "start", event, this._uiHash( index ) );
	},

	_slide: function( event, index, newVal ) {
		var allowed, otherVal,
			currentValue = this.value(),
			newValues = this.values();

		if ( this._hasMultipleValues() ) {
			otherVal = this.values( index ? 0 : 1 );
			currentValue = this.values( index );

			if ( this.options.values.length === 2 && this.options.range === true ) {
				newVal =  index === 0 ? Math.min( otherVal, newVal ) : Math.max( otherVal, newVal );
			}

			newValues[ index ] = newVal;
		}

		if ( newVal === currentValue ) {
			return;
		}

		allowed = this._trigger( "slide", event, this._uiHash( index, newVal, newValues ) );

		// A slide can be canceled by returning false from the slide callback
		if ( allowed === false ) {
			return;
		}

		if ( this._hasMultipleValues() ) {
			this.values( index, newVal );
		} else {
			this.value( newVal );
		}
	},

	_stop: function( event, index ) {
		this._trigger( "stop", event, this._uiHash( index ) );
	},

	_change: function( event, index ) {
		if ( !this._keySliding && !this._mouseSliding ) {

			//store the last changed value index for reference when handles overlap
			this._lastChangedValue = index;
			this._trigger( "change", event, this._uiHash( index ) );
		}
	},

	value: function( newValue ) {
		if ( arguments.length ) {
			this.options.value = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, 0 );
			return;
		}

		return this._value();
	},

	values: function( index, newValue ) {
		var vals,
			newValues,
			i;

		if ( arguments.length > 1 ) {
			this.options.values[ index ] = this._trimAlignValue( newValue );
			this._refreshValue();
			this._change( null, index );
			return;
		}

		if ( arguments.length ) {
			if ( $.isArray( arguments[ 0 ] ) ) {
				vals = this.options.values;
				newValues = arguments[ 0 ];
				for ( i = 0; i < vals.length; i += 1 ) {
					vals[ i ] = this._trimAlignValue( newValues[ i ] );
					this._change( null, i );
				}
				this._refreshValue();
			} else {
				if ( this._hasMultipleValues() ) {
					return this._values( index );
				} else {
					return this.value();
				}
			}
		} else {
			return this._values();
		}
	},

	_setOption: function( key, value ) {
		var i,
			valsLength = 0;

		if ( key === "range" && this.options.range === true ) {
			if ( value === "min" ) {
				this.options.value = this._values( 0 );
				this.options.values = null;
			} else if ( value === "max" ) {
				this.options.value = this._values( this.options.values.length - 1 );
				this.options.values = null;
			}
		}

		if ( $.isArray( this.options.values ) ) {
			valsLength = this.options.values.length;
		}

		this._super( key, value );

		switch ( key ) {
			case "orientation":
				this._detectOrientation();
				this._removeClass( "ui-slider-horizontal ui-slider-vertical" )
					._addClass( "ui-slider-" + this.orientation );
				this._refreshValue();
				if ( this.options.range ) {
					this._refreshRange( value );
				}

				// Reset positioning from previous orientation
				this.handles.css( value === "horizontal" ? "bottom" : "left", "" );
				break;
			case "value":
				this._animateOff = true;
				this._refreshValue();
				this._change( null, 0 );
				this._animateOff = false;
				break;
			case "values":
				this._animateOff = true;
				this._refreshValue();

				// Start from the last handle to prevent unreachable handles (#9046)
				for ( i = valsLength - 1; i >= 0; i-- ) {
					this._change( null, i );
				}
				this._animateOff = false;
				break;
			case "step":
			case "min":
			case "max":
				this._animateOff = true;
				this._calculateNewMax();
				this._refreshValue();
				this._animateOff = false;
				break;
			case "range":
				this._animateOff = true;
				this._refresh();
				this._animateOff = false;
				break;
		}
	},

	_setOptionDisabled: function( value ) {
		this._super( value );

		this._toggleClass( null, "ui-state-disabled", !!value );
	},

	//internal value getter
	// _value() returns value trimmed by min and max, aligned by step
	_value: function() {
		var val = this.options.value;
		val = this._trimAlignValue( val );

		return val;
	},

	//internal values getter
	// _values() returns array of values trimmed by min and max, aligned by step
	// _values( index ) returns single value trimmed by min and max, aligned by step
	_values: function( index ) {
		var val,
			vals,
			i;

		if ( arguments.length ) {
			val = this.options.values[ index ];
			val = this._trimAlignValue( val );

			return val;
		} else if ( this._hasMultipleValues() ) {

			// .slice() creates a copy of the array
			// this copy gets trimmed by min and max and then returned
			vals = this.options.values.slice();
			for ( i = 0; i < vals.length; i += 1 ) {
				vals[ i ] = this._trimAlignValue( vals[ i ] );
			}

			return vals;
		} else {
			return [];
		}
	},

	// Returns the step-aligned value that val is closest to, between (inclusive) min and max
	_trimAlignValue: function( val ) {
		if ( val <= this._valueMin() ) {
			return this._valueMin();
		}
		if ( val >= this._valueMax() ) {
			return this._valueMax();
		}
		var step = ( this.options.step > 0 ) ? this.options.step : 1,
			valModStep = ( val - this._valueMin() ) % step,
			alignValue = val - valModStep;

		if ( Math.abs( valModStep ) * 2 >= step ) {
			alignValue += ( valModStep > 0 ) ? step : ( -step );
		}

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat( alignValue.toFixed( 5 ) );
	},

	_calculateNewMax: function() {
		var max = this.options.max,
			min = this._valueMin(),
			step = this.options.step,
			aboveMin = Math.round( ( max - min ) / step ) * step;
		max = aboveMin + min;
		if ( max > this.options.max ) {

			//If max is not divisible by step, rounding off may increase its value
			max -= step;
		}
		this.max = parseFloat( max.toFixed( this._precision() ) );
	},

	_precision: function() {
		var precision = this._precisionOf( this.options.step );
		if ( this.options.min !== null ) {
			precision = Math.max( precision, this._precisionOf( this.options.min ) );
		}
		return precision;
	},

	_precisionOf: function( num ) {
		var str = num.toString(),
			decimal = str.indexOf( "." );
		return decimal === -1 ? 0 : str.length - decimal - 1;
	},

	_valueMin: function() {
		return this.options.min;
	},

	_valueMax: function() {
		return this.max;
	},

	_refreshRange: function( orientation ) {
		if ( orientation === "vertical" ) {
			this.range.css( { "width": "", "left": "" } );
		}
		if ( orientation === "horizontal" ) {
			this.range.css( { "height": "", "bottom": "" } );
		}
	},

	_refreshValue: function() {
		var lastValPercent, valPercent, value, valueMin, valueMax,
			oRange = this.options.range,
			o = this.options,
			that = this,
			animate = ( !this._animateOff ) ? o.animate : false,
			_set = {};

		if ( this._hasMultipleValues() ) {
			this.handles.each( function( i ) {
				valPercent = ( that.values( i ) - that._valueMin() ) / ( that._valueMax() -
					that._valueMin() ) * 100;
				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
				if ( that.options.range === true ) {
					if ( that.orientation === "horizontal" ) {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								left: valPercent + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								width: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					} else {
						if ( i === 0 ) {
							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
								bottom: ( valPercent ) + "%"
							}, o.animate );
						}
						if ( i === 1 ) {
							that.range[ animate ? "animate" : "css" ]( {
								height: ( valPercent - lastValPercent ) + "%"
							}, {
								queue: false,
								duration: o.animate
							} );
						}
					}
				}
				lastValPercent = valPercent;
			} );
		} else {
			value = this.value();
			valueMin = this._valueMin();
			valueMax = this._valueMax();
			valPercent = ( valueMax !== valueMin ) ?
					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
					0;
			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );

			if ( oRange === "min" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "horizontal" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					width: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
			if ( oRange === "min" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: valPercent + "%"
				}, o.animate );
			}
			if ( oRange === "max" && this.orientation === "vertical" ) {
				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( {
					height: ( 100 - valPercent ) + "%"
				}, o.animate );
			}
		}
	},

	_handleEvents: {
		keydown: function( event ) {
			var allowed, curVal, newVal, step,
				index = $( event.target ).data( "ui-slider-handle-index" );

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.PAGE_UP:
				case $.ui.keyCode.PAGE_DOWN:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					event.preventDefault();
					if ( !this._keySliding ) {
						this._keySliding = true;
						this._addClass( $( event.target ), null, "ui-state-active" );
						allowed = this._start( event, index );
						if ( allowed === false ) {
							return;
						}
					}
					break;
			}

			step = this.options.step;
			if ( this._hasMultipleValues() ) {
				curVal = newVal = this.values( index );
			} else {
				curVal = newVal = this.value();
			}

			switch ( event.keyCode ) {
				case $.ui.keyCode.HOME:
					newVal = this._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = this._valueMax();
					break;
				case $.ui.keyCode.PAGE_UP:
					newVal = this._trimAlignValue(
						curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages )
					);
					break;
				case $.ui.keyCode.PAGE_DOWN:
					newVal = this._trimAlignValue(
						curVal - ( ( this._valueMax() - this._valueMin() ) / this.numPages ) );
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if ( curVal === this._valueMax() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal + step );
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if ( curVal === this._valueMin() ) {
						return;
					}
					newVal = this._trimAlignValue( curVal - step );
					break;
			}

			this._slide( event, index, newVal );
		},
		keyup: function( event ) {
			var index = $( event.target ).data( "ui-slider-handle-index" );

			if ( this._keySliding ) {
				this._keySliding = false;
				this._stop( event, index );
				this._change( event, index );
				this._removeClass( $( event.target ), null, "ui-state-active" );
			}
		}
	}
} );


/*!
 * jQuery UI Effects 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Effects Core
//>>group: Effects
// jscs:disable maximumLineLength
//>>description: Extends the internal jQuery effects. Includes morphing and easing. Required by all other effects.
// jscs:enable maximumLineLength
//>>docs: http://api.jqueryui.com/category/effects-core/
//>>demos: http://jqueryui.com/effect/



var dataSpace = "ui-effects-",
	dataSpaceStyle = "ui-effects-style",
	dataSpaceAnimated = "ui-effects-animated",

	// Create a local jQuery because jQuery Color relies on it and the
	// global may not exist with AMD and a custom build (#10199)
	jQuery = $;

$.effects = {
	effect: {}
};

/*!
 * jQuery Color Animations v2.1.2
 * https://github.com/jquery/jquery-color
 *
 * Copyright 2014 jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 *
 * Date: Wed Jan 16 08:47:09 2013 -0600
 */
( function( jQuery, undefined ) {

	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor " +
		"borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",

	// Plusequals test for += 100 -= 100
	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,

	// A set of RE's that can match strings and generate color tuples.
	stringParsers = [ {
			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ],
					execResult[ 3 ],
					execResult[ 4 ]
				];
			}
		}, {
			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			parse: function( execResult ) {
				return [
					execResult[ 1 ] * 2.55,
					execResult[ 2 ] * 2.55,
					execResult[ 3 ] * 2.55,
					execResult[ 4 ]
				];
			}
		}, {

			// This regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ], 16 )
				];
			}
		}, {

			// This regex ignores A-F because it's compared against an already lowercased string
			re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
			parse: function( execResult ) {
				return [
					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
				];
			}
		}, {
			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/,
			space: "hsla",
			parse: function( execResult ) {
				return [
					execResult[ 1 ],
					execResult[ 2 ] / 100,
					execResult[ 3 ] / 100,
					execResult[ 4 ]
				];
			}
		} ],

	// JQuery.Color( )
	color = jQuery.Color = function( color, green, blue, alpha ) {
		return new jQuery.Color.fn.parse( color, green, blue, alpha );
	},
	spaces = {
		rgba: {
			props: {
				red: {
					idx: 0,
					type: "byte"
				},
				green: {
					idx: 1,
					type: "byte"
				},
				blue: {
					idx: 2,
					type: "byte"
				}
			}
		},

		hsla: {
			props: {
				hue: {
					idx: 0,
					type: "degrees"
				},
				saturation: {
					idx: 1,
					type: "percent"
				},
				lightness: {
					idx: 2,
					type: "percent"
				}
			}
		}
	},
	propTypes = {
		"byte": {
			floor: true,
			max: 255
		},
		"percent": {
			max: 1
		},
		"degrees": {
			mod: 360,
			floor: true
		}
	},
	support = color.support = {},

	// Element for support tests
	supportElem = jQuery( "<p>" )[ 0 ],

	// Colors = jQuery.Color.names
	colors,

	// Local aliases of functions called often
	each = jQuery.each;

// Determine rgba support immediately
supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;

// Define cache name and alpha properties
// for rgba and hsla spaces
each( spaces, function( spaceName, space ) {
	space.cache = "_" + spaceName;
	space.props.alpha = {
		idx: 3,
		type: "percent",
		def: 1
	};
} );

function clamp( value, prop, allowEmpty ) {
	var type = propTypes[ prop.type ] || {};

	if ( value == null ) {
		return ( allowEmpty || !prop.def ) ? null : prop.def;
	}

	// ~~ is an short way of doing floor for positive numbers
	value = type.floor ? ~~value : parseFloat( value );

	// IE will pass in empty strings as value for alpha,
	// which will hit this case
	if ( isNaN( value ) ) {
		return prop.def;
	}

	if ( type.mod ) {

		// We add mod before modding to make sure that negatives values
		// get converted properly: -10 -> 350
		return ( value + type.mod ) % type.mod;
	}

	// For now all property types without mod have min and max
	return 0 > value ? 0 : type.max < value ? type.max : value;
}

function stringParse( string ) {
	var inst = color(),
		rgba = inst._rgba = [];

	string = string.toLowerCase();

	each( stringParsers, function( i, parser ) {
		var parsed,
			match = parser.re.exec( string ),
			values = match && parser.parse( match ),
			spaceName = parser.space || "rgba";

		if ( values ) {
			parsed = inst[ spaceName ]( values );

			// If this was an rgba parse the assignment might happen twice
			// oh well....
			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
			rgba = inst._rgba = parsed._rgba;

			// Exit each( stringParsers ) here because we matched
			return false;
		}
	} );

	// Found a stringParser that handled it
	if ( rgba.length ) {

		// If this came from a parsed string, force "transparent" when alpha is 0
		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
		if ( rgba.join() === "0,0,0,0" ) {
			jQuery.extend( rgba, colors.transparent );
		}
		return inst;
	}

	// Named colors
	return colors[ string ];
}

color.fn = jQuery.extend( color.prototype, {
	parse: function( red, green, blue, alpha ) {
		if ( red === undefined ) {
			this._rgba = [ null, null, null, null ];
			return this;
		}
		if ( red.jquery || red.nodeType ) {
			red = jQuery( red ).css( green );
			green = undefined;
		}

		var inst = this,
			type = jQuery.type( red ),
			rgba = this._rgba = [];

		// More than 1 argument specified - assume ( red, green, blue, alpha )
		if ( green !== undefined ) {
			red = [ red, green, blue, alpha ];
			type = "array";
		}

		if ( type === "string" ) {
			return this.parse( stringParse( red ) || colors._default );
		}

		if ( type === "array" ) {
			each( spaces.rgba.props, function( key, prop ) {
				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
			} );
			return this;
		}

		if ( type === "object" ) {
			if ( red instanceof color ) {
				each( spaces, function( spaceName, space ) {
					if ( red[ space.cache ] ) {
						inst[ space.cache ] = red[ space.cache ].slice();
					}
				} );
			} else {
				each( spaces, function( spaceName, space ) {
					var cache = space.cache;
					each( space.props, function( key, prop ) {

						// If the cache doesn't exist, and we know how to convert
						if ( !inst[ cache ] && space.to ) {

							// If the value was null, we don't need to copy it
							// if the key was alpha, we don't need to copy it either
							if ( key === "alpha" || red[ key ] == null ) {
								return;
							}
							inst[ cache ] = space.to( inst._rgba );
						}

						// This is the only case where we allow nulls for ALL properties.
						// call clamp with alwaysAllowEmpty
						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
					} );

					// Everything defined but alpha?
					if ( inst[ cache ] &&
							jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {

						// Use the default of 1
						inst[ cache ][ 3 ] = 1;
						if ( space.from ) {
							inst._rgba = space.from( inst[ cache ] );
						}
					}
				} );
			}
			return this;
		}
	},
	is: function( compare ) {
		var is = color( compare ),
			same = true,
			inst = this;

		each( spaces, function( _, space ) {
			var localCache,
				isCache = is[ space.cache ];
			if ( isCache ) {
				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
				each( space.props, function( _, prop ) {
					if ( isCache[ prop.idx ] != null ) {
						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
						return same;
					}
				} );
			}
			return same;
		} );
		return same;
	},
	_space: function() {
		var used = [],
			inst = this;
		each( spaces, function( spaceName, space ) {
			if ( inst[ space.cache ] ) {
				used.push( spaceName );
			}
		} );
		return used.pop();
	},
	transition: function( other, distance ) {
		var end = color( other ),
			spaceName = end._space(),
			space = spaces[ spaceName ],
			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
			start = startColor[ space.cache ] || space.to( startColor._rgba ),
			result = start.slice();

		end = end[ space.cache ];
		each( space.props, function( key, prop ) {
			var index = prop.idx,
				startValue = start[ index ],
				endValue = end[ index ],
				type = propTypes[ prop.type ] || {};

			// If null, don't override start value
			if ( endValue === null ) {
				return;
			}

			// If null - use end
			if ( startValue === null ) {
				result[ index ] = endValue;
			} else {
				if ( type.mod ) {
					if ( endValue - startValue > type.mod / 2 ) {
						startValue += type.mod;
					} else if ( startValue - endValue > type.mod / 2 ) {
						startValue -= type.mod;
					}
				}
				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
			}
		} );
		return this[ spaceName ]( result );
	},
	blend: function( opaque ) {

		// If we are already opaque - return ourself
		if ( this._rgba[ 3 ] === 1 ) {
			return this;
		}

		var rgb = this._rgba.slice(),
			a = rgb.pop(),
			blend = color( opaque )._rgba;

		return color( jQuery.map( rgb, function( v, i ) {
			return ( 1 - a ) * blend[ i ] + a * v;
		} ) );
	},
	toRgbaString: function() {
		var prefix = "rgba(",
			rgba = jQuery.map( this._rgba, function( v, i ) {
				return v == null ? ( i > 2 ? 1 : 0 ) : v;
			} );

		if ( rgba[ 3 ] === 1 ) {
			rgba.pop();
			prefix = "rgb(";
		}

		return prefix + rgba.join() + ")";
	},
	toHslaString: function() {
		var prefix = "hsla(",
			hsla = jQuery.map( this.hsla(), function( v, i ) {
				if ( v == null ) {
					v = i > 2 ? 1 : 0;
				}

				// Catch 1 and 2
				if ( i && i < 3 ) {
					v = Math.round( v * 100 ) + "%";
				}
				return v;
			} );

		if ( hsla[ 3 ] === 1 ) {
			hsla.pop();
			prefix = "hsl(";
		}
		return prefix + hsla.join() + ")";
	},
	toHexString: function( includeAlpha ) {
		var rgba = this._rgba.slice(),
			alpha = rgba.pop();

		if ( includeAlpha ) {
			rgba.push( ~~( alpha * 255 ) );
		}

		return "#" + jQuery.map( rgba, function( v ) {

			// Default to 0 when nulls exist
			v = ( v || 0 ).toString( 16 );
			return v.length === 1 ? "0" + v : v;
		} ).join( "" );
	},
	toString: function() {
		return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
	}
} );
color.fn.parse.prototype = color.fn;

// Hsla conversions adapted from:
// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021

function hue2rgb( p, q, h ) {
	h = ( h + 1 ) % 1;
	if ( h * 6 < 1 ) {
		return p + ( q - p ) * h * 6;
	}
	if ( h * 2 < 1 ) {
		return q;
	}
	if ( h * 3 < 2 ) {
		return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6;
	}
	return p;
}

spaces.hsla.to = function( rgba ) {
	if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
		return [ null, null, null, rgba[ 3 ] ];
	}
	var r = rgba[ 0 ] / 255,
		g = rgba[ 1 ] / 255,
		b = rgba[ 2 ] / 255,
		a = rgba[ 3 ],
		max = Math.max( r, g, b ),
		min = Math.min( r, g, b ),
		diff = max - min,
		add = max + min,
		l = add * 0.5,
		h, s;

	if ( min === max ) {
		h = 0;
	} else if ( r === max ) {
		h = ( 60 * ( g - b ) / diff ) + 360;
	} else if ( g === max ) {
		h = ( 60 * ( b - r ) / diff ) + 120;
	} else {
		h = ( 60 * ( r - g ) / diff ) + 240;
	}

	// Chroma (diff) == 0 means greyscale which, by definition, saturation = 0%
	// otherwise, saturation is based on the ratio of chroma (diff) to lightness (add)
	if ( diff === 0 ) {
		s = 0;
	} else if ( l <= 0.5 ) {
		s = diff / add;
	} else {
		s = diff / ( 2 - add );
	}
	return [ Math.round( h ) % 360, s, l, a == null ? 1 : a ];
};

spaces.hsla.from = function( hsla ) {
	if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
		return [ null, null, null, hsla[ 3 ] ];
	}
	var h = hsla[ 0 ] / 360,
		s = hsla[ 1 ],
		l = hsla[ 2 ],
		a = hsla[ 3 ],
		q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
		p = 2 * l - q;

	return [
		Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
		Math.round( hue2rgb( p, q, h ) * 255 ),
		Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
		a
	];
};

each( spaces, function( spaceName, space ) {
	var props = space.props,
		cache = space.cache,
		to = space.to,
		from = space.from;

	// Makes rgba() and hsla()
	color.fn[ spaceName ] = function( value ) {

		// Generate a cache for this space if it doesn't exist
		if ( to && !this[ cache ] ) {
			this[ cache ] = to( this._rgba );
		}
		if ( value === undefined ) {
			return this[ cache ].slice();
		}

		var ret,
			type = jQuery.type( value ),
			arr = ( type === "array" || type === "object" ) ? value : arguments,
			local = this[ cache ].slice();

		each( props, function( key, prop ) {
			var val = arr[ type === "object" ? key : prop.idx ];
			if ( val == null ) {
				val = local[ prop.idx ];
			}
			local[ prop.idx ] = clamp( val, prop );
		} );

		if ( from ) {
			ret = color( from( local ) );
			ret[ cache ] = local;
			return ret;
		} else {
			return color( local );
		}
	};

	// Makes red() green() blue() alpha() hue() saturation() lightness()
	each( props, function( key, prop ) {

		// Alpha is included in more than one space
		if ( color.fn[ key ] ) {
			return;
		}
		color.fn[ key ] = function( value ) {
			var vtype = jQuery.type( value ),
				fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
				local = this[ fn ](),
				cur = local[ prop.idx ],
				match;

			if ( vtype === "undefined" ) {
				return cur;
			}

			if ( vtype === "function" ) {
				value = value.call( this, cur );
				vtype = jQuery.type( value );
			}
			if ( value == null && prop.empty ) {
				return this;
			}
			if ( vtype === "string" ) {
				match = rplusequals.exec( value );
				if ( match ) {
					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
				}
			}
			local[ prop.idx ] = value;
			return this[ fn ]( local );
		};
	} );
} );

// Add cssHook and .fx.step function for each named hook.
// accept a space separated string of properties
color.hook = function( hook ) {
	var hooks = hook.split( " " );
	each( hooks, function( i, hook ) {
		jQuery.cssHooks[ hook ] = {
			set: function( elem, value ) {
				var parsed, curElem,
					backgroundColor = "";

				if ( value !== "transparent" && ( jQuery.type( value ) !== "string" ||
						( parsed = stringParse( value ) ) ) ) {
					value = color( parsed || value );
					if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
						curElem = hook === "backgroundColor" ? elem.parentNode : elem;
						while (
							( backgroundColor === "" || backgroundColor === "transparent" ) &&
							curElem && curElem.style
						) {
							try {
								backgroundColor = jQuery.css( curElem, "backgroundColor" );
								curElem = curElem.parentNode;
							} catch ( e ) {
							}
						}

						value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
							backgroundColor :
							"_default" );
					}

					value = value.toRgbaString();
				}
				try {
					elem.style[ hook ] = value;
				} catch ( e ) {

					// Wrapped to prevent IE from throwing errors on "invalid" values like
					// 'auto' or 'inherit'
				}
			}
		};
		jQuery.fx.step[ hook ] = function( fx ) {
			if ( !fx.colorInit ) {
				fx.start = color( fx.elem, hook );
				fx.end = color( fx.end );
				fx.colorInit = true;
			}
			jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
		};
	} );

};

color.hook( stepHooks );

jQuery.cssHooks.borderColor = {
	expand: function( value ) {
		var expanded = {};

		each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
			expanded[ "border" + part + "Color" ] = value;
		} );
		return expanded;
	}
};

// Basic color names only.
// Usage of any of the other color names requires adding yourself or including
// jquery.color.svg-names.js.
colors = jQuery.Color.names = {

	// 4.1. Basic color keywords
	aqua: "#00ffff",
	black: "#000000",
	blue: "#0000ff",
	fuchsia: "#ff00ff",
	gray: "#808080",
	green: "#008000",
	lime: "#00ff00",
	maroon: "#800000",
	navy: "#000080",
	olive: "#808000",
	purple: "#800080",
	red: "#ff0000",
	silver: "#c0c0c0",
	teal: "#008080",
	white: "#ffffff",
	yellow: "#ffff00",

	// 4.2.3. "transparent" color keyword
	transparent: [ null, null, null, 0 ],

	_default: "#ffffff"
};

} )( jQuery );

/******************************************************************************/
/****************************** CLASS ANIMATIONS ******************************/
/******************************************************************************/
( function() {

var classAnimationActions = [ "add", "remove", "toggle" ],
	shorthandStyles = {
		border: 1,
		borderBottom: 1,
		borderColor: 1,
		borderLeft: 1,
		borderRight: 1,
		borderTop: 1,
		borderWidth: 1,
		margin: 1,
		padding: 1
	};

$.each(
	[ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ],
	function( _, prop ) {
		$.fx.step[ prop ] = function( fx ) {
			if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
				jQuery.style( fx.elem, prop, fx.end );
				fx.setAttr = true;
			}
		};
	}
);

function getElementStyles( elem ) {
	var key, len,
		style = elem.ownerDocument.defaultView ?
			elem.ownerDocument.defaultView.getComputedStyle( elem, null ) :
			elem.currentStyle,
		styles = {};

	if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
		len = style.length;
		while ( len-- ) {
			key = style[ len ];
			if ( typeof style[ key ] === "string" ) {
				styles[ $.camelCase( key ) ] = style[ key ];
			}
		}

	// Support: Opera, IE <9
	} else {
		for ( key in style ) {
			if ( typeof style[ key ] === "string" ) {
				styles[ key ] = style[ key ];
			}
		}
	}

	return styles;
}

function styleDifference( oldStyle, newStyle ) {
	var diff = {},
		name, value;

	for ( name in newStyle ) {
		value = newStyle[ name ];
		if ( oldStyle[ name ] !== value ) {
			if ( !shorthandStyles[ name ] ) {
				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
					diff[ name ] = value;
				}
			}
		}
	}

	return diff;
}

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

$.effects.animateClass = function( value, duration, easing, callback ) {
	var o = $.speed( duration, easing, callback );

	return this.queue( function() {
		var animated = $( this ),
			baseClass = animated.attr( "class" ) || "",
			applyClassChange,
			allAnimations = o.children ? animated.find( "*" ).addBack() : animated;

		// Map the animated objects to store the original styles.
		allAnimations = allAnimations.map( function() {
			var el = $( this );
			return {
				el: el,
				start: getElementStyles( this )
			};
		} );

		// Apply class change
		applyClassChange = function() {
			$.each( classAnimationActions, function( i, action ) {
				if ( value[ action ] ) {
					animated[ action + "Class" ]( value[ action ] );
				}
			} );
		};
		applyClassChange();

		// Map all animated objects again - calculate new styles and diff
		allAnimations = allAnimations.map( function() {
			this.end = getElementStyles( this.el[ 0 ] );
			this.diff = styleDifference( this.start, this.end );
			return this;
		} );

		// Apply original class
		animated.attr( "class", baseClass );

		// Map all animated objects again - this time collecting a promise
		allAnimations = allAnimations.map( function() {
			var styleInfo = this,
				dfd = $.Deferred(),
				opts = $.extend( {}, o, {
					queue: false,
					complete: function() {
						dfd.resolve( styleInfo );
					}
				} );

			this.el.animate( this.diff, opts );
			return dfd.promise();
		} );

		// Once all animations have completed:
		$.when.apply( $, allAnimations.get() ).done( function() {

			// Set the final class
			applyClassChange();

			// For each animated element,
			// clear all css properties that were animated
			$.each( arguments, function() {
				var el = this.el;
				$.each( this.diff, function( key ) {
					el.css( key, "" );
				} );
			} );

			// This is guarnteed to be there if you use jQuery.speed()
			// it also handles dequeuing the next anim...
			o.complete.call( animated[ 0 ] );
		} );
	} );
};

$.fn.extend( {
	addClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return speed ?
				$.effects.animateClass.call( this,
					{ add: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.addClass ),

	removeClass: ( function( orig ) {
		return function( classNames, speed, easing, callback ) {
			return arguments.length > 1 ?
				$.effects.animateClass.call( this,
					{ remove: classNames }, speed, easing, callback ) :
				orig.apply( this, arguments );
		};
	} )( $.fn.removeClass ),

	toggleClass: ( function( orig ) {
		return function( classNames, force, speed, easing, callback ) {
			if ( typeof force === "boolean" || force === undefined ) {
				if ( !speed ) {

					// Without speed parameter
					return orig.apply( this, arguments );
				} else {
					return $.effects.animateClass.call( this,
						( force ? { add: classNames } : { remove: classNames } ),
						speed, easing, callback );
				}
			} else {

				// Without force parameter
				return $.effects.animateClass.call( this,
					{ toggle: classNames }, force, speed, easing );
			}
		};
	} )( $.fn.toggleClass ),

	switchClass: function( remove, add, speed, easing, callback ) {
		return $.effects.animateClass.call( this, {
			add: add,
			remove: remove
		}, speed, easing, callback );
	}
} );

} )();

/******************************************************************************/
/*********************************** EFFECTS **********************************/
/******************************************************************************/

( function() {

if ( $.expr && $.expr.filters && $.expr.filters.animated ) {
	$.expr.filters.animated = ( function( orig ) {
		return function( elem ) {
			return !!$( elem ).data( dataSpaceAnimated ) || orig( elem );
		};
	} )( $.expr.filters.animated );
}

if ( $.uiBackCompat !== false ) {
	$.extend( $.effects, {

		// Saves a set of properties in a data storage
		save: function( element, set ) {
			var i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
				}
			}
		},

		// Restores a set of previously saved properties from a data storage
		restore: function( element, set ) {
			var val, i = 0, length = set.length;
			for ( ; i < length; i++ ) {
				if ( set[ i ] !== null ) {
					val = element.data( dataSpace + set[ i ] );
					element.css( set[ i ], val );
				}
			}
		},

		setMode: function( el, mode ) {
			if ( mode === "toggle" ) {
				mode = el.is( ":hidden" ) ? "show" : "hide";
			}
			return mode;
		},

		// Wraps the element around a wrapper that copies position properties
		createWrapper: function( element ) {

			// If the element is already wrapped, return it
			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				return element.parent();
			}

			// Wrap the element
			var props = {
					width: element.outerWidth( true ),
					height: element.outerHeight( true ),
					"float": element.css( "float" )
				},
				wrapper = $( "<div></div>" )
					.addClass( "ui-effects-wrapper" )
					.css( {
						fontSize: "100%",
						background: "transparent",
						border: "none",
						margin: 0,
						padding: 0
					} ),

				// Store the size in case width/height are defined in % - Fixes #5245
				size = {
					width: element.width(),
					height: element.height()
				},
				active = document.activeElement;

			// Support: Firefox
			// Firefox incorrectly exposes anonymous content
			// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
			try {
				active.id;
			} catch ( e ) {
				active = document.body;
			}

			element.wrap( wrapper );

			// Fixes #7595 - Elements lose focus when wrapped.
			if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
				$( active ).trigger( "focus" );
			}

			// Hotfix for jQuery 1.4 since some change in wrap() seems to actually
			// lose the reference to the wrapped element
			wrapper = element.parent();

			// Transfer positioning properties to the wrapper
			if ( element.css( "position" ) === "static" ) {
				wrapper.css( { position: "relative" } );
				element.css( { position: "relative" } );
			} else {
				$.extend( props, {
					position: element.css( "position" ),
					zIndex: element.css( "z-index" )
				} );
				$.each( [ "top", "left", "bottom", "right" ], function( i, pos ) {
					props[ pos ] = element.css( pos );
					if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
						props[ pos ] = "auto";
					}
				} );
				element.css( {
					position: "relative",
					top: 0,
					left: 0,
					right: "auto",
					bottom: "auto"
				} );
			}
			element.css( size );

			return wrapper.css( props ).show();
		},

		removeWrapper: function( element ) {
			var active = document.activeElement;

			if ( element.parent().is( ".ui-effects-wrapper" ) ) {
				element.parent().replaceWith( element );

				// Fixes #7595 - Elements lose focus when wrapped.
				if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
					$( active ).trigger( "focus" );
				}
			}

			return element;
		}
	} );
}

$.extend( $.effects, {
	version: "1.12.0",

	define: function( name, mode, effect ) {
		if ( !effect ) {
			effect = mode;
			mode = "effect";
		}

		$.effects.effect[ name ] = effect;
		$.effects.effect[ name ].mode = mode;

		return effect;
	},

	scaledDimensions: function( element, percent, direction ) {
		if ( percent === 0 ) {
			return {
				height: 0,
				width: 0,
				outerHeight: 0,
				outerWidth: 0
			};
		}

		var x = direction !== "horizontal" ? ( ( percent || 100 ) / 100 ) : 1,
			y = direction !== "vertical" ? ( ( percent || 100 ) / 100 ) : 1;

		return {
			height: element.height() * y,
			width: element.width() * x,
			outerHeight: element.outerHeight() * y,
			outerWidth: element.outerWidth() * x
		};

	},

	clipToBox: function( animation ) {
		return {
			width: animation.clip.right - animation.clip.left,
			height: animation.clip.bottom - animation.clip.top,
			left: animation.clip.left,
			top: animation.clip.top
		};
	},

	// Injects recently queued functions to be first in line (after "inprogress")
	unshift: function( element, queueLength, count ) {
		var queue = element.queue();

		if ( queueLength > 1 ) {
			queue.splice.apply( queue,
				[ 1, 0 ].concat( queue.splice( queueLength, count ) ) );
		}
		element.dequeue();
	},

	saveStyle: function( element ) {
		element.data( dataSpaceStyle, element[ 0 ].style.cssText );
	},

	restoreStyle: function( element ) {
		element[ 0 ].style.cssText = element.data( dataSpaceStyle ) || "";
		element.removeData( dataSpaceStyle );
	},

	mode: function( element, mode ) {
		var hidden = element.is( ":hidden" );

		if ( mode === "toggle" ) {
			mode = hidden ? "show" : "hide";
		}
		if ( hidden ? mode === "hide" : mode === "show" ) {
			mode = "none";
		}
		return mode;
	},

	// Translates a [top,left] array into a baseline value
	getBaseline: function( origin, original ) {
		var y, x;

		switch ( origin[ 0 ] ) {
		case "top":
			y = 0;
			break;
		case "middle":
			y = 0.5;
			break;
		case "bottom":
			y = 1;
			break;
		default:
			y = origin[ 0 ] / original.height;
		}

		switch ( origin[ 1 ] ) {
		case "left":
			x = 0;
			break;
		case "center":
			x = 0.5;
			break;
		case "right":
			x = 1;
			break;
		default:
			x = origin[ 1 ] / original.width;
		}

		return {
			x: x,
			y: y
		};
	},

	// Creates a placeholder element so that the original element can be made absolute
	createPlaceholder: function( element ) {
		var placeholder,
			cssPosition = element.css( "position" ),
			position = element.position();

		// Lock in margins first to account for form elements, which
		// will change margin if you explicitly set height
		// see: http://jsfiddle.net/JZSMt/3/ https://bugs.webkit.org/show_bug.cgi?id=107380
		// Support: Safari
		element.css( {
			marginTop: element.css( "marginTop" ),
			marginBottom: element.css( "marginBottom" ),
			marginLeft: element.css( "marginLeft" ),
			marginRight: element.css( "marginRight" )
		} )
		.outerWidth( element.outerWidth() )
		.outerHeight( element.outerHeight() );

		if ( /^(static|relative)/.test( cssPosition ) ) {
			cssPosition = "absolute";

			placeholder = $( "<" + element[ 0 ].nodeName + ">" ).insertAfter( element ).css( {

				// Convert inline to inline block to account for inline elements
				// that turn to inline block based on content (like img)
				display: /^(inline|ruby)/.test( element.css( "display" ) ) ?
					"inline-block" :
					"block",
				visibility: "hidden",

				// Margins need to be set to account for margin collapse
				marginTop: element.css( "marginTop" ),
				marginBottom: element.css( "marginBottom" ),
				marginLeft: element.css( "marginLeft" ),
				marginRight: element.css( "marginRight" ),
				"float": element.css( "float" )
			} )
			.outerWidth( element.outerWidth() )
			.outerHeight( element.outerHeight() )
			.addClass( "ui-effects-placeholder" );

			element.data( dataSpace + "placeholder", placeholder );
		}

		element.css( {
			position: cssPosition,
			left: position.left,
			top: position.top
		} );

		return placeholder;
	},

	removePlaceholder: function( element ) {
		var dataKey = dataSpace + "placeholder",
				placeholder = element.data( dataKey );

		if ( placeholder ) {
			placeholder.remove();
			element.removeData( dataKey );
		}
	},

	// Removes a placeholder if it exists and restores
	// properties that were modified during placeholder creation
	cleanUp: function( element ) {
		$.effects.restoreStyle( element );
		$.effects.removePlaceholder( element );
	},

	setTransition: function( element, list, factor, value ) {
		value = value || {};
		$.each( list, function( i, x ) {
			var unit = element.cssUnit( x );
			if ( unit[ 0 ] > 0 ) {
				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
			}
		} );
		return value;
	}
} );

// Return an effect options object for the given parameters:
function _normalizeArguments( effect, options, speed, callback ) {

	// Allow passing all options as the first parameter
	if ( $.isPlainObject( effect ) ) {
		options = effect;
		effect = effect.effect;
	}

	// Convert to an object
	effect = { effect: effect };

	// Catch (effect, null, ...)
	if ( options == null ) {
		options = {};
	}

	// Catch (effect, callback)
	if ( $.isFunction( options ) ) {
		callback = options;
		speed = null;
		options = {};
	}

	// Catch (effect, speed, ?)
	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
		callback = speed;
		speed = options;
		options = {};
	}

	// Catch (effect, options, callback)
	if ( $.isFunction( speed ) ) {
		callback = speed;
		speed = null;
	}

	// Add options to effect
	if ( options ) {
		$.extend( effect, options );
	}

	speed = speed || options.duration;
	effect.duration = $.fx.off ? 0 :
		typeof speed === "number" ? speed :
		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
		$.fx.speeds._default;

	effect.complete = callback || options.complete;

	return effect;
}

function standardAnimationOption( option ) {

	// Valid standard speeds (nothing, number, named speed)
	if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) {
		return true;
	}

	// Invalid strings - treat as "normal" speed
	if ( typeof option === "string" && !$.effects.effect[ option ] ) {
		return true;
	}

	// Complete callback
	if ( $.isFunction( option ) ) {
		return true;
	}

	// Options hash (but not naming an effect)
	if ( typeof option === "object" && !option.effect ) {
		return true;
	}

	// Didn't match any standard API
	return false;
}

$.fn.extend( {
	effect: function( /* effect, options, speed, callback */ ) {
		var args = _normalizeArguments.apply( this, arguments ),
			effectMethod = $.effects.effect[ args.effect ],
			defaultMode = effectMethod.mode,
			queue = args.queue,
			queueName = queue || "fx",
			complete = args.complete,
			mode = args.mode,
			modes = [],
			prefilter = function( next ) {
				var el = $( this ),
					normalizedMode = $.effects.mode( el, mode ) || defaultMode;

				// Sentinel for duck-punching the :animated psuedo-selector
				el.data( dataSpaceAnimated, true );

				// Save effect mode for later use,
				// we can't just call $.effects.mode again later,
				// as the .show() below destroys the initial state
				modes.push( normalizedMode );

				// See $.uiBackCompat inside of run() for removal of defaultMode in 1.13
				if ( defaultMode && ( normalizedMode === "show" ||
						( normalizedMode === defaultMode && normalizedMode === "hide" ) ) ) {
					el.show();
				}

				if ( !defaultMode || normalizedMode !== "none" ) {
					$.effects.saveStyle( el );
				}

				if ( $.isFunction( next ) ) {
					next();
				}
			};

		if ( $.fx.off || !effectMethod ) {

			// Delegate to the original method (e.g., .show()) if possible
			if ( mode ) {
				return this[ mode ]( args.duration, complete );
			} else {
				return this.each( function() {
					if ( complete ) {
						complete.call( this );
					}
				} );
			}
		}

		function run( next ) {
			var elem = $( this );

			function cleanup() {
				elem.removeData( dataSpaceAnimated );

				$.effects.cleanUp( elem );

				if ( args.mode === "hide" ) {
					elem.hide();
				}

				done();
			}

			function done() {
				if ( $.isFunction( complete ) ) {
					complete.call( elem[ 0 ] );
				}

				if ( $.isFunction( next ) ) {
					next();
				}
			}

			// Override mode option on a per element basis,
			// as toggle can be either show or hide depending on element state
			args.mode = modes.shift();

			if ( $.uiBackCompat !== false && !defaultMode ) {
				if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, done );
				}
			} else {
				if ( args.mode === "none" ) {

					// Call the core method to track "olddisplay" properly
					elem[ mode ]();
					done();
				} else {
					effectMethod.call( elem[ 0 ], args, cleanup );
				}
			}
		}

		// Run prefilter on all elements first to ensure that
		// any showing or hiding happens before placeholder creation,
		// which ensures that any layout changes are correctly captured.
		return queue === false ?
			this.each( prefilter ).each( run ) :
			this.queue( queueName, prefilter ).queue( queueName, run );
	},

	show: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "show";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.show ),

	hide: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "hide";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.hide ),

	toggle: ( function( orig ) {
		return function( option ) {
			if ( standardAnimationOption( option ) || typeof option === "boolean" ) {
				return orig.apply( this, arguments );
			} else {
				var args = _normalizeArguments.apply( this, arguments );
				args.mode = "toggle";
				return this.effect.call( this, args );
			}
		};
	} )( $.fn.toggle ),

	cssUnit: function( key ) {
		var style = this.css( key ),
			val = [];

		$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
			if ( style.indexOf( unit ) > 0 ) {
				val = [ parseFloat( style ), unit ];
			}
		} );
		return val;
	},

	cssClip: function( clipObj ) {
		if ( clipObj ) {
			return this.css( "clip", "rect(" + clipObj.top + "px " + clipObj.right + "px " +
				clipObj.bottom + "px " + clipObj.left + "px)" );
		}
		return parseClip( this.css( "clip" ), this );
	},

	transfer: function( options, done ) {
		var element = $( this ),
			target = $( options.to ),
			targetFixed = target.css( "position" ) === "fixed",
			body = $( "body" ),
			fixTop = targetFixed ? body.scrollTop() : 0,
			fixLeft = targetFixed ? body.scrollLeft() : 0,
			endPosition = target.offset(),
			animation = {
				top: endPosition.top - fixTop,
				left: endPosition.left - fixLeft,
				height: target.innerHeight(),
				width: target.innerWidth()
			},
			startPosition = element.offset(),
			transfer = $( "<div class='ui-effects-transfer'></div>" )
				.appendTo( "body" )
				.addClass( options.className )
				.css( {
					top: startPosition.top - fixTop,
					left: startPosition.left - fixLeft,
					height: element.innerHeight(),
					width: element.innerWidth(),
					position: targetFixed ? "fixed" : "absolute"
				} )
				.animate( animation, options.duration, options.easing, function() {
					transfer.remove();
					if ( $.isFunction( done ) ) {
						done();
					}
				} );
	}
} );

function parseClip( str, element ) {
		var outerWidth = element.outerWidth(),
			outerHeight = element.outerHeight(),
			clipRegex = /^rect\((-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto),?\s*(-?\d*\.?\d*px|-?\d+%|auto)\)$/,
			values = clipRegex.exec( str ) || [ "", 0, outerWidth, outerHeight, 0 ];

		return {
			top: parseFloat( values[ 1 ] ) || 0,
			right: values[ 2 ] === "auto" ? outerWidth : parseFloat( values[ 2 ] ),
			bottom: values[ 3 ] === "auto" ? outerHeight : parseFloat( values[ 3 ] ),
			left: parseFloat( values[ 4 ] ) || 0
		};
}

$.fx.step.clip = function( fx ) {
	if ( !fx.clipInit ) {
		fx.start = $( fx.elem ).cssClip();
		if ( typeof fx.end === "string" ) {
			fx.end = parseClip( fx.end, fx.elem );
		}
		fx.clipInit = true;
	}

	$( fx.elem ).cssClip( {
		top: fx.pos * ( fx.end.top - fx.start.top ) + fx.start.top,
		right: fx.pos * ( fx.end.right - fx.start.right ) + fx.start.right,
		bottom: fx.pos * ( fx.end.bottom - fx.start.bottom ) + fx.start.bottom,
		left: fx.pos * ( fx.end.left - fx.start.left ) + fx.start.left
	} );
};

} )();

/******************************************************************************/
/*********************************** EASING ***********************************/
/******************************************************************************/

( function() {

// Based on easing equations from Robert Penner (http://www.robertpenner.com/easing)

var baseEasings = {};

$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
	baseEasings[ name ] = function( p ) {
		return Math.pow( p, i + 2 );
	};
} );

$.extend( baseEasings, {
	Sine: function( p ) {
		return 1 - Math.cos( p * Math.PI / 2 );
	},
	Circ: function( p ) {
		return 1 - Math.sqrt( 1 - p * p );
	},
	Elastic: function( p ) {
		return p === 0 || p === 1 ? p :
			-Math.pow( 2, 8 * ( p - 1 ) ) * Math.sin( ( ( p - 1 ) * 80 - 7.5 ) * Math.PI / 15 );
	},
	Back: function( p ) {
		return p * p * ( 3 * p - 2 );
	},
	Bounce: function( p ) {
		var pow2,
			bounce = 4;

		while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
		return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
	}
} );

$.each( baseEasings, function( name, easeIn ) {
	$.easing[ "easeIn" + name ] = easeIn;
	$.easing[ "easeOut" + name ] = function( p ) {
		return 1 - easeIn( 1 - p );
	};
	$.easing[ "easeInOut" + name ] = function( p ) {
		return p < 0.5 ?
			easeIn( p * 2 ) / 2 :
			1 - easeIn( p * -2 + 2 ) / 2;
	};
} );

} )();

var effect = $.effects;


/*!
 * jQuery UI Effects Blind 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Blind Effect
//>>group: Effects
//>>description: Blinds the element.
//>>docs: http://api.jqueryui.com/blind-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectBlind = $.effects.define( "blind", "hide", function( options, done ) {
	var map = {
			up: [ "bottom", "top" ],
			vertical: [ "bottom", "top" ],
			down: [ "top", "bottom" ],
			left: [ "right", "left" ],
			horizontal: [ "right", "left" ],
			right: [ "left", "right" ]
		},
		element = $( this ),
		direction = options.direction || "up",
		start = element.cssClip(),
		animate = { clip: $.extend( {}, start ) },
		placeholder = $.effects.createPlaceholder( element );

	animate.clip[ map[ direction ][ 0 ] ] = animate.clip[ map[ direction ][ 1 ] ];

	if ( options.mode === "show" ) {
		element.cssClip( animate.clip );
		if ( placeholder ) {
			placeholder.css( $.effects.clipToBox( animate ) );
		}

		animate.clip = start;
	}

	if ( placeholder ) {
		placeholder.animate( $.effects.clipToBox( animate ), options.duration, options.easing );
	}

	element.animate( animate, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Bounce 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Bounce Effect
//>>group: Effects
//>>description: Bounces an element horizontally or vertically n times.
//>>docs: http://api.jqueryui.com/bounce-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectBounce = $.effects.define( "bounce", function( options, done ) {
	var upAnim, downAnim, refValue,
		element = $( this ),

		// Defaults:
		mode = options.mode,
		hide = mode === "hide",
		show = mode === "show",
		direction = options.direction || "up",
		distance = options.distance,
		times = options.times || 5,

		// Number of internal animations
		anims = times * 2 + ( show || hide ? 1 : 0 ),
		speed = options.duration / anims,
		easing = options.easing,

		// Utility:
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ),
		i = 0,

		queuelen = element.queue().length;

	$.effects.createPlaceholder( element );

	refValue = element.css( ref );

	// Default distance for the BIGGEST bounce is the outer Distance / 3
	if ( !distance ) {
		distance = element[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
	}

	if ( show ) {
		downAnim = { opacity: 1 };
		downAnim[ ref ] = refValue;

		// If we are showing, force opacity 0 and set the initial position
		// then do the "first" animation
		element
			.css( "opacity", 0 )
			.css( ref, motion ? -distance * 2 : distance * 2 )
			.animate( downAnim, speed, easing );
	}

	// Start at the smallest distance if we are hiding
	if ( hide ) {
		distance = distance / Math.pow( 2, times - 1 );
	}

	downAnim = {};
	downAnim[ ref ] = refValue;

	// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
	for ( ; i < times; i++ ) {
		upAnim = {};
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		element
			.animate( upAnim, speed, easing )
			.animate( downAnim, speed, easing );

		distance = hide ? distance * 2 : distance / 2;
	}

	// Last Bounce when Hiding
	if ( hide ) {
		upAnim = { opacity: 0 };
		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;

		element.animate( upAnim, speed, easing );
	}

	element.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Clip 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Clip Effect
//>>group: Effects
//>>description: Clips the element on and off like an old TV.
//>>docs: http://api.jqueryui.com/clip-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectClip = $.effects.define( "clip", "hide", function( options, done ) {
	var start,
		animate = {},
		element = $( this ),
		direction = options.direction || "vertical",
		both = direction === "both",
		horizontal = both || direction === "horizontal",
		vertical = both || direction === "vertical";

	start = element.cssClip();
	animate.clip = {
		top: vertical ? ( start.bottom - start.top ) / 2 : start.top,
		right: horizontal ? ( start.right - start.left ) / 2 : start.right,
		bottom: vertical ? ( start.bottom - start.top ) / 2 : start.bottom,
		left: horizontal ? ( start.right - start.left ) / 2 : start.left
	};

	$.effects.createPlaceholder( element );

	if ( options.mode === "show" ) {
		element.cssClip( animate.clip );
		animate.clip = start;
	}

	element.animate( animate, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );

} );


/*!
 * jQuery UI Effects Drop 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Drop Effect
//>>group: Effects
//>>description: Moves an element in one direction and hides it at the same time.
//>>docs: http://api.jqueryui.com/drop-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectDrop = $.effects.define( "drop", "hide", function( options, done ) {

	var distance,
		element = $( this ),
		mode = options.mode,
		show = mode === "show",
		direction = options.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		motion = ( direction === "up" || direction === "left" ) ? "-=" : "+=",
		oppositeMotion = ( motion === "+=" ) ? "-=" : "+=",
		animation = {
			opacity: 0
		};

	$.effects.createPlaceholder( element );

	distance = options.distance ||
		element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ) / 2;

	animation[ ref ] = motion + distance;

	if ( show ) {
		element.css( animation );

		animation[ ref ] = oppositeMotion + distance;
		animation.opacity = 1;
	}

	// Animate
	element.animate( animation, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Explode 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Explode Effect
//>>group: Effects
// jscs:disable maximumLineLength
//>>description: Explodes an element in all directions into n pieces. Implodes an element to its original wholeness.
// jscs:enable maximumLineLength
//>>docs: http://api.jqueryui.com/explode-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectExplode = $.effects.define( "explode", "hide", function( options, done ) {

	var i, j, left, top, mx, my,
		rows = options.pieces ? Math.round( Math.sqrt( options.pieces ) ) : 3,
		cells = rows,
		element = $( this ),
		mode = options.mode,
		show = mode === "show",

		// Show and then visibility:hidden the element before calculating offset
		offset = element.show().css( "visibility", "hidden" ).offset(),

		// Width and height of a piece
		width = Math.ceil( element.outerWidth() / cells ),
		height = Math.ceil( element.outerHeight() / rows ),
		pieces = [];

	// Children animate complete:
	function childComplete() {
		pieces.push( this );
		if ( pieces.length === rows * cells ) {
			animComplete();
		}
	}

	// Clone the element for each row and cell.
	for ( i = 0; i < rows; i++ ) { // ===>
		top = offset.top + i * height;
		my = i - ( rows - 1 ) / 2;

		for ( j = 0; j < cells; j++ ) { // |||
			left = offset.left + j * width;
			mx = j - ( cells - 1 ) / 2;

			// Create a clone of the now hidden main element that will be absolute positioned
			// within a wrapper div off the -left and -top equal to size of our pieces
			element
				.clone()
				.appendTo( "body" )
				.wrap( "<div></div>" )
				.css( {
					position: "absolute",
					visibility: "visible",
					left: -j * width,
					top: -i * height
				} )

				// Select the wrapper - make it overflow: hidden and absolute positioned based on
				// where the original was located +left and +top equal to the size of pieces
				.parent()
					.addClass( "ui-effects-explode" )
					.css( {
						position: "absolute",
						overflow: "hidden",
						width: width,
						height: height,
						left: left + ( show ? mx * width : 0 ),
						top: top + ( show ? my * height : 0 ),
						opacity: show ? 0 : 1
					} )
					.animate( {
						left: left + ( show ? 0 : mx * width ),
						top: top + ( show ? 0 : my * height ),
						opacity: show ? 1 : 0
					}, options.duration || 500, options.easing, childComplete );
		}
	}

	function animComplete() {
		element.css( {
			visibility: "visible"
		} );
		$( pieces ).remove();
		done();
	}
} );


/*!
 * jQuery UI Effects Fade 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Fade Effect
//>>group: Effects
//>>description: Fades the element.
//>>docs: http://api.jqueryui.com/fade-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectFade = $.effects.define( "fade", "toggle", function( options, done ) {
	var show = options.mode === "show";

	$( this )
		.css( "opacity", show ? 0 : 1 )
		.animate( {
			opacity: show ? 1 : 0
		}, {
			queue: false,
			duration: options.duration,
			easing: options.easing,
			complete: done
		} );
} );


/*!
 * jQuery UI Effects Fold 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Fold Effect
//>>group: Effects
//>>description: Folds an element first horizontally and then vertically.
//>>docs: http://api.jqueryui.com/fold-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectFold = $.effects.define( "fold", "hide", function( options, done ) {

	// Create element
	var element = $( this ),
		mode = options.mode,
		show = mode === "show",
		hide = mode === "hide",
		size = options.size || 15,
		percent = /([0-9]+)%/.exec( size ),
		horizFirst = !!options.horizFirst,
		ref = horizFirst ? [ "right", "bottom" ] : [ "bottom", "right" ],
		duration = options.duration / 2,

		placeholder = $.effects.createPlaceholder( element ),

		start = element.cssClip(),
		animation1 = { clip: $.extend( {}, start ) },
		animation2 = { clip: $.extend( {}, start ) },

		distance = [ start[ ref[ 0 ] ], start[ ref[ 1 ] ] ],

		queuelen = element.queue().length;

	if ( percent ) {
		size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
	}
	animation1.clip[ ref[ 0 ] ] = size;
	animation2.clip[ ref[ 0 ] ] = size;
	animation2.clip[ ref[ 1 ] ] = 0;

	if ( show ) {
		element.cssClip( animation2.clip );
		if ( placeholder ) {
			placeholder.css( $.effects.clipToBox( animation2 ) );
		}

		animation2.clip = start;
	}

	// Animate
	element
		.queue( function( next ) {
			if ( placeholder ) {
				placeholder
					.animate( $.effects.clipToBox( animation1 ), duration, options.easing )
					.animate( $.effects.clipToBox( animation2 ), duration, options.easing );
			}

			next();
		} )
		.animate( animation1, duration, options.easing )
		.animate( animation2, duration, options.easing )
		.queue( done );

	$.effects.unshift( element, queuelen, 4 );
} );


/*!
 * jQuery UI Effects Highlight 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Highlight Effect
//>>group: Effects
//>>description: Highlights the background of an element in a defined color for a custom duration.
//>>docs: http://api.jqueryui.com/highlight-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectHighlight = $.effects.define( "highlight", "show", function( options, done ) {
	var element = $( this ),
		animation = {
			backgroundColor: element.css( "backgroundColor" )
		};

	if ( options.mode === "hide" ) {
		animation.opacity = 0;
	}

	$.effects.saveStyle( element );

	element
		.css( {
			backgroundImage: "none",
			backgroundColor: options.color || "#ffff99"
		} )
		.animate( animation, {
			queue: false,
			duration: options.duration,
			easing: options.easing,
			complete: done
		} );
} );


/*!
 * jQuery UI Effects Size 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Size Effect
//>>group: Effects
//>>description: Resize an element to a specified width and height.
//>>docs: http://api.jqueryui.com/size-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectSize = $.effects.define( "size", function( options, done ) {

	// Create element
	var baseline, factor, temp,
		element = $( this ),

		// Copy for children
		cProps = [ "fontSize" ],
		vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
		hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],

		// Set options
		mode = options.mode,
		restore = mode !== "effect",
		scale = options.scale || "both",
		origin = options.origin || [ "middle", "center" ],
		position = element.css( "position" ),
		pos = element.position(),
		original = $.effects.scaledDimensions( element ),
		from = options.from || original,
		to = options.to || $.effects.scaledDimensions( element, 0 );

	$.effects.createPlaceholder( element );

	if ( mode === "show" ) {
		temp = from;
		from = to;
		to = temp;
	}

	// Set scaling factor
	factor = {
		from: {
			y: from.height / original.height,
			x: from.width / original.width
		},
		to: {
			y: to.height / original.height,
			x: to.width / original.width
		}
	};

	// Scale the css box
	if ( scale === "box" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			from = $.effects.setTransition( element, vProps, factor.from.y, from );
			to = $.effects.setTransition( element, vProps, factor.to.y, to );
		}

		// Horizontal props scaling
		if ( factor.from.x !== factor.to.x ) {
			from = $.effects.setTransition( element, hProps, factor.from.x, from );
			to = $.effects.setTransition( element, hProps, factor.to.x, to );
		}
	}

	// Scale the content
	if ( scale === "content" || scale === "both" ) {

		// Vertical props scaling
		if ( factor.from.y !== factor.to.y ) {
			from = $.effects.setTransition( element, cProps, factor.from.y, from );
			to = $.effects.setTransition( element, cProps, factor.to.y, to );
		}
	}

	// Adjust the position properties based on the provided origin points
	if ( origin ) {
		baseline = $.effects.getBaseline( origin, original );
		from.top = ( original.outerHeight - from.outerHeight ) * baseline.y + pos.top;
		from.left = ( original.outerWidth - from.outerWidth ) * baseline.x + pos.left;
		to.top = ( original.outerHeight - to.outerHeight ) * baseline.y + pos.top;
		to.left = ( original.outerWidth - to.outerWidth ) * baseline.x + pos.left;
	}
	element.css( from );

	// Animate the children if desired
	if ( scale === "content" || scale === "both" ) {

		vProps = vProps.concat( [ "marginTop", "marginBottom" ] ).concat( cProps );
		hProps = hProps.concat( [ "marginLeft", "marginRight" ] );

		// Only animate children with width attributes specified
		// TODO: is this right? should we include anything with css width specified as well
		element.find( "*[width]" ).each( function() {
			var child = $( this ),
				childOriginal = $.effects.scaledDimensions( child ),
				childFrom = {
					height: childOriginal.height * factor.from.y,
					width: childOriginal.width * factor.from.x,
					outerHeight: childOriginal.outerHeight * factor.from.y,
					outerWidth: childOriginal.outerWidth * factor.from.x
				},
				childTo = {
					height: childOriginal.height * factor.to.y,
					width: childOriginal.width * factor.to.x,
					outerHeight: childOriginal.height * factor.to.y,
					outerWidth: childOriginal.width * factor.to.x
				};

			// Vertical props scaling
			if ( factor.from.y !== factor.to.y ) {
				childFrom = $.effects.setTransition( child, vProps, factor.from.y, childFrom );
				childTo = $.effects.setTransition( child, vProps, factor.to.y, childTo );
			}

			// Horizontal props scaling
			if ( factor.from.x !== factor.to.x ) {
				childFrom = $.effects.setTransition( child, hProps, factor.from.x, childFrom );
				childTo = $.effects.setTransition( child, hProps, factor.to.x, childTo );
			}

			if ( restore ) {
				$.effects.saveStyle( child );
			}

			// Animate children
			child.css( childFrom );
			child.animate( childTo, options.duration, options.easing, function() {

				// Restore children
				if ( restore ) {
					$.effects.restoreStyle( child );
				}
			} );
		} );
	}

	// Animate
	element.animate( to, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: function() {

			var offset = element.offset();

			if ( to.opacity === 0 ) {
				element.css( "opacity", from.opacity );
			}

			if ( !restore ) {
				element
					.css( "position", position === "static" ? "relative" : position )
					.offset( offset );

				// Need to save style here so that automatic style restoration
				// doesn't restore to the original styles from before the animation.
				$.effects.saveStyle( element );
			}

			done();
		}
	} );

} );


/*!
 * jQuery UI Effects Scale 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Scale Effect
//>>group: Effects
//>>description: Grows or shrinks an element and its content.
//>>docs: http://api.jqueryui.com/scale-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectScale = $.effects.define( "scale", function( options, done ) {

	// Create element
	var el = $( this ),
		mode = options.mode,
		percent = parseInt( options.percent, 10 ) ||
			( parseInt( options.percent, 10 ) === 0 ? 0 : ( mode !== "effect" ? 0 : 100 ) ),

		newOptions = $.extend( true, {
			from: $.effects.scaledDimensions( el ),
			to: $.effects.scaledDimensions( el, percent, options.direction || "both" ),
			origin: options.origin || [ "middle", "center" ]
		}, options );

	// Fade option to support puff
	if ( options.fade ) {
		newOptions.from.opacity = 1;
		newOptions.to.opacity = 0;
	}

	$.effects.effect.size.call( this, newOptions, done );
} );


/*!
 * jQuery UI Effects Puff 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Puff Effect
//>>group: Effects
//>>description: Creates a puff effect by scaling the element up and hiding it at the same time.
//>>docs: http://api.jqueryui.com/puff-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectPuff = $.effects.define( "puff", "hide", function( options, done ) {
	var newOptions = $.extend( true, {}, options, {
		fade: true,
		percent: parseInt( options.percent, 10 ) || 150
	} );

	$.effects.effect.scale.call( this, newOptions, done );
} );


/*!
 * jQuery UI Effects Pulsate 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Pulsate Effect
//>>group: Effects
//>>description: Pulsates an element n times by changing the opacity to zero and back.
//>>docs: http://api.jqueryui.com/pulsate-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectPulsate = $.effects.define( "pulsate", "show", function( options, done ) {
	var element = $( this ),
		mode = options.mode,
		show = mode === "show",
		hide = mode === "hide",
		showhide = show || hide,

		// Showing or hiding leaves off the "last" animation
		anims = ( ( options.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
		duration = options.duration / anims,
		animateTo = 0,
		i = 1,
		queuelen = element.queue().length;

	if ( show || !element.is( ":visible" ) ) {
		element.css( "opacity", 0 ).show();
		animateTo = 1;
	}

	// Anims - 1 opacity "toggles"
	for ( ; i < anims; i++ ) {
		element.animate( { opacity: animateTo }, duration, options.easing );
		animateTo = 1 - animateTo;
	}

	element.animate( { opacity: animateTo }, duration, options.easing );

	element.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Shake 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Shake Effect
//>>group: Effects
//>>description: Shakes an element horizontally or vertically n times.
//>>docs: http://api.jqueryui.com/shake-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectShake = $.effects.define( "shake", function( options, done ) {

	var i = 1,
		element = $( this ),
		direction = options.direction || "left",
		distance = options.distance || 20,
		times = options.times || 3,
		anims = times * 2 + 1,
		speed = Math.round( options.duration / anims ),
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		positiveMotion = ( direction === "up" || direction === "left" ),
		animation = {},
		animation1 = {},
		animation2 = {},

		queuelen = element.queue().length;

	$.effects.createPlaceholder( element );

	// Animation
	animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
	animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
	animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;

	// Animate
	element.animate( animation, speed, options.easing );

	// Shakes
	for ( ; i < times; i++ ) {
		element
			.animate( animation1, speed, options.easing )
			.animate( animation2, speed, options.easing );
	}

	element
		.animate( animation1, speed, options.easing )
		.animate( animation, speed / 2, options.easing )
		.queue( done );

	$.effects.unshift( element, queuelen, anims + 1 );
} );


/*!
 * jQuery UI Effects Slide 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Slide Effect
//>>group: Effects
//>>description: Slides an element in and out of the viewport.
//>>docs: http://api.jqueryui.com/slide-effect/
//>>demos: http://jqueryui.com/effect/



var effectsEffectSlide = $.effects.define( "slide", "show", function( options, done ) {
	var startClip, startRef,
		element = $( this ),
		map = {
			up: [ "bottom", "top" ],
			down: [ "top", "bottom" ],
			left: [ "right", "left" ],
			right: [ "left", "right" ]
		},
		mode = options.mode,
		direction = options.direction || "left",
		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
		positiveMotion = ( direction === "up" || direction === "left" ),
		distance = options.distance ||
			element[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ),
		animation = {};

	$.effects.createPlaceholder( element );

	startClip = element.cssClip();
	startRef = element.position()[ ref ];

	// Define hide animation
	animation[ ref ] = ( positiveMotion ? -1 : 1 ) * distance + startRef;
	animation.clip = element.cssClip();
	animation.clip[ map[ direction ][ 1 ] ] = animation.clip[ map[ direction ][ 0 ] ];

	// Reverse the animation if we're showing
	if ( mode === "show" ) {
		element.cssClip( animation.clip );
		element.css( ref, animation[ ref ] );
		animation.clip = startClip;
		animation[ ref ] = startRef;
	}

	// Actually animate
	element.animate( animation, {
		queue: false,
		duration: options.duration,
		easing: options.easing,
		complete: done
	} );
} );


/*!
 * jQuery UI Effects Transfer 1.12.0
 * http://jqueryui.com
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license.
 * http://jquery.org/license
 */

//>>label: Transfer Effect
//>>group: Effects
//>>description: Displays a transfer effect from one element to another.
//>>docs: http://api.jqueryui.com/transfer-effect/
//>>demos: http://jqueryui.com/effect/



var effect;
if ( $.uiBackCompat !== false ) {
	effect = $.effects.define( "transfer", function( options, done ) {
		$( this ).transfer( options, done );
	} );
}
var effectsEffectTransfer = effect;




}));

/*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011â€“2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}(jQuery);
!function ($) {

    "use strict";

    // TABCOLLAPSE CLASS DEFINITION
    // ======================

    var TabCollapse = function (el, options) {
        this.options   = options;
        this.$tabs  = $(el);

        this._accordionVisible = false; //content is attached to tabs at first
        this._initAccordion();
        this._checkStateOnResize();


        // checkState() has gone to setTimeout for making it possible to attach listeners to
        // shown-accordion.bs.tabcollapse event on page load.
        // See https://github.com/flatlogic/bootstrap-tabcollapse/issues/23
        var that = this;
        setTimeout(function() {
          that.checkState();
        }, 0);
    };

    TabCollapse.DEFAULTS = {
        accordionClass: 'visible-xs',
        tabsClass: 'hidden-xs',
        accordionTemplate: function(heading, groupId, parentId, active) {
            return  '<div class="panel panel-default">' +
                    '   <div class="panel-heading">' +
                    '      <h4 class="panel-title">' +
                    '      </h4>' +
                    '   </div>' +
                    '   <div id="' + groupId + '" class="panel-collapse collapse ' + (active ? 'in' : '') + '">' +
                    '       <div class="panel-body js-tabcollapse-panel-body">' +
                    '       </div>' +
                    '   </div>' +
                    '</div>'

        }
    };

    TabCollapse.prototype.checkState = function(){
        if (this.$tabs.is(':visible') && this._accordionVisible){
            this.showTabs();
            this._accordionVisible = false;
        } else if (this.$accordion.is(':visible') && !this._accordionVisible){
            this.showAccordion();
            this._accordionVisible = true;
        }
    };

    TabCollapse.prototype.showTabs = function(){
        var view = this;
        this.$tabs.trigger($.Event('show-tabs.bs.tabcollapse'));

        var $panelHeadings = this.$accordion.find('.js-tabcollapse-panel-heading').detach();

        $panelHeadings.each(function() {
            var $panelHeading = $(this),
            $parentLi = $panelHeading.data('bs.tabcollapse.parentLi');

            var $oldHeading = view._panelHeadingToTabHeading($panelHeading);

            $parentLi.removeClass('active');
            if ($parentLi.parent().hasClass('dropdown-menu') && !$parentLi.siblings('li').hasClass('active')) {
                $parentLi.parent().parent().removeClass('active');
            }

            if (!$oldHeading.hasClass('collapsed')) {
                $parentLi.addClass('active');
                if ($parentLi.parent().hasClass('dropdown-menu')) {
                    $parentLi.parent().parent().addClass('active');
                }
            } else {
                $oldHeading.removeClass('collapsed');
            }

            $parentLi.append($panelHeading);
        });

        if (!$('li').hasClass('active')) {
            $('li').first().addClass('active')
        }

        var $panelBodies = this.$accordion.find('.js-tabcollapse-panel-body');
        $panelBodies.each(function(){
            var $panelBody = $(this),
                $tabPane = $panelBody.data('bs.tabcollapse.tabpane');
            $tabPane.append($panelBody.contents().detach());
        });
        this.$accordion.html('');

        if(this.options.updateLinks) {
            var $tabContents = this.getTabContentElement();
            $tabContents.find('[data-toggle-was="tab"], [data-toggle-was="pill"]').each(function() {
                var $el = $(this);
                var href = $el.attr('href').replace(/-collapse$/g, '');
                $el.attr({
                    'data-toggle': $el.attr('data-toggle-was'),
                    'data-toggle-was': '',
                    'data-parent': '',
                    href: href
                });
            });
        }

        this.$tabs.trigger($.Event('shown-tabs.bs.tabcollapse'));
    };

    TabCollapse.prototype.getTabContentElement = function(){
        var $tabContents = $(this.options.tabContentSelector);
        if($tabContents.length === 0) {
            $tabContents = this.$tabs.siblings('.tab-content');
        }
        return $tabContents;
    };

    TabCollapse.prototype.showAccordion = function(){
        this.$tabs.trigger($.Event('show-accordion.bs.tabcollapse'));

        var $headings = this.$tabs.find('li:not(.dropdown) [data-toggle="tab"], li:not(.dropdown) [data-toggle="pill"]'),
            view = this;
        $headings.each(function(){
            var $heading = $(this),
                $parentLi = $heading.parent();
            $heading.data('bs.tabcollapse.parentLi', $parentLi);
            view.$accordion.append(view._createAccordionGroup(view.$accordion.attr('id'), $heading.detach()));
        });

        if(this.options.updateLinks) {
            var parentId = this.$accordion.attr('id');
            var $selector = this.$accordion.find('.js-tabcollapse-panel-body');
            $selector.find('[data-toggle="tab"], [data-toggle="pill"]').each(function() {
                var $el = $(this);
                var href = $el.attr('href') + '-collapse';
                $el.attr({
                    'data-toggle-was': $el.attr('data-toggle'),
                    'data-toggle': 'collapse',
                    'data-parent': '#' + parentId,
                    href: href
                });
            });
        }

        this.$tabs.trigger($.Event('shown-accordion.bs.tabcollapse'));
    };

    TabCollapse.prototype._panelHeadingToTabHeading = function($heading) {
        var href = $heading.attr('href').replace(/-collapse$/g, '');
        $heading.attr({
            'data-toggle': 'tab',
            'href': href,
            'data-parent': ''
        });
        return $heading;
    };

    TabCollapse.prototype._tabHeadingToPanelHeading = function($heading, groupId, parentId, active) {
        $heading.addClass('js-tabcollapse-panel-heading ' + (active ? '' : 'collapsed'));
        $heading.attr({
            'data-toggle': 'collapse',
            'data-parent': '#' + parentId,
            'href': '#' + groupId
        });
        return $heading;
    };

    TabCollapse.prototype._checkStateOnResize = function(){
        var view = this;
        $(window).resize(function(){
            clearTimeout(view._resizeTimeout);
            view._resizeTimeout = setTimeout(function(){
                view.checkState();
            }, 100);
        });
    };


    TabCollapse.prototype._initAccordion = function(){
        var randomString = function() {
            var result = "",
                possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for( var i=0; i < 5; i++ ) {
                result += possible.charAt(Math.floor(Math.random() * possible.length));
            }
            return result;
        };

        var srcId = this.$tabs.attr('id'),
            accordionId = (srcId ? srcId : randomString()) + '-accordion';

        this.$accordion = $('<div class="panel-group ' + this.options.accordionClass + '" id="' + accordionId +'"></div>');
        this.$tabs.after(this.$accordion);
        this.$tabs.addClass(this.options.tabsClass);
        this.getTabContentElement().addClass(this.options.tabsClass);
    };

    TabCollapse.prototype._createAccordionGroup = function(parentId, $heading){
        var tabSelector = $heading.attr('data-target'),
            active = $heading.data('bs.tabcollapse.parentLi').is('.active');

        if (!tabSelector) {
            tabSelector = $heading.attr('href');
            tabSelector = tabSelector && tabSelector.replace(/.*(?=#[^\s]*$)/, ''); //strip for ie7
        }

        var $tabPane = $(tabSelector),
            groupId = $tabPane.attr('id') + '-collapse',
            $panel = $(this.options.accordionTemplate($heading, groupId, parentId, active));
        $panel.find('.panel-heading > .panel-title').append(this._tabHeadingToPanelHeading($heading, groupId, parentId, active));
        $panel.find('.panel-body').append($tabPane.contents().detach())
            .data('bs.tabcollapse.tabpane', $tabPane);

        return $panel;
    };



    // TABCOLLAPSE PLUGIN DEFINITION
    // =======================

    $.fn.tabCollapse = function (option) {
        return this.each(function () {
            var $this   = $(this);
            var data    = $this.data('bs.tabcollapse');
            var options = $.extend({}, TabCollapse.DEFAULTS, $this.data(), typeof option === 'object' && option);

            if (!data) $this.data('bs.tabcollapse', new TabCollapse(this, options));
        });
    };

    $.fn.tabCollapse.Constructor = TabCollapse;


}(window.jQuery);
/**
 * jQuery.scrolling-tabs
 * @version v0.0.1
 * @link https://github.com/mikejacobson/jquery-bootstrap-scrolling-tabs
 * @author Mike Jacobson <michaeljjacobson1@gmail.com>
 * @license MIT License, http://www.opensource.org/licenses/MIT
 *
 * jQuery plugin version of Angular directive angular-bootstrap-scrolling-tabs:
 * https://github.com/mikejacobson/angular-bootstrap-scrolling-tabs
 *
 * Usage:
 *
 *    Use case #1: HTML-defined tabs
 *    ------------------------------
 *    Demo: http://plnkr.co/edit/thyD0grCxIjyU4PoTt4x?p=preview
 *
 *      Sample HTML:
 *
 *           <!-- Nav tabs -->
 *           <ul class="nav nav-tabs" role="tablist">
 *             <li role="presentation" class="active"><a href="#tab1" role="tab" data-toggle="tab">Tab Number 1</a></li>
 *             <li role="presentation"><a href="#tab2" role="tab" data-toggle="tab">Tab Number 2</a></li>
 *             <li role="presentation"><a href="#tab3" role="tab" data-toggle="tab">Tab Number 3</a></li>
 *             <li role="presentation"><a href="#tab4" role="tab" data-toggle="tab">Tab Number 4</a></li>
 *           </ul>
 *
 *           <!-- Tab panes -->
 *           <div class="tab-content">
 *             <div role="tabpanel" class="tab-pane active" id="tab1">Tab 1 content...</div>
 *             <div role="tabpanel" class="tab-pane" id="tab2">Tab 2 content...</div>
 *             <div role="tabpanel" class="tab-pane" id="tab3">Tab 3 content...</div>
 *             <div role="tabpanel" class="tab-pane" id="tab4">Tab 4 content...</div>
 *           </div>
 *
 *
 *      JavaScript:
 *
 *            $('.nav-tabs').scrollingTabs();
 *
 *
 *
 *    Use Case #2: Data-driven tabs
 *    -----------------------------
 *    Demo: http://plnkr.co/edit/MWBjLnTvJeetjU3NEimg?p=preview
 *
 *      Sample HTML:
 *
 *          <!-- build .nav-tabs and .tab-content in here -->
 *          <div id="tabs-inside-here"></div>
 *
 *
 *      JavaScript:
 *
 *             $('#tabs-inside-here').scrollingTabs({
 *               tabs: tabs, // required
 *               propPaneId: 'paneId', // optional
 *               propTitle: 'title', // optional
 *               propActive: 'active', // optional
 *               propDisabled: 'disabled', // optional
 *               propContent: 'content', // optional
 *               ignoreTabPanes: false, // optional
 *               scrollToTabEdge: false // optional
 *             });
 *
 *      Settings/Options:
 *
 *        tabs:             tabs data array
 *        prop*:            name of your tab object's property name that
 *                          corresponds to that required tab property if
 *                          your property name is different than the
 *                          standard name (paneId, title, etc.)
 *        ignoreTabPanes:   relevant for data-driven tabs only--set to true if
 *                          you want the plugin to only touch the tabs
 *                          and to not generate the tab pane elements
 *                          that go in .tab-content. By default, the plugin
 *                          will generate the tab panes based on the content
 *                          property in your tab data, if a content property
 *                          is present.
 *        scrollToTabEdge:  set to true if you want to force full-width tabs
 *                          to display at the left scroll arrow. i.e., if the
 *                          scrolling stops with only half a tab showing,
 *                          it will snap the tab to its edge so the full tab
 *                          shows.
 *
 *
 *      On tabs data change:
 *
 *            $('#tabs-inside-here').scrollingTabs('refresh');
 *
 *      On tabs data change, if you want the active tab to be set based on
 *      the updated tabs data (i.e., you want to override the current
 *      active tab setting selected by the user), for example, if you
 *      added a new tab and you want it to be the active tab:
 *
 *             $('#tabs-inside-here').scrollingTabs('refresh', {
 *               forceActiveTab: true
 *             });
 *
 *      Any options that can be passed into the plugin can be set on the
 *      plugin's 'defaults' object instead so you don't have to pass them in:
 *
 *             $.fn.scrollingTabs.defaults.tabs = tabs;
 *             $.fn.scrollingTabs.defaults.forceActiveTab = true;
 *             $.fn.scrollingTabs.defaults.scrollToTabEdge = true;
 *
 *
 *      To destroy:
 *
 *            $('#tabs-inside-here').scrollingTabs('destroy');
 *
 *      If you were wrapping markup, the markup will be restored; if your tabs
 *      were data-driven, the tabs will be destroyed along with the plugin.
 *
 */
;(function ($, window) {
  'use strict';

  var CONSTANTS = {
    CONTINUOUS_SCROLLING_TIMEOUT_INTERVAL: 50, // timeout interval for repeatedly moving the tabs container
                                                // by one increment while the mouse is held down--decrease to
                                                // make mousedown continous scrolling faster
    SCROLL_OFFSET_FRACTION: 6, // each click moves the container this fraction of the fixed container--decrease
                               // to make the tabs scroll farther per click
    DATA_KEY_IS_MOUSEDOWN: 'ismousedown'
  };

  // smartresize from Paul Irish (debounced window resize)
  (function (sr) {
    var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced() {
        var obj = this, args = arguments;
        function delayed() {
          if (!execAsap) {
            func.apply(obj, args);
          }
          timeout = null;
        }

        if (timeout) {
          clearTimeout(timeout);
        } else if (execAsap) {
          func.apply(obj, args);
        }

        timeout = setTimeout(delayed, threshold || 100);
      };
    };
    $.fn[sr] = function (fn) { return fn ? this.bind('resize.scrtabs', debounce(fn)) : this.trigger(sr); };

  })('smartresize');



  /* ***********************************************************************************
   * ElementsHandler - Class that each instance of ScrollingTabsControl will instantiate
   * **********************************************************************************/
  function ElementsHandler(scrollingTabsControl) {
    var ehd = this;

    ehd.stc = scrollingTabsControl;
  }

  // ElementsHandler prototype methods
  (function (p) {
      p.initElements = function (options) {
        var ehd = this;

        ehd.setElementReferences();

        if (options.isWrappingAngularUITabset) {
          ehd.moveTabContentOutsideScrollContainer(options);
        }

        ehd.setEventListeners();
      };

      p.moveTabContentOutsideScrollContainer = function (options) {
        var ehd = this,
            stc = ehd.stc,
            $tabsContainer = stc.$tabsContainer,
            tabContentCloneCssClass = 'scrtabs-tab-content-clone',
            tabContentHiddenCssClass = 'scrtabs-tab-content-hidden',
            $tabContent = $tabsContainer.find('.tab-content').not('.' + tabContentCloneCssClass),
            $currTcClone,
            $newTcClone;

        // if the tabs won't be changing, we can just move the
        // the .tab-content outside the scrolling container right now
        if (!options.isWatchingTabs) {
          $tabContent.appendTo($tabsContainer);
          return;
        }

        /* if we're watching the tabs for changes, we can't just
         * move the .tab-content outside the scrolling container because
         * that will break the angular-ui directive dependencies, and
         * an error will be thrown as soon as the tabs change;
         * so we leave the .tab-content where it is but hide it, then
         * make a clone and move the clone outside the scroll container,
         * which will be the visible .tab-content.
         */

        // hide the original .tab-content if it's not already hidden
        if (!$tabContent.hasClass(tabContentHiddenCssClass)) {
          $tabContent.addClass(tabContentHiddenCssClass);
        }

        // create new clone
        $newTcClone = $tabContent
                        .clone()
                        .removeClass(tabContentHiddenCssClass)
                        .addClass(tabContentCloneCssClass);

        // get the current clone, if it exists
        $currTcClone = $tabsContainer.find('.' + tabContentCloneCssClass);

        if ($currTcClone.length) { // already a clone there so replace it
          $currTcClone.replaceWith($newTcClone);
        } else {
          $tabsContainer.append($newTcClone);
        }

      };

      p.refreshAllElementSizes = function () {
        var ehd = this,
            stc = ehd.stc,
            smv = stc.scrollMovement,
            scrollArrowsWereVisible = stc.scrollArrowsVisible,
            actionsTaken = {
              didScrollToActiveTab: false
            },
            minPos;

        ehd.setElementWidths();
        ehd.setScrollArrowVisibility();

        if (stc.scrollArrowsVisible) {
          ehd.setFixedContainerWidthForJustVisibleScrollArrows();
        }

        // this could have been a window resize or the removal of a
        // dynamic tab, so make sure the movable container is positioned
        // correctly because, if it is far to the left and we increased the
        // window width, it's possible that the tabs will be too far left,
        // beyond the min pos.
        if (stc.scrollArrowsVisible || scrollArrowsWereVisible) {
          if (stc.scrollArrowsVisible) {
            // make sure container not too far left
            minPos = smv.getMinPos();
            if (stc.movableContainerLeftPos < minPos) {
              smv.incrementScrollRight(minPos);
            } else {
              smv.scrollToActiveTab({
                isOnWindowResize: true
              });

              actionsTaken.didScrollToActiveTab = true;
            }
          } else {
            // scroll arrows went away after resize, so position movable container at 0
            stc.movableContainerLeftPos = 0;
            smv.slideMovableContainerToLeftPos();
          }
        }

        return actionsTaken;
      };

      p.setElementReferences = function () {
        var ehd = this,
            stc = ehd.stc,
            $tabsContainer = stc.$tabsContainer;

        stc.isNavPills = false;

        stc.$fixedContainer = $tabsContainer.find('.scrtabs-tabs-fixed-container');
        stc.$movableContainer = $tabsContainer.find('.scrtabs-tabs-movable-container');
        stc.$tabsUl = $tabsContainer.find('.nav-tabs');

        // check for pills
        if (!stc.$tabsUl.length) {
          stc.$tabsUl = $tabsContainer.find('.nav-pills');

          if (stc.$tabsUl.length) {
            stc.isNavPills = true;
          }
        }

        stc.$tabsLiCollection = stc.$tabsUl.find('> li');
        stc.$leftScrollArrow = $tabsContainer.find('.scrtabs-js-tab-scroll-arrow-left');
        stc.$rightScrollArrow = $tabsContainer.find('.scrtabs-js-tab-scroll-arrow-right');
        stc.$scrollArrows = stc.$leftScrollArrow.add(stc.$rightScrollArrow);

        stc.$win = $(window);
      };

      p.setElementWidths = function () {
        var ehd = this,
            stc = ehd.stc;

        stc.containerWidth = stc.$tabsContainer.outerWidth();
        stc.winWidth = stc.$win.width();

        stc.scrollArrowsCombinedWidth = stc.$leftScrollArrow.outerWidth() + stc.$rightScrollArrow.outerWidth();

        ehd.setFixedContainerWidth();
        ehd.setMovableContainerWidth();
      };

      p.setEventListeners = function () {
        var ehd = this,
            stc = ehd.stc,
            evh = stc.eventHandlers; // eventHandlers

        stc.$leftScrollArrow.off('.scrtabs').on({
          'mousedown.scrtabs': function (e) { evh.handleMousedownOnLeftScrollArrow.call(evh, e); },
          'mouseup.scrtabs': function (e) { evh.handleMouseupOnLeftScrollArrow.call(evh, e); },
          'click.scrtabs': function (e) { evh.handleClickOnLeftScrollArrow.call(evh, e); }
        });

        stc.$rightScrollArrow.off('.scrtabs').on({
          'mousedown.scrtabs': function (e) { evh.handleMousedownOnRightScrollArrow.call(evh, e); },
          'mouseup.scrtabs': function (e) { evh.handleMouseupOnRightScrollArrow.call(evh, e); },
          'click.scrtabs': function (e) { evh.handleClickOnRightScrollArrow.call(evh, e); }
        });

        stc.$win.smartresize(function (e) { evh.handleWindowResize.call(evh, e); });

      };

      p.setFixedContainerWidth = function () {
        var ehd = this,
            stc = ehd.stc;

        stc.$fixedContainer.width(stc.fixedContainerWidth = stc.$tabsContainer.outerWidth());
      };

      p.setFixedContainerWidthForJustHiddenScrollArrows = function () {
        var ehd = this,
            stc = ehd.stc;

        stc.$fixedContainer.width(stc.fixedContainerWidth);
      };

      p.setFixedContainerWidthForJustVisibleScrollArrows = function () {
        var ehd = this,
            stc = ehd.stc;

        stc.$fixedContainer.width(stc.fixedContainerWidth - stc.scrollArrowsCombinedWidth);
      };

      p.setMovableContainerWidth = function () {
        var ehd = this,
            stc = ehd.stc,
            $tabLi = stc.$tabsUl.find('li');

        stc.movableContainerWidth = 0;

        if ($tabLi.length) {

          $tabLi.each(function __getLiWidth() {
            var $li = $(this),
                totalMargin = 0;

            if (stc.isNavPills) { // pills have a margin-left, tabs have no margin
              totalMargin = parseInt($li.css('margin-left'), 10) + parseInt($li.css('margin-right'), 10);
            }

            stc.movableContainerWidth += ($li.outerWidth() + totalMargin);
          });

          stc.movableContainerWidth += 1;

          // if the tabs don't span the width of the page, force the
          // movable container width to full page width so the bottom
          // border spans the page width instead of just spanning the
          // width of the tabs
          if (stc.movableContainerWidth < stc.fixedContainerWidth) {
            stc.movableContainerWidth = stc.fixedContainerWidth;
          }
        }

        stc.$movableContainer.width(stc.movableContainerWidth);
      };

      p.setScrollArrowVisibility = function () {
        var ehd = this,
            stc = ehd.stc,
            shouldBeVisible = stc.movableContainerWidth > stc.fixedContainerWidth;

        if (shouldBeVisible && !stc.scrollArrowsVisible) {
          stc.$scrollArrows.show();
          stc.scrollArrowsVisible = true;
          ehd.setFixedContainerWidthForJustVisibleScrollArrows();
        } else if (!shouldBeVisible && stc.scrollArrowsVisible) {
          stc.$scrollArrows.hide();
          stc.scrollArrowsVisible = false;
          ehd.setFixedContainerWidthForJustHiddenScrollArrows();
        }
      };

  }(ElementsHandler.prototype));




  /* ***********************************************************************************
   * EventHandlers - Class that each instance of ScrollingTabsControl will instantiate
   * **********************************************************************************/
  function EventHandlers(scrollingTabsControl) {
    var evh = this;

    evh.stc = scrollingTabsControl;
  }

  // prototype methods
  (function (p){
    p.handleClickOnLeftScrollArrow = function (e) {
      var evh = this,
          stc = evh.stc;

      stc.scrollMovement.incrementScrollLeft();
    };

    p.handleClickOnRightScrollArrow = function (e) {
      var evh = this,
          stc = evh.stc,
          scrollMovement = stc.scrollMovement;

      scrollMovement.incrementScrollRight(scrollMovement.getMinPos());
    };

    p.handleMousedownOnLeftScrollArrow = function (e) {
      var evh = this,
          stc = evh.stc;

      stc.scrollMovement.startScrollLeft();
    };

    p.handleMousedownOnRightScrollArrow = function (e) {
      var evh = this,
          stc = evh.stc;

      stc.scrollMovement.startScrollRight();
    };

    p.handleMouseupOnLeftScrollArrow = function (e) {
      var evh = this,
          stc = evh.stc;

      stc.scrollMovement.stopScrollLeft();
    };

    p.handleMouseupOnRightScrollArrow = function (e) {
      var evh = this,
          stc = evh.stc;

      stc.scrollMovement.stopScrollRight();
    };

    p.handleWindowResize = function (e) {
      var evh = this,
          stc = evh.stc,
          newWinWidth = stc.$win.width();

      if (newWinWidth === stc.winWidth) {
        return false; // false alarm
      }

      stc.winWidth = newWinWidth;
      stc.elementsHandler.refreshAllElementSizes();
    };

  }(EventHandlers.prototype));




  /* ***********************************************************************************
   * ScrollMovement - Class that each instance of ScrollingTabsControl will instantiate
   * **********************************************************************************/
  function ScrollMovement(scrollingTabsControl) {
    var smv = this;

    smv.stc = scrollingTabsControl;
  }

  // prototype methods
  (function (p) {

    p.continueScrollLeft = function () {
      var smv = this,
          stc = smv.stc;

      setTimeout(function() {
        if (stc.$leftScrollArrow.data(CONSTANTS.DATA_KEY_IS_MOUSEDOWN) && (stc.movableContainerLeftPos < 0)) {
          if (!smv.incrementScrollLeft()) { // scroll limit not reached, so keep scrolling
            smv.continueScrollLeft();
          }
        }
      }, CONSTANTS.CONTINUOUS_SCROLLING_TIMEOUT_INTERVAL);
    };

    p.continueScrollRight = function (minPos) {
      var smv = this,
          stc = smv.stc;

      setTimeout(function() {
        if (stc.$rightScrollArrow.data(CONSTANTS.DATA_KEY_IS_MOUSEDOWN) && (stc.movableContainerLeftPos > minPos)) {
          // slide tabs LEFT -> decrease movable container's left position
          // min value is (movableContainerWidth - $tabHeader width)
          if (!smv.incrementScrollRight(minPos)) {
            smv.continueScrollRight(minPos);
          }
        }
      }, CONSTANTS.CONTINUOUS_SCROLLING_TIMEOUT_INTERVAL);
    };

    p.decrementMovableContainerLeftPos = function (minPos) {
      var smv = this,
          stc = smv.stc;

      stc.movableContainerLeftPos -= (stc.fixedContainerWidth / CONSTANTS.SCROLL_OFFSET_FRACTION);
      if (stc.movableContainerLeftPos < minPos) {
        stc.movableContainerLeftPos = minPos;
      } else if (stc.scrollToTabEdge) {
        smv.setMovableContainerLeftPosToTabEdge('right');

        if (stc.movableContainerLeftPos < minPos) {
          stc.movableContainerLeftPos = minPos;
        }
      }
    };

    p.getMinPos = function () {
      var smv = this,
          stc = smv.stc;

      return stc.scrollArrowsVisible ? (stc.fixedContainerWidth - stc.movableContainerWidth - stc.scrollArrowsCombinedWidth) : 0;
    };

    p.getMovableContainerCssLeftVal = function () {
      var smv = this,
          stc = smv.stc;

      return (stc.movableContainerLeftPos === 0) ? '0' : stc.movableContainerLeftPos + 'px';
    };

    p.incrementScrollLeft = function () {
      var smv = this,
          stc = smv.stc;

      stc.movableContainerLeftPos += (stc.fixedContainerWidth / CONSTANTS.SCROLL_OFFSET_FRACTION);

      if (stc.movableContainerLeftPos > 0) {
        stc.movableContainerLeftPos = 0;
      } else if (stc.scrollToTabEdge) {
        smv.setMovableContainerLeftPosToTabEdge('left');

        if (stc.movableContainerLeftPos > 0) {
          stc.movableContainerLeftPos = 0;
        }
      }

      smv.slideMovableContainerToLeftPos();

      return (stc.movableContainerLeftPos === 0); // indicates scroll limit reached
    };

    p.incrementScrollRight = function (minPos) {
      var smv = this,
          stc = smv.stc;

      smv.decrementMovableContainerLeftPos(minPos);
      smv.slideMovableContainerToLeftPos();

      return (stc.movableContainerLeftPos === minPos);
    };

    p.scrollToActiveTab = function (options) {
      var smv = this,
          stc = smv.stc,
          $activeTab,
          activeTabWidth,
          activeTabLeftPos,
          rightArrowLeftPos,
          overlap;

      // if the active tab is not fully visible, scroll till it is
      if (!stc.scrollArrowsVisible) {
        return;
      }

      $activeTab = stc.$tabsUl.find('li.active');

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

      activeTabWidth = $activeTab.outerWidth();
      activeTabLeftPos = $activeTab.offset().left;

      rightArrowLeftPos = stc.$rightScrollArrow.offset().left;
      overlap = activeTabLeftPos + activeTabWidth - rightArrowLeftPos;

      if (overlap > 0) {
        stc.movableContainerLeftPos = (options.isOnWindowResize || options.isOnTabsRefresh) ? (stc.movableContainerLeftPos - overlap) : -overlap;
        smv.slideMovableContainerToLeftPos();
      }
    };

    p.setMovableContainerLeftPosToTabEdge = function (scrollArrowClicked) {
      var smv = this,
          stc = smv.stc,
          offscreenWidth = -stc.movableContainerLeftPos,
          totalTabWidth = 0;

        // make sure LeftPos is set so that a tab edge will be against the
        // left scroll arrow so we won't have a partial, cut-off tab
        stc.$tabsLiCollection.each(function (index) {
          var tabWidth = $(this).width();

          totalTabWidth += tabWidth;

          if (totalTabWidth > offscreenWidth) {
            stc.movableContainerLeftPos = (scrollArrowClicked === 'left') ? -(totalTabWidth - tabWidth) : -totalTabWidth;
            return false; // exit .each() loop
          }

        });
    };

    p.slideMovableContainerToLeftPos = function () {
      var smv = this,
          stc = smv.stc,
          leftVal;

      stc.movableContainerLeftPos = stc.movableContainerLeftPos / 1;
      leftVal = smv.getMovableContainerCssLeftVal();

      stc.$movableContainer.stop().animate({ left: leftVal }, 'slow', function __slideAnimComplete() {
        var newMinPos = smv.getMinPos();

        // if we slid past the min pos--which can happen if you resize the window
        // quickly--move back into position
        if (stc.movableContainerLeftPos < newMinPos) {
          smv.decrementMovableContainerLeftPos(newMinPos);
          stc.$movableContainer.stop().animate({ left: smv.getMovableContainerCssLeftVal() }, 'fast');
        }
      });
    };

    p.startScrollLeft = function () {
      var smv = this,
          stc = smv.stc;

      stc.$leftScrollArrow.data(CONSTANTS.DATA_KEY_IS_MOUSEDOWN, true);
      smv.continueScrollLeft();
    };

    p.startScrollRight = function () {
      var smv = this,
          stc = smv.stc;

      stc.$rightScrollArrow.data(CONSTANTS.DATA_KEY_IS_MOUSEDOWN, true);
      smv.continueScrollRight(smv.getMinPos());
    };

    p.stopScrollLeft = function () {
      var smv = this,
          stc = smv.stc;

      stc.$leftScrollArrow.data(CONSTANTS.DATA_KEY_IS_MOUSEDOWN, false);
    };

    p.stopScrollRight = function () {
      var smv = this,
          stc = smv.stc;

      stc.$rightScrollArrow.data(CONSTANTS.DATA_KEY_IS_MOUSEDOWN, false);
    };

  }(ScrollMovement.prototype));



  /* **********************************************************************
   * ScrollingTabsControl - Class that each directive will instantiate
   * **********************************************************************/
  function ScrollingTabsControl($tabsContainer) {
    var stc = this;

    stc.$tabsContainer = $tabsContainer;

    stc.movableContainerLeftPos = 0;
    stc.scrollArrowsVisible = true;
    stc.scrollToTabEdge = false;

    stc.scrollMovement = new ScrollMovement(stc);
    stc.eventHandlers = new EventHandlers(stc);
    stc.elementsHandler = new ElementsHandler(stc);
  }

  // prototype methods
  (function (p) {
    p.initTabs = function (options) {
      var stc = this,
          elementsHandler = stc.elementsHandler,
          scrollMovement = stc.scrollMovement;

      if (options.scrollToTabEdge) {
        stc.scrollToTabEdge = true;
      }

      setTimeout(function __initTabsAfterTimeout() {
        var actionsTaken;

        elementsHandler.initElements(options);
        actionsTaken = elementsHandler.refreshAllElementSizes();

        if (!actionsTaken.didScrollToActiveTab) {
          scrollMovement.scrollToActiveTab({
            isOnTabsRefresh: options.isWatchingTabs
          });
        }


      }, 100);
    };


  }(ScrollingTabsControl.prototype));




  ////////////////////////////////////////////
  //
  // plugin-specific stuff
  //
  ////////////////////////////////////////////
  var tabElements = (function () {

    return {
      getElTabPaneForLi: getElTabPaneForLi,
      getNewElNavTabs: getNewElNavTabs,
      getNewElScrollerElementWrappingNavTabsInstance: getNewElScrollerElementWrappingNavTabsInstance,
      getNewElTabAnchor: getNewElTabAnchor,
      getNewElTabContent: getNewElTabContent,
      getNewElTabLi: getNewElTabLi,
      getNewElTabPane: getNewElTabPane
    };

    ///////////////////

    // ---- retrieve existing elements from the DOM ----------
    function getElTabPaneForLi($li) {
      return $($li.find('a').attr('href'));
    }


    // ---- create new elements ----------
    function getNewElNavTabs() {
      return $('<ul class="nav nav-tabs" role="tablist"></ul>');
    }

    function getNewElScrollerElementWrappingNavTabsInstance($navTabsInstance) {
      var $tabsContainer = $('<div class="scrtabs-tab-container"></div>'),
          $leftArrow = $('<div class="scrtabs-tab-scroll-arrow scrtabs-js-tab-scroll-arrow-left"><span class="glyphicon glyphicon-chevron-left"></span></div>'),
          $rightArrow = $('<div class="scrtabs-tab-scroll-arrow scrtabs-js-tab-scroll-arrow-right"><span class="glyphicon glyphicon-chevron-right"></span></div>'),
          $fixedContainer = $('<div class="scrtabs-tabs-fixed-container"></div>'),
          $movableContainer = $('<div class="scrtabs-tabs-movable-container"></div>');

      return $tabsContainer
                .append($leftArrow,
                        $fixedContainer.append($movableContainer.append($navTabsInstance)),
                        $rightArrow);
    }

    function getNewElTabAnchor(tab, propNames) {
      return $('<a role="tab" data-toggle="tab"></a>')
              .attr('href', '#' + tab[propNames.paneId])
              .html(tab[propNames.title]);
    }

    function getNewElTabContent() {
      return $('<div class="tab-content"></div>');
    }

    function getNewElTabLi(tab, propNames, forceActiveTab) {
      var $li = $('<li role="presentation" class=""></li>'),
          $a = getNewElTabAnchor(tab, propNames).appendTo($li);

      if (tab[propNames.disabled]) {
        $li.addClass('disabled');
        $a.attr('data-toggle', '');
      } else if (forceActiveTab && tab[propNames.active]) {
        $li.addClass('active');
      }

      return $li;
    }

    function getNewElTabPane(tab, propNames, forceActiveTab) {
      var $pane = $('<div role="tabpanel" class="tab-pane"></div>')
                  .attr('id', tab[propNames.paneId])
                  .html(tab[propNames.content]);

      if (forceActiveTab && tab[propNames.active]) {
        $pane.addClass('active');
      }

      return $pane;
    }


  }()); // tabElements

  var tabUtils = (function () {

    return {
      didTabOrderChange: didTabOrderChange,
      getIndexOfClosestEnabledTab: getIndexOfClosestEnabledTab,
      getTabIndexByPaneId: getTabIndexByPaneId,
      storeDataOnLiEl: storeDataOnLiEl
    };

    ///////////////////

    function didTabOrderChange($currTabLis, updatedTabs, propNames) {
      var isTabOrderChanged = false;

      $currTabLis.each(function (currDomIdx) {
        var newIdx = getTabIndexByPaneId(updatedTabs, propNames.paneId, $(this).data('tab')[propNames.paneId]);

        if ((newIdx > -1) && (newIdx !== currDomIdx)) { // tab moved
          isTabOrderChanged = true;
          return false; // exit .each() loop
        }
      });

      return isTabOrderChanged;
    }

    function getIndexOfClosestEnabledTab($currTabLis, startIndex) {
      var lastIndex = $currTabLis.length - 1,
          closestIdx = -1,
          incrementFromStartIndex = 0,
          testIdx = 0;

      // expand out from the current tab looking for an enabled tab;
      // we prefer the tab after us over the tab before
      while ((closestIdx === -1) && (testIdx >= 0)) {

        if ( (((testIdx = startIndex + (++incrementFromStartIndex)) <= lastIndex) &&
              !$currTabLis.eq(testIdx).hasClass('disabled')) ||
              (((testIdx = startIndex - incrementFromStartIndex) >= 0) &&
               !$currTabLis.eq(testIdx).hasClass('disabled')) ) {

          closestIdx = testIdx;

        }
      }

      return closestIdx;
    }

    function getTabIndexByPaneId(tabs, paneIdPropName, paneId) {
      var idx = -1;

      tabs.some(function (tab, i) {
        if (tab[paneIdPropName] === paneId) {
          idx = i;
          return true; // exit loop
        }
      });

      return idx;
    }

    function storeDataOnLiEl($li, tabs, index) {
      $li.data({
        tab: $.extend({}, tabs[index]), // store a clone so we can check for changes
        index: index
      });
    }

  }()); // tabUtils


  function buildNavTabsAndTabContentForTargetElementInstance($targetElInstance, settings) {
    var tabs = settings.tabs,
        propNames = {
          paneId: settings.propPaneId,
          title: settings.propTitle,
          active: settings.propActive,
          disabled: settings.propDisabled,
          content: settings.propContent
        },
        ignoreTabPanes = settings.ignoreTabPanes,
        hasTabContent = tabs.length && tabs[0][propNames.content] !== undefined,
        $navTabs = tabElements.getNewElNavTabs().appendTo($targetElInstance),
        $tabContent = tabElements.getNewElTabContent(),
        $scroller;

    if (!tabs.length) {
      return;
    }

    tabs.forEach(function(tab, index) {
      tabElements
        .getNewElTabLi(tab, propNames, true) // true -> forceActiveTab
        .appendTo($navTabs);

      // build the tab panes if we weren't told to ignore them and there's
      // tab content data available
      if (!ignoreTabPanes && hasTabContent) {
        tabElements
          .getNewElTabPane(tab, propNames, true) // true -> forceActiveTab
          .appendTo($tabContent);
      }
    });

    $scroller = wrapNavTabsInstanceInScroller($navTabs, settings).after($tabContent);

    $targetElInstance.data({
      scrtabs: {
        tabs: tabs,
        propNames: propNames,
        ignoreTabPanes: ignoreTabPanes,
        hasTabContent: hasTabContent,
        scroller: $scroller
      }
    });

    // once the nav-tabs are wrapped in the scroller, attach each tab's
    // data to it for reference later; we need to wait till they're
    // wrapped in the scroller because we wrap a *clone* of the nav-tabs
    // we built above, not the original nav-tabs
    $scroller.find('.nav-tabs > li').each(function (index) {
      tabUtils.storeDataOnLiEl($(this), tabs, index);
    });
  }

  function checkForTabAdded(refreshData) {
    var updatedTabsArray = refreshData.updatedTabsArray,
        propNames = refreshData.propNames,
        ignoreTabPanes = refreshData.ignoreTabPanes,
        options = refreshData.options,
        $currTabLis = refreshData.$currTabLis,
        $navTabs = refreshData.$navTabs,
        $currTabContentPanesContainer = ignoreTabPanes ? null : refreshData.$currTabContentPanesContainer,
        $currTabContentPanes = ignoreTabPanes ? null : refreshData.$currTabContentPanes,
        isInitTabsRequired = false;

    // make sure each tab in the updated tabs array has a corresponding DOM element
    updatedTabsArray.forEach(function (tab, idx) {
      var $li = $currTabLis.find('a[href="#' + tab[propNames.paneId] + '"]'),
          isTabIdxPastCurrTabs = (idx >= $currTabLis.length),
          $pane;

      if (!$li.length) { // new tab
        isInitTabsRequired = true;

        // add the tab, add its pane (if necessary), and refresh the scroller
        $li = tabElements.getNewElTabLi(tab, propNames, options.forceActiveTab);
        tabUtils.storeDataOnLiEl($li, updatedTabsArray, idx);

        if (isTabIdxPastCurrTabs) { // append to end of current tabs
          $li.appendTo($navTabs);
        } else {                        // insert in middle of current tabs
          $li.insertBefore($currTabLis.eq(idx));
        }

        if (!ignoreTabPanes && tab[propNames.content] !== undefined) {
          $pane = tabElements.getNewElTabPane(tab, propNames, options.forceActiveTab);
          if (isTabIdxPastCurrTabs) { // append to end of current tabs
            $pane.appendTo($currTabContentPanesContainer);
          } else {                        // insert in middle of current tabs
            $pane.insertBefore($currTabContentPanes.eq(idx));
          }
        }

      }

    });

    return isInitTabsRequired;
  }

  function checkForTabPropertiesUpdated(refreshData) {
    var tabLiData = refreshData.tabLi,
        ignoreTabPanes = refreshData.ignoreTabPanes,
        $li = tabLiData.$li,
        $contentPane = tabLiData.$contentPane,
        origTabData = tabLiData.origTabData,
        newTabData = tabLiData.newTabData,
        propNames = refreshData.propNames,
        isInitTabsRequired = false;

    // update tab title if necessary
    if (origTabData[propNames.title] !== newTabData[propNames.title]) {
      $li.find('a[role="tab"]')
          .html(origTabData[propNames.title] = newTabData[propNames.title]);

      isInitTabsRequired = true;
    }

    // update tab active state if necessary
    if (refreshData.options.forceActiveTab) {
      // set the active tab based on the tabs array regardless of the current
      // DOM state, which could have been changed by the user clicking a tab
      // without those changes being reflected back to the tab data
      $li[newTabData[propNames.active] ? 'addClass' : 'removeClass']('active');

      $contentPane[newTabData[propNames.active] ? 'addClass' : 'removeClass']('active');

      origTabData[propNames.active] = newTabData[propNames.active];

      isInitTabsRequired = true;
    }

    // update tab content pane if necessary
    if (!ignoreTabPanes && origTabData[propNames.content] !== newTabData[propNames.content]) {
      $contentPane.html(origTabData[propNames.content] = newTabData[propNames.content]);
      isInitTabsRequired = true;
    }

    return isInitTabsRequired;
  }

  function checkForTabRemoved(refreshData) {
    var tabLiData = refreshData.tabLi,
        ignoreTabPanes = refreshData.ignoreTabPanes,
        $li = tabLiData.$li,
        idxToMakeActive;

    if (tabLiData.newIdx !== -1) { // tab was not removed--it has a valid index
      return false;
    }

    // if this was the active tab, make the closest enabled tab active
    if ($li.hasClass('active')) {

      idxToMakeActive = tabUtils.getIndexOfClosestEnabledTab(refreshData.$currTabLis, tabLiData.currDomIdx);
      if (idxToMakeActive > -1) {
        refreshData.$currTabLis
          .eq(idxToMakeActive)
          .addClass('active');

        if (!ignoreTabPanes) {
          refreshData.$currTabContentPanes
            .eq(idxToMakeActive)
            .addClass('active');
        }
      }
    }

    $li.remove();

    if (!ignoreTabPanes) {
      tabLiData.$contentPane.remove();
    }

    return true;
  }

  function checkForTabsOrderChanged(refreshData) {
    var $currTabLis = refreshData.$currTabLis,
        updatedTabsArray = refreshData.updatedTabsArray,
        propNames = refreshData.propNames,
        ignoreTabPanes = refreshData.ignoreTabPanes,
        newTabsCollection = [],
        newTabPanesCollection = ignoreTabPanes ? null : [];

    if (!tabUtils.didTabOrderChange($currTabLis, updatedTabsArray, propNames)) {
      return false;
    }

    // the tab order changed...
    updatedTabsArray.forEach(function (t, i) {
      var paneId = t[propNames.paneId];

      newTabsCollection.push(
          $currTabLis
            .find('a[role="tab"][href="#' + paneId + '"]')
            .parent('li')
          );

      if (!ignoreTabPanes) {
        newTabPanesCollection.push($('#' + paneId));
      }
    });

    refreshData.$navTabs.append(newTabsCollection);

    if (!ignoreTabPanes) {
      refreshData.$currTabContentPanesContainer.append(newTabPanesCollection);
    }

    return true;
  }

  function checkForTabsRemovedOrUpdated(refreshData) {
    var $currTabLis = refreshData.$currTabLis,
        updatedTabsArray = refreshData.updatedTabsArray,
        propNames = refreshData.propNames,
        isInitTabsRequired = false;


    $currTabLis.each(function (currDomIdx) {
      var $li = $(this),
          origTabData = $li.data('tab'),
          newIdx = tabUtils.getTabIndexByPaneId(updatedTabsArray, propNames.paneId, origTabData[propNames.paneId]),
          newTabData = (newIdx > -1) ? updatedTabsArray[newIdx] : null;

      refreshData.tabLi = {
        $li: $li,
        currDomIdx: currDomIdx,
        newIdx: newIdx,
        $contentPane: tabElements.getElTabPaneForLi($li),
        origTabData: origTabData,
        newTabData: newTabData
      };

      if (checkForTabRemoved(refreshData)) {
        isInitTabsRequired = true;
        return; // continue to next $li in .each() since we removed this tab
      }

      if (checkForTabPropertiesUpdated(refreshData)) {
        isInitTabsRequired = true;
      }
    });

    return isInitTabsRequired;
  }

  function destroyPlugin() {
    var $targetElInstance = $(this),
        scrtabsData = $targetElInstance.data('scrtabs'),
        $tabsContainer;

    if (!scrtabsData) {
      return;
    }

    if (scrtabsData.isWrapperOnly) { // we just wrapped nav-tabs markup, so restore it
      // $targetElInstance is the ul.nav-tabs
      $tabsContainer = $targetElInstance.parents('.scrtabs-tab-container');

      if ($tabsContainer.length) {
        $tabsContainer.replaceWith($targetElInstance);
      }

    } else { // we generated the tabs from data so destroy everything we created
      if (scrtabsData.scroller && scrtabsData.scroller.initTabs) {
        scrtabsData.scroller.initTabs = null;
      }

      // $targetElInstance is the container for the ul.nav-tabs we generated
      $targetElInstance
        .find('.scrtabs-tab-container')
        .add('.tab-content')
        .remove();
    }

    $targetElInstance.removeData('scrtabs');
  }

  function refreshTargetElementInstance($container, options) {
    var instanceData = $container.data().scrtabs,
        scroller = instanceData.scroller,
        $navTabs = $container.find('.scrtabs-tab-container .nav-tabs'),
        $currTabContentPanesContainer = $container.find('.tab-content'),
        isInitTabsRequired = false,
        refreshData = {
          options: options,
          updatedTabsArray: instanceData.tabs,
          propNames: instanceData.propNames,
          ignoreTabPanes: instanceData.ignoreTabPanes,
          $navTabs: $navTabs,
          $currTabLis: $navTabs.find('> li'),
          $currTabContentPanesContainer: $currTabContentPanesContainer,
          $currTabContentPanes: $currTabContentPanesContainer.find('.tab-pane')
        };

    if (checkForTabAdded(refreshData)) {
      isInitTabsRequired = true;
    }

    if (checkForTabsOrderChanged(refreshData)) {
      isInitTabsRequired = true;
    }

    if (checkForTabsRemovedOrUpdated(refreshData)) {
      isInitTabsRequired = true;
    }

    if (isInitTabsRequired) {
      scroller.initTabs();
    }
  }

  function wrapNavTabsInstanceInScroller($navTabsInstance, settings) {
    var $scroller = tabElements.getNewElScrollerElementWrappingNavTabsInstance($navTabsInstance.clone(true)), // use clone because we replaceWith later
        scrollingTabsControl = new ScrollingTabsControl($scroller);

    $navTabsInstance.replaceWith($scroller);

    $scroller.initTabs = function () {
      scrollingTabsControl.initTabs(settings);
    };

    $scroller.initTabs();

    return $scroller;
  }



  ////////////////////////

  var methods = {
    destroy: function() {
      var $targetEls = this;

      $targetEls.each(destroyPlugin);
    },

    init: function(options) {
      var $targetEls = this,
          settings = $.extend({}, $.fn.scrollingTabs.defaults, options || {});

      // ---- tabs NOT data-driven -------------------------
      if (!settings.tabs) {

        // just wrap the selected .nav-tabs element(s) in the scroller
        return $targetEls.each(function() {

          wrapNavTabsInstanceInScroller($(this).data({
            scrtabs: {
              isWrapperOnly: true
            }
          }), settings);

        });
      }


      // ---- tabs data-driven -------------------------
      return $targetEls.each(function () {
        buildNavTabsAndTabContentForTargetElementInstance($(this), settings);
      });
    },

    refresh: function(options) {
      var $targetEls = this,
          settings = $.extend({}, $.fn.scrollingTabs.defaults, options || {});

      // to preserve the tab positions if we're just adding or removing
      // a tab, don't completely rebuild the tab structure, but check
      // for differences between the new tabs array and the old
      $targetEls.each(function () {
        refreshTargetElementInstance($(this), settings);
      });
    }
  };


  $.fn.scrollingTabs = function(methodOrOptions) {

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

  $.fn.scrollingTabs.defaults = {
    tabs: null,
    propPaneId: 'paneId',
    propTitle: 'title',
    propActive: 'active',
    propDisabled: 'disabled',
    propContent: 'content',
    ignoreTabPanes: false,
    scrollToTabEdge: false,
    forceActiveTab: false
  };



}(jQuery, window));


function SuggestController() {
    var _this = this;

    var request = {};

    var response = {};
    
    var req = false;

    this.init = function() {
        // Change back to the old behavior of auto-complete
        // http://jqueryui.com/docs/Upgrade_Guide_184#Autocomplete
        jQuery.ui.autocomplete.prototype._renderItem = function (ul, item) {
            return jQuery("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul);
        };

        req = false;

        jQuery('form[data-suggest]').each(function () {
            var $form = $(this);
            var customClasses = '';
            
            var attr = $form.attr('data-custom-ui-autocomplete-class');
            if (typeof attr !== typeof undefined && attr !== false) {
                customClasses = attr;
            }

            $form.find('input.js-solr-q').autocomplete({
                source: function (request, response) {
                    _this.request = request;
                    _this.response = response;
                    if (req) {
                        req.abort();
                        response();
                    }

                    req = jQuery.ajax({
                        url: $form.data('suggest'),
                        dataType: 'json',
                        data: {
                            termLowercase: request.term.toLowerCase(),
                            termOriginal: request.term,
                            L: $form.find('input[name="L"]').val()
                        },
                        success: _this.handleSuggestResponse
                    });
                },
                select: function (event, ui) {
                    this.value = ui.item.value;
                    $form.submit();
                },
                delay: 0,
                minLength: 2,
                classes: {
                    'ui-autocomplete': customClasses
                }
            });
            

        });
    };

    this.handleSuggestResponse = function (data) {
        req = false;
        var output = [];
        jQuery.each(data, function (term, termIndex) {
            output.push({
                label: term.replace(new RegExp('(?![^&;]+;)(?!<[^<>]*)(' +
                    jQuery.ui.autocomplete.escapeRegex(_this.request.term) +
                    ')(?![^<>]*>)(?![^&;]+;)', 'gi'), '<strong>$1</strong>'),
                value: term
            });
        });

        _this.response(output);
    };
}
jQuery(document).ready(function () {
    var solrSuggestController = new SuggestController();
    solrSuggestController.init();

    jQuery("body").on("tx_solr_updated", function() {
        solrSuggestController.init();
    });
});

/**
 * animOnScroll.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
;( function( window ) {

	'use strict';

	var docElem = window.document.documentElement;

	function getViewportH() {
		var client = docElem['clientHeight'],
		inner = window['innerHeight'];

		if( client < inner )
			return inner;
		else
			return client;
	}

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	// http://stackoverflow.com/a/5598797/989439
	function getOffset( el ) {
		var offsetTop = 0, offsetLeft = 0;
		do {
			if ( !isNaN( el.offsetTop ) ) {
				offsetTop += el.offsetTop;
			}
			if ( !isNaN( el.offsetLeft ) ) {
				offsetLeft += el.offsetLeft;
			}
		} while( el = el.offsetParent )

			return {
			top : offsetTop,
			left : offsetLeft
		}
	}

	function inViewport( el, h ) {
		var elH = el.offsetHeight,
		scrolled = scrollY(),
		viewed = scrolled + getViewportH(),
		elTop = getOffset(el).top,
		elBottom = elTop + elH,
		// if 0, the element is considered in the viewport as soon as it enters.
		// if 1, the element is considered in the viewport only when it's fully inside
		// value in percentage (1 >= h >= 0)
		h = h || 0;

		return (elTop + elH * h) <= viewed && (elBottom - elH * h) >= scrolled;
	}

	function extend( a, b ) {
		for( var key in b ) { 
			if( b.hasOwnProperty( key ) ) {
				a[key] = b[key];
			}
		}
		return a;
	}

	function AnimOnScroll( el, options ) {	
		this.el = el;
		this.options = extend( this.defaults, options );
		this._init();
	}

	AnimOnScroll.prototype = {
			defaults : {
				// Minimum and a maximum duration of the animation (random value is chosen)
				minDuration : 0,
				maxDuration : 0,
				// The viewportFactor defines how much of the appearing item has to be visible in order to trigger the animation
				// if we'd use a value of 0, this would mean that it would add the animation class as soon as the item is in the viewport. 
				// If we were to use the value of 1, the animation would only be triggered when we see all of the item in the viewport (100% of it)
				viewportFactor : 0
			},
			_init : function() {

				this.items = this.el;
				this.itemsCount = this.items.length;
				this.itemsRenderedCount = 0;
				this.didScroll = false;

				var self = this;

				if( Modernizr.cssanimations ) {
					$.each(self.items, function(index, item) {
						// the items already shown...
						if( inViewport( item ) ) {
							self._checkTotalRendered();
							$(item).addClass('shown');
						}
					});

					// animate on scroll the items inside the viewport
					window.addEventListener( 'scroll', function() {
						self._onScrollFn();
					}, false );
					window.addEventListener( 'resize', function() {
						self._resizeHandler();
					}, false );
				}
			
			},
			_onScrollFn : function() {
				var self = this;
				if( !this.didScroll ) {
					this.didScroll = true;
					setTimeout( function() { self._scrollPage(); }, 60 );
				}
			},
			_scrollPage : function() {
				var self = this;

				$.each(self.items, function(index, item) {
					if( !$(item).hasClass('shown') && !$(item).hasClass('animate')  && inViewport(item, self.options.viewportFactor) ) {
						setTimeout( function() {
							var perspY = scrollY() + getViewportH() / 2;


							$(item).addClass('animate');
						}, 25 );
					}
				});
				this.didScroll = false;
			},
			_resizeHandler : function() {
				var self = this;
				function delayed() {
					self._scrollPage();
					self.resizeTimeout = null;
				}
				if ( this.resizeTimeout ) {
					clearTimeout( this.resizeTimeout );
				}
				this.resizeTimeout = setTimeout( delayed, 1000 );
			},
			_checkTotalRendered : function() {
				++this.itemsRenderedCount;
				if( this.itemsRenderedCount === this.itemsCount ) {
					window.removeEventListener( 'scroll', this._onScrollFn );
				}
			}
	}

	// add to global namespace
	window.AnimOnScroll = AnimOnScroll;

} )( window );
/////////////////////////
//super globals       //
/////////////////////////
function log(m){console.log(m)};

/**
 * Check if element is visible in the current viewport
 * 
 * @param Object el
 * @param int offset
 * @returns Boolean
 * @author: John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/
 */
function isElementInViewport (el, offset) {

    //special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    if (typeof el == "object" && typeof el.getBoundingClientRect == "function") {
        var rect = el.getBoundingClientRect();

        if (typeof offset === "undefined") {
            offset = 0;
        }

        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.top <= ($(window).height() + offset) &&
            rect.right <= $(window).width()
        );		
    }
    return null;

};

/* scrollBottom plugin */
$.fn.scrollBottom = function() { 
    return $(document).height() - this.scrollTop() - this.height(); 
};

/**
 * Get position of an element
 * 
 * @param	String	id of the element
 * @retrun	Object
 */
function getPosition(id) {
    var element = $(id);
    var top = $(element).offset().top;
    return {'top': top, 'bottom': top + $(element).outerHeight()};
};

// Polyfills

// Object.entries()
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Polyfill
if (!Object.entries) {
    Object.entries = function( obj ){
        var ownProps = Object.keys( obj ),
        i = ownProps.length,
        resArray = new Array(i); // preallocate the Array
        while (i--)
            resArray[i] = [ownProps[i], obj[ownProps[i]]];

        return resArray;
    };
}


//Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
                   'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
                   'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
                   'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
                   'timeStamp', 'trace', 'warn'
                   ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());


//this plugin appends a hidden select box to a div element, so that on phone devices
//a native ui element can be opened
(function($) {
    var udgMobileSelect = (function() {

        return function() {

            var settings = {
                    cssLinkPath : null, // css path of links for select box
                    aTitlePath : null // select the title for the select box
            };

            this.init = function(options) {

                settings = $.fn.extend(settings, options);

                return this.each(function() {

                    var triggerBox = $(this);
                    var selectBox = $("<select></select>");

                    if (typeof settings.id == 'string') {
                        selectBox.attr('id', settings.id)
                    }

                    var css = {
                            width:  '100%',
                            height: '100%',
                            boxSizing : 'border-box',
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            opacity: 0,
                            display:'block'
                    };
                    if (typeof settings.css == 'object') {
                        css = $.fn.extend(css, settings.css);
                    }

                    selectBox.css(css);

                    // add links as option elements
                    var elems = triggerBox.find('ul li > a');
                    if (settings.cssLinkPath !== null) {
                        elems = $(settings.cssLinkPath);
                    }

                    var current = 0;

                    $.each (elems, function(key, val) {
                        var link  = $(val).attr('href');
                        var title = $(val).text();

                        if($(val).hasClass('current')) {
                            current = key;
                        }

                        if (settings.aTitlePath !== null) {
                            title = $(val).find(settings.aTitlePath).text();
                        }

                        selectBox.append('<option value="' + link + '">' + title + '</option>');
                    });

                    if ($('#native-group-switch-extension').length == 1) {
                        selectBox.append($('#native-group-switch-extension').children());
                    }

                    $('option:nth-child('+(current + 1)+')', selectBox).prop('selected', true);

                    // bind change event
                    selectBox.on('change', function() {
                        var link = $(this).children('option:selected').val();

                        if (typeof link !== 'undefined') {
                            document.location.href = link;
                        }
                    });

                    triggerBox.css('position', 'relative'); // selectBox must be positioned inside triggerBox
                    triggerBox.prepend(selectBox);
                });
            }
        };

    })();

    $.fn.udgMobileSelect = function() {
        var tmp = new udgMobileSelect();
        return tmp.init.apply(this, arguments);
    }

})(jQuery);
//add the grid overlay
(function($) {

    var udgGridOverlay = {

            settings : {},

            init : function(options) {

                udgGridOverlay.settings = $.fn.extend(udgGridOverlay.settings, options);

                return this.each(function() {

                    var gridOverlay = [
                                       '<div class="gridOverlay">',
                                       '<div class="col-xs-content">',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '<div class="col-md-1 col-sm-1 col-xs-1"></div>',
                                       '</div>',
                                       '</div>'
                                       ];

                    var overlayElem = $(gridOverlay.join(""));

                    $(this).addClass('show-grid');
                    $(this).append(overlayElem);

                });
            },

            destroy : function() {
                return this.each(function() {
                    $(this).removeClass('show-grid');
                    $('.gridOverlay').remove();
                });
            }

    }

    $.fn.udgGridOverlay = function(method) {

        if (typeof udgGridOverlay[method] !== 'undefined') {
            return udgGridOverlay[method].apply(this, Array.prototype.slice.call(arguments, 1));
        }

        return udgGridOverlay.init.apply(this, arguments);
    }

})(jQuery);

//takes an ul list and creates an dropdown
(function($) {

    var udgDropdown = (function() {

        var settings = {
                ulSelector : null      // css selector, with the ul list, to be shown
        };

        return function() {

            this.init = function(options) {

                settings = $.extend(settings, options);

                return this.each(function() {




                    var dropdown = null;
                    if (settings.ulSelector !== null) {
                        dropdown = $(settings.ulSelector);
                    } else {
                        dropdown = $(this).next('ul');
                    }

                    if ('openLinksInNewWindow' in settings && settings.openLinksInNewWindow) {
                        $(dropdown).find('a').attr("target", "_blank");
                    }

                    var selected = dropdown.find('.current a').html();

                    if (typeof selected !== 'undefined') {
                        var caret = [
                                     "<span class='dropup'>",
                                     "<span class='caret caret-white'></span>",
                                     "</span>"
                                     ];
                        var caretTemp;
                        if (dropdown.is(':hidden')) {
                            caretTemp = caret;
                            caret = [ caretTemp[1] ]; //remove dropup

                        }

                        $(this).html(selected + caret.join(""));
                    }

                    $(this).find('span').first().addClass('hidden-xs');

                    /**
                     * selektierten eintrag ausblenden
                     */
                    dropdown.find('.current').css('display', 'none');

                    $(this).parent().on('click', function(e) {
                        e.stopPropagation();

                        if (dropdown.is(':hidden')) {
                            dropdown.slideDown(400, "swing");
                            $(this).find('.caret-white').addClass('caret-up-white');
                            $(this).find('.caret-white').removeClass('caret-white');
                        } else {
                            dropdown.slideUp(400, "swing");
                            $(this).find('.caret-up-white').addClass('caret-white');
                            $(this).find('.caret-up-white').removeClass('caret-up-white');
                        }
                    });

                    $('html').on('click', function(e) {
                        dropdown.hide();
                    });
                });
            }
        }

    })();

    $.fn.udgDropdown = function(method) {
        var tmp = new udgDropdown();
        return tmp.init.apply(this, arguments);
    }

})(jQuery);
/**
 * Erstellt eine Paginate-Dropdown basierend 
 * auf dem Bootstrap-Dropdown mit Pfeilen zur vorherigen/nächsten Seite
 */
(function($) {
    var pagination = (function() {

        var currentPage = 1;

        var settings = {
                jumpTo : null
        };

        /**
         * set links in prev and next
         */
        var prevAndNextButtons = function(ulList, pagePrev, pageNext) {
            var currentElement = ulList.find('li.current');

            // cursor auf default setzen, wenn nicht klickbar
            if (currentPage <= 1 || currentPage === null) {
                pagePrev.hide();
            } else {
                pagePrev.show();
            }

            // auf Seite vorher wechseln
            if (currentPage > 1) {
                pagePrev.click(function(){
                    currentElement.prev().find('a').click();
                }).css('display', 'inline-block');
            }

            // auf Seite danach wechseln
            if (currentElement.next().is('li')) {
                pageNext.click(function(){
                    currentElement.next().find('a').click();
                }).css('display', 'inline-block');
            }
        };

        return function() {

            this.init = function(options) {

                var settings = $.extend(settings, options);

                return this.each(function() {

                    var self = $(this);
                    var pagePrev = $('<a class="pagePrev"></a>').hide();
                    var pageNext = $('<a class="pageNext"></a>').hide();

                    if (settings.jumpTo) {
                        $.each([$('.dropdown-menu a', self), pagePrev, pageNext], function(index, element) {
                            element.click(function(){
                                $('html, body').animate({scrollTop: settings.jumpTo}, 250, 'linear');
                            });
                        });
                    }

                    currentPage = parseInt($('.dropdown-select', self).text());

                    prevAndNextButtons($('.dropdown-menu', self), pagePrev, pageNext);

                    pagePrev.insertBefore(self);
                    pageNext.insertAfter(self);

                });
            }
        }
    })();

    $.fn.pagination = function(method) {
        var paginate = new pagination();
        return paginate.init.apply(this, arguments);
    }

})(jQuery);
/**
 * Erstellt eine Paginate-Dropdown mit Pfeilen zur vorherigen/nächsten Seite
 */
(function($) {

    var udgPaginate = (function() {

        var settings = {
                ulList : null,
                bxSlider : false
        };

        var currentPage = null;
        var numPages = null;


        /**
         * set links in prev and next
         */
        var prevAndNextButtons = function(ulList, pagePrev, pageNext) {

            var currentElement = ulList.find('li.current');

            // cursor auf default setzen, wenn nicht klickbar
            if (currentPage <= 1 || currentPage === null) {
                pagePrev.css('visibility', 'hidden');
            } else {
                pagePrev.css('visibility', 'visible');
            }

            if (currentElement.next().is('li')) {
                pageNext.css('visibility', 'visible');
            } else {
                pageNext.css('visibility', 'hidden');
            }

            // carousel in bxslider
            if (settings.bxSlider && currentPage <= 1) {
                currentPage = numPages+1;
            } else if (settings.bxSlider && currentPage >= numPages) {
                currentPage = 0;
            }

            var $prev = currentElement.prev().children('a');

            // auf Seite vorher wechseln
            if ($prev.length) {

                var href = $prev.attr('href');
                pagePrev.attr('href', href);

                if (settings.bxSlider) {
                    var idx = $prev.attr('data-slide-index');
                    pagePrev.attr('data-slide-index', idx);
                }
            }

            // auf Seite danach wechseln
            if (currentPage !== null && currentElement.next().is('li')) {

                var next = currentElement.next().children('a');
                var href = next.attr('href');

                pageNext.attr('href', href);

                if (settings.bxSlider) {
                    var idx = next.attr('data-slide-index');
                    pageNext.attr('data-slide-index', idx);
                }
            }

        }

        return function() {

            this.init = function(options) {

                settings = $.extend(settings, options);

                return this.each(function() {
                    var ulList = null;

                    if (settings.ulList === null) {
                        ulList = $(this).find('ul');
                    } else {
                        ulList = $(settings.ulList);
                    }

                    $(this).addClass('udgPaginate');

                    var dropdown = $('<div class="dropdown"></div>');
                    var trigger  = $('<div class="trigger"></div>');
                    var pagePrev = $('<a class="pagePrev"></a>');
                    var pageNext = $('<a class="pageNext"></a>');

                    currentPage = parseInt(ulList.find('li.current').text());
                    numPages    = parseInt(ulList.find('li').length);

                    prevAndNextButtons(ulList, pagePrev, pageNext);
                    ulList.find('li:not(li.current)').hide();
                    // klappt das dropdown aus
                    trigger.on('click', function() {
                        ulList.find('li:not(li.current)').toggle();
                    });

                    ulList.wrap(dropdown);
                    ulList.after(trigger);

                    $(this).prepend(pagePrev);
                    $(this).append(pageNext);

                });
            }

            // update prev and next links:
            // this is needed, if there is no request that reloads the page and slider
            // automatically
            this.updatePager = function() {

                var ulList = null;

                if (settings.ulList === null) {
                    ulList = $(this).find('ul');
                } else {
                    ulList = $(settings.ulList);
                }

                currentPage = parseInt(ulList.find('li.current').text());
                numPages    = parseInt(ulList.find('li').length);

                var pagePrev = $(this).find('.pagePrev');
                var pageNext = $(this).find('.pageNext');

                prevAndNextButtons(ulList, pagePrev, pageNext);

            }

            this.destroy = function() {

                return this.each (function() {

                    $(this).removeClass('udgPaginate');

                    var html = $(this).find('.dropdown').html();
                    $(this).find('.dropdown').remove();
                    $(this).append(html); // unwrap ulList

                    $(this).find('.pagePrev, .pageNext, .trigger').remove();

                });
            }
        }
    })();


    $.fn.udgPaginate = function(method) {
        var paginate = new udgPaginate();

        if (method === 'updatePager') {
            return paginate.updatePager.apply(this, Array.prototype.slice.call(arguments, 1));
        }

        if (method === 'destroy') {
            return paginate.destroy.apply(this, Array.prototype.slice.call(arguments, 1));
        }

        return paginate.init.apply(this, arguments);
    }

})(jQuery);
/**
 * legt eine ul-liste über ein select field
 */
(function($) {
    var udgSelectDropdown = (function() {

        var updateScrollbar = function(dropdown) {
            dropdown.css({ 'height' : 'auto', 'maxHeight' : '270px', 'overflow' : 'hidden'});
            dropdown.mCustomScrollbar("destroy");
            dropdown.mCustomScrollbar({
                axis:"y",
                theme: 'inset'
            });
        }

        var hashCode = function(string) {
            var hash = 0, i, chr;

            for (i = 0; i < string.length; i++) {
                chr   = string.charCodeAt(i);
                hash  = ((hash << 5) - hash) + chr;
                hash |= 0; // Convert to 32bit integer
            }
            return hash; 
        }

        return function() {

            var settings = {
                change : 'submit',
                lineHeight : 28,
                scrollable: false,
                disabled: false,
                multiple: false
            };

            var currentValue = null;

            var closeOtherDropDowns = function(dropdown) {
                $('.udgDropdown .dropdown').not(dropdown).find('li:not(.current)').css('display', 'none');
                $('.udgDropdown .dropdown').not(dropdown).find('.active-dropdown').removeClass("active-dropdown");

                $.each($('.udgDropdown.open'), function(index, element) {
                    if (!$(element).find('.dropdown').is(dropdown)) {
                        $(element).removeClass('open');
                    }
                });
            }


            this.init = function(options) {

                settings = $.extend(settings, options);
                var index = 0;
                return this.each (function() {

                    var select = $(this);
                    select.wrap('<div class="udgDropdown"></div>');

                    settings.multiple = select.attr('multiple') === 'multiple' ? true : false;
                    select.css('display', 'none');

                    if (settings.multiple) {
                        select.parent().addClass('udgMultiSelect');
                    }

                    var zindex =  9999 - index++;
                    if(settings.hasOwnProperty('zIndex')) {
                        zindex = settings.zIndex;
                    }
                    var dropdown = $('<div class="dropdown' + (settings.scrollable ? ' mCustomScrollbar' : '') + '" style="z-index: '+ zindex +'"></div>');
                    var selected = $(select).children("option:selected");
                    var ul       = $('<ul></ul>');
                    var trigger  = $('<div class="trigger clickable"></div>');
                    var options = select.find('option');

                    if (settings.multiple) {

                        var id = 'chk' + hashCode(select.attr('name'));

                        $.each(options, function(key, option) {
                            if ($(option).text().replace(/\s/g, "").length > 0) {
                                if(key == 0) {
                                    var $defaultOption = $('<li data-value="0" class="current isvisible">' + $(option).text() + '</li>');

                                    ul.append($defaultOption);
                                    ul.append($('<li role="separator" class="divider"></li>'));

                                    $defaultOption.on('click', function(event) {
                                        openClose($(this));
                                    });
                                } else {
                                    var checkboxId = id + '-' + $(option).val();
                                    var checkbox = $('<input id="' + checkboxId + '" type="checkbox" name="'+$(option).text()+'" value="'+$(option).val()+'" />');
                                    var label = $('<label for="' + checkboxId + '">' + $(option).text() + '</label>');
                                    var li = $('<li data-value="' + $(option).val() + '" />');

                                    li.append(checkbox);
                                    li.append(label);
                                }
                                ul.append(li);
                            }
                        });

                        var openClose = function($element) {
                            if($element.closest('.dropdown').hasClass('disabled')) {
                                return;
                            }
                            closeOtherDropDowns(dropdown);
                            ul.find('li').toggle();
                            ul.find('li').toggleClass("isvisible");
                            ul.find('li.current').show();
                            ul.find('li.current').addClass("isvisible");

                            // add/remove "open" CSS-Class
                            var $udgMultiSelect = $element.closest('.udgMultiSelect');
                            if ($udgMultiSelect.find('li:visible').length > 1) {
                                $udgMultiSelect.addClass('open');
                            } else {
                                $udgMultiSelect.removeClass('open');
                            }
                        };

                        // open and close dropdown
                        trigger.on('click', function(event) {
                            openClose($(this));
                        });

                        // add or remove selection from select
                        ul.find('input[type="checkbox"]').on('click', function(e) {
                            var $self = $(this);
                            var selected = [];
                            $.each(select.find('option'), function(index, option) {
                                var $option = $(option);
                                if ( $option.is(':selected') && $option.val() != $self.val() ) {
                                    selected.push($option.val());
                                }
                            });
                            if ($self.is(':checked')) {
                                selected.push($self.val());
                            }
                            select.val(selected);

                            // set number of selected checkboxes or default text
                            var $overview = $(this).closest('ul').find('.current');
                            var text = selected.length;
                            if (selected.length == 0) {
                                text = $(this).closest('.udgMultiSelect').find('select option:eq(0)').text();
                            } else {
                                if(typeof select.attr('data-selected-value') === 'string') {
                                    text = select.attr('data-selected-value').replace(/%n/, selected.length);
                                }                           
                            }

                            $overview.text(text);
                            select.trigger('change');
                        });

                    } else {
                        $.each(options, function(key, option) {

                            if ($(option).text().replace(/\s/g, "").length > 0) {

                                var text = $(option).text();
                                text = text.replace(/(&reg;|®)/g, "<sup>&reg;</sup>");
                                text = text.replace(/\+/g, "<sup>+</sup>");

                                var li = $('<li data-value="' + $(option).val() + '" class="clickable">' + text + '</li>');

                                if(key == 0 && $(select).children('option').length > 1) {
                                    var tempText = $(selected).text().replace(/(&reg;|®)/g, "<sup>&reg;</sup>");
                                    tempText = tempText.replace(/\+/g, "<sup>+</sup>");     
                                    ul.append($('<li data-value="' + $(selected).val() + '" class="clickable">' + tempText + '</li>'));
                                    ul.append($('<li role="separator" class="divider"></li>'));
                                }

                                if($(option).attr("data-divider") && $(option).attr("data-divider") == 1) {
                                    ul.append($('<li role="separator" class="divider"></li>'));
                                }

                                if ($(option).is(':selected')) {
                                    currentValue = $(option).val();

                                    li.addClass('current');
                                    li.addClass('isvisible');
                                }
                                ul.append(li);
                            }
                        });

                        ul.find('li').on('click', function(e) {
                            ul.find('li.current').removeClass('current text-ellipsis');
                            $(this).addClass('current');

                            currentValue = $(this).attr('data-value');

                            select.find('option').each(function() {
                                $(this).attr('selected', ($(this).val() === currentValue));
                            });

                            // nur ändern, wenn dropdown geöffnet ist
                            if (ul.find('li:visible').length > 1) {
                                if (typeof settings.beforeChange === 'function') {
                                    settings.beforeChange(select);
                                }
                                select.trigger('change');
                            }
                        });

                        trigger.add(ul).on('click', function() {

                            if ($(this).closest('.dropdown').hasClass('disabled')) {
                                return;
                            }

                            closeOtherDropDowns(dropdown);

                            ul.toggleClass( "active-dropdown" );
                            ul.find('li').toggle();
                            ul.find('li').toggleClass( "isvisible" );
                            ul.find('li.current').show();
                            ul.find('li.current').addClass( "isvisible" );

                            if (ul.find('li.isvisible').length > 1) {
                                var $current = ul.find('li.current');
                                var $first = ul.find('li:first-child');
                                
                                // fallback to prevent empty entry on first place
                                // in that case show the current selected on top of the unfolded list
                                if (ul.find('li:visible').length > 1 && $first.is(':hidden')) {
                                    $first.text($current.text());
                                    $first.attr('data-value', $current.attr('data-value'));
                                    $first.removeClass('disabled');
                                }
                                
                                // wenn liste sichtbar , dann text-ellipsis entfernen
                                $current.removeClass('text-ellipsis');
                            } else {
                                // wenn zusammengeklappt , dann ausgewählten eintrag auspunkten
                                if (ul.find('li.current').height() > settings.lineHeight ){
                                    ul.find('li.current').addClass("text-ellipsis");
                                }
                            }

                            // scrollbar aktualisieren, wenn inhalt sich geändert hat
                            if (settings.scrollable) {
                                updateScrollbar(dropdown);
                            }
                        });
                    }

                    dropdown.append(ul);
                    dropdown.append(trigger);


                    if (ul.children('li').length <= 1 || settings.disabled) {
                        dropdown.addClass('disabled');
                    }

                    select.after(dropdown);

                    if (settings.scrollable) {
                        updateScrollbar(dropdown);
                    }

                    if (ul.find('li.current').height() > settings.lineHeight) {
                        ul.find('li.current').addClass("text-ellipsis");
                    }


                    /**
                     * submittet das formular beim ändern des dropdowns
                     */
                    if (typeof settings.change !== 'undefined') {
                        if (settings.change === 'submit') {
                            select.on('change', function () {
                                if (!($(this).hasClass('dontsubmit'))) {
                                    $(this).parents('form').submit();
                                }
                            });
                        } else if (typeof settings.change === 'function') { // callback function for onChange event
                            select.on('change', function(event) {
                                settings.change.call(null, select);
                            });
                        }
                    }
                });
            }
        }
    })();

    $.fn.udgSelectDropdown = function(method) {
        var tmp = new udgSelectDropdown();
        return tmp.init.apply(this, arguments);
    }
})(jQuery);

/**
 * styles für udgRadiobtn
 */
(function($) {
    var udgRadiobtn = (function() {
        return function() {
            this.init = function(options) {
                return this.each (function(index) {
                    var radio = $(this);

                    radio.find('label').wrapInner('<span class="radiolabel"></span>');
                    radio.find('label').prepend('<span class="radioouter"><span class="radioinner"></span></span>');
                    radio.find('label').append('<span style="clear: both"></span>');

                });
            }
        }
    })();

    $.fn.udgRadiobtn = function(method) {
        var tmp = new udgRadiobtn();

        return tmp.init.apply(this, arguments);
    }
})(jQuery);
/**
 * styles für udgCheckbox
 */
(function($) {
    var udgCheckbox = (function() {
        return function() {
            this.init = function(options) {
                return this.each (function(index) {
                    var checkbox = $(this);

                    checkbox.find('label').wrapInner('<span class="checkboxlabel"></span>');
                    checkbox.find('label').prepend('<span class="checkboxouter"><span class="checkboxinner"></span></span>');
                    checkbox.find('label').append('<span style="clear: both"></span>');

                });
            }
        }
    })();

    $.fn.udgCheckbox = function(method) {
        var tmp = new udgCheckbox();

        return tmp.init.apply(this, arguments);
    }
})(jQuery);
/**
 * styles für udgTextarea
 */
(function($) {
    var udgTextarea = (function() {
        return function() {
            this.init = function(options) {
                return this.each (function(index) {
                    var textarea = $(this);
                    var defaulttext = textarea.siblings('input[type="hidden"]').val();
                    $(document).on('submit',textarea.parent('form'),function(){
                        if(textarea.val() == defaulttext){
                            textarea.val('');
                        }
                    });
                    textarea.on('focus', function() {
                        if(textarea.val() == defaulttext){
                            textarea.val('');
                        }
                    });
                    textarea.on('blur', function() {
                        if(textarea.val() == ''){
                            textarea.val(defaulttext);
                        }
                    });

                });
            }
        }
    })();

    $.fn.udgTextarea = function(method) {
        var tmp = new udgTextarea();

        return tmp.init.apply(this, arguments);
    }
})(jQuery);
/**
 * styles für udgInput
 */
(function($) {
    var udgInput = (function() {
        return function() {
            this.init = function(options) {
                return this.each (function(index) {
                    var input = $(this);
                    var defaulttext = input.siblings('input[type="hidden"]').val();
                    $(document).on('submit',input.parent('form'),function(){
                        if(input.val() == defaulttext){
                            input.val('');
                        }
                    });
                    input.on('focus', function() {
                        if(input.val() == defaulttext){
                            input.val('');
                        }
                    });
                    input.on('blur', function() {
                        if(input.val() == ''){
                            input.val(defaulttext);
                        }
                    });

                });
            }
        }
    })();

    $.fn.udgInput = function(method) {
        var tmp = new udgInput();

        return tmp.init.apply(this, arguments);
    }
})(jQuery);
/**
 * styles für udgSubmit
 */
(function($) {
    var udgSubmit = (function() {
        return function() {
            this.init = function(options) {
                return this.each (function(index) {
                    var btn = $(this);
                    var submit = btn.find('input[type="submit"]');
                    submit.hide();

                    var newButton = $('<div class="col-md-4"><span class="submitme button_1">'+ submit.val() +'</span></div><div class="col-md-1"></div>');
                    btn.append(newButton);
                    newButton.on('click', function() {
                        $(this).parents('form').find('input[type="submit"]').click();
                    });

                });
            }
        }
    })();

    $.fn.udgSubmit = function(method) {
        var tmp = new udgSubmit();

        return tmp.init.apply(this, arguments);
    }
})(jQuery);
/**
 * make search icon in input field clickable
 */
(function($) {

    var settings = {
            iconWidth: 40
    };

    var udgInputIcon = (function() {

        return function() {

            this.init = function(options) {

                settings = $.extend(settings, options);

                var input = $(this);

                input.on('mousemove', function(e) {
                    var posX = e.clientX - this.getBoundingClientRect().left;

                    if (posX >= (this.offsetWidth - settings.iconWidth)) {
                        input.addClass('pointer');
                        input.off('click').on('click', function() {
                            input.parents('form').submit();
                        });
                    } else {
                        input.removeClass('pointer');
                        input.off('click');
                    }
                });
            }
        }
    })();

    $.fn.udgInputIcon = function(method) {
        var tmp = new udgInputIcon();

        return tmp.init.apply(this, arguments);
    }
})(jQuery);
//button 1: text wird ausgepunktet, wenn der text zu lang ist
(function($) {

    var b1 = (function() {

        return function() {
            this.init = function(options) {

                return this.each(function() {

                    var textWidth = 9999;
                    var buttonArrow = 40;
                    var truncate = false;

                    do {

                        textWidth = $(this).textWidth("16px HelveticaNeueW02-55Roma");

                        // text ist zu lange
                        if (textWidth > ($(this).width() - 40)) {
                            var txt = $(this).text().trim();

                            txt = txt.substring(0, (txt.length - 5));

                            $(this).text(txt);

                            truncate = true;
                        }

                    } while (textWidth > ($(this).width() - 40));

                    if (truncate) {
                        $(this).text(txt + " ...");
                    }
                });
            }
        }
    })();

    // berechnet die breite des textes
    $.fn.textWidth = function (font) {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext("2d");
        ctx.font = font || "bold 16px HelveticaNeueW02-55Roma";

        return ctx.measureText($(this).text().trim()).width;
    };

    $.fn.button1 = function(options) {
        var tmp = new b1();
        return tmp.init.call(this, options);
    }

})(jQuery);
//bricht den text in button_3 um, wenn der text >= das elternelement ist, da sonst
//die pfeil-grafik ohne text umbricht
(function($) {

    var button3 = (function() {

        return function() {

            var settings = {
                    arrowWidth : 37 // breite der pfeil-grafik in px
            };

            this.init = function(options) {

                settings = $.extend(settings, options);

                return this.each(function() {

                    var lineHeight = $(this).css('line-height').replace("px", "");


                    if ($(this).attr('data-allow-tags') && $(this).attr('data-allow-tags') == 'br') {

                    } else {
                        $(this).html($(this).html().replace("<br>", ""));   
                    }

                    // wenn die zeilenhöhe größer als die line-height ist +
                    // die textbreite + pfeil-grafik größer als die elementbreite ist,
                    // ist die zeile noch nicht umgebrochen
                    if ($(this).height() > lineHeight) {

                        $(this).css('width', '100%');

                        var lines = $(this).height() / lineHeight;

                        // wenn der pfeil den unterschied zwischen umbruch und nicht umbruch ausmacht, soll
                        // das ganze letzte wort umgebrochen werden und nicht nur der pfeil.
                        // --
                        // der pfeil ist 38px breit
                        if ( ($(this).textWidth("bold 16px HelveticaNeueW02-55Roma") + settings.arrowWidth) > ($(this).width() * (lines - 1)) &&
                                ($(this).textWidth("bold 16px HelveticaNeueW02-55Roma") < ($(this).width() * (lines - 1))) ) {

                            $(this).breakLine();
                        }

                    }
                });

            }
        }

    })();

    // berechnet die breite des textes
    $.fn.textWidth = function (font) {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext("2d");
        ctx.font = font || "bold 16px HelveticaNeueW02-55Roma";
        return ctx.measureText($(this).text().trim()).width;
    };

    // bricht das letzte wort in der zeile um
    $.fn.breakLine = function() {
        var text = $(this).text();
        text = text.split(" ");

        text[text.length-1] = "<br>" + text[text.length-1];

        $(this).html(text.join(" "));
    }

    $.fn.button3 = function(options) {
        var b3 = new button3();
        return b3.init.call(this, options);
    }

})(jQuery);
//berechnet, ob der text ein- oder zweizeilig angezeigt werden soll
(function($) {

    var ql = (function() {

        return function() {

            this.init = function(options) {

                return this.each(function() {

                    $(this).find('.quicklinks-button').each(function(k, v) {
                        var textWidth = $(v).find('.button-inner a').textWidth("16px HelveticaNeueW02-65Medi");
                        var compWidth = $(v).find('.button-inner a').width();

                        if (textWidth > compWidth) {
                            $(v).find('.button-inner a').addClass('two-lines');
                        } else {
                            $(v).find('.button-inner a').removeClass('two-lines');
                        }

                    });
                });

            }

        }
    })();

    // berechnet die breite des textes
    $.fn.textWidth = function (font) {
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext("2d");
        ctx.font = font || "bold 16px HelveticaNeueW02-55Roma";
        return ctx.measureText($(this).text().trim()).width;
    };

    $.fn.quicklinks = function(options) {
        var tmp = new ql();
        return tmp.init.call(this, options);
    }

})(jQuery);

/**
 * lay the link in a typo3 teaser box (textpic) over the whole teaserbox´
 */
(function($) {

    var teaserLink = (function() {

        return function() {

            this.init = function() {

                return this.each(function() {
                    var link = $(this).find('a').attr('href');
                    $(this).css('cursor', 'pointer');
                    $(this).on('click', function(e) {
                        e.preventDefault();
                        document.location.href = link;
                    });
                });
            }
        }
    })();

    $.fn.teaserLink = function(options) {
        var tmp = new teaserLink();
        tmp.init.call(this, options);
    }
})(jQuery);
//erstellt ein akkordeon
(function($) {

    var akkordeon = (function() {

        return function() {

            var settings = {
                    elementClass : '.akkordeon-element > .no-margin > .col-xs-content',
                    h2FirstHeader : 'header',
                    collapseAll : false
            };

            this.init = function(options) {
                settings = $.extend(settings, options);

                return this.each(function() {

                    // find all header divs
                    var headers = $(this).find(settings.elementClass + ' > ' + settings.h2FirstHeader + ' h2');
                    // find all content divs
                    var content = $(this).find(settings.elementClass + ' > ' + settings.h2FirstHeader).next();

                    headers.each(function() {
                        var el = $(this);
                        var txt = el.text().trim();
                        var check = txt.match(/^\d*\./);
                        if(check && check.length > 0){
                            var numTxt = check[0];
                            var numTxt = numTxt.substr(0,numTxt.length-1);
                            var re = new RegExp('('+numTxt+')\.(.*)');
                            txt = txt.replace(re,'<span class="akkordeonNumPoint col-xs-1">$1</span><p class="col-xs-8 akkordeonText">$2</p>');
                            el.addClass("akkordeonNumPointHead").html(txt);
                        }
                    });
                    headers.addClass('csc-firstHeader header col-xs-12');
                    headers.parent().parent().addClass('akkordeonNumPointContainer');
                    content.addClass('content');

                    // pfeil in header wird in ie9 nicht korrekt angezeigt
                    if ($('html').hasClass('ie9')) {
                        headers.each(function(k, v) {
                            // console.log('width: ' + w);
                            var w = $(v).width();

                            var styles = [
                                          'background-image: url(../typo3conf/ext/udg_template/Resources/Public/Svg/arrow_down_wico_ie9.svg)',
                                          'background-position: ' + (w - 40) + 'px center',
                                          'background-size: auto 3.5rem !important'
                                          ];

                            $(v).attr('style' , styles.join(";"));
                        });
                    }

                    // // hide all content divs but first
                    content.css('display', 'none');

                    if (settings.collapseAll === true) {
                        content.css('display', 'block');
                        headers.addClass('collapsed');
                    }

                    // on click on header, only show content div for header
                    headers.on('click', function() {

                        if (settings.collapseAll === true) {
                            if ($(this).hasClass('collapsed')) {
                                $(this).removeClass('collapsed');
                                $(this).parent().next('.content').hide();
                            } else {
                                $(this).addClass('collapsed');
                                $(this).parent().next('.content').show();
                            }

                            return ;
                        }

                        // only show if content is hidden, else hide it
                        var setVisible = $(this).parent().next().is(':hidden');

                        content.css('display', 'none');
                        headers.removeClass('collapsed');

                        if (setVisible) {
                            $(this).parent().next('.content').show();
                            $(this).addClass('collapsed');
                        }

                    });
                });
            }
        }

    })();

    $.fn.akkordeon = function(options) {
        var tmp = new akkordeon();
        tmp.init.call(this, options);
    }

})(jQuery);
//initiert die teaserboxen
(function($) {

    var teaserblocks = (function() {

        return function() {

            this.init = function() {

                return this.each(function() {

                    var obj = $(this);
                    var elems = obj.find('.teaserblock');
                    var buttons = obj.find('.teaserblock a.button_2:not(.teaserblock__link)');

                    obj.find('.teaserblock .headline, .teaserblock .teaser-headline').each(function(k, v) {
                        // text node
                        if (v.nodeType == 3) {
                            var replaceSZ = $(v).text().replace("ß", "SS");
                            $(v).text(replaceSZ);
                        }
                    });

                    buttons.on('click', function(e) {
                        e.preventDefault();

                        var el = $(this);

                        buttons.show();

                        // hide button of teaserblock, when collapsed
                        el.hide();

                        // show truncated quotes and text of other teaser blocks and hide untruncated quotes and text
                        var parentBlock = buttons.parent();
                        parentBlock.find('.text').removeClass('visible').addClass('hidden');
                        parentBlock.find('.hiddenimages').removeClass('visible').addClass('hidden');
                        parentBlock.find('.text.truncate').removeClass('hidden').addClass('visible');
                        parentBlock.find('.hiddenimages.truncate').removeClass('hidden').addClass('visible');

                        var hiddenimages = el.closest('.teaserblock').siblings().find('.hiddenimages');
                        hiddenimages.removeClass('visible').addClass('hidden');

                        // show untruncated quote and text of this teaserblock
                        el.closest('.teaserblock').find('.text').removeClass('hidden').addClass('visible');
                        el.closest('.teaserblock').find('.hiddenimages').removeClass('hidden').addClass('visible');
                        el.closest('.teaserblock').find('.text.truncate').removeClass('visible').addClass('hidden');
                        el.closest('.teaserblock').find('.hiddenimages.truncate').removeClass('visible').addClass('hidden');

                        return false;
                    });

                });
            }
        }
    })();

    $.fn.teaserblocks = function(options) {
        var tb = new teaserblocks();
        tb.init.call(this, options);
    }

})(jQuery);
//tab navigation (M300)
(function($) {

    var tabnavigation = (function() {

        // show arrows if there is not enough space
        var arrowNav = function(obj, menu) {

            var widthMenu = 0;
            var calcWidth = 'auto';
            var widthNav = obj.find('.tab-menu').width();

            $.each(menu, function (k, v) {
                widthMenu += $(v).outerWidth(true);
            });

            if (widthMenu > widthNav) {

                // remove margin of first and last element
                menu.first().css('margin-left', '0em');
                menu.last().css('margin-right', '0em');

                obj.find('.tab-menu .arrow-left, .tab-menu .arrow-right').remove();

                var arrowLeft  = $('<div class="arrow-left"></div>');
                var arrowRight = $('<div class="arrow-right"></div>');

                // show elements on the left
                arrowLeft.on('click', function() {
                    $(menu.get().reverse()).each(function(k, v) {
                        if ($(v).is(':hidden')) {
                            $(v).show();
                            return false;
                        }
                    });
                });

                // show hidden elements on the right
                arrowRight.on('click', function() {
                    widthMenu = 0;
                    $.each(menu, function (k, v) {
                        if ($(v).is(':visible')) {
                            widthMenu += $(v).outerWidth(true);
                        }
                    });
                    widthNav = obj.find('.tab-menu ul').width();

                    // if size of visible elements is smaller than the navbar, then stop scrolling
                    if (!(widthMenu > widthNav)) {
                        return false;
                    }

                    menu.each(function(k, v) {
                        if (!$(v).is(':hidden')) {
                            $(v).hide();
                            return false;
                        }
                    });

                });

                obj.find('.tab-menu').prepend(arrowLeft);
                obj.find('.tab-menu').append(arrowRight);
                var calcWidth = Math.floor(widthNav - (obj.find('.tab-menu .arrow-left').width() * 2));

            } else {
                obj.find('.tab-menu .arrow-left, .tab-menu .arrow-right').remove();
                menu.show();
            }

            if(calcWidth < obj.find('.tab-menu li.active').width())
                obj.find('.tab-menu').addClass('two-lines-tab-menu');
            else if(obj.find('.tab-menu').hasClass('two-lines-tab-menu'))
                obj.find('.tab-menu').removeClass('two-lines-tab-menu');

            obj.find('.tab-menu ul').width(calcWidth);

        }

        var stringToUri = function(string) {
            if (string.length) {
                var uri = string.toLowerCase();
                uri = uri.replace(/\u00e4/g, "ae");
                uri = uri.replace(/\u00fc/g, "ue");
                uri = uri.replace(/\u00f6/g, "oe");
                uri = uri.replace(/\u00df/g, "ss");
                uri = uri.replace(/ /g, "-");
                return uri.trim();
            }
            return string.trim();
        }

        // if tab-navigation is created from backend layout in typo3 , the menu list has to be created automatically
        // by moving the h2 header above the raster layouts to an ul-list
        var buildMenu = function(obj) {
            //var content = $(obj).find('.tab-content > div');
            var content = $(obj).children('.tab-content').children('div');
            var menu = $('<div class="tab-menu"></div>');
            var ul = $('<ul></ul>');

            var deeplink = $('.deeplink');
            var active = false;
            var path = null;

            if (deeplink.attr('data-uid')) {
                active = deeplink.attr('data-uid');
            } else {
                if (location.pathname.length) {
                    var pathArr = location.pathname.split('/');  
                    if (pathArr.length) {
                        pathArr = pathArr.filter(function(e){return e});
                        if (pathArr.length) {
                            path = pathArr[pathArr.length - 1];
                        }
                    }
                }               
            }

            content.each (function(k, v) {
                // header above raster layout must be of type h2
                var header = $(v).children('div').children('header').children('h2').clone();
                var className = '';

                if (active) {
                    if (active == $(v).find('[data-uid]').attr('data-uid')) {
                        className = 'active';
                    }
                } else if (path.length && stringToUri(header.text()) === path) {
                    className = 'active';
                    active = true;
                }

                // if header contains <sup>-tag, use html, else text
                if (header.html() != undefined && header.html().match(/(<sup>(.*?)<\/sup>)|(<br\\?>)/gi)) {
                    ul.append($('<li class="'+className+'">' + header.html() + '</li>'));
                } else {
                    if (active == false && header.find('.active').length) {
                        className = 'active';
                        active=true;
                    }

                    ul.append($('<li class="'+className+'">' + header.text() + '</li>'));
                }

                $(v).children('div').children('header').remove();
            });

            menu.append(ul);
            $(obj).prepend(menu);

            // check if selected tab is visible in menu
            var activeElement = menu.find('li.active');

            var visibleInTabnavigation = function(tab) {
                var menuRightBorder =  menu.offset().left + menu.width();
                var tabRightBorder =  tab.offset().left + tab.width() + 70;
                return menuRightBorder >= tabRightBorder;
            }

            if (active == false) {
                if (activeElement.length > 0 && visibleInTabnavigation(activeElement) == false && ul.children.length > 1) {
                    $.each(ul.children(), function(index, tab) {
                        if (visibleInTabnavigation(activeElement) == false && !$(tab).is(activeElement)) {
                            $(tab).hide();
                        } else {
                            return false;
                        }
                    });
                }               
            }


            return $(obj).find('.tab-menu li');
        }

        return function() {

            this.init = function() {

                return this.each(function() {

                    var obj = $(this);
                    var content = $(obj).children('.tab-content').children('div');

                    var menu = null;

                    if (!$(obj).find('.tab-menu').length) {
                        menu = buildMenu(obj);
                    } else {
                        menu = obj.find('.tab-menu li');
                    }

                    content.hide();

                    var active = obj.find('.tab-content > .active');
                    // select tab from shortcut
                    if (active.length == 1) {
                        var activeDiv = active.closest('.tab-content > div');
                        var index = activeDiv.index() + 1;
                        $('.tab-menu ul li:nth-child('+ index +')').addClass('active');
                        activeDiv.show();
                    } else if (obj.find('.tab-menu li.active').length == 0) {
                        // first entry is visible by default
                        menu.first().addClass('active');
                        content.first().show();
                    } else {
                        content.eq(obj.find('.tab-menu li.active').index()).show();
                    }

                    // check if given tab is inside viewport
                    var tabIsVisble = function(tab) {
                        var tabOffset = tab.offset();
                        var tabRightBorder = tab.offset().left + tab.width() + 80;
                        return $(window).width() >= tabRightBorder;
                    }

                    // only show content of selected element
                    menu.on('click', function(e) {

                        var elem = $(this);

                        menu.removeClass('active');
                        elem.addClass('active');

                        // hide prev element if current is not in viewport completely
                        if (elem.prev().length > 0 && tabIsVisble(elem) == false) {
                            elem.prev().hide();
                        }

                        $.each(menu, function(k, v) {
                            if (elem.is($(v))) {
                                content.hide();
                                content.eq(k).show();
                            }
                        });

                        if (typeof WITTENSTEIN.hotspot.specialEffectsHandler === 'function') {
                            WITTENSTEIN.hotspot.specialEffectsHandler();
                        }
                    });

                    arrowNav(obj, menu);

                    $(window).resize(function() {
                        arrowNav(obj, menu);
                    });
                });
            }
        }
    })();

    $.fn.tabnavigation = function(options) {
        var tn = new tabnavigation();
        tn.init.call(this, options);
    }

})(jQuery);

//extended tabs (M300x)
(function($) {
    $.fn.tabs = function(options) {

        var settings = $.extend({
            nav: '<ul class="nav-tabs" role="tablist"/>',
            activeClassName: 'active'
        }, options );

        /**
         * Generate random id for elements
         * 
         * @return String
         */
        var getRandomId = function() {
            var S4 = function() {
                return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
            };
            return 'tab-' + (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
        };

        /**
         * Create navigation from given element
         * 
         * @return Object nav
         */
        var makeNavigation = function(obj) {

            var nav = $(settings.nav);
            var tab = $('<li/>');
            var content = obj.children('.tab-content').children('div');

            if (!nav.prop('tagName').match(/UL/i)) {
                tab = $('<div/>');
            }

            var active = 0;
            var activeNotSet = true;

            content.each(function(index, element) {
                // header above raster layout must be of type h2
                //var header = $(element).find('h2:first');
                var header = $(element).children('div').children('header').children('h2');
                var newTab = tab.clone();

                if (typeof $(element).attr('id') != 'undefined') {
                    var id = $(element).attr('id');
                } else {
                    var id = getRandomId();
                    $(element).attr('id', id);
                }
                var link = $('<a data-toggle="tab" href="#'+id +'" />');

                if (activeNotSet) {
                    if (header.hasClass(settings.activeClassName) || header.find('.'+settings.activeClassName).length) {
                        newTab.addClass(settings.activeClassName);
                        activeNotSet = false;
                        active = index;
                    }           
                }

                // if header contains <sup>-tag, use html, else text
                if (header.html() != undefined && header.html().match(/(<sup>(.*?)<\/sup>)|(<br\\?>)/gi)) {
                    link.append(header.html());
                } else {
                    link.append(header.text());
                }
                newTab.append(link);
                nav.append(newTab);
                header.remove();
                $(element).addClass('tab-pane');
            });

            if (activeNotSet) {
                nav.children().first().addClass(settings.activeClassName);
            }
            content.eq(active).addClass(settings.activeClassName).tab('show');

            if( parseInt(obj.attr('data-reverse')) == 1 ) {
                obj.append(nav);
            } else {
                obj.prepend(nav);
            }

            return nav;
        };

        /**
         * Build and append dropdown
         */
        var tabs2Dropdown = function(obj) {
            // hide original tab navigation
            obj.find('.nav-tabs:first').addClass('navtab-hidden-'+obj.attr('data-breakpoint'));

            var buildButton = function(navtab) {
                var wrapper = $('<div class="btn-group tab-dropdown-container dropdown-visible-'+obj.attr('data-breakpoint')+'"/>');
                navtab.removeClass('nav-tabs').addClass('dropdown-menu');

                var button = $('<button type="button" class="btn btn-default dropdown-toggle tab-dropdown" data-toggle="dropdown"/>');
                var caret = $('<span class="caret"/>');
                // text for button
                var text = navtab.children('li.active').length == 1 ? navtab.children('li.active').text() : navtab.children('li:first').text();
                button.text(text);
                button.append(caret);

                wrapper.append(button);
                wrapper.append(navtab);

                // remove original click behavior on clone
                navtab.find('a[data-toggle="tab"]').removeAttr('data-toggle');
                // add new one
                navtab.on('click', 'li > a', function() {

                    wrapper.siblings().removeClass('tab-dropdown-active');
                    wrapper.addClass('tab-dropdown-active');

                    button.text($(this).text());
                    button.append(caret);
                    var link = $('.nav-tabs a[data-toggle="tab"][href="' + $(this).attr('href') + '"]');
                    link.trigger('click');
                    return false;
                });
                return wrapper;             
            };

            // build each tab element as dropdown
            if (obj.find('.tab-navigation[data-mode="0"]').length > 0) {
                $.each(obj.find('.nav-tabs:first li'), function(index, element) {
                    var navTab = $('<ul/>').append($(element).clone())
                    var button = buildButton(navTab);
                    // append button to DOM
                    if ($(element).closest('ul').parent().children('.tab-dropdown-container').length > 0) {
                        $(element).closest('ul').parent().children('.tab-dropdown-container:last').after(button);
                    } else {
                        button.addClass('tab-dropdown-active');
                        $(element).closest('ul').parent().prepend(button);
                    }
                });
            } else {
                // build tabs in one dropdown
                var originalNavTabs = obj.find('.nav-tabs:first');
                var button = buildButton(originalNavTabs.clone());
                // append button to DOM
                $(originalNavTabs).parent().prepend(button);
                button.addClass('tab-dropdown-active');
            }
        };  

        // add list elements to parents dropdown
        var subTabs2Dropdown = function(obj) {
            var parentNav = obj.closest('.tab-navigation.extended[data-mode="dropdown"]');
            if (parentNav.length > 0) {

                var originalNavTabs = obj.find('.nav-tabs:first');
                // hide original tab navigation
                originalNavTabs.addClass('navtab-hidden-'+obj.closest('.tab-navigation.extended[data-mode="dropdown"]').attr('data-breakpoint'));

                var position = originalNavTabs.closest('.tab-pane').index(); 
                var dropdown = parentNav.children(':eq('+position+')').find('.dropdown-menu');
                var button = dropdown.prev('.dropdown-toggle');
                var caret = $('<span class="caret"/>');

                var link = dropdown.find('li:first a');
                var ul = $('<ul/>');
                $.each(originalNavTabs.children('li'), function(index, element) {
                    var li = $(element).clone();
                    li.removeClass('active');
                    var a = li.children('a:first');
                    a.removeAttr('data-toggle')
                    a.text( link.text() + ' ' + a.text() ); 
                    ul.append(li);

                    if (index == 0) {
                        button.text(a.text());
                        button.append(caret);
                    }
                });

                link.parent().append(ul);
                link.hide();

                // click listenter to change text in dropdown
                originalNavTabs.on('click', 'li > a', function() {
                    link.trigger('click');
                    var dropdownLink = dropdown.find('a[href="'+$(this).attr('href')+'"]');
                    dropdownLink.parent().siblings().removeClass('active');
                    dropdownLink.parent().addClass('active');
                    button.text(dropdownLink.text());
                    button.append(caret);
                });
            }
        };

        /**
         * 
         */
        var tabs2DropdownInOneButton = function(obj) {
            var originalNavTabs = obj.find('.nav-tabs:first');
            var navTabs = originalNavTabs.clone();
            var wrapper = $('<div class="btn-group tab-dropdown-container tab-dropdown-single"/>');

            navTabs.removeClass('nav-tabs').addClass('dropdown-menu');
            var button = $('<button type="button" class="btn btn-default dropdown-toggle tab-dropdown" data-toggle="dropdown"/>');
            var caret = $('<span class="caret"/>');
            button.text(navTabs.children('li.active').text());
            button.append(caret);

            wrapper.append(button);
            wrapper.append(navTabs);

            // append button to DOM
            //originalNavTabs.parent().append(wrapper);
            originalNavTabs.after(wrapper)

            // remove original click behavior
            navTabs.find('a[data-toggle="tab"]').removeAttr('data-toggle');
            // add new one
            navTabs.on('click', 'li > a', function() {
                toggleButton($(this), true);
                return false;
            });
            // toggle button if original tabs are clicked
            originalNavTabs.on('click', 'li > a', function() {
                var element = $('.dropdown-menu a[href="' + $(this).attr('href') + '"]');
                toggleButton(element, false);
            });

            var toggleButton = function(element, triggerClick) {

                var text = $(element).text();
                if (triggerClick) {
                    var link = $('.nav-tabs a[href="' + $(element).attr('href') + '"]');
                    link.trigger('click');
                } else {
                    var link = wrapper.find('a[href="'+$(element).attr('href')+'"]');
                    var ul = link.next('ul');

                    if (ul.length > 0) {
                        //text = link.next('ul').find('li:first > a').text();
                        var active = ul.find('li.active').length > 0 ? ul.find('li.active') : ul.find('li:first');
                        text = active.children('a').text();
                        link.hide();
                    }
                }
                $(element).parent().addClass('active');
                $(element).parent().siblings().removeClass('active');
                button.text(text);
                button.append(caret);
            };
        };

        // add list elements to parents dropdown
        var subTabs2DropdownInOneButton = function(obj) {
            var dropdown = obj.closest('.tab-navigation.extended[data-mode="dropdown"]').find('.tab-dropdown-single').children('.dropdown-menu');
            if (dropdown.length > 0) {
                var originalNavTabs = obj.find('.nav-tabs:first');
                var button = dropdown.prev('.dropdown-toggle');
                var id = obj.closest('.tab-pane').attr('id');
                var link = dropdown.find('a[href="#'+id+'"]');
                var dropdownLi = link.parent();

                if (dropdownLi.prev().length && !dropdownLi.prev().hasClass('divider')) {
                    dropdownLi.before( $('<li role="separator" class="divider" />') )
                }

                var ul = $('<ul/>');
                $.each(originalNavTabs.children('li'), function(index, element) {
                    var li = $(element).clone();
                    li.removeClass('active');
                    var a = li.children('a:first');
                    a.text( link.text() + ' ' + a.text() ); 
                    ul.append(li);
                });
                dropdownLi.append(ul);
                link.hide();

                ul.on('click', 'li > a', function() {
                    $(this).closest('ul').prev().trigger('click');
                });

                // change text in dropdown
                originalNavTabs.on('click', 'li > a', function() {
                    var dropdownLink = dropdown.find('a[href="'+$(this).attr('href')+'"]');
                    dropdownLink.parent().siblings().removeClass('active');
                    dropdownLink.parent().addClass('active');
                    button.text(dropdownLink.html());
                });

                if(dropdown.children('.active').children('ul').length > 0) {
                    dropdown.children('.active').find('ul li:first a').trigger('click')
                }
            }
        };

        return this.each(function() {
            var self = $(this);

            // create navigation as required by bootstrap
            var nav = makeNavigation(self);

            // append third party libs
            switch (self.attr('data-mode')) {
            case 'scrolling': 
                //self.scrollingTabs();
                break;
            case 'collapse':
                self.tabCollapse();
                break;
            case 'dropdown':
                tabs2Dropdown(self);
                tabs2DropdownInOneButton(self);
                break;
            default:
                subTabs2Dropdown(self);
            subTabs2DropdownInOneButton(self);
            }
        });
    }
})(jQuery);

//css modification for layouts (gridelements)
(function($) {

    // anpassung für layouts 8-4 (4-8), text und bild
    var layout = (function() {

        return function() {

            var settings = {
                    'layout' : 'layout-84'
            };

            this.init = function(options) {

                settings = $.extend(settings, options);

                return this.each(function() {

                    switch (settings.layout) {
                    case 'layout-714':

                        if ($(this).find('.col-md-7 li.start-slide video')) {
                            var height = parseInt($(this).find('.col-md-7 li.start-slide .clearfix').outerHeight(true))
                            + parseInt($(this).find('.col-md-7 li.start-slide .videoIosWrap').css('padding-top'));
                            $(this).find('.col-md-4').css('margin-top', height + 'px');
                        }

                        var buttonContent = $(this).find('.button_3');
                        if(WITTENSTEIN.isMediaXS()) {
                            if ($(this).find('.button_3').length) {
                                $.each($(this).find('.button_3'), function(index, button){
                                    $(button).html($(button).html().replace(/&nbsp;/gi,''));
                                });
                            }
                        }

                        break;

                    case 'layout-84':
                        $(this).find('iframe').parent().addClass('container-iframe');
                        break;

                    case 'layout-48':

                        // .. und auch bei videos in der mediathek soll der text auf gleicher höhe anfangen
                        if ($(this).find('.col-md-8 li.start-slide video')) {
                            var height = parseInt($(this).find('.col-md-8 li.start-slide .clearfix').outerHeight(true))
                            + parseInt($(this).find('.col-md-8 li.start-slide .videoIosWrap').css('padding-top'));
                            $(this).find('.col-md-4').css('margin-top', height + 'px');
                        }

                        break;

                    case 'magazin':

                        $(this).parent('.csc-firstHeader').css('padding-left', '4px');

                        // magazin raster-layout
                        // spaltenbreite von teaser6 und teaser7 ändern, wenn teaser6 mit teaser7 vertauscht wurde.
                        if ($(this).find('.row2 > .col-md-3:last .teaser6').length) {

                            $(this).find('.row2 > .col-md-6').removeClass('col-md-6').addClass('col-md-3');
                            $(this).find('.row2 > .col-md-3:last').removeClass('col-md-3').addClass('col-md-6');
                        }

                        // spaltenbreite in breakpoint sm
                        if ($(this).find('.row2 > .col-sm-4:last .teaser6').length) {
                            $(this).find('.row2 > .col-sm-8').removeClass('col-sm-8').addClass('col-sm-4');
                            $(this).find('.row2 > .col-sm-4:last').removeClass('col-sm-4').addClass('col-sm-8');
                        }

                        /**
                         * set fix width for each teaser, else it may happen that the width is no integer value
                         * and the scale effect does not appear smooth
                         *
                         * (START)
                         */
                        {
                            var teaserClasses = [
                                                 '.teaser1',
                                                 '.teaser2',
                                                 '.teaser3',
                                                 '.teaser4',
                                                 '.teaser5',
                                                 '.teaser6',
                                                 '.teaser7',
                                                 ];

                            for (var i in teaserClasses) {
                                var teaser = $(this).find(teaserClasses[i]);

                                $.each(teaser, function(k, v) {
                                    $(v).attr('style', '');
                                    $(v).attr('style', 'width: ' + $(v).width() + 'px');
                                });

                            }
                        }
                        /**
                         * (END)
                         */

                        break;

                    case 'menu-flyout':

                        if ( ($(this).find('.col-md-6.middle-left .col-xs-content > h2').length >= 1 || $(this).find('.col-md-6.middle-left .col-xs-content > header > h2').length >= 1) &&
                                $(this).find('.col-md-6.middle-right .col-xs-content > h2').length == 0 && 
                                $(this).find('.col-md-6.middle-right .col-xs-content > header > h2').length == 0) {

                            $(this).find('.col-md-6.middle-right .col-xs-content').prepend($('<h2 class="empty-h2">&nbsp;</h2>'));
                            $(this).find('.col-md-6.middle-right').css('padding-left', '0');
                        }

                        if ($(this).find('.col-md-6.middle-left h2').length >= 1 &&
                                $(this).find('.col-md-6.middle-right h2:not(.empty-h2)').length >= 1) {

                            $(this).find('.col-md-6.middle-right').css('border-left', '1px solid #e4e4e4');

                            var maxH = Math.max.apply(this, $.map($(this).find('.col-md-3, .col-md-6'), function(v) { return $(v).height(); }));
                            $(this).find('.col-md-6.middle-left, .col-md-6.middle-right').height(maxH);

                        }

                        // set height of headlines to the max height, so that all content begins on the same line
                        var maxHeight = Math.max.apply(this, $.map($(this).find('h2'), function(v) { return $(v).height() }));
                        $(this).find('h2').height(maxHeight);

                        var $subheadlines = $(this).find('.col-md-6.middle-right .col-xs-content h3');
                        if ($subheadlines.length) {
                            var text = $subheadlines.text().trim();
                            $subheadlines.parent().parent('.col-xs-content').parent('.no-margin').remove();
                            $(this).find('.col-md-6.middle-right ul.csc-menu').prepend($('<li><p><b>' + text + '</b></p></li>'));
                        }

                        if (!WITTENSTEIN.isMediaMD()) {
                            // reset height
                            $(this).find('.col-md-6.middle-left, .col-md-6.middle-right').css('height', 'auto');
                            $(this).find('h2.csc-firstHeader').css('height', 'auto');
                        }

                        break;

                    default:
                        break;
                    }

                });
            }
        }
    })();

    $.fn.layout = function(options) {
        var l = new layout();
        l.init.call(this, options);
    }
})(jQuery);
//spam protection
//replace [at] with @ on click
(function($) {

    var spamprotection = (function() {

        return function() {

            this.init = function() {
                return this.each(function() {

                    $(this).on('click', function(e) {

                        var href = $(this).attr('href') ;

                        $(this).attr('href', href.replace("[at]", "@").
                                replace("%5Bat%5D", "@"));
                    })
                });
            }
        }
    })();

    $.fn.spamprotection = function(options) {
        var e = new spamprotection();
        e.init.call(this, options);
    }
})(jQuery);
//kompetenzen
(function($) {

    var kompetenzen = (function() {

        var centerImages = function() {
            // container width
            var cw = $(this).outerWidth(true);

            $(this).find('img').each(function() {
                // image width
                var iw = $(this).attr('width');

                var left = (iw - cw) / 2 ;

                $(this).css('left', '-' + left + 'px');
            });
        }

        return function() {

            this.init = function() {

                return this.each(function() {

                    var obj = this;
                    centerImages.apply(obj);

                    $(window).resize(function() {
                        centerImages.apply(obj);
                    });

                });
            }
        }
    })();

    $.fn.kompetenzen = function(options) {
        var k = new kompetenzen();
        k.init.call(this, options);
    }

})(jQuery);
(function($) {
    "use strict";

    var lastScrollTop = $(window).scrollTop(),
    lastScrollLeft = $(window).scrollLeft();
    
    $(window).on("scroll", function(event) {
        var scrollTop = $(this).scrollTop(),
        scrollLeft = $(this).scrollLeft(),
        directionX = "",
        directionY = "";

        if (scrollTop > lastScrollTop) {
            directionY = "down";
        } else if (scrollTop < lastScrollTop) {
            directionY = "up";
        }

        if (scrollLeft > lastScrollLeft) {
            directionX = "left";
        } else if (scrollLeft < lastScrollLeft) {
            directionX = "right";
        }

        lastScrollTop = scrollTop;
        lastScrollLeft = scrollLeft;
        event.directionX = directionX;
        event.directionY = directionY;
    });

}(jQuery));

(function($) {
    $.fn.tabs2Accordion = function(options) {

        var settings = $.extend({
            activeClassName: 'active'
        }, options );

        /**
         * Generate random id for elements
         * 
         * @return String
         */
        var getRandomId = function() {
            var S4 = function() {
                return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
            };
            return 'ta-' + (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
        };

        /**
         * Create navigation from given element
         * 
         * @return Object nav
         */
        var makeNavigation = function($obj) {
            var $content = $obj.find('.tab-content > div');
            var $ul = $('<ul class="nav nav-tabs" />');
            var active = false;
            var activeIndex = 0;

            $content.each(function(index, element) {
                var $header = $(element).find('header > h2:first');
                var id = $header.parent().attr('id') ? $header.parent().attr('id') : getRandomId();
                var $li = $('<li/>');
                var $link = $('<a href="#' + id + '" data-toggle="tab" />');

                if (!active) {
                    if ($header.hasClass(settings.activeClassName) || $header.find('.'+settings.activeClassName).length) {
                        $li.addClass(settings.activeClassName);
                        active = true;
                        activeIndex = index;
                    }           
                }                

                // if header contains <sup>-tag, use html, else text
                if ($header.html() != undefined && $header.html().match(/(<sup>(.*?)<\/sup>)|(<br\\?>)/gi)) {
                    $link.append($header.html());
                } else {
                    $link.append($header.text());
                }
                $header.remove();

                $li.append($link);
                $ul.append($li);
            });
            $obj.prepend($ul);
            if (!active) {
                $ul.find('li:first').addClass(settings.activeClassName);
            }

            $obj.addClass('tab-accordion__style-' + $ul.children().length);
        }

        /**
         * Create content from given element
         * 
         * @return Object nav
         */
        var makeContent = function($obj) {
            var $headlines = $obj.find('.nav-tabs > li > a');
            var $ce = $obj.find('.tab-content > div');

            // create accordion headings
            if ($headlines.length) {
                $.each($headlines, function(index, headline) {
                    var id = getRandomId();
                    var $headline = $(headline);
                    var $wrapper = $('<div class="tab-pane" id="' + $headline.attr('href').replace(/^#/, '') + '" />');
                    var $accordion = $('<div class="panel panel-default" />');

                    var $heading = $('<div class="panel-heading"></div>');
                    var $title = $('<h3><a data-index="' + index + '" href="#' + id + '" data-toggle="collapse" ' + 'data-parent=".tab-pane">' + $headline.text() + '</a></h3>');
                    var $content = $('<div id="' + id + '" class="panel-collapse collapse clearfix" />');

                    if ($headline.closest('li').hasClass(settings.activeClassName)) {
                        $heading.addClass(settings.activeClassName);
                        $wrapper.addClass(settings.activeClassName);
                        $content.addClass('in');
                    }

                    $heading.append($title);
                    $accordion.append($heading);
                    $accordion.append($content);
                    $wrapper.append($accordion);
                    $wrapper.appendTo($obj.find('.tab-content'));
                    $content.append($ce[index]);
                });
            }
        }

        /**
         * Append click listener
         */
        var appendListener = function($obj) {
            // synchronize tabs on accordion click
            var $accordions = $obj.find('h3 a[data-toggle="collapse"]');
            $accordions.click(function() {
                $obj.find('.nav.nav-tabs li').removeClass(settings.activeClassName);
                $obj.find('.tab-pane').removeClass(settings.activeClassName);
                $obj.find('.nav.nav-tabs li').eq($(this).attr('data-index')).addClass(settings.activeClassName);
                $obj.find('.tab-pane').eq($(this).attr('data-index')).addClass(settings.activeClassName);

                var $heading = $(this).closest('.panel-heading');
                $obj.find('.panel-heading').not($heading).removeClass(settings.activeClassName);
                $heading.toggleClass(settings.activeClassName);
            });

            // synchronize accordions on tab click
            var $tabs = $obj.find('.nav.nav-tabs a');
            $tabs.on('shown.bs.tab', function (e) {
                $obj.find('.panel-collapse.in').removeClass('in');
                $obj.find('.tab-pane.active .panel-collapse').addClass('in');

                $obj.find('.panel-heading').removeClass(settings.activeClassName);
                $obj.find('.tab-pane.active .panel-heading').addClass(settings.activeClassName);
            })
        }

        return this.each(function() {
            var $self = $(this);
            makeNavigation($self);
            makeContent($self);
            appendListener($self);
        });
    }
})(jQuery);
var WITTENSTEIN = {

        // breakpoints
        SCREEN_XS  : 320,
        SCREEN_IS  : 600,
        SCREEN_SM  : 900,
        SCREEN_MD  : 1024,
        SCREEN_MP  : 1194,
        SCREEN_LG  : 1600,

        // sets a cookie
        setCookie : function(key, value, path, domain, days) {

            if (typeof key === 'undefined' || typeof value === 'undefined') {
                throw new Error("no key and/or value specified");
            }

            if (typeof path === 'undefined') {
                path = '/';
            }

            var expires = '';
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days*24*60*60*1000));
                expires = 'expires='+date.toUTCString()+';';
            }

            // if true set cross-subdomain
            var parts = location.hostname.split('.');
            var subdomain = parts.shift();
            domain = domain ? 'domain='+parts.join('.')+';' : '';

            return document.cookie = key + '=' + value + ';path=' + path + ';' + domain + expires;
        },

        // reads the value of key
        readCookie : function(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for(var i=0;i < ca.length;i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                if (c.indexOf(nameEQ) == 0) {
                    return c.substring(nameEQ.length,c.length);
                }
            }
            return null;
        },

        // delete a cookie key
        deleteCookie : function(name) {
            // if true set cross-subdomain
            var parts = location.hostname.split('.');
            var subdomain = parts.shift();
            domain = 'domain=.'+parts.join('.')+'; ';
            document.cookie = name + "=;path=/;" + domain + "expires=Thu, 01 Jan 1970 00:00:00 GMT";
        },

        // check viewports
        isMediaXS: function() {
            return window.innerWidth < WITTENSTEIN.SCREEN_IS;
        },

        isMediaIS : function() {
            return window.innerWidth < WITTENSTEIN.SCREEN_SM &&
            window.innerWidth >= WITTENSTEIN.SCREEN_IS ;
        },

        isMediaSM : function() {
            return window.innerWidth < WITTENSTEIN.SCREEN_MD &&
            window.innerWidth >= WITTENSTEIN.SCREEN_SM;
        },

        isMediaMD : function() {
            return window.innerWidth >= WITTENSTEIN.SCREEN_MD;
        },

        isMediaLG : function() {
            return window.innerWidth >= WITTENSTEIN.SCREEN_LG;
        },

        isPortable : function() {
            return WITTENSTEIN.isMediaXS() || WITTENSTEIN.isMediaIS();
        },

        isMobile : function() {
            return window.innerWidth < WITTENSTEIN.SCREEN_MD;
        },

        // equal and greater
        isGreaterThenMediaXS : function() {
            return window.innerWidth >= WITTENSTEIN.SCREEN_XS;
        },
        isGreaterThenMediaIS : function() {
            return window.innerWidth >= WITTENSTEIN.SCREEN_IS;
        },
        isGreaterThenMediaSM : function() {
            return window.innerWidth >= WITTENSTEIN.SCREEN_SM;
        },
        isGreaterThenMediaMD : function() {
            return window.innerWidth >= WITTENSTEIN.SCREEN_MD;
        },
        isGreaterThenMediaLG : function() {
            return window.innerWidth >= WITTENSTEIN.SCREEN_LG;
        },

        //get ios version
        //read: iOSversion[0] >= 6 -> is version 6 or higher
        iOSversion : function() {
            if (/iP(hone|od|ad)/.test(navigator.platform)) {
                // supports iOS 2.0 and later: <http://bit.ly/TJjs1V>
                var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
                return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
            }
            return false;
        },

        // check if device is a mobile device
        isMobileDevice : function() {
            return (navigator.userAgent.match(/Android/i) ||
                    navigator.userAgent.match(/webOS/i) ||
                    navigator.userAgent.match(/iPhone/i) ||
                    navigator.userAgent.match(/iPod/i) ||
                    navigator.userAgent.match(/BlackBerry/i) ||
                    navigator.userAgent.match(/Windows Phone/i));
        },

        isTabletDevice : function() {
            return (navigator.userAgent.match(/Android/i) ||
                    navigator.userAgent.match(/iPad/i) ||
                    navigator.userAgent.match(/Android 3.0/i)||
                    navigator.userAgent.match(/Tablet/i) ||
                    navigator.userAgent.match(/Kindle/i));
        },

        init : function () {

            // load jQuery events
            WITTENSTEIN.layout.init();

            // Group switch
            WITTENSTEIN.groupswitch.init();

            // Pressebereich
            WITTENSTEIN.presse.init();

            // Newsblog
            WITTENSTEIN.newsblog.init();

            // Produktbereich
            WITTENSTEIN.produkte.init();

            // Kontakt
            WITTENSTEIN.kontakt.init();

            // Module ( Modulbaukasten )
            WITTENSTEIN.module.init();

            // Karrierebereich
            WITTENSTEIN.jobs.init();
            WITTENSTEIN.educationWall.init();
            WITTENSTEIN.educationApply.init();

            // Standort
            WITTENSTEIN.standort.init();

            // Service
            WITTENSTEIN.service.init();

            // Downloadbereich
            WITTENSTEIN.download.init();

            // Suche
            WITTENSTEIN.suche.init();

            // hotspot
            WITTENSTEIN.hotspot.init();
            WITTENSTEIN.hotspotMap.init();

            // videoquotes
            WITTENSTEIN.videoquotes.init();

            // product variants
            WITTENSTEIN.productvariants.init();

            // video collection
            WITTENSTEIN.videoCollection.init();

            // turntables
            WITTENSTEIN.mediathek.init();

            // tiles
            WITTENSTEIN.tile.init();
            
            // flexbox statements module
            WITTENSTEIN.flexboxStatements.init();
            
            // slider
            WITTENSTEIN.slider.init()

            // cube
            WITTENSTEIN.cube.init();

            // append video handler
            WITTENSTEIN.videoHandler.init();
            
            // Application Process
            WITTENSTEIN.applicationProcess.init();            
        }

};

$(function () {
    WITTENSTEIN.init();
});


/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.layout = (function($) {

    var overlay = false;
    var _toggle = false;

    /**
     * Smooth Scrolling
     */
    var smoothScrolling = function() {
        var url = window.location.href;
        if (url.match(/\?anchor=/)) {
            var anchor = '#' + url.substring(url.indexOf("?anchor=")).replace(/\?anchor=/, '');
            $('html,body').animate({scrollTop: $(anchor).offset().top-50}, 1000);

            if (history.pushState) {
                url = url.replace(/\?anchor=/g, '#');
                history.pushState({}, null, url);
            }
        }
        $("a[href*=#]").click(function() {
            var hrefArray = $(this).attr('href').split('#');
            var anchor = hrefArray[1];
            var regExp = new RegExp(/^[a-zA-Z0-9_-]+$/i);

            // check if anchor is valid
            if ( regExp.test(anchor) ) {
                $(this).attr('href', $(this).attr('href').replace(/#/, '?anchor='));
            }
        });
    }

    /**
     * button3 zeilenumbruch kontrollieren
     * button1 text auspunkten
     */
    var buttons = function() {
        var appendLineBreaksAtTheEndOfLine = function() {
            $.each($('.button_3'), function(index, button) {
                // skip news headlines
                if ($(button).closest('.news-text').length == 0) {
                    $(button).button3();
                }
            });         
        };

        appendLineBreaksAtTheEndOfLine();

        $('.button_1').load(function() {
            $('.button_1').button1();
        });

        $(window).resize(function() {
            appendLineBreaksAtTheEndOfLine();
            $('.button_1').load(function() {
                $('.button_1').button1();
            });
        });
    }

    // show subnavigation on mouseover
    // NOTICE: the css of the navigation and menu-flyout is changed dynamically!
    var navigation = function() {

        // close mobile search
        $('.navigation--toggler button').click(function(){
            if ($('.searchform__form--mobile').attr('aria-expanded') === 'true') {
                $('.searchform--mobile button').click();
            }
        });

        $('.navbar-nav .navigation__item').mousemove(function() {
            if (overlay === false && $(this).children('.navigation__flyout').length) {
                $('.bg-overlay').addClass('show');
                overlay = true;
            }
        });

        $('.navbar-nav').on({
            mouseleave: function() {
                $(this).removeClass('open');
                $(this).find('[data-state="active"]').addClass('active').removeAttr('data-state');
                $('.bg-overlay').fadeOut(function() {
                    $(this).removeClass('show');
                    overlay = false;
                });
            }
        });

        $('.navbar-nav li.sub').hover(function() {
            if (!$(this).parent().hasClass('open')) {
                $(this).parent().addClass('open');
            }
        });

        $('.navbar-nav li').hover(function() {
            if ($(this).siblings('.active').length) {
                $(this).siblings('.active').attr('data-state', 'active').removeClass('active');
            }
        });

        // caret hinzufÃ¼gen, wenn weitere links in unterpunkten vorhanden
        $('.navigation--mobile .navbar-nav .menu-item').each(function(k, v) {
            if ($(v).next('.menu-flyout').find('a').length) {
                $(v).append('<div class="caret caret-wico"></div>');
            }
        });

        // bei klick auf menu link keine weiteren events ausfÃ¼hren
        $('.navigation--mobile .menu-item:not(.additionalLink) > a').on('click', function(e) {
            // keine aktion bei klick auf 1. level-link, menÃ¼ soll ausklappen
            return e.preventDefault();
        });

        // menu in xs and sm view
        $('.navigation--mobile .navbar-nav > li > .menu-item').on('click', function(e) {
            // show hide 2. level
            if ($(this).siblings('.menu-flyout').is(':hidden')) {
                $('.navigation--mobile .navbar-nav > li > .menu-flyout').attr('style', 'display: none !important');
                $('.navigation--mobile .navbar-nav > li > .menu-item .caret').removeClass('caret-up-wico');
                $(this).siblings('.menu-flyout').attr('style', 'display: block !important');
                $(this).children('.caret').addClass('caret-up-wico');
            } else {
                $(this).siblings('.menu-flyout').attr('style', 'display: none !important');
                $(this).children('.caret').removeClass('caret-up-wico');
            }

            // fÃ¼gt einen pfeil an die Ã¼berschrift an, wenn es eine 3. ebene gibt
            if (!$('.menu-flyout .csc-menu').parents('.col-md-3, .col-md-6').find('h2 .caret').length) {
                $('.menu-flyout .csc-menu').parents('.col-md-3, .col-md-6').find('h2').append('<div class="caret caret-right-wico"></div>');
            }
        });

        $('.navbar-nav > li > .menu-item ~ .menu-flyout h2').on('click', function(e) {
            // show hide 3. level
            if ($(this).siblings('.csc-menu').is(':hidden')) {
                $('.navbar-nav > li > .menu-flyout .csc-menu').attr('style', 'display: none !important');
                $(this).parents('.col-md-6').find('.middle-left .csc-menu, .middle-right .csc-menu').attr('style', 'display: block !important');
                $(this).next('.csc-menu').attr('style', 'display: block !important');

                // Wenn Liste unter einer Ãœberschrift angesiedelt ist unterhalb von middle-left und middle-right (wie z.B. bei Leistungen und Produkte)
                // soll auch das MenÃ¼ unter middle-right ausklappen
                if ($(this).parents('.middle-left').next('.middle-right').find('h2.empty-h2').length) {
                    $(this).parents('.middle-left').next('.middle-right').find('h2.empty-h2').next('.csc-menu').attr('style', 'display: block !important');
                }
                $(this).children('.caret').addClass('caret-up-wico');
            } else {
                $(this).next('.csc-menu').attr('style', 'display: none !important');

                if ($(this).parents('.middle-left').next('.middle-right').find('h2.empty-h2').length) {
                    $(this).parents('.middle-left').next('.middle-right').find('h2.empty-h2').next('.csc-menu').attr('style', 'display: none !important');
                }
                $(this).children('.caret').removeClass('caret-up-wico');
            }
        });

        // show subnavigation (menu-flyout) on mouseenter
        $('.navigation--default > li').on('mouseenter', function(e) {
            if (!WITTENSTEIN.isMediaMD()) {
                return false;
            }
            $(this).find('.navigation__flyout').layout({
                layout: 'menu-flyout'
            });
        });

        /** IE11 Workaround for grid in Kompetenzen Flyout */
        // if IE11
        if (Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject) {
            if ($('.navigation__flyout .sub-kompetenzen').length > 0) {
                var $kompetenzenMitSub = $('.navigation__flyout .kompetenzen-mit-sub');
                var $subKompetenzen = $('.navigation__flyout .sub-kompetenzen');
                var $nextSiblings = $subKompetenzen.nextAll();

                if ($nextSiblings.length) {
                    var nextSiblingsHeight = 0;

                    $.each($nextSiblings, function(index, sibling) {
                        nextSiblingsHeight += $(sibling).outerHeight();
                    });

                    if ($subKompetenzen.height() > nextSiblingsHeight) {
                        var $placeholder = $('<li class="ie-grid-placeholder"></li>');
                        $placeholder.css('height', $subKompetenzen.height() - nextSiblingsHeight + 'px');
                        $kompetenzenMitSub.append($placeholder);
                    }
                }
            }
        }
    }

    /**
     * Function for sticky navi
     */
    var stickyNavigation = function() {
        var $header = $('header.head');
        var $metanavigation = $('nav.metanavigation');
        var duration = 250;
        var sticky = false;

        var headerHeight = $header.outerHeight();

        var showSticky = function() {
            if (sticky) {
                return;
            }
            sticky = true;
            $header.css({
                top: -$header.height()
            }).addClass('head--sticky');
            $metanavigation.css('margin-bottom', headerHeight);

            $header.stop().animate({
                top: 0
            }, duration);
        };

        var hideSticky = function(heightToShowToolbar) {
            if (!sticky) {
                return;
            }
            sticky = false;
            $header.stop().animate({
                top: -heightToShowToolbar
            }, duration, function() {
                $metanavigation.css('margin-bottom', 0);
                $header.css('top', 0).removeClass('head--sticky');
            });
        }

        var stickyNaviScrollHandler = function(event) {
            var scrollHeight = window.pageYOffset;
            var heightToShowToolbar = $metanavigation.height() + $header.height();

            if (WITTENSTEIN.isMobile() && typeof event != 'undefined') {
                heightToShowToolbar = $header.height() * 3;

                if (event.directionY == 'up' && scrollHeight >= heightToShowToolbar) {
                    showSticky();
                } else {
                    hideSticky(heightToShowToolbar);
                }
            } else {
                if (scrollHeight >= heightToShowToolbar) {
                    showSticky();
                } else {
                    hideSticky(heightToShowToolbar);
                }
            }
        };

        stickyNaviScrollHandler();
        // Show and hide sticky navi
        $(window).on('scroll', stickyNaviScrollHandler);

        // smooth scrolling
        $('.toolbar-top-link').bind('click', function(){
            $('html, body').animate({scrollTop: $('body').offset().top}, 250, 'linear');
        });
    }

    /**
     * Handler for search form
     */
    var searchForm = function() {
        var $searchform = $('.searchform--default');
        var $button = $searchform.children('button');
        var $headCol = $searchform.closest('.head__col');
        var $navigation = $('.navigation--default');
        var activeClassName = 'searchform--active';
        var $defaultInput =  $searchform.find('input[type="text"]');
        var $errorMessage = $('.searchform__error');
        var minLength = 2;

        var showForm = function() {
            $searchform.addClass(activeClassName);
            $navigation.addClass('disabled');
            $headCol.attr('style', 'position: relative;');
            $searchform.css({
                width: '100%'
            });
            $defaultInput.focus();
        };

        var hideForm = function() {
            $($searchform).css({
                width: '3rem'
            });
            $errorMessage.hide();

            setTimeout(function() {
                $headCol.removeAttr('style');
                $searchform.removeClass(activeClassName);
                $navigation.removeClass('disabled');
            }, 250)
        };
        
        var submitValidation = function($input) {
            if ($input.val().length < minLength) {
                // show warning
                $errorMessage.show();
                return false;
            } else {
                $errorMessage.hide();
            }
        };
        
        $searchform.submit(function() {
            return submitValidation($defaultInput);
        });

        $button.click(function() {
            var $wrapper = $(this).closest('.searchform');
            $wrapper.hasClass(activeClassName) ?  hideForm() : showForm();
        });
        
        var bgOverlayIsVisible = false;
        var $mobileSearchform = $('.searchform__form--mobile');
        var $mobileInput = $mobileSearchform.find('input[type="text"]');
        
        $mobileSearchform.submit(function() {
            return submitValidation($mobileInput);
        });
        
        $('.searchform--mobile button').click(function(event) {
            if ($mobileSearchform.attr('aria-expanded') === 'true') {
                $('.bg-overlay').removeClass('show');
                bgOverlayIsVisible = false;
            } else {
                $('.bg-overlay').addClass('show');
                bgOverlayIsVisible = true;
                // close navigation menu if open
                var $toggler = $('.navigation--toggler button');
                if ($toggler.attr('aria-expanded') === 'true') {
                    $toggler.click();
                }

                window.setTimeout(function () { 
                    $mobileInput.focus();
                }, 0);
            }
        });
        
        // hide warning on keyup
        var hideWarning = function(e) {
            var code = e.keyCode || e.which;
            if (code !== 13) {
                $errorMessage.hide();    
            }
        };
        $defaultInput.keyup(hideWarning);
        $mobileInput.keyup(hideWarning);

        if ($('#tx-solr-search-form-pi-results').length) {
            var $solrInput = $('#tx-solr-search-form-pi-results').find('input[type="text"]');
            var value = $solrInput.val();
            $solrInput.focus().val('').val(value);
        }

        // hide bg-overlay
        $(window).resize(function() {
            if (!WITTENSTEIN.isMobile() && bgOverlayIsVisible) {
                $('.searchform--mobile button').click();
            }
        });

        $('html').on('click', function(event) {
            if (!$searchform.is(event.target) && $searchform.has(event.target).length === 0) {
                hideForm();
            }
        });
    }

    var cookieBanner = function(){
        if($('#cookie_info').length>0) {
            var cookie = $('#cookie_info').attr("data");
            $('#cookie_info').hide();
            var bCookieInfo = Cookies.get(cookie);
            if ((!bCookieInfo) || (bCookieInfo == "false")) {
                //fix for mobile problem
                if($('#cookie_info').hasClass("showing")){
                    $('#cookie_info').slideUp();
                    $('#cookie_info').removeClass( "showing" );
                }else{
                    $('#cookie_info').addClass( "showing" );
                    $('#cookie_info').slideDown('slow');
                }
                Cookies.set(cookie, 'false', {
                    expires: 1,
                    path: '/'
                });
            }

            $('#cookie_info_button a').click(function (e) {
                e.preventDefault();
                $('#cookie_info').removeClass( "showing" );
                $('#cookie_info').slideUp();
                Cookies.set(cookie, 'true', {
                    expires: 30,
                    path: '/'
                });
            });
        }
    }

    /**
     * dont show the content in mobile view , when navbar is collapsed
     */
    var overlapNavbar = function(isHidden) {
        isHidden = false || isHidden;
        if ($('.navbar-collapse:hidden').length || isHidden) {
            $('section.content').height('auto');
            $('section.content > .row').css('display', 'block');

        } else {
            $('section.content').height($('.navigation').height() + $('.navbar-nav').height() + 'px');
            $('section.content > .row').hide();
        }
        $('.search-collapsed').hide();
    }

    // show/hide cross links
    var footer = function() {
        $('.footer-crosslinks header, .footer-crosslinks2 header, .footer-lang h2').on('click', function() {
            if (WITTENSTEIN.isPortable()) {
                var ver = WITTENSTEIN.iOSversion();
                if (ver[0] < 6) {
                    $(this).next('ul')[0].setAttribute("style", "display: block !important");
                }else{
                    $(this).next('ul').slideToggle();
                    $(this).children('h2').toggleClass( "arrow-helper" );
                }
            }
        });

        // hide or show cross links for different breakpoints
        $(window).resize(function() {
            if (WITTENSTEIN.isPortable()) {
                $('.footer-crosslinks header, .footer-crosslinks2 header, .footer-lang h2').next('ul').hide();
                $('.footer-crosslinks header, .footer-crosslinks2 header, .footer-lang h2').removeClass('arrow-helper');
            } else {
                $('.footer-crosslinks header, .footer-crosslinks2 header, .footer-lang h2').next('ul').show();
            }
        });
    }

    /**
     * lazy loading for img-tags
     */
    var lazyLoad = function() {
        $('.iecollection').each(function( index ) {
            var img = $(this).prev('source').last().attr('data-srcset');
            $(this).attr('src', img);
        });
    }

    /**
     * init pagination dropdown(s)
     */
    var pagination = function() {
        $('.page-navigation').udgPaginate('destroy').udgPaginate();
    }

    /**
     * add Useragent to html tag
     * this is done for ie10 fixes
     */
    var useragent = function() {
        var doc = document.documentElement;
        doc.setAttribute('data-useragent', navigator.userAgent);
    }

    /**
     * feature detection, checks for IE11
     * this is done for ie11 fixes
     */
    var checkIE11 = function() {
        if (Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject) {
            $('html').addClass('ie11');
        }
    }

    /**
     * feature detection, checks for IE9
     * this is done for ie9 fixes
     */
    var checkIE9 = function() {
        var nav = navigator.userAgent.toLowerCase();
        var ver = ((nav.indexOf('msie') != -1) ? parseInt(nav.split('msie')[1]) : false);

        if (ver == 9) {
            $('html').addClass('ie9');
        };
    }

    /**
     * placeholder fix
     */
    var placeholder = function() {
        $('input, textarea').placeholder();

        $('[placeholder]').focus(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
                input.removeClass('placeholder');
            }
        }).blur(function() {
            var input = $(this);
            if (input.val() == '' || input.val() == input.attr('placeholder')) {
                input.addClass('placeholder');
                input.val(input.attr('placeholder'));
            }
        }).blur();
    }

    /**
     * close the drop down when clicked on another dropdown
     */
    var dropdownHelper = function() {
        $('.dropdown-menu li').click(function(event) {
            // don't close dropdown if no link was clicked
            if($(this).children('a').length === 0) {
                event.stopPropagation();
            }
        });

        $(document).on('click', function (event) {
            /** @todo: fixme*/
            /*var wrapper = $(event.target).parent();         
            var regex = /(dropdown)|(^mCSB_)/g;

            if ( !(regex.test(wrapper.attr("class"))) ) {
                $('.dropdown li:not(.current)').css('display', 'none');
                $('.active-dropdown').removeClass("active-dropdown");
            }*/
        }).on('keydown', function(e){
            var dropdown = $('.active-dropdown');
            // pre-select on keybord input
            if (dropdown.length > 0) {
                var value = String.fromCharCode(e.keyCode);

                var li = $("li:not(.disabled)", dropdown).filter(function () {
                    try {
                        return new RegExp("^" + value, "i").test($(this).text().replace(/[^a-zA-Z ]/g, "")); 
                    } catch(e) {
                        return null;
                    }
                }).first();

                var select = dropdown.parent().prev();

                if (li.length == 1 && li.prop("tagName").toLowerCase() == 'li') {
                    // change selection
                    var current = li.clone();
                    li.addClass('hover current').siblings().removeClass('hover current');
                    dropdown.children(":first").replaceWith(current);

                    // prepare for submit
                    currentValue = li.attr('data-value');

                    select.find('option').each(function() {
                        $(this).attr('selected', ($(this).val() === currentValue));
                    });

                    current.on('click', function(e) {
                        select.trigger('change');
                    });
                }

                // search on enter
                if ($.inArray(e.keyCode, [13]) !== -1) {
                    $('.dropdown li:not(.current)').css('display', 'none');
                    $('.dropdown li').removeClass('hover');
                    select.trigger('change');
                }                   
            }
        });
    }

    /* prevent page scrolling while certain dropdowns are open */
    $('.metanavigation__dropdown .dropdown-toggle, .navbar-toggle, .groupswitch .dropdown-toggle').click(function() {
        if (window.innerWidth<WITTENSTEIN.SCREEN_SM) {
            setTimeout(function() {
                if ($('.metanavigation__dropdown .dropdown-toggle').attr('aria-expanded')==='true' ||
                    $('.navbar-toggle').attr('aria-expanded')==='true' ||
                    $('.groupswitch .dropdown-toggle').attr('aria-expanded')==='true') {
                    $('html').addClass('prevent-page-scrolling');
                } else {
                    $('html').removeClass('prevent-page-scrolling');
                }
            }, 100);
        }
    });

    $('.metanavigation__dropdown, .groupswitch').click(function() {
        if ($(this).find('.dropdown-toggle').attr('aria-expanded')!='true') {
            $('html').removeClass('prevent-page-scrolling');
        }
    });
    /* set viewport height value as custom property for mobile browsers with disappearing URL bars */
    var viewportHeight = function() {
        var vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', vh+'px');
    }
    viewportHeight();
    window.addEventListener('resize', viewportHeight);

    /**
     * Smooth scrolling for anchor links
     */
    var anchorLinks = function() {
        $('a[data-anchor]').click(function(){
            // anchor is on current page
            if( $(this).attr("href") == window.location.pathname) {
                var $element = $($(this).attr('data-anchor'));
                if ($element.length > 0) {
                    var position = $element.offset().top;

                    if (WITTENSTEIN.isMobileDevice()) {
                        $('html,body').scrollTop(position)
                    } else {
                        $('html,body').animate({scrollTop: position}, 1200);
                    }
                    return false;
                }
            }
        });
    };

    return {

        init : function() {
            lazyLoad();
            navigation();
            stickyNavigation();
            searchForm();
            footer();
            pagination();
            useragent();
            checkIE9();
            checkIE11();
            placeholder();
            buttons();
            smoothScrolling();
            dropdownHelper();
            cookieBanner();
            anchorLinks();

            // replace [at] with @ on click
            $('.email a').spamprotection();
        },
        /* IE Bug
         * SCRIPT1003 : Expected https://docs.microsoft.com/de-de/scripting/javascript/misc/expected-colon */
        placeholder: placeholder

    }

})(jQuery);

/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.applicationProcess=(function($) {

    "use strict";

    /**
     * Append slider
     */
    var initialize = function() {
        $('.udgprocess__slider').on({
            init:  function(event, slick) {
                // change acitve step on click in process menu
                slick.$slider.closest('.udgprocess').find('.udgprocess__step').click(function() {
                    slick.slickGoTo(parseInt($(this).parent().attr('data-index')));
                });
            },
            beforeChange: function(event, slick, currentSlide, nextSlide) {
                if (currentSlide != nextSlide) {
                    // change active class in steps
                    var $process = slick.$slider.siblings('.udgprocess__process');
                    if ($process.length) {
                        var activeClass = 'active';
                        $process.find('.udgprocess__step').removeClass(activeClass);
                        $process.find('.udgprocess__step:eq(' + nextSlide + ')').addClass(activeClass);
                    }

                    var $process = slick.$slider.find('.udgprocess__content');
                    if ($process.length) {
                        var activeClass = 'active';
                        $process.find('.udgprocess__step').removeClass(activeClass);
                        slick.$slider.find('.udgprocess__content:eq(' + nextSlide + ') .udgprocess__step').addClass(activeClass);
                    }

                    // update counter
                    var $counter = slick.$slider.siblings('.udgprocess__counter');
                    if ($counter.length) {
                        $counter.find('span').text(nextSlide + 1);
                    }
                }
            }
        }).slick({
            dots: false,
            infinite: false,
            speed: 300,
            adaptiveHeight: false,
            variableWidth: false,
            prevArrow: '<div class="slick-prev"></div>',
            nextArrow: '<div class="slick-next"></div>',
            slidesToShow: 1,
            responsive: [{
                breakpoint: 600, // is
                settings: {
                    arrows: false,
                }
            },{
                breakpoint: 900, // sm
                settings: {
                    arrows: false,
                }
            },
            {
                breakpoint: 1024, // md
                settings: {
                    arrows: false,
                }
            }]
        });
    }

    /**
     * Got to first step on tab change
     */
    var handleTabAccordionClick = function() {
        var $process = $('.udgprocess');
        var $tabAccordion = $process.closest('.tab-accordion');
        if ($tabAccordion.length) {
            $tabAccordion.find('.nav.nav-tabs a, .panel-heading a[data-toggle]').click(function() {
                // change acitve step on click in process menu
                $process.find('.udgprocess__step-container[data-index="0"] .udgprocess__step').click();
            });
        }
    }

    return {
        init : function() {
            if ($('.udgprocess').length) {
                initialize();
                handleTabAccordionClick();
            }
        }
    }
})(jQuery);
/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.tile=(function($) {
	
	var bodytextSelector = '.csc-textpic-text';
	
	var timer = null;

	/**
	 * Add fade in and fade out on each tile
	 */
	var addHoverEffect = function(){
		$(".tile").mouseenter(function(){
			$('.tile').removeClass('active');
			var bodytext = $(bodytextSelector, $(this));
			$(".tile " + bodytextSelector).not(bodytext).slideUp('slow');
            bodytext.stop(true,true);
			if (!bodytext.is(":visible")) {
				bodytext.slideDown('slow');
			}
			
			if (typeof timer != null) {
				clearInterval(timer);
			}
		}).mouseleave(function(){
			$(bodytextSelector, $(this)).stop(true,true).slideUp('slow');
			addInterval($(this).closest('.tiles'));
		});
	};

	/**
	 * Add scroll effects
	 */
	var addScrollEffect = function(){
		new AnimOnScroll( $('.tile'), {
			minDuration : 0.4,
			maxDuration : 0.7,
			viewportFactor : 0.2
		} );
	};

	/**
	 * Open tile
	 */
	var openTile = function(tile) {
		if (!tile.hasClass('active')) {
			
			var tiles = tile.closest('.tiles');
			tiles.find('.tile').removeClass('active');
			$(bodytextSelector, tiles).stop(true,true).slideUp('slow');
			
			tile.addClass('active').find(bodytextSelector).slideToggle('medium');
		}
	};
	
	/**
	 * Append interval timer to tiles
	 * 
	 * @params	Object	.tiles
	 */
	var addInterval = function(modul) {
		if (modul.attr('data-timer') == 1 && $(modul).attr('data-interval') > 0) {
			var interval = parseInt($(modul).attr('data-interval'));
			// setTimeout
			timer = setInterval(function(){
				var tile =  modul.find('.tile:first');
				if (modul.find('.tile.active').length > 0) {
					if (modul.find('.tile.active').parent().next().length) {
						tile = modul.find('.tile.active').parent().next().find('.tile');
					}
				}
				openTile(tile);
			}, interval)
		}
	};
	
	/**
	 * Append timer to all tiles
	 */
	var start = function() {
		$.each($('.tiles'), function(index, modul) {
			addInterval($(modul));
		});
	};

	return {
		init : function() {
			addScrollEffect();
			addHoverEffect();
			start();
		}
	}

})(jQuery);
/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.mediathek=(function($) {

	/**
	 * Append SpriteSpin
	 */
	var mediaSlider = function() {

		$('.turntable').spritespin('destroy');

		$.each($('.turntable'), function(index, turntable) {
			// im elternelement sollte in den hiddenfields der dateipfad stehen
			var source = [];
			$(turntable).parent().find('input[type=hidden]').each(function(i, j) {
				source.push($(j).val());
			});

			// bildverhältnis
			var imgW = $(turntable).parent().find('input[type=hidden]').first().attr('data-width');
			var imgH = $(turntable).parent().find('input[type=hidden]').first().attr('data-height');
			var ratio = imgW / imgH;

			var width  = $(turntable).parent().width();

			if (width > imgW) {
				width = imgW;
			}

			var spin = $(turntable);
			var slide = $($(turntable).attr('data-turntable-slider'));

			$(turntable).spritespin({
				source : source,
				width: width,
				height: (width / ratio),
				frameTime: 80,
				animate: false,
				onLoad: function() {
					slide.slider({
						min: 0,
						max: source.length - 1,
						slide: function(e, ui) {
							var api = $(turntable).spritespin('api');
							api.stopAnimation();
							api.updateFrame(ui.value);
						}
					});
				},
				onFrame: function(e, data) {
					slide.slider('value', data.frame);
				}
			});
		});
		// add turntable-arrow afterwards
		$('.turntable').prepend($('<div class="turntable-arrow"></div>'));
	}

	/**
	 * Append bxSlider
	 */
	var appendSlider = function() {
		var pagerCustom = '.bx-pager';
		var touchEnabled = false;
		var controls = false;
		if(WITTENSTEIN.isMobile()) {
			pagerCustom = false;
			touchEnabled = true;
			controls = true;
		}
		var slider = $('.mediathek-slide .bxslider').bxSlider({
			adaptiveHeight: true,
			slideWidth: 1186,
			pagerCustom: pagerCustom,
			touchEnabled: touchEnabled,
			useCSS: false,
			infiniteLoop: false,
			controls: controls,
			prevText: '',
			nextText: '',
			onSliderLoad: function(currentIndex) {
				if(!WITTENSTEIN.isMobile()) {
					var thumbActive = $('<img src="/typo3conf/ext/udg_template/Resources/Public/Images/presse/Thumb_active2.png" alt="" class="thumbactive">');
					$('.bx-pager').find('a').append(thumbActive);
					$('.bx-pager').find("[data-slide-index='" + currentIndex + "']").addClass('activeitem');

					if (currentIndex == 0) {
						disablePrev();
					}
					var count = $('.bx-pager').closest('.mediathek-slide').find('.bxslider li').length;
					if (count == 1) {
						disableNext();
					}
				}
			},
			onSlideAfter: function($slideElement, oldIndex, newIndex) {
				if(!WITTENSTEIN.isMobile()) {
					if (slider) {
						var pager = slider.closest('.mediathek-slide').find('.bx-pager');
						$(pager).find('a').removeClass('activeitem');
						$(pager).find('a[data-slide-index="' + newIndex + '"]').addClass('activeitem');
					}
				}
				//
				// if (newIndex > 0) {
				// 	enablePrev();
				// } else if (newIndex == 0) {
				// 	disablePrev();
				// }
				// if ($slideElement.next().length > 0) {
				// 	enableNext();
				// } else {
				// 	disableNext();
				// }
			}
		});

        if (slider) {
            var pagers = slider.closest('.mediathek-slide').find('.bx-pager');
			$(pagers).each(function() {
				var numSlides = $(this).children('a:not(.bx-clone)').length;
				if (numSlides > 1) {
					$(this).bxSlider({
                        slideWidth: 142,
                        minSlides: 1,
                        maxSlides: 4,
                        moveSlides: 1,
                        slideMargin: 17,
                        useCSS: false,
                        pager: false,
                        adaptiveHeight: true,
                        controls: true,
                        infiniteLoop: true,
						touchEnabled: false
                    });
				}
                if (numSlides < 4) {
                    // pager wrapper zentriert anzeigen, maximal vier bilder breit
                    // 142px ist die thumbnail groesse, 16px abstand und 96px für die navigationspfeile
                    $(this).closest('.bx-pager-wrapper').width(numSlides * (142 + 16) + 96 + 'px');
                }
			});
		}




		function disablePrev() {
			$('.bx-pager').closest('.mediathek-slide').find('.bx-prev').addClass('disabled');
		}
		function disableNext() {
			$('.bx-pager').closest('.mediathek-slide').find('.bx-next').addClass('disabled');
		}
		function enablePrev() {
			$('.bx-pager').closest('.mediathek-slide').find('.bx-prev').removeClass('disabled');
		}
		function enableNext() {
			$('.bx-pager').closest('.mediathek-slide').find('.bx-next').removeClass('disabled');
		}
	};

	/**
	 * Append turntables
	 */
	var turntables = function() {
		// turntables
		WITTENSTEIN.module.initStandaloneTurntables();
	};

	/**
	 * Resize function
	 */
	var resize = function() {
		mediaSlider();
	};

	return {
		init : function() {
			mediaSlider();
			turntables();
			// bxSlider as last
			// because the plugin clone a lot of stuff
			appendSlider();

			$(window).resize(resize);
		}
	}

})(jQuery);

/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.hotspot=(function($) {

    /**
     * @var XMLHttpRequest
     */
    var xhr;

    /**
     * @var string
     */
    var popoverContentTemplate = '\
        <div class="popover content-popover" role="tooltip">\
        <div class="popover-close"></div> \
        <h3 class="popover-title"></h3>\
        <div class="popover-content clearfix"></div>\
        </div>';

    /**
     * @var string
     */
    var popoverHotspotTemplate = {
            'default': '<div class="popover" role="tooltip"><div class="arrow"></div><div class="popover-content clearfix"></div></div>',
            'style1': '<div class="popover" role="tooltip"><div class="popover-content"></div></div>',
            'style2': '<div class="popover" role="tooltip">\
                <div class="arrow"></div>\
                <h3 class="popover-title"></h3>\
                <div class="popover-content clearfix"></div></div>',
    };

    /**
     * @var string
     */
    var results;

    /**
     * @var int
     */
    var startSlide = 0;

    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    /**
     * Show spinner
     */
    var showSpinner = function() {
        $(results).prepend("<div class='ajax-loading' style='background-position: center 100px;'></div>");
    };

    /**
     * Hide spinner
     */
    var hideSpinner = function() {
        $('.ajax-loading' , $(results)).remove();
    };

    /**
     * Add popovers to hotspots
     */
    var addContentPopover = function() {
        $('.information-link').popover({
            trigger: 'click',
            html: true,
            title: '',
            template: popoverContentTemplate,
            placement: 'top',
            content: function () {
                return $('.bxslider .active .content-storage').html();
            }
        }).on('show.bs.popover', function (e) {
            // hide other popovers
            $('.hotspot-image span').popover('hide').removeClass('hotspot-active');
        }).on('shown.bs.popover',function (e) {
            $('.popover-close').click(function(){
                $('.information-link').popover('hide');
            });
        });
    };

    /**
     * Add popovers to hotspots
     */
    var addHotspotPopover = function() {

        $('.hotspot-image span').each(function(index, hotspot) {

            var $storage = $('div[data-hotspot-content="'+$(hotspot).attr('id')+'"]');
            var template  = popoverHotspotTemplate[$storage.attr('data-hotspot-style')] ? popoverHotspotTemplate[$storage.attr('data-hotspot-style')] : popoverHotspotTemplate['default'];

            $(hotspot).on('click', function(e){

                var $wrapper = $(this).closest('.hotspot-show-wrapper');
                if ( $wrapper.hasClass('style1') && (WITTENSTEIN.isMediaXS() || WITTENSTEIN.isMediaIS()) ) {
                    return;
                } else {

                    var $image = $(this).closest('.hotspot-image');

                    if ($image.hasClass('hotspots-visible-lg') && !WITTENSTEIN.isGreaterThenMediaLG()) {
                        return;
                    } else if ($image.hasClass('hotspots-visible-md') && !WITTENSTEIN.isGreaterThenMediaMD()) {
                        return;
                    } else if ($image.hasClass('hotspots-visible-sm') && !WITTENSTEIN.isGreaterThenMediaSM()) {
                        return;					
                    } else if ($image.hasClass('hotspots-visible-is') && !WITTENSTEIN.isGreaterThenMediaIS()) {
                        return;
                    } else if ($image.hasClass('hotspots-visible-xs') && !WITTENSTEIN.isGreaterThenMediaXS()) {
                        return;					
                    }

                    var activeClassName = 'hotspot-active';

                    // hide other popovers
                    var $siblings = $(this).siblings('span, .information-link');
                    $siblings.popover('hide');
                    $siblings.removeClass(activeClassName);

                    if ($(this).hasClass(activeClassName)) {
                        $(this).popover('hide');
                        $(this).removeClass(activeClassName);
                    } else {
                        $(this).popover('show');
                        $(this).addClass(activeClassName);
                    }
                }
            }).popover({
                trigger: 'manual',
                html: true,
                title: $storage.attr('data-hotspot-title'),
                template: template,
                placement: $storage.attr('data-hotspot-placement'),
                content: function () {
                    return $storage.html();
                }
            });
        }).promise().done( function(){
            if (WITTENSTEIN.isMediaXS() || WITTENSTEIN.isMediaIS()) {
                $('.hotspot-image span').first().addClass('hotspot-active');
            }
        });
    };

    /**
     * Close popover on outside click
     *
     * @return void
     */
    var closePopoverOnOutsideClickListener = function() {
        $('body').on('click', function (e) {
            $('.information-link, .hotspot-image span').each(function () {
                //the 'is' for buttons that trigger popups
                //the 'has' for icons within a button that triggers a popup
                if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                    $(this).popover('hide');
                    if ($(this).next().hasClass('popover')) {
                        $(this).next().remove();
                    }
                }
            });
        });
    };

    /**
     * Add popovers
     */
    var addPopovers = function() {
        addHotspotPopover();
        addContentPopover();
        //closePopoverOnOutsideClickListener();
    };

    /**
     * Reload content
     */
    var reload = function(data) {
        hideSpinner();
        $(results).replaceWith(data);
        addAjaxListener();
        appendSlider();
    }

    /**
     * Attach AJAX listener
     */
    var addAjaxListener = function() {
        $('.hotspot-link--ajax').click(function() {
            // save selection
            startSlide = $(this).attr('data-index')|0;
            results = $(this).closest('.tx-udghotspot-wrapper');
            showSpinner();
            abortRequest();
            xhr = $.ajax({
                url: $(this).attr('href'),
                method: 'get',
                success: reload
            });
            return false;
        });
    };

    /**
     * Append bxSlider
     */
    var appendSlider = function() {

        $('.hotspot-show-wrapper .bxslider[data-bxslider-controls]').each(function(index, bxslider) {

            var controls = $(bxslider).attr('data-bxslider-controls') > 0 ? true : false;
            var pager = $(bxslider).attr('data-bxslider-pager') > 0 ? true : false;

            var touchEnabled = true;
            var infiniteLoop = true;

            if ($(bxslider).children('li').not('.bx-clone').length <= 1) {
                controls = false;
                pager = false;
                touchEnabled = false;
                infiniteLoop = false;
            }

            $(bxslider).bxSlider({
                adaptiveHeight: true,
                slideWidth: 1180,
                touchEnabled: touchEnabled,
                infiniteLoop: infiniteLoop,
                startSlide: startSlide,
                pager: pager,
                prevText: '',
                nextText: '',
                controls: controls,
                onSliderLoad: function(currentIndex) {
                    startSlide = 0;
                    addPopovers();
                }
            });
        });
    };

    /**
     * Append bxSlider for hotspots for small views
     */
    var appendHotspotSlider = function() {

        $('.hotspots .bxslider').each(function(index, bxslider) {

            var controls = true;
            var pager = true;
            var touchEnabled = true;
            var infiniteLoop = true;

            if ($(bxslider).children('li').not('.bx-clone').length <= 1) {
                controls = false;
                pager = false;
                touchEnabled = false;
                infiniteLoop = false;
            }

            $(bxslider).bxSlider({
                adaptiveHeight: true,
                touchEnabled: touchEnabled,
                infiniteLoop: false,
                pager: pager,
                prevText: '',
                nextText: '',
                controls: controls,
                width: '100%',
                maxSlides: 1,
                onSlideBefore: function($slideElement, oldIndex, newIndex) {
                    var hotspot = $(bxslider).closest('.hotspots').siblings('.hotspot-image').children('span').eq(newIndex);
                    hotspot.siblings('span').hide();
                    hotspot.show();
                },
                onSlideAfter: function($slideElement, oldIndex, newIndex) {
                    var hotspot = $(bxslider).closest('.hotspots').siblings('.hotspot-image').children('span').eq(newIndex);
                    hotspot.addClass('hotspot-active');
                }
            });
        });
    };

    /**
     * Append bxSlider for hotspots for small views
     */
    var appendSlickSlider = function() {
        $('.hotspot-show-wrapper .slick-slider').each(function(index, slickSlider) {
            $(slickSlider).on({
                beforeChange: function(event, slick, currentSlide, nextSlide){
                    var hotspot = $(slick.$slides.get(slick.currentSlide)).closest('.hotspot-show-wrapper').find('.hotspot-image:first-child').children('span').eq(nextSlide);
                    hotspot.siblings('span').hide();
                    hotspot.show();
                },
                afterChange: function(event, slick, currentSlide){
                    var hotspot = $(slick.$slides.get(slick.currentSlide)).closest('.hotspot-show-wrapper').find('.hotspot-image:first-child').children('span').eq(currentSlide);
                    hotspot.addClass('hotspot-active');
                }
            }).slick({
                dots: ($(slickSlider).attr('data-pager') == 1 ? true : false),
                infinite: true,
                speed: 300,
                slidesToShow: 1,
                adaptiveHeight: true
            });
        });	
    }

    /**
     * Single image effect function
     */
    var specialEffectsHandler = function() {

        // animation duration for jQuery's fadeIn / fadeOut
        var duration = 3000;
        var getOptions = function($image) {
            return {
                loop: ($image.attr('data-hotspot-animationloop') === '1'),
                pause: (parseInt($image.attr('data-hotspot-animationpause')) > 0 ? parseInt($image.attr('data-hotspot-animationpause')) : 3000)
            }
        };

        var fadeOut = function($image) {
            var options =  getOptions($image);

            if ($image.is(':visible') && typeof $image.attr('data-visible') === 'undefined') {
                // show image if is between 50% and 70% of the viewport
                var gridTop = $(window).height() - $(window).height() * 0.4;
                // On each scroll check if `image` is in interested viewport
                var thisTop = $image.offset().top - $(window).scrollTop();

                if (thisTop <= gridTop) {
                    $image.attr('data-visible', 'none');
                    $image.fadeOut(duration, function() {
                        if (options.loop) {
                            setTimeout(function() {
                                fadeIn($image);
                            }, options.pause);
                        }
                    });
                }
            }
        };

        var fadeIn = function($image) {
            $image.fadeIn(duration, function() {
                $image.removeAttr('data-visible');
                fadeOut($image);
            }); 
        };

        if($('.hotspot-image .preview-image').length) {
            $.each($('.hotspot-image .preview-image'), function(index, image) {
                var $image = $(image);
                if ($image.is(":visible")) {
                    fadeOut($image);
                    $(document).on('scroll', function() {
                        fadeOut($image);
                    });
                } else {
                    $image.show(0, function() {
                        $image.removeAttr('data-visible');
                    });
                }
            });
        }
    }

    /**
     * Show and hide hotspots depending on current viewport
     */
    var hotspotVisibilityManager = function() {
        var $hotspot = $('.hotspot-image span.hotspot-active');
        $hotspot.removeClass('hotspot-active').popover('hide').show();

        if ($hotspot.length === 0) {
            $hotspot = $('.hotspot-image span').first();
        }

        if (WITTENSTEIN.isGreaterThenMediaIS()) {
            $hotspot.siblings('span').show();
        } else {
            $hotspot.siblings('span').popover('hide');
            $hotspot.siblings('span').hide();
            $hotspot.siblings('span').removeClass('hotspot-active');
        }
    }

    /**
     * Resize function
     */
    var resize = function() {
        $('.popover').remove();
        hotspotVisibilityManager();
    }

    return {
        init : function() {

            // detail view
            if ($('.hotspot-show-wrapper').length || $('.hotspot-singleimage-wrapper').length) {

                if ($('.hotspot-show-wrapper .bxslider[data-bxslider-controls]').length) {
                    appendSlider();
                } else {
                    addPopovers();
                }

                if ($('.hotspot-show-wrapper').length ) {
                    appendSlickSlider();
                    appendHotspotSlider();
                    specialEffectsHandler();                    
                }
            }

            // list view
            if ($('.hotspot-list-wrapper').length) {
                addAjaxListener()
            }

            hotspotVisibilityManager();
            $(window).resize(resize);
        },

        specialEffectsHandler: specialEffectsHandler
    }

})(jQuery);

/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.hotspotMap=(function($) {

    "use strict";

    /**
     * @var XMLHttpRequest
     */
    var xhr;

    /**
     * Helper
     */
    var _memory = {};

    /**
     * @var string
     */
    var popoverTemplate = '\
        <div class="popover content-popover" role="tooltip">\
        <div class="popover-close"></div> \
        <div class="popover-content clearfix"></div>\
        </div>';

    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    /**
     * AJAX search function
     */
    var search = function(callback) {
        abortRequest();
        var $form = $('.udghotspot__map-mobile .map-filter');
        xhr = $.ajax({
            url: $form.attr('action'),
            method: $form.attr('method'),
            data: $form.serializeArray(),
            success: callback
        });
    }

    /**
     * Append slider
     */
    var initializeSlider = function() {
        $('.map-results').slick({
            dots: true,
            infinite: true,
            speed: 300,
            adaptiveHeight: false,
            variableWidth: false,
            arrows: false
        });
    }

    /**
     * Change selects on change
     */
    var handleSelects = function() {
        var $selects = $('.udghotspot__map-mobile select:not(.dontsubmit)');

        // save current selection
        $.each($selects, function(index, select) {
            _memory[$(select).attr('name')] = $(select).val();
        });

        // add dropdowns
        $selects.addClass('dontsubmit').udgSelectDropdown().change(function() {
            var $self = $(this);
            var key = $self.attr('name');

            // fire search only on changes
            if (_memory[key] != $self.val()) {
                _memory[key] = $self.val();

                var ajaxClass = 'ajax-loading';
                $('.map-results').addClass(ajaxClass);

                search(function(data) {
                    // replace results
                    $('.map-results').removeClass(ajaxClass);
                    $('.map-results').replaceWith($(data).find('.map-results'));
                    initializeSlider();
                });
            }
        });
    }

    /**
     * Show hotspot content on click
     */
    var handlePopovers = function() {
        $('.udghotspot__map .hotspot-image span').each(function(index, hotspot) {
            var $storage = $('div[data-hotspot-content="'+$(hotspot).attr('id')+'"]');
            var activeClassName = 'hotspot-active';
            
            $(hotspot).on('click', function(e){
                // hide other popovers
                var $siblings = $(this).siblings('span');
                $siblings.popover('hide');
                $siblings.removeClass(activeClassName);

                if ($(this).hasClass(activeClassName)) {
                    $(this).popover('hide');
                    $(this).removeClass(activeClassName);
                } else {
                    $(this).popover('show');
                    $(this).addClass(activeClassName);
                }
            }).popover({
                trigger: 'manual',
                html: true,
                title: $storage.attr('data-hotspot-title'),
                template: popoverTemplate,
                placement: $storage.attr('data-hotspot-placement'),
                content: function () {
                    return $storage.html();
                }
            }).on('shown.bs.popover', function (event) {
                var $popup = $('#' + $(event.target).attr('aria-describedby'));
                $popup.find('.popover-close').click(function (e) {
                    $('.' + activeClassName).click();
                });
            });
        });
    }

    return {
        init : function() {
            var $container = $('.udghotspot__map-mobile');
            if ($container.length) {
                initializeSlider();
                handleSelects();
                handlePopovers();
            }
        }
    }

})(jQuery);
/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.videoquotes=(function($) {

    "use strict";

    /**
     * XMLHttpRequest
     */
    var xhr;

    /**
     * string
     */
    var results = '.videoquotes';

    /**
     * int
     */
    var currentQuote = 0;

    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    /**
     * Show spinner
     */
    var showSpinner = function() {
        $(results).prepend("<div class='ajax-loading' style='background-position: center 100px;'></div>");
    };

    /**
     * Hide spinner
     */
    var hideSpinner = function() {
        $('.ajax-loading' , $(results)).remove();
    };

    /**
     * Attach AJAX listener
     */
    var load = function(url, callback) {
        showSpinner();
        abortRequest();
        xhr = $.ajax({
            url: url,
            method: 'get',
            success: function(response) {
                hideSpinner();
                callback(response);
            }
        });
    };

    /**
     * Load Player
     */
    var loadVideoPlayer = function(videoId) {
        VideoPlayer.Collection.addPlayerById('mi24player_' + videoId, {
            success: function(playerApi){
                $('#mi24player_' + videoId).find('.mi-poster').hide();
                playerApi.registerEventListener('playing', function() {
                    /* pause other videos when playing again */
                    WITTENSTEIN.videoHandler.pause('mi24player_' + videoId);
                });
                /* pause other videos... */
                WITTENSTEIN.videoHandler.pause('mi24player_' + videoId);
                /* ...because we want to play now */
                playerApi.play();
            }
        });
    };

    /**
     * VideoManager handler for AJAX calls
     * 
     * @params  String  url
     * @return  void
     */
    var videoManagerHandler = function(url) {
        load(url, function(response) {
            $(results).replaceWith(response);

            // append videos
            var initialSlide = $('.slick-videos div[data-video-active]').attr('data-video-active') | 0;
            $('.slick-videos').on({
                init:  function(event, slick){
                    var videoId = $(slick.$slides.get(slick.currentSlide)).attr('data-video');
                    loadVideoPlayer(videoId);
                },
                beforeChange:  function(event, slick, currentSlide, nextSlide){
                    var videoId = $(slick.$slides.get(currentSlide)).attr('data-video');
                    VideoPlayer.Collection.removePlayerById('mi24player_' + videoId);
                },
                afterChange: function(event, slick, currentSlide, nextSlide){
                    var videoId = $(slick.$slides.get(currentSlide)).attr('data-video');
                    loadVideoPlayer(videoId);
                }
            }).slick({
                infinite: true,
                speed: 300,
                slidesToShow: 1,
                adaptiveHeight: true,
                touchMove: false,
                swipe: false,
                initialSlide: initialSlide,
                prevArrow: '<div class="slick-prev"></div>',
                nextArrow: '<div class="slick-next"></div>'
            });

            $('.videoquotes__show .slick-arrow').click(function(e){
                e.stopPropagation();
                if ($(this).hasClass('slick-prev')) {
                    $('.slick-slider').slick('slickPrev')
                } else {
                    $('.slick-slider').slick('slickNext')
                }
            });

            // append backlink
            $('.back-to-list').click(function(){
                load($(this).attr('href'), function(response) {
                    $(results).replaceWith(response);
                    WITTENSTEIN.videoquotes.init();
                });
                return false;
            });
        });
    };

    /**
     * Append slider
     */
    var initialize = function() {
        // append slider
        $('.videoquotes__list .slick-slider').on({
            init:  function(event, slick){
                $(slick.$slides.get(slick.currentSlide)).find('.cite-wrapper').show();
            },
            beforeChange: function(event, slick, currentSlide, nextSlide){
                $(slick.$slides.get(slick.currentSlide)).find('.cite-wrapper').hide();
            },
            afterChange: function(event, slick, currentSlide){
                $(slick.$slides.get(slick.currentSlide)).find('.cite-wrapper').show().fadeTo(100, 1);		
            }
        }).slick({
            infinite: true,
            speed: 300,
            centerMode: true,
            variableWidth: true,
            initialSlide: currentQuote,
            prevArrow: '<div class="slick-prev"></div>',
            nextArrow: '<div class="slick-next"></div>'
        }).on('click', '.slick-slide', function (e) {
            e.stopPropagation();
            var index = $(this).data("slick-index");

            currentQuote = index;

            // show video
            if ($(this).hasClass('slick-current')) {
                var $videoLink = $(this).find('.video-link');
                var url = $videoLink.attr('data-action-uri');

                if (typeof url !== typeof undefined && url !== false) {
                    videoManagerHandler(url);
                }
            } else if ($('.slick-slider').slick('slickCurrentSlide') !== index) {
                // slide to next
                $('.slick-slider').slick('slickGoTo', index);
            }
        });
    };

    return {
        init : function() {
            if ($('.videoquotes').length) {
                initialize();
            }
        }
    }

})(jQuery);
/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.videoCollection=(function($) {

    /**
     * @var Array
     */
    var loadedVideos = [];

    var $container = $('.video-collection__container');

    /**
     * Animate Tiles
     */
    var animateTiles = function() {
        if (window.innerWidth < WITTENSTEIN.SCREEN_SM) {
            initSliderForMobile();
        }
    }

    /**
     * Append slick slider for devices smaller than 900px, destroy at higher resolutions.
     */
    var initSliderForMobile = function() {
        if (window.innerWidth < WITTENSTEIN.SCREEN_SM && !$container.hasClass('slick-slider')) {
            $container.slick({
                mobileFirst: true,
                dots: true,
                arrows: false,
                infinite: true,
                adaptiveHeight: false,
                slide: '.video-collection__item--slide', // ignore others
                responsive: [{
                    breakpoint: WITTENSTEIN.SCREEN_SM,
                    settings: "unslick"
                }]
            });
        }
    }

    var toggleYoutubeIframeVideo = function(state, videoId) {
        // hide if state == 'hide', show video otherwise
        var div = document.getElementById(videoId);
        
        if (div !== null) {
            var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
            div.style.display = state == 'hide' ? 'none' : '';
            var func = 'pauseVideo';
            iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
        }
    }

    /**
     * Append video player
     */
    var loadVideos = function() {
        var $players = $container.find('.video-collection__player');
        $.each($players, function(key, container) {            
            if ($(container).attr('id').length) {
                VideoPlayer.Collection.addPlayerById($(container).attr('id'), {
                    success: function (playerApi) {
                        playerApi.registerEventListener('playing', function(event){
                            // pause other videos
                            var $currentPlayer = $('#' + event.target.id).closest('.video-collection__player');
                            WITTENSTEIN.videoHandler.pause($currentPlayer.attr('id'));
                        });
                    },
                    parameters: {
                        videoId: $(container).data('video'),
                        playerId: $(container).data('player'),
                        configType: "vmpro",
                        flashPath: "//e.video-cdn.net/v2/",
                        apiUrl: "//d.video-cdn.net/play"
                    }
                });
            }
        });
    }

    return {
        init : function() {
            $('.video-collection').on('show.bs.collapse',function(e){
                // This event fires immediately when the show instance method is called.
                var videoContainer = $(e.target).find('[data-collection-video-url]');
                var videoId = videoContainer.attr('data-collection-video-id');
                if(typeof videoId !== 'undefined') {
                    //  video 
                    if (loadedVideos.indexOf(videoId) == -1 ) {
                        loadedVideos.push(videoId);
                        $('<script src="'+videoContainer.attr('data-collection-video-url')+'"></script>').insertAfter( videoContainer );
                    }
                } else {
                    var $ytVideoContainer = $(e.target).find('div.embed-container');
                    if(typeof $ytVideoContainer !== 'undefined' && $ytVideoContainer.length > 0) {
                        var $ytVideoId = $ytVideoContainer.attr('id');
                        toggleYoutubeIframeVideo('show', $ytVideoId)
                    }
                }
            }).on('hide.bs.collapse',function(e){
                // This event is fired immediately when the hide method has been called. 
                var videoId = $(e.target).find('[video-id]').attr('video-id');
                if(typeof videoId !== 'undefined' && videoId.length) {
                    var Player = VideoPlayer.Collection.getPlayerById('mi24player_' + videoId);
                    Player.pause();
                } else { // it must be a youtube video
                    var $ytVideoContainer = $(e.target).find('div.embed-container');
                    var $ytVideoId = $ytVideoContainer.attr('id');
                    toggleYoutubeIframeVideo('hide', $ytVideoId)
                }
            });

            if ($('.video-collection__container').length) {
                animateTiles();
                $(document).on('scroll', animateTiles);
                $(window).resize(initSliderForMobile);
                // register player
                loadVideos();
            }
        }
    }
})(jQuery);

/**
 * 3d-Cube
 */
WITTENSTEIN.cube=(function($) {

    "use strict";

    var $viewport = $('.cube__viewport');
    var $faces = $('.cube__face');
    var $links = $('.cube__link');
    var $cube = $('.cube');
    var touch = document.ontouchmove !== undefined;

    var n = $faces.length; 
    var styles = [];
    var _style;

    var frames = 25;
    /* how much to rotate when dragging */
    var factor = 3;
    var side;
    var max_amount;

    /* rotation angle per 1px move */
    var unit;

    /* whether cube is being dragged */
    var flag = false;
    var dragged = false;
    var tmp;
    var dragTmp = [];
    var perspective;
    var p0 = { 'x': 0, 'y': 0};
    var intervalId = null;

    var coords = {
            x: -15,
            y: -135,
            z: 15,
    };

    var initialize = function() {
        _style = getComputedStyle($faces[0]);
        side = parseInt(_style.width.split('px')[0], 10);
        max_amount = factor*side;
        unit = 360/max_amount;
        perspective = 'perspective(' + parseInt($faces[0].offsetHeight/8) + 'rem) ';
    };

    var drag = function(e) {
        /* distance and angle values since starting to drag */
        var p1 = { 'x': e.clientX - p0.x, 'y': e.clientY - p0.y }; 
        var angle = {'x': -p1.y*unit, 'y': p1.x*unit};

        coords.x = angle.x;
        coords.y = angle.y;

        dragged = true;

        /* current transform values */
        for(var i = 0; i < n; i++) {
            tmp = 'rotateX(' + angle.x + 'deg)' + 'rotateY(' + angle.y + 'deg)' + styles[i];
            $faces[i].style.transform = perspective + tmp;
            $faces[i].style['-webkit-transform'] = perspective + tmp;
            dragTmp[i] = tmp;
        }
    };

    var draw = function(coords) {
        /* position all the faces on the cube */
        for(var i = 0; i < n; i++) { 
            if (typeof dragTmp[i] === 'string') {
                tmp = dragTmp[i];
            } else {
                tmp = ((i < 4) ? 'rotateY(' + i*90 + 'deg)' : 'rotateX(' + Math.pow(-1, i)*90 + 'deg)') + ' translateZ(' + side/2 + 'px) ';
            }
            tmp = ' rotateX(' + coords.x + 'deg) rotateY(' + coords.y + 'deg) rotateZ(' + coords.z + 'deg)' +  tmp;

            $faces[i].style.transform = perspective + tmp;
            $faces[i].style['-webkit-transform'] = perspective + tmp;
            styles[i] = tmp;
        }
    };

    $(document).keydown(function(evt) {
        switch(evt.keyCode) {
        case 37: // left
            stopInterval();
            coords.y -= 5;
            draw(coords);
            break;

        case 38: // up
            evt.preventDefault();
            stopInterval();
            coords.x += 5;
            draw(coords);
            break;

        case 39: // right
            stopInterval();
            coords.y += 5;
            draw(coords);
            break;

        case 40: // down
            evt.preventDefault();
            stopInterval();
            coords.x -= 5;
            draw(coords);
            break;
        default:
            break;
        };
    })

    var loop = function() {
        coords.x += 1;
        coords.y += 1;
        //coords.z += 1;
        draw(coords);
    };

    var stopInterval = function () {
        if (intervalId) {
            clearInterval(intervalId);
        }
    };

    return {
        init : function() {
            if ($cube.length) {
                $viewport.mouseover(stopInterval);

                $cube.bind('mousedown touchstart', function(e) {
                    // Get touch coords
                    if (e.originalEvent.touches) {
                        e = e.originalEvent.touches[0];
                    } else {
                        e.preventDefault();
                        e.stopPropagation();
                    }

                    p0 = { 'x': e.clientX, 'y': e.clientY };
                    flag = true;
                    dragged = false;

                    $cube.bind('mousemove touchmove', function(event) {
                        // Only perform rotation if one touch or mouse (e.g. still scale with pinch and zoom)
                        if(!touch || !(event.originalEvent && event.originalEvent.touches.length > 1)) {
                            event.preventDefault();
                            event.originalEvent.touches ? event = event.originalEvent.touches[0] : null;
                            drag(event);
                        }
                    })
                })
                $(document).bind('mouseup touchend', function(e) {
                    if(flag) {
                        // transform values at end of drag
                        for(var i = 0; i < n; i++) {
                            _style = $faces[i].style;
                            tmp = _style.transform || _style['-webkit-transform'];
                            styles[i] = tmp.replace(perspective, '');
                        }
                        $cube.unbind('mousemove touchmove');
                    }
                    flag = false;
                });

                /* draw cube */
                initialize();
                styles = [];

                draw(coords);

                var fancyboxAfterShow = function() {
                    $('.bg-overlay').show();
                    var videoId = $(this.element).attr('data-video');
                    var Player = VideoPlayer.Collection.getPlayerById("mi24player_" + videoId);
                    Player.play();
                };

                var fancyboxBeforeClose = function() {
                    var videoId = $(this.element).attr('data-video');
                    var Player = VideoPlayer.Collection.getPlayerById("mi24player_" + videoId);
                    Player.pause();
                    $('.bg-overlay').hide();
                };

                if(!touch) {
                    intervalId = setInterval(loop, frames);
                }
                
                $(window).resize(function() {
                    initialize();
                    styles = [];
                    dragTmp = [];
                    tmp = '';
                    coords = {
                            x: -15,
                            y: -135,
                            z: 15,
                    };
                    draw(coords);
                });

                $links.fancybox({
                    height: 'auto',
                    fitToView: true,
                    autoSize: false,
                    closeClick: false,
                    openEffect: 'none',
                    closeEffect: 'none',
                    afterShow: fancyboxAfterShow,
                    beforeClose: fancyboxBeforeClose
                });
            }
        }
    }

})(jQuery);
/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.flexboxStatements=(function($) {

    /**
     * Animate Tiles
     */
    var animateTiles = function() {
        if (window.innerWidth < WITTENSTEIN.SCREEN_MP) {
            initSliderForMobile();
        }
    }

    /**
     * Append slick slider for devices smaller than 900px, destroy at higher resolutions.
     */
    var initSliderForMobile = function() {
        var $container = $('.udgflexbox__statements');
        if (window.innerWidth < WITTENSTEIN.SCREEN_MP && !$container.hasClass('slick-slider')) {
            $container.on({
                beforeChange: function(event, slick, currentSlide, nextSlide){
                    var $video = $(slick.$slides.get(slick.currentSlide)).find('[id^="mi24player_"]');
                    if ($video.attr('id').length) {
                        VideoPlayer.Collection.getPlayerById($video.attr('id')).stop();
                    }
                },
                destroy: function(event, slick){
                    $container.attr('data-slick-destroyed', 'true');
                }
            }).slick({
                mobileFirst: true,
                dots: true,
                arrows: false,
                infinite: true,
                adaptiveHeight: true,
                slide: '.udgflexbox__statement', // ignore others
                responsive: [{
                    breakpoint: (WITTENSTEIN.SCREEN_MP),
                    settings: "unslick"
                }]
            });
        }
    }

    /**
     * Handler for fancybox
     */
    var fancyboxHandler = function() {
        var videoSelector = '.udgflexbox__statement--media-video';
        $(videoSelector).click(function() {

            var $video = $(this).children(':first');
            var $link = $(this);
            var $videoContainer = $video.parent();

            if (window.innerWidth >= WITTENSTEIN.SCREEN_MP) {
                $.fancybox({
                    href: '#' + $video.attr('id'),
                    autoSize: false,
                    height: 'auto',
                    width: '80%',
                    maxWidth: '1200px',
                    wrapCSS: 'udglightbox-wrap',
                    beforeLoad: function() {
                        $videoContainer.css({
                            width: $videoContainer.width() + 'px',
                            height: $videoContainer.height() + 'px'
                        });
                    },
                    beforeShow: function() {
                        $('.bg-overlay').show();
                    },
                    afterShow: function() {
                        VideoPlayer.Collection.getPlayerById($video.attr('id')).play();
                    },
                    beforeClose: function() {
                        VideoPlayer.Collection.getPlayerById($video.attr('id')).stop();
                    },
                    afterClose: function() {
                        $('.bg-overlay').hide();
                        $videoContainer.css({
                            width: 'auto',
                            height: 'auto'
                        });
                        $video.show();
                    }
                });
                event.preventDefault();
                event.stopImmediatePropagation();
            }
            return false;
        });

        $('.udgflexbox__statement--body h2').click(function() {
            $(this).closest('.udgflexbox__statement').find(videoSelector).click();
        });
    }

    return {
        init : function() {
            if ($('.udgflexbox__statements').length) {
                fancyboxHandler();
                initSliderForMobile();
                $(window).resize(initSliderForMobile);
            }
        }
    }
})(jQuery);
/**
 * Responsible for the behavior of the videos.
 * Play only one at the same time.
 */
WITTENSTEIN.videoHandler = (function($) {

    /* selector for movingimages */
    var movingImageVideoSelector = '[id^="mi24player_"]';

    /* selector for youtube */
    var youtubeVideoSelector = '.yt-player-iframe';

    /**
     * Pause other videos.
     * Public for using as a callback from AJAX
     * 
     * @params  String|null player id
     */
    var pause = function(currentPlayerId) {

        // pause movingimages
        $.each($(movingImageVideoSelector) , function(index, player) {
            var id = $(player).attr('id');
            if (currentPlayerId !== id) {
                if ($(player).children('.mi-player').length) {
                    VideoPlayer.Collection.getPlayerById(id).pause();
                }
            }
        });

        // pause youtube
        if (UDG.YT.players.length) {
            $.each(UDG.YT.players , function(index, player) {
                if (player.a.id != currentPlayerId) {
                    player.pauseVideo();
                }
            });
        }
    }

    /**
     * Called from YT player onStateChange Event
     */
    var onYouTubeStateChange = function(event) {
        if (event.data == YT.PlayerState.PLAYING) {
            pause(event.target.a.id);
        }
    }

    /**
     * The API will call this function when the page has finished
     * downloading the JavaScript for the player API, which enables
     * you to then use the API on your page. Thus, this function might
     * create the player objects that you want to display when the page loads.
     */
    var onYouTubeIframeAPIReady = function() {

        // Resolve multiple onYouTubeIframeAPIReady.
        YTdeferred.done(function(){
            UDG.YT.resolve();
            // add static iframes to onYouTubeStateChange
            $.each($(youtubeVideoSelector), function(index, iframe) {
                UDG.YT.players.push(new YT.Player(iframe, {
                    events: {
                        'onStateChange': WITTENSTEIN.videoHandler.onYouTubeStateChange
                    }
                }));
            });

            // append scroll listener
            $(document).on('scroll', function(){
                $.each(UDG.YT.players, function(index, player) {
                    if (typeof player.getPlayerState === 'function') {
                        if (player.getPlayerState() == YT.PlayerState.PLAYING) {
                            if (!isInViewport($(player.a))) {
                                player.pauseVideo();
                            }
                        }
                    }
                });
            });
        });
    }

    /**
     * Check if $element is in viewport
     * 
     * @return Boolean
     */
    var isInViewport = function($element) {
        var elementTop = $element.offset().top;
        var elementBottom = elementTop + $element.outerHeight();
        var viewportTop = $(window).scrollTop();
        var viewportBottom = viewportTop + $(window).height();
        return elementBottom > viewportTop && elementTop < viewportBottom;
    }

    /**
     * Stop movingimages if they out of the viewport
     */
    var movingImageOnScroll = function() {
        if ($(movingImageVideoSelector).length) {
            $(document).on('scroll', function(){
                // pause movingimages
                $.each($(movingImageVideoSelector) , function(index, player) {
                    if (!isInViewport($(player))) {
                        if ($(player).children('.mi-player').length) {
                            VideoPlayer.Collection.getPlayerById($(player).attr('id')).pause();
                        }
                    }
                });
            });
        }
    }

    /**
     * Append listener on load
     */
    var init = function() {
        // YT API call
        onYouTubeIframeAPIReady();
        // add scroll listener for movingimage
        movingImageOnScroll();
    }

    /** public methods */
    return {
        init : init,
        pause: pause,
        onYouTubeStateChange: onYouTubeStateChange
    }
})(jQuery);

// initialize google maps (footer, job detail page, career)
WITTENSTEIN.maps = (function($) {

	var scriptLoaded = false;
	
	var _self;
	
    /**
     * get marker location
     *
     * @return void
     */
    var getLocation = function(latitude, longitude, callback) {
        var geocoder = new google.maps.Geocoder();

        //var latitude = $('#map-latitude').val() ;
        //var longitude = $('#map-longitude').val();

        var address = [
            $('#map-street').val(),
            $('#map-housenr').val(),
            ',',
            $('#map-zip').val(),
            $('#map-city').val(),
        ];

        if (latitude !== '' && longitude !== '') {
            callback(latitude, longitude);
            return ;
        }

        geocoder.geocode({
                address : address.join(' ')
            },
            function(results, status) {
                if (status === google.maps.GeocoderStatus.OK) {

                    var latitude  = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng();

                    callback(latitude, longitude);
                }
        });
    };

    var getZoomElement = function(map) {
        var zoomElem = document.createElement('div');
        var zoomIn   = document.createElement('img');
        var zoomOut  = document.createElement('img');

        zoomElem.style.marginRight = "100px";
        zoomElem.style.marginBottom = "20px";
        zoomElem.style.float = "left";

        zoomIn.setAttribute("width", "42");
        zoomIn.setAttribute("height", "36");

        zoomIn.style.display = "block";
        zoomOut.style.display = "block";
        zoomIn.style.cursor = "pointer";
        zoomOut.style.cursor = "pointer";

        zoomOut.setAttribute("width", "42");
        zoomOut.setAttribute("height", "35");

        zoomIn.setAttribute("src", "/typo3conf/ext/udg_template/Resources/Public/Images/map_zoomplus.png");
        zoomOut.setAttribute("src", "/typo3conf/ext/udg_template/Resources/Public/Images/map_zoomminus.png");

        zoomElem.appendChild(zoomIn);
        zoomElem.appendChild(zoomOut);

        google.maps.event.addDomListener(zoomIn, 'click', function() {

            var zoom = map.getZoom() + 1;

            if (zoom > 18) {
                zoom = 18;
            }

            map.setZoom( zoom );
        });

        google.maps.event.addDomListener(zoomOut, 'click', function() {

            var zoom = map.getZoom() - 1 ;

            if (zoom < 3) {
                zoom = 3;
            }

            map.setZoom( zoom );
        });

        zoomElem.index = 1;

        return zoomElem;
    }

    /**
     * @param double latitude  Breitengrad
     * @param double longitude LÃ¤ngengrad
     * @param string mapId     Dom ID der Karte
     */
    return function(latitude, longitude, mapId, mapOptions) {


		var styles = [
			{
				featureType: "poi",
				elementType: "labels",
				stylers: [
					{ visibility: "off" }
				]
			}
		];

		// Breitengrad
		var latitude;
		// Laengengrad
		var longitude;

		_self = this;

		this.showMarker = true;
		this.zoom = 15;

        _self.latitude = latitude;
        _self.longitude = longitude;

        _self.mapOptions = {
            zoom: 15,
            disableDefaultUI: true,
            draggable: false,
            scrollwheel: false
        };

        _self.mapOptions = $.extend(_self.mapOptions, mapOptions)

        this.init = function(callback) {

            mapOptions = $.extend(_self.mapOptions, {
                // draggable: false,
                // scrollwheel: false,
                center: new google.maps.LatLng(-34.397, 150.644),
                styles: styles,
				zoom: this.zoom
            });

            _self.map = new google.maps.Map(
                document.getElementById(mapId),
                mapOptions
            );

            getLocation(_self.latitude, _self.longitude, function(latitude, longitude) {

                _self.map.setCenter(new google.maps.LatLng(latitude, longitude));

				if (_self.showMarker) {

					_self.setMapMarker(latitude, longitude);
				}

            });

            if (typeof callback == 'function') {
            	callback();
            }
        }

        /**
         * load map only if viewport nearby footer
         */
        this.lazyLoading = function(callback) {
        	var canvas = $('#' + mapId);
        	$(window).on('DOMContentLoaded load resize scroll', function(){
        		
        		var elementInViewport = isElementInViewport(canvas, 50);
        		
        		if ( scriptLoaded == false && (elementInViewport == true || elementInViewport == null) ) {
        			scriptLoaded = true;
    		        var address = [
    		            $('#map-street').val(),
    		            $('#map-housenr').val(),
    		            ',',
    		            $('#map-zip').val(),
    		            $('#map-city').val(),
    		        ];
    		        var geocoder = new google.maps.Geocoder();
    		        geocoder.geocode({
    		        	address : address.join(' ')
    		        }, function(results, status) {
    		        	if (status === google.maps.GeocoderStatus.OK) {
    		        		var latitude  = results[0].geometry.location.lat();
    		        		var longitude = results[0].geometry.location.lng();

    		    
    		        		var footerMap = new google.maps.Map(document.getElementById(mapId), {
    		                    center: new google.maps.LatLng(latitude, longitude),
    		                    styles: styles,
    		    				zoom: _self.zoom,
    		    				disableDefaultUI: true
    		                });
    		        		
    		        		footerMap.setCenter(new google.maps.LatLng(latitude, longitude));
    		        		_self.getMarker(footerMap, latitude, longitude);
    		  
    		        	}
    		        });
        		}
        	});
        }
        
		this.showMarker = function(val) {
			this.showMarker = val;
		}

		this.setZoom = function(zoom) {
			this.zoom = zoom;
		}

        this.getMap = function() {
            return _self.map;
        }
        
        this.getMarker = function(map, latitude, longitude) {
            return new google.maps.Marker({
				position: new google.maps.LatLng(latitude, longitude),
				map: map,
				icon: '/typo3conf/ext/udg_template/Resources/Public/Images/mapico.png'
			});
        }

		this.setMapMarker = function(latitude, longitude, callback) {

			var marker = _self.getMarker(_self.map, latitude, longitude);

			if (typeof callback === 'undefined' && _self.mapOptions.draggable === false) {
				google.maps.event.addListener(_self.map, 'click', function() {
					window.open("https://www.google.de/maps/@" + latitude + "," + longitude + ",15z");
					_self.map.setCenter(marker.getPosition());
				});
				google.maps.event.addListener(_self.map, 'bounds_changed', function() {
				  	_self.map.setCenter(marker.getPosition());
				});
			} else if (typeof callback !== 'undefined') {
				callback(marker);
			}

			return marker;
		}

        /**
         * add a custom element to zoom in and out
         */
        this.zoomElement = function() {

            var zoomElem = getZoomElement(_self.map);

            _self.map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(zoomElem);

        }

        // zeigt ein info-fenster auf der karte an
        this.addInfoWindow = function(content) {

            // zuletzt hinzugefÃ¼gtes infoWindow / zoomElem entfernen
            _self.map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].pop();

            var container = document.createElement('div');
            var infoWindow = document.createElement('div');

            infoWindow.innerHTML = content.join("");

            infoWindow.style.padding = "0 2em 2em 2em";
            infoWindow.style.marginBottom = "20px";
            infoWindow.style.marginRight = "20px";
            infoWindow.style.float = "left";
            infoWindow.style.backgroundColor = "#FFFFFF";
            infoWindow.style.bottom  = "14px !important";
            infoWindow.style.opacity = ".9";
            infoWindow.style.maxWidth = "400px";

            var zoomElem = getZoomElement(_self.map);

            container.appendChild(infoWindow);
            container.appendChild(zoomElem);

            _self.map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(container);

            zoomElem.style.marginTop = infoWindow.clientHeight - zoomElem.clientHeight + 'px';

        }

        /**
         * get latitude and longitude from geocoder api
         */
        this.getLatLon = function(address, region, callback) {
            var geocoder = new google.maps.Geocoder();
            var searchstring = { 'address' : address };

            if (region) {
                searchstring['region'] = region;
            }

            var result = [];

            geocoder.geocode(searchstring, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {

                    _self.setLat( results[0].geometry.location.lat() );
                    _self.setLon( results[0].geometry.location.lng() );

                    if (typeof callback !== 'undefined') {

                        callback.apply(_self);
                    }
                }
            });

            return result;

        }

        /**
         * @param float lat
         */
        this.setLat = function(lat) {
            _self.latitude = lat;
        }

        /**
         * @param float lon
         */
        this.setLon = function(lon) {
            _self.longitude = lon;
        }

    }

})(jQuery);
/**
 * initialize all global jQuery events, handlers , grouped by their subject
 */
WITTENSTEIN.slider=(function($) {

    "use strict";

    /**
     * Append slider
     */
    var initialize = function() {

        // append slider
        $.each($('.udgslider'), function(index, slider) {
            var $slider = $(slider);
            var infinite = Boolean(Number($slider.attr('data-infinite')));

            $slider.find('.udgslider__img-container').slick({
                dots: true,
                infinite: infinite,
                speed: 300,
                adaptiveHeight: false,
                variableWidth: false,
                prevArrow: '<div class="slick-prev"></div>',
                nextArrow: '<div class="slick-next"></div>',
                asNavFor: '.udgslider__elem-container',
                responsive: [{
                    breakpoint: 600, // is
                    settings: {
                        arrows: false
                    }
                },{
                    breakpoint: 900, // sm
                    settings: {
                        arrows: false
                    }
                },
                {
                    breakpoint: 1024, // md
                    settings: {
                        arrows: false
                    }
                },
                {
                    breakpoint: 1194, // mp
                    settings: {
                        arrows: false
                    }
                }]
            });

            $slider.find('.udgslider__elem-container').slick({
                dots: false,
                infinite: infinite,
                speed: 300,
                adaptiveHeight: false,
                variableWidth: false,
                arrows: false,
                asNavFor: '.udgslider__img-container'
            });
        });
    };

    return {
        init : function() {
            if ($('.udgslider').length) {
                initialize();
            }
        }
    }

})(jQuery);
/**
 * Group switch module
 */
WITTENSTEIN.groupswitch = (function($) {

    /**
     * Append effects
     */
    var toggleAnimation = function() {
        var duration = 200;
        var $bsDropdown = $('.dropdown').not('.tab-navigation');
        var $metaBreadcrumb = $('.metanavigation__breadcrumb');
        $bsDropdown.on('show.bs.dropdown', function() {
            if ($(this).hasClass('groupswitch')) {
                // close navigation menu if open
                var $navigationToggler = $('.navigation--toggler button');
                if ($navigationToggler.attr('aria-expanded') === 'true') {
                    $navigationToggler.click();
                }

                // close mobile search
                if ($('.searchform__form--mobile').attr('aria-expanded') === 'true') {
                    $('.searchform--mobile button').click();
                }
                $('.bg-overlay').addClass('show');
            }
            $(this).addClass('animate');
            $(this).closest('.head__col').addClass('open');
            $(this).find('.dropdown-menu').first().stop(true, true).fadeIn(duration);
            $metaBreadcrumb.addClass('open');
        }).on('hidden.bs.dropdown', function() {
            $metaBreadcrumb.removeClass('open');
        });

        // Add slideUp animation to Bootstrap dropdown when collapsing.
        $('.dropdown').not('.tab-navigation').on('hide.bs.dropdown', function() {
            var $dropdown = $(this);
            $dropdown.find('.dropdown-menu').first().stop(true, true).fadeOut(duration, function(){
                $dropdown.removeClass('animate');
                if ($dropdown.hasClass('groupswitch')) {
                    $('.bg-overlay').removeClass('show');
                }
                $dropdown.closest('.head__col').removeClass('open');
            });
        });
    }

    return {
        init : function() {
            toggleAnimation();
        }
    }
})(jQuery);

/**
 * events/functions in Presse/Publikationen
 */
WITTENSTEIN.presse = (function($) {

    /**
     * XMLHttpRequest
     */
    var xhr;

    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    var sliders = [];

    /**
     * - button 3 in mobile ansicht in move-archiv
     */
    var moveArchiv = function() {
        var mobile = window.matchMedia("screen and (max-width: 600px)");

        if (mobile.matches) {
            $('.move-archiv .button_1').addClass('button_3').removeClass('button_1');
        }
    };


    /**
     * initialisiert den slider in der mediathek detailansicht
     * und wechselt in der album ansicht zwischen listen- und gallerie-ansicht
     */
    var mediathek = function() {

        // Slider Detailansicht
        if ($('.mediathek-detail .bxslider').length) {

            // destroy all previously initiated sliders
            $.each(sliders, function(k,v) {
                v.destroySlider();
            });

            $('.mediathek-detail .bxslider').each(function(k, v) {
                var pagerId = '#bx-pager-' + k;
                $(v).next('.album-pager').attr('id', pagerId.substr(1));

                var startSlide = ($(v).find('li.start-slide').length ? $(v).find('li.start-slide').index() : 0);

                if (startSlide === ($(v).find('li').length - 1)) {
                    // wenn startSlide das letzte Element ist, nimm -1
                    startSlide = -1 ;
                }

                var slider = $(v).bxSlider({
                    captions: true,
                    video: true,
                    //pagerCustom : pagerId,
                    pager: false,
                    infiniteLoop: true,
                    hideControlOnEnd: false,
                    startSlide : startSlide,
                    onSliderLoad: function(currentIndex) {
                        var $currentSlide = $('.bxslider li:not(.bx-clone)').eq(currentIndex);
                        if($currentSlide.find('div.iframe-wrapper').attr('data-autoplay')) {
                            var ytIframe = $currentSlide.find('iframe');
                            if(typeof ytIframe !== 'undefined') {
                                ytIframe.get(0).contentWindow.postMessage('{"event" : "command" , "func" : "playVideo", "args": ""}', '*');
                            }
                        }
                        $('.product-mediathek .bx-controls-direction').show();
                    },
                    onSlideAfter: function($slideElement, oldIndex, newIndex) {
                        // stop youtube videos on slide
                        $('iframe[src*="https://www.youtube.com/embed/"]').each(function() {
                            this.contentWindow.postMessage('{"event" : "command" , "func" : "pauseVideo", "args": ""}', '*');
                        });
                        // start youtube video in current slide if autoplay=1
                        if($slideElement.find('div.iframe-wrapper').attr('data-autoplay')) {
                            var ytIframe = $slideElement.find('iframe');
                            if(typeof ytIframe !== 'undefined') {
                                ytIframe.get(0).contentWindow.postMessage('{"event" : "command" , "func" : "playVideo", "args": ""}', '*');
                            }
                        }
                        // index in pager richtig setzen
                        $(pagerId + ' ul li').removeAttr('class').removeAttr('style');
                        $.each($(pagerId + ' ul li'), function(key, val) {
                            if (newIndex === key) {
                                $(val).addClass('current');
                            }
                        });

                        // don't reset current selection of other media elements (if any) after AJAX response
                        $slideElement.addClass('start-slide').siblings().removeClass('start-slide');

                        // aktualisiert die prev/next buttons im pager
                        $('.mediathek-detail ' + pagerId).udgPaginate('updatePager', {bxSlider: true});

                        // stop youtube videos on slide
                        $('.mediathek-detail .bxslider .fluid-width-video-wrapper object').each(function(i, j) {
                            var src = $(j).attr('data');
                            $(j).attr('data', '').attr('data', src);
                        });
                    }
                });

                sliders.push(slider);

                // workaround 
                // @see: https://github.com/stevenwanderski/bxslider-4/issues/560
                if ($('.bx-loading').length > 0) {
                    $('.bx-loading').remove();			
                }


                $(v).find('li a:not(.download-link)').each(function(key, val) {
                    $(val).attr('data-fancybox', 'media-lightbox' + key);
                });

                $(v).find('li a[data-fancybox]').fancybox({
                    loop: false,
                    fitToView: true,
                    scrolling: false,
                    autoCenter: true,
                    autoResize: true,
                    autoSize: true,
                    type: 'ajax',

                    beforeLoad : function() {
                        // add load animation
                        $('.fancybox-inner').prepend("<div class='ajax-loading'></div>");
                    },
                    beforeShow: function() {
                        $(".fancybox-inner").find("iframe").addClass("image-wrapper" );

                        // workaround
                        // @see: https://github.com/fancyapps/fancyBox/issues/993
                        $('.fancybox-wrap').appendTo('.fancybox-overlay');
                    },
                    afterShow : function () {

                        //$('.fancybox-prev').css('display','none');
                        //$('.fancybox-next').css('display','none');
                        $('.bg-overlay').show();
                        $('.fancybox-inner .arrow-close').on('click', function() {
                            $.fancybox.close();
                        });

                        // set width and height dynamically
                        var w = $('.turntable-container input:hidden').first().attr('data-width');
                        var h = $('.turntable-container input:hidden').first().attr('data-height');

                        $('.turntable-container').width(w).height(h);

                        if (typeof turntable == 'function') {
                            turntable();
                        }


                        $('.fancybox-inner .ajax-loading').remove();
                    },
                    afterClose : function () {
                        $('.bg-overlay').hide();
                    }
                });

                $('.mediathek-detail ' + pagerId).udgPaginate('destroy').udgPaginate({bxSlider: true});
            });

        }

        // click events zum wechseln der album ansicht
        switchAlbumView();

        // pagination in album
        $('.mediathek .page-navigation').udgPaginate('destroy').udgPaginate();
    };

    /**
     * Videos in bxslider dont play only IE, therefore fallback solution with slick slider
     */
    var movingimage = function(initialSlide) {

        var currentVideo = null;

        $('.mediathek-detail .bxslider').on({
            init:  function(event, slick){
                var $videoContainer = $(slick.$slides.get(slick.currentSlide)).find('.mediathek-movingimage[data-video]');
                if ($videoContainer.length > 0) {
                    VideoPlayer.Collection.addPlayerById('mi24player_' + $videoContainer.attr('data-video'), {
                        success: function(playerApi){
                            playerApi.play();
                            currentVideo = $videoContainer.attr('data-video');
                        }
                    });
                }
            },
            beforeChange: function(event, slick, currentSlide, nextSlide){
                var $videoContainer = $(slick.$slides.get(slick.currentSlide)).find('.mediathek-movingimage[data-video]');
                if ($videoContainer.length > 0) {
                    VideoPlayer.Collection.removePlayerById('mi24player_' + $videoContainer.attr('data-video'));
                }
            },
            afterChange: function(event, slick, currentSlide){
                var $videoContainer = $(slick.$slides.get(slick.currentSlide)).find('.mediathek-movingimage[data-video]');

                if ($videoContainer.length > 0 && currentVideo !== $videoContainer.attr('data-video')) {
                    VideoPlayer.Collection.addPlayerById('mi24player_' + $videoContainer.attr('data-video'), {
                        success: function(playerApi){
                            playerApi.play();
                            currentVideo = $videoContainer.attr('data-video');
                        }
                    });
                }
            }
        }).slick({
            infinite: false,
            speed: 300,
            centerMode: false,
            variableWidth: false,
            initialSlide: initialSlide|0,
            swipe: false,
            prevArrow: '<div class="slick-prev"></div>',
            nextArrow: '<div class="slick-next"></div>'
        });
    };

    /**
     * ajax aufruf bei teasern und thumbnails in mediathek
     */
    var mediathekAjax = function() {

        $('.mediathek-constant').on('click', '.teasers a, .media-thumb a:not(.download), a.button_back, .page-navigation a', function(e) {
            if (!$(this).hasClass('download')) {
                e.preventDefault();
                var parent = $(this).closest( ".mediathek-constant").find("> div");

                $(parent).prepend("<div class='ajax-loading lightgrey1'></div>");

                var url = $(this).attr('href');

                var index = 0;
                var teaser = $(this).closest('.teaser[data-index]');
                if(teaser) {
                    index = teaser.attr('data-index');
                }

                $.get(url, function(data) {

                    var liste = $('.media.liste').length ;

                    $(parent).replaceWith($(data).children('div').first());

                    if ($('.mediathek-movingimage').length > 0) {
                        movingimage(index);
                    } else {
                        picturefill();
                        mediathek();

                        WITTENSTEIN.module.initTeaserSlider();

                        // if page-navigation is used, and list view was set, change to list view
                        if (liste) {
                            $('.album-liste').trigger('click');
                        }
                    }
                });
            }
        });
    };

    /**
     * init dropdowns
     */
    var pressemitteilungen = function(searchValue) {
        $('.news-filter select').udgSelectDropdown();
        $('.news-filter .search_field').udgInputIcon();

        if(typeof searchValue === 'string') {
            $('.search_field').val(searchValue);
        }
        WITTENSTEIN.layout.placeholder();

    };

    /**
     * ajax aufruf bei filtern in pressemitteilungen
     */
    var presseAjax = function() {
        $('.news').parent().off().on('submit', '.news-filter form', function(e) {
            e.preventDefault();

            var $searchField = $('.search_field');
            var searchValue = $searchField.val();
            if (searchValue === $searchField.attr('placeholder') ) {
                $searchField.val("");
            }

            $('.news-list-view, .no-news-found').prepend("<div class='ajax-loading'></div>");

            $.post($(this).attr('action'), $(this).serializeArray(), function(data) {
                $('.news').replaceWith($(data));
                pressemitteilungen(searchValue);
                $('.news .news-pagination').pagination();
            });

        });

        $('.news .news-pagination').pagination();
        $('.news').parent().on('click', '.news-pagination a', function(e) {
            e.preventDefault();
            var searchValue = $('.search_field').val();
            $('.news-list-view, .no-news-found').prepend("<div class='ajax-loading'></div>");
            $.get($(this).attr('href'), function(data) {
                $('.news').replaceWith($(data));
                pressemitteilungen(searchValue);
                $('.news .news-pagination').pagination();
            });
        });
    };

    /**
     * wechselt zwischen der Gallerie- und Listenansicht
     */
    var switchAlbumView = function() {
        $('.album-liste').on('click', function(e) {
            e.preventDefault();
            $('.media, .album-views').removeClass('liste').addClass('liste');

            $(this).addClass('active');
            $('.album-gallerie').removeClass('active');
        });
        $('.album-gallerie').on('click', function(e) {
            e.preventDefault();
            $('.media, .album-views').removeClass('liste');

            $(this).addClass('active');
            $('.album-liste').removeClass('active');
        });
    };

    /**
     *  lightbox für Magazin
     */
    var lightbox = function() {
        var links = $( ".magazin .csc-textpic-imagewrap .csc-textpic-image a");
        var linkparent = links.parent();

        linkparent.css(
            "position", "relative"
        );

        links.each(function(k, v) {
            $('<img src="/typo3conf/ext/udg_template/Resources/Public/Images/presse/Zoom-Icon2.png" alt="" class="zoomicon" />').insertAfter($(v).find("picture"));
            $(v).attr("data-lightbox", 'move-lightbox-' + k);
        });
    };

    /**
     * initialisiert den slider in der pressedetailseite
     */
    var pressedetail = function() {
        $('.news-single .mediathek-album .bxslider').bxSlider({
            captions: false,
            video: true,
            useCSS: false,
            controls: false,
            // pager: false,
            pagerCustom : '.bx-pager',
            onSlideAfter: function($slideElement, oldIndex, newIndex) {
                // downloadlink bei bildern austauschen
                var downloadlink = $slideElement.find('.download-link').clone();
                $('.download-media a').remove();
                $('.download-media').append(downloadlink);

                // index in pager richtig setzen
                $('.bx-pager ul li').removeAttr('class').removeAttr('style');
                $.each($('.bx-pager ul li'), function(key, val) {
                    if (newIndex === key) {
                        $(val).addClass('current');
                    }
                });

                // aktualisiert die prev/next buttons im pager
                $('.pressemitteilung .mediathek-album .bx-pager').udgPaginate('updatePager', {bxSlider: true});

                // stop youtube videos on slide
                $('iframe[src*="https://www.youtube.com/embed/"]').each(function() {
                    this.contentWindow.postMessage('{"event" : "command" , "func" : "pauseVideo", "args": ""}', '*');
                });
            }
        });


        $('.pressemitteilung .mediathek-album .bx-pager').udgPaginate('updatePager', {bxSlider: true});

        var downloadlink = $('.start-slide').first().find('.download-link').clone();
        $('.download-media a').remove();
        $('.download-media').append(downloadlink);

    };

    /**
     * Load more button for event calendar
     */
    var eventCalendar = function() {
        $('.news__load').click(function() {
            var $self = $(this);
            abortRequest();
            var loadClass = 'news__load--ajax';
            $self.addClass(loadClass);

            $.get($self.attr('href'), function(response) {
                $('.article-container').append($(response).find('.article-container .article'));
                $self.removeClass(loadClass);
                
                var $btn = $(response).find('.news__btn-group');
                $self.unbind('click');
                if ($btn.length) {
                    $('.news__btn-group').replaceWith($btn);
                    eventCalendar();
                } else {
                    $self.remove();
                }
            });
            return false;
        });
    } 

    return {
        init : function() {
            if ($('.mediathek-constant').length) {
                lightbox();
                mediathek();
                mediathekAjax();
            }

            if ($('.news').length) {
                pressemitteilungen();
                presseAjax();
            }

            if ($('.news-single').length) {
                pressedetail();
            }

            if ($('.move-archiv').length) {
                moveArchiv();
            }

            if ($('.news__load').length) {
                eventCalendar();
            }
        }
    }

})(jQuery);

/**
 * events/functions in newsblog
 */
WITTENSTEIN.newsblog = (function($) {

    /**
     * init dropdowns
     */
    var initDropdowns = function() {
        $('.newsblog select[name!="tx_udgnewsblog_pi1[months]"]').udgSelectDropdown();
        $('.newsblog select[name="tx_udgnewsblog_pi1[months]"]').udgSelectDropdown({
            disabled: true
        });
        $('.newsblog .search_field').udgInputIcon();
    };

    /**
     * append bxslider
     */
    var newsblogdetail = function() {
        $('.newsblog .newsblog-detail-view .bxslider').bxSlider({
            captions: false,
            video: true,
            useCSS: false,
            controls: false,
            infiniteLoop: true,
            // pager: false,
            pagerCustom : '.bx-pager',
            onSlideAfter: function($slideElement, oldIndex, newIndex) {
                // downloadlink bei bildern austauschen
                var downloadlink = $slideElement.find('.download-link').clone();
                $('.download-media a').remove();
                $('.download-media').append(downloadlink);

                // index in pager richtig setzen
                $('.bx-pager ul li').removeAttr('class').removeAttr('style');
                $.each($('.bx-pager ul li'), function(key, val) {
                    if (newIndex === key) {
                        $(val).addClass('current');
                    }
                });

                // aktualisiert die prev/next buttons im pager
               $('.newsblog .newsblog-detail-view .mediathek-album .bx-pager').udgPaginate('updatePager', {bxSlider: true});

                // stop youtube videos on slide
                $('iframe[src*="https://www.youtube.com/embed/"]').each(function() {
                    this.contentWindow.postMessage('{"event" : "command" , "func" : "pauseVideo", "args": ""}', '*');
                });
            }
        });
        $('.newsblog .newsblog-detail-view .mediathek-album .bx-pager').udgPaginate('updatePager', {bxSlider: true});

        var downloadlink = $('.start-slide').first().find('.download-link').clone();
        $('.download-media a').remove();
        $('.download-media').append(downloadlink);
    };
    /**
     * append AJAX listener
     */
    var appendAjaxListener = function() {

        var state = null;

        // filter
        (function() {
            $('.newsblog .filter form').off().on('submit', function(e) {
                state = 'filter';
                e.preventDefault();

                // remove placeholder from empty inputs
                $(this).find('[placeholder]').each(function() {
                    var input = $(this);
                    if (input.val() == input.attr('placeholder')) {
                        input.val('');
                    }
                });
                getContent($(this).attr('action'), $(this).serialize(), true);

                // add placeholder to empty inputs
                $(this).find('[placeholder]').each(function() {
                    var input = $(this);
                    if (input.val() == '') {
                        input.val(input.attr('placeholder'));
                    }
                });

                return false;
            });
        })();
        // pagination
        var paginationListener = function() {
            state = 'pagination';
            $('.newsblog .news-pagination').pagination({
                jumpTo: $('#newsblog-results').position().top
            });
            $('.newsblog .pagination a').on('click', function(e) {
                e.preventDefault();
                getContent( $(this).attr('href'), null, true);
                return false;
            });  
        };
        paginationListener();

        // get data form server
        // called from pagination, filter and popstate listerner
        var getContent = function(url, data, pushState) {
            var reload = function(response) {
                // History API Supported
                if (pushState && Modernizr.history) {
                    //history.pushState(null, null, url);   
                }
                $('#newsblog-results').replaceWith($('#newsblog-results', response));

                // check if year was selected
                var monthsDropdown = $('.newsblog select[name="tx_udgnewsblog_pi1[months]"]').siblings('.dropdown');
                if ( $('.newsblog select[name="tx_udgnewsblog_pi1[years]"]').val() > 0 ) {				
                    monthsDropdown.removeClass('disabled');
                } else {
                    monthsDropdown.addClass('disabled');
                    monthsDropdown.find('ul li').removeClass('current isvisible').hide();
                    var initState = monthsDropdown.find('ul li.divider').next();
                    monthsDropdown.find('ul li:first-child').replaceWith(initState.clone());
                    initState.addClass('current isvisible').show();
                    $('.newsblog select[name="tx_udgnewsblog_pi1[months]"]').val("0");
                }
                paginationListener();
            };
            $('#newsblog-results').prepend("<div class='ajax-loading'></div>");

            if (state == 'filter') {
                $.post(url, data, reload);
            } else {
                $.get(url, reload);
            }
        }
    };

    return {

        init : function() {
            if ($('.newsblog').length) {
                if ($('.newsblog .filter').length) {
                    initDropdowns();
                    appendAjaxListener();
                }
                if ($('.newsblog .newsblog-detail-view').length) {
                    newsblogdetail();
                }
            }
        }
    }
})(jQuery);

/**
 * Produktübersicht und -detailseite
 */
WITTENSTEIN.produkte = (function($) {

    "use strict";

    /**
     * @var XMLHttpRequest
     */
    var xhr;

    /** selectors */
    var categoryDropdownSelector = "select[name='tx_udgproducts_pi1[category]']";
    var subcategoryDropdownSelector = "select[name='tx_udgproducts_pi1[subcategory]']";
    var businessunitDropdownSelector = "select[name='tx_udgproducts_pi1[businessunit]']";
    var linesDropdownSelector = "select[name='tx_udgproducts_pi1[lines][]']";

    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    /**
     * Prepend loading icon
     */
    var ajaxLoading = function($element) {
        $element.prepend("<div class='ajax-loading' style='background-position: center 100px;'></div>");
    }

    /**
     * Replace selects with dropdowns
     */
    var udgDropdown = function(loadAll){
        var selector = loadAll ? '.filter' : '.dropdowns-container';
        $(selector + ' .udgDropdown').css('width', $('.udgDropdown').outerWidth(true) - 60);
        $(selector + ' .dropdown').addClass('dontsubmit');
        $(selector + ' .search_field').udgInputIcon();
        $(selector + ' .dropdown').udgSelectDropdown();
    }

    /**
     * Append fancybox to i-link
     */
    var lineInfoBox = function() {
        $(".line-infobox-link").fancybox({
            href :'#line-infobox',
            maxWidth: 900,
            wrapCSS : 'line-infobox-wrap',
            beforeShow: function() {
                $('.bg-overlay').css('z-index', '10002').addClass('show');
            },
            beforeClose: function() {
                $('.bg-overlay').css('z-index', '10000').removeClass('show');
            }
        });
    }

    /**
     * Set dropdown and select to value
     */
    var setDropdown = function(selector, value) {
        var $select = $(selector);
        var $dropdown = $select.next();
        $dropdown.find('li').removeClass('current isvisible').hide();
        $dropdown.find('li[data-value="' + value + '"]').first().addClass('current isvisible').show();
        $select.find('option').removeAttr('selected');
        $select.find('option[value="' + value + '"]').attr('selected', true);
    }

    /**
     * Reset filter
     */
    var resetFilter = function(doNotResetBusinessunit) {
        setDropdown(categoryDropdownSelector, 0);
        setDropdown(subcategoryDropdownSelector, 0);
        if (typeof doNotResetBusinessunit == 'undefined' || !doNotResetBusinessunit) {
            setDropdown(businessunitDropdownSelector, 0);
        }
        $(linesDropdownSelector).val([]);
        $('.udgMultiSelect input').prop('checked', false);
    }

    /**
     * xs view transforms filter and products into accordion
     */
    var accordionListener = function(appendFilterToggle) {

        var toggleElements = appendFilterToggle ? '.categoryWrapper .category, .headline-toggle' :  '.categoryWrapper .category';
        var $wrapper = $('#product-categories');

        $(toggleElements).on('touchmove', function() {
            $wrapper.attr('data-touch', 'touchmove');
        });

        $(toggleElements).on('touchend mousedown', function(e) {
            e.preventDefault();
            var filterToggle = $(this).hasClass('headline-toggle');
            if( WITTENSTEIN.isMediaXS() && typeof $wrapper.attr('data-touch') === 'undefined' ) {
                var ver = WITTENSTEIN.iOSversion();
                if (ver[0] < 6) {
                    if (filterToggle) {
                        $('.filter-toggle').setAttribute("style", "display: block !important");
                    } else {
                        $(this).next('.productWrapper')[0].setAttribute("style", "display: block !important");
                        $(this).find('.description')[0].setAttribute("style", "display: block !important");
                    }
                } else {
                    if (filterToggle) {
                        $('.filter-toggle').slideToggle();
                    } else {
                        $(this).next('.productWrapper').slideToggle();
                        $(this).find('.description').slideToggle();
                    }
                }
                $(this).toggleClass( "arrow-helper" );
            } else {
                $wrapper.removeAttr('data-touch');
            }
        });
    };

    /**
     * Load data by selected values
     */
    var search = function(push) {
        ajaxLoading($('.ajax-loading-area'));
        abortRequest();
        var $form = $('#filter-searchform');
        var filterIsVisible = $('.filter-toggle').is(":visible");
        var updatePushState = typeof push != 'undefined' ? push : true;

        xhr = $.ajax({
            method: 'POST',
            url: $form.attr('action'),
            data: $form.serializeArray(),
            success: function(data) {

                var selectors = ['.seo-text', '.ajax-loading-area'];

                // replace dropdowns when result is not empty
                if ( $(data).find('#filter-searchform').attr('data-categories-contain-products') == 1 ) {

                    var $multiSelect = $(data).find('.udgMultiSelect');
                    var addUdgDropdowns2AllSelects = true;

                    if ($multiSelect.length) {
                        if ($('.udgMultiSelect').length > 0) {
                            selectors.push('.dropdowns-container');
                            addUdgDropdowns2AllSelects = false;
                        } else {
                            selectors.push('.filter');
                        }
                    } else {
                        selectors.push('.filter');
                    }

                    $.each(selectors, function(index, selector){
                        $(selector).replaceWith($(data).find(selector));
                    });

                    // open current dropdown after replacement again (mobile only)
                    if (filterIsVisible) {
                        $('.filter-toggle').show();
                    }

                    // update pushstate
                    if (typeof history.pushState != 'undefined' && updatePushState) {
                        var url = $('.ajax-loading-area').attr('data-current-uri');
                        if (typeof url === 'string') {
                            var state = {
                                'category': $(categoryDropdownSelector).val(),
                                'subcategory': $(subcategoryDropdownSelector).val(),
                                'businessunit': $(businessunitDropdownSelector).val(),
                                'lines': $(linesDropdownSelector).val()
                            };
                            history.pushState(state, null, url);
                        }
                    }

                    // append listener
                    accordionListener(addUdgDropdowns2AllSelects);
                    udgDropdown(addUdgDropdowns2AllSelects);

                } else {
                    // no results
                    $.each(selectors, function(index, selector){
                        $(selector).replaceWith($(data).find(selector));
                    });
                    // append reset listener
                    $('.reset-filter').click(function(){
                        resetFilter();
                        search();
                    });
                }
            }
        });
    }

    /**
     * History pop
     */
    var popstateListener = function() {
        if (typeof history.pushState != 'undefined') {
            window.addEventListener('popstate', function(e){
                var state = e.state;
                if (state !== null) {                                        
                    setDropdown(categoryDropdownSelector, state.category);
                    setDropdown(subcategoryDropdownSelector, state.subcategory);
                    setDropdown(businessunitDropdownSelector, state.businessunit);
                    search(false);
                }
            });
        }
    }

    /**
     * Update results on filter changes
     */
    var filterDropdowns = function() {
        $('.product-overview-container').on('change', '.filter select', function() {
            // reset all filters on businessunit change
            if ((new RegExp('tx_udgproducts_pi1\\[businessunit\\]')).test($(this).attr('name'))) {                
                resetFilter(true);
            } else {
                // reset subcategory on category change
                if ((new RegExp('tx_udgproducts_pi1\\[category\\]')).test($(this).attr('name'))) {
                    setDropdown(subcategoryDropdownSelector, '0'); 
                }                
            }
            search();
        });
    }

    /**
     * Filter preselection by anchor
     */
    var linePrefilter = function() {
        var hash = window.location.hash.toLowerCase().replace(/^#/, '');
        var name = null;
        // extract line name
        $.each($(linesDropdownSelector).children('option'), function(index, option) {
            var line = $(option).text().toLowerCase().replace(/\s+/g, '-');
            if (hash == line) {
                name = $(option).text();
                return false;
            }
        });

        if (name !== null) {
            var $checkbox = $('input[name="' + name + '"]');
            // select checkbox
            $checkbox.click();
            // remove ancher on next  checkbox click
            $checkbox.closest('ul').find('input[type="checkbox"]').bind('click', function() {
                if (window.location.hash.match(/^#/)) {
                    history.pushState("", document.title, window.location.pathname + window.location.search);
                }
            });
        }
    }

    // initialisiert die dropdowns und den Slider im Produktteaser auf der Startseite
    var productfinder = function() {
        var initializeDropdown = true;
        var initDropdownsAndSlider = function(infiniteLoop) {

            if (initializeDropdown == true) {
                $('.product-filter .udgDropdown').udgSelectDropdown({
                    change: null
                });
                initializeDropdown = false;
            } else {
                $('.product-filter .subcategory-wrapper .udgDropdown').udgSelectDropdown({
                    change: null
                });
            }

            if (typeof infiniteLoop == 'undefined') {
                infiniteLoop = true;
            }

            if ($('.product-slider .teaser').length >= 4) {
                $('.product-slider:not(.no-slider)').bxSlider({
                    slideWidth: 290,
                    minSlides: 1,
                    maxSlides: 4,
                    moveSlides: 1,
                    slideMargin: '10',
                    pager: false,
                    adaptiveHeight: true,
                    infiniteLoop: infiniteLoop,
                    useCSS: false,
                    controls: ($('.product-slider .productWrapper:not(.bx-clone)').length > 4)
                });
            }

            $('.product-slider .productWrapper').css('visibility', 'visible');
        }

        $('.productfinder').on('change', '.product-filter select', function(e) {
            e.stopImmediatePropagation();

            // reset subcategory filter
            if ($(this).hasClass('reset-siblings')) {
                $('.productfinder .product-filter .subcategory-wrapper select').val('0');
            }

            var form = $(this).parents('form');
            var url = form.attr('action');
            var formData = form.serializeArray();
            var that = $(this);

            ajaxLoading($('.productfinder .teaser-products'));
            $.post(url, formData, function (data) {
                $('.productfinder .product-filter .subcategory-wrapper').replaceWith($('.subcategory-wrapper', data));
                $('.productfinder .teaser-products').replaceWith($(data).find('.teaser-products'));
                initDropdownsAndSlider(!(that.val() > 0));
            });
        });
        initDropdownsAndSlider();
    }

    return {
        init : function() {
            if ($('.product-overview-container').length) {
                accordionListener(true);
                udgDropdown(true);
                filterDropdowns();
                lineInfoBox();
                popstateListener();
                linePrefilter();
            }

            if($('.productfinder').length) {
                productfinder();
            }
        }
    }

})(jQuery);
/**
 * Product variants
 */
WITTENSTEIN.productvariants = (function($) {

    'use strict';

    var handleItemClick = function(event) {
        if (window.innerWidth >= 900) {
            return;
        }
        var el = event.currentTarget.parentElement;
        while (!el.classList.contains('product-variants__item')) {
            el = el.parentElement;
        }
        el.classList.toggle('product-variants__item--open');
        event.preventDefault();
        event.stopImmediatePropagation();
    }

    var appendClickListener = function() {
        var items = document.querySelectorAll('.product-variants__item>a[rel="media-slider"]');
        for (var i = 0; i < items.length; i++) {
            items[i].querySelector('.product-variants__textwrapper').addEventListener('click', handleItemClick);
        }
    }

    return {
        init : function() {
            if($('.product-variants').length) {
                appendClickListener();
            }
        }
    }

})(jQuery);
/**
 * Kontaktformular
 */
WITTENSTEIN.kontakt = (function($) {

    /**
     * init plugins for input elements
     */
    var inputs = function() {
        $('.powermail_select').css('width', $('.powermail_select').outerWidth(true) - 60);
        $('.powermail_select').addClass('dontsubmit');
        $('.powermail_select').udgSelectDropdown({
            'scrollable' : true
        });
        $('.powermail_radio_inner').udgRadiobtn();
        $('.powermail_check_inner').udgCheckbox();
        $('.powermail_fieldwrap_type_submit').udgSubmit();
        $('.tx-felogin-pi1 form fieldset div:has(input[type="submit"])').udgSubmit();

        // add and remove parsley-error class for dropdowns
        var errorClass = 'parsley-error';
        var $select = $('form[data-parsley-validate] select[required="required"]');

        if ($select.length) {
            $select.on('change', function(){
                if ($(this).val().length) {
                    $(this).siblings('.dropdown').removeClass(errorClass);
                    $(this).siblings('.parsley-errors-list').empty();
                } else {
                    $(this).siblings('.dropdown').addClass(errorClass);
                    var $message = $('<li>' + $(this).attr('data-parsley-required-message') + '</li>');
                    $(this).siblings('.parsley-errors-list').append($message);
                }
            }).parsley().on('field:error', function(el) {
                var $dropdown = el.$element.siblings('.dropdown');
                if ($dropdown.length) {
                    $dropdown.addClass(errorClass);
                }
            }).on('field:success', function(el) {
                var $dropdown = el.$element.siblings('.dropdown');
                if ($dropdown.length) {
                    $dropdown.removeClass(errorClass);
                }
            });
        }
    };

    return {
        init : function() {
            inputs();
        }   
    }
})(jQuery);
/**
 * global verwendete module
 */
WITTENSTEIN.module = (function($) {

	var carousel = null;

	/**
	 * initialisiert die 360° Ansicht
	 */
	var turntable = function() {

		$('.turntable').spritespin('destroy');

		$.each($('.turntable'), function(k, v) {
			// im elternelement sollte in den hiddenfields der dateipfad stehen
			var source = [];
			$(v).parent().find('input[type=hidden]').each(function(i, j) {
				source.push($(j).val());
			});

			// bildverhältnis
			var imgW = $(v).parent().find('input[type=hidden]').first().attr('data-width');
			var imgH = $(v).parent().find('input[type=hidden]').first().attr('data-height');
			var ratio = imgW / imgH;

			var width  = $(v).parent().width();

			if (width > imgW) {
				width = imgW;
			}

			var slide = $('#turntable-slider');
			var spin = $('.turntable');

			$(v).spritespin({
				source : source,
				width: width,
				height: (width / ratio),
				frameTime: 80,
				animate: false,
				onLoad: function() {
					slide.slider({
						min: 0,
						max: source.length - 1,
						slide: function(e, ui) {
							var api = spin.spritespin('api');
							api.stopAnimation();
							api.updateFrame(ui.value);
						}
					});
				},
				onFrame: function(e, data) {
					slide.slider('value', data.frame);
				}
			});

		});

		// add turntable-arrow afterwards
		$('.turntable').prepend($('<div class="turntable-arrow"></div>'));

	}

	/**
	 * Slider stellt Mediaelemente dar (z.B. in Produktdetailansicht)
	 */
	var mediaElementSlider = function(args) {
		if ($('.mediaelement-slider').length < 1) {
			return;
		}
		let sliderSelector = '.mediaelement-slider';
		// stop youtube on change
		$('.mediaelement-slider a[data-slide-index]').click(function(){
			$.each($(sliderSelector).find('iframe'), function(index, iframe) {
				var src = $(iframe).attr('src');
				$(iframe).attr('src', '').attr('src', src);
			});
		});

		// slides in carousel
		var numSlides = $(sliderSelector + ' .bxslider li').length;

		var carouselOptions = {
				slideWidth: 142,
				minSlides: 1,
				maxSlides: 4,
				moveSlides: 1,
				slideMargin: 17,
				pager: false,
				useCSS: false,
				adaptiveHeight: true,
				controls: false,
				infiniteLoop: false,
				onSliderLoad: function(currentIndex) {
					$(sliderSelector + ' .bx-pager').find("a").removeClass('activeitem');
					$(sliderSelector + ' .bx-pager').find("[data-slide-index='" + currentIndex + "']").addClass('activeitem');

					var thumbActive = $('<img src="/typo3conf/ext/udg_template/Resources/Public/Images/presse/Thumb_active2.png" alt="" class="thumbactive">');
					$(sliderSelector + ' .bx-pager').find('a').append(thumbActive);
				}
		};

		if (numSlides >= 4) {
			carouselOptions.infiniteLoop = true;
			carouselOptions.controls = true;
		}

		if (numSlides > 1) {

			// add carousel
			$.each( $(sliderSelector + ' .bx-pager').not('.album-pager') , function(index, bxPager) {
				var $bxPager = $(bxPager);

				if ($bxPager.closest('.product__contentelement').length) {
					var ceSliderOptions = $.extend({}, carouselOptions);
					ceSliderOptions.maxSlides = 6;
					ceSliderOptions.infiniteLoop = false;
					$bxPager.bxSlider(ceSliderOptions);
				} else {
					carousel = $bxPager.bxSlider(carouselOptions);
				}
			});

			// thumbnails that are smaller should be centered vertically
			$(sliderSelector + '.bx-pager-wrapper .bx-pager').find('a img:not(.play-icon)').each(function(k,v) {
				var height = $(v).attr('height');

				if (height < 78) {
					var padding = parseInt((78 - height) / 2);
					$(v).css('padding', padding + 'px 0px');
				}
			});

			if (numSlides < 4) {
				// pager wrapper zentriert anzeigen, maximal vier bilder breit
				// 142px ist die thumbnail groesse, 16px abstand und 96px für die navigationspfeile
				$(sliderSelector + '.bx-pager-wrapper').width(numSlides * (142 + 16) + 96 + 'px');
			}
		}

		var removeIframeLink = function(elem) {
			// wenn aktuelles element ein iframe ist, soll das href-attribut entfernt werden, da
			// der IE9 sonst dem Link folgt, anstelle das Video abzuspielen
			if (elem.find('iframe').length) {
				var src = elem.find('a').attr('href');
				elem.find('a').attr('data-src', src);
				elem.find('a').removeAttr('href');
			} else {
				$(sliderSelector + 'iframe').each(function(k, v) {
					var src = $(v).parents('a').attr('data-src');
					$(v).parents('a').attr('href', src);
					$(v).parents('a').removeAttr('data-src');
				});
			}
		}

		// slider options
		var options = {
				pagerCustom: '.bx-pager',
				controls: false,
				video: true,
				useCSS: false,
				slideWidth: 99999,
				minSlides: 1,
				maxSlides: 1,
				moveSlides: 1,
				onSlideBefore: function($slideElement, oldIndex, newIndex) {
					removeIframeLink($slideElement);
				},
				onSlideAfter: function($slideElement, oldIndex, newIndex) {

					if (carousel !== null) {
						carousel.find("a").removeClass('activeitem');
						carousel.find("[data-slide-index='" + newIndex + "']").addClass('activeitem');
					}

					var imgH = $slideElement.find('img:not(.zoomicon)').height();
					$(sliderSelector + '> .bx-wrapper .bx-controls .bx-controls-direction').first().css('top', (imgH / 2));
				},
				onSliderLoad: function(currentIndex) {
					var elem = $(sliderSelector + '.bxslider li:not(.bx-clone)').eq(currentIndex);
					removeIframeLink(elem);

					$(sliderSelector + '.bx-wrapper li div.image-desc, ' +
							sliderSelector + '.bx-wrapper li div.turntable-desc').each(function(k, v) {

								if (!WITTENSTEIN.isPortable()) {

									var height = $(this).parents('.bx-viewport').outerHeight(true);

									if (height > 450) {
										height = 450;
									}

									$(this).css('height', height);

									// product headline avalible
									if ($(this).next().hasClass('description')) {
										var bxViewportHeight = $(this).next().height() * 2 + height;
										$(this).closest('.bx-viewport').css('height', bxViewportHeight);
									}

									var img = $(this).find('img:not(.zoomicon, .view360)');
									$(this).find('img:not(.zoomicon, .view360)').css('padding-top', (((height - 2) - parseInt(img.height())) / 2) + 'px');

								} else {
									$(this).css('height', 'auto');
								}

							});

					var imgH = $(sliderSelector + '.bxslider li:nth-child(' + currentIndex + 1 + ')').find('img:not(.zoomicon)').height();
					$(sliderSelector + '> .bx-wrapper .bx-controls .bx-controls-direction').first().css('top', (imgH / 2));

				}
		};

		var slider = null;
		var loadSlider = function() {

			// enable controls in xs, sm
			if (!WITTENSTEIN.isMediaMD()) {
				options = $.extend(options, {controls: false, pager: true, pagerCustom: null});
			} else {
				options = $.extend(options, {controls: false, pagerCustom: '.bx-pager'});
			}

			if (numSlides == 1) {
				options.pager = false;
				options.autoHover = false;
				options.controls = false;
				options.auto = false;
				options.touchEnabled = false;
				options.preventDefaultSwipeY = false
			}

			// disable swiping in product detail view because fancybox is appended
			if ($('.mediaelement-slider').parent().hasClass('product-media')) {
				options.touchEnabled = false;
			}

			// init slider
			slider = $('.mediaelement-slider ul.bxslider').bxSlider(options);
			$('.mediaelement-slider').css('visibility', 'visible');

		}

		loadSlider();


		var is = window.matchMedia("screen and (max-width: 600px)");
		var sm = window.matchMedia("screen and (max-width: 900px)");
		var md = window.matchMedia("screen and (max-width: 1024px)");

		if (is.matches || sm.matches || md.matches) {
			if (slider != null) {
				loadSlider();
			}
		}

		// no swipe if element is a turntable
		$('.mediaelement-slider li').on('touchstart', function(e) {
			if (typeof slider !== 'undefined' && slider !== null) {
				var el = slider.getCurrentSlideElement();

				if ($(el).find('.turntable').length > 0) {
					e.stopPropagation();
				}
			}
		});

		// // hide fancybox arrows if only one content element exists
		var fancyBoxArrows = ($('.bx-pager a[data-slide-index]').length > 1);

		/**
		 * lightbox in slider
		 */
		var links = $('.mediaelement-slider .bxslider li:not(.bx-clone) a[rel="media-slider"]').fancybox({
			arrows: fancyBoxArrows,
			beforeLoad : function() {
				// add load animation
				$('.fancybox-inner').prepend("<div class='ajax-loading'></div>");
			},
			beforeShow: function() {
				$(".fancybox-inner").find("iframe").addClass("image-wrapper" );
				$(".fancybox-inner .image-wrapper h2 br").replaceWith(' ');
			},
			afterShow : function () {
				$('.bg-overlay').show();
				$('.fancybox-inner .arrow-close').on('click', function() {
					$.fancybox.close();
				});

				// set width and height dynamically
				var w = $('.turntable-container input:hidden').first().attr('data-width');
				var h = $('.turntable-container input:hidden').first().attr('data-height');

				$('.turntable-container').width(w).height(h);

				turntable();

				$('.fancybox-inner .ajax-loading').remove();
			},
			afterClose : function () {
				$('.bg-overlay').hide();
			},
			autoSize: false,
			transitionIn: 'none',
			transitionOut: 'none',
			helpers : {
				closeClick: false,
				overlay : {
					locked : true
				}
			},
			nextEffect : 'none',
			prevEffect : 'none'
		});

		// add zoom-icon
		$.each(links, function(key, link) {
			$(link).find('img').after($('<img src="/typo3conf/ext/udg_template/Resources/Public/Images/presse/Zoom-Icon.png" alt="" class="zoomicon" />'));

			// hide video on hover, else it shines over the img on hover
			$(link).hover(function() {
				$(this).parents('.bxslider').find('li video').css('visibility', 'hidden');

				// zentriert das zoomicon
				var h = parseInt($(this).height());
				var w = parseInt($(this).width());

				if (!(h > 0)) {
					h = $(this).find('img:not(.zoomicon, .view360)').height();
				}
				if (!(w > 0)) {
					w = $(this).find('img:not(.zoomicon, .view360)').width();
				}

				$(this).find('.zoomicon').css('left', (w / 2) - 20 + 'px');
				$(this).find('.zoomicon').css('top', (h / 2) - 20 + 'px');


			}, function() {
				$(this).parents('.bxslider').find('li video').css('visibility', 'visible');
			});
		});

		$(window).resize(function() {
			turntable();
		});
	}

	var standaloneTurntables = function() {
		/**
		 * lightbox in slider
		 */
		var links = $('.hotspot-show-wrapper a[rel="media-slider"], .product-variants__item a[rel="media-slider"], .product-variants__downloads a[rel="fancybox"]').fancybox({
			arrows: false,
			beforeLoad : function() {
				// add load animation
				$('.fancybox-inner').prepend("<div class='ajax-loading'></div>");
			},
			beforeShow: function() {
				$(".fancybox-inner").find("iframe").addClass("image-wrapper" );
			},
			afterShow : function () {
				$('.bg-overlay').show();
				$('.fancybox-inner .arrow-close').on('click', function() {
					$.fancybox.close();
				});

				// set width and height dynamically
				var w = $('.turntable-container input:hidden').first().attr('data-width');
				var h = $('.turntable-container input:hidden').first().attr('data-height');

				$('.turntable-container').width(w).height(h);

				turntable();

				$('.fancybox-inner .ajax-loading').remove();

			},
			afterClose : function () {
				$('.bg-overlay').hide();
			},
			height: (WITTENSTEIN.isMediaXS() ? '30%' : '70%'), // fuer iframe
			width: '70%', // fuer iframe
			transitionIn: 'none',
			transitionOut: 'none',
			helpers : {
				closeClick: false,
				overlay : {
					locked : true
				}
			}
		});
	};

	/**
	 * Zeigt die Publikationen auf der Presse-Seite in einem Slider an
	 */
	var initMoveSlider = function() {
		var mobile = window.matchMedia("screen and (max-width: 600px)");

		//one image alway up-top (Move slider)
		var sliderMove = $('.slider-onepic .grid-slider').bxSlider({
			minSlides: 1,
			maxSlides: 1,
			pager: false,
			nextText: '',
			prevText: '',
			touchEnabled: mobile.matches,

			// Pfeile in Publikationen immer mittig zum Bild
			onSliderLoad : function(currentIndex) {
				if(!WITTENSTEIN.isMediaMD()){

					$('.grid-slider').closest('.bx-wrapper').find('.bx-prev').addClass('add-arrow-left');
					$('.grid-slider').closest('.bx-wrapper').find('.bx-next').addClass('add-arrow-right');

					$.each($('.slider-onepic .slide:not(.bx-clone)'), function(k, v) {
						if (k === currentIndex) {
							var imgHeight = $(v).find('img').height();
							if(imgHeight != null){
								$(v).parents('.bx-wrapper').find('.bx-controls-direction a').css('top', Math.round(imgHeight / 2) + 'px');

							}else{
								$(v).parents('.bx-wrapper').find('.bx-controls-direction a').css('top', '50%');
							}
						}
					});
				}else{
					$('.slider-onepic .bx-controls-direction a').css('top', '50%');
				}
			},
			onSlideAfter : function($slideElement, oldIndex, newIndex) {
				if(!WITTENSTEIN.isMediaMD()){
					var imgHeight = $slideElement.find('img').height();
					if(imgHeight != null){
						$slideElement.parents('.bx-wrapper').find('.bx-controls-direction a').css('top', Math.round(imgHeight / 2) + 'px');
					}else{
						$slideElement.parents('.bx-wrapper').find('.bx-controls-direction a').css('top', '50%');
					}
				}else{
					$('.slider-onepic .bx-controls-direction a').css('top', '50%');
				}
			}
		});


		// in Mobilansicht wird Button_3 zu Button_1
		if (mobile.matches) {
			$('.magazin .button_1, .teaser .button_1').addClass('button_3').removeClass('button_1');
		}
	}

	/**
	 * Zeigt 1-3 Teaser in einem Slider für Mobile- und Tablet-Devices an
	 * (wird z.B. für die Teaser auf der Presse-Seite oder in der Produktdetailseite verwendet.)
	 */
	var initTeaserSlider = function() {
		var teaserSlider = [];

		// slider mit diesen klassen werden initialisiert
		// ein teaserslider sollte daher eine dieser klassen besitzen
		var classes = [
			'.slider-sm-average .grid-slider',
			'.teaser-slider:not(.no-slider)',
			'.layout-444',
			] ;

		var loadSliders = function(slideWidth) {

			// settings for other sliders for teaser boxes etc.
			var settingsXS = {
					pager: true,
					adaptiveHeight: true,
					slideMargin: 10
			};

			var settings = {
					slideWidth: parseInt(slideWidth) > 0 ? parseInt(slideWidth) : 384,
							minSlides: 1,
							maxSlides: 3,
							moveSlides: 1,
							slideMargin: 10,
							pager: false,
							adaptiveHeight: true,
							prevText: '',
							nextText: '',
							touchEnabled: true
			};

			// destroy sliders first (for media MD)
			$.each(teaserSlider, function(k, v) {
				if (typeof v == 'object' && typeof v.destroySlider == 'function') {
					v.destroySlider();
				}
			});

			if (WITTENSTEIN.isMediaXS()) {

				// init slider for media XS
				$.each($(classes.join(", ").slice(0, -2)), function(k, v) {
					$(v).each(function(i, j) {
						settingsXS.pager = ($(j).children('div:not(.bx-clone)').length > 1);
						settingsXS.touchEnabled = ($(j).children('div:not(.bx-clone)').length > 1);
						settingsXS.controls = ($(j).children('div:not(.bx-clone)').length > 1);
						teaserSlider.push($(j).bxSlider(settingsXS));
					});
				});
			} else if (!WITTENSTEIN.isMediaMD()) {

				// init slider for media IS, SM
				$.each($(classes.join(", ").slice(0, -2)), function(k, v) {
					$(v).each (function(i, j) {
						if (!$(j).hasClass('teaser')) {
							delete settings.slideWidth;

							settings.pager = ($(j).children('div:not(.bx-clone)').length > 1);
							settings.adaptiveHeight = false;
							settings.touchEnabled = ($(j).children('div:not(.bx-clone)').length > 1);
							settings.controls = ($(j).children('div:not(.bx-clone)').length > 1);

							var teasersW = 0;
							$(j).children('div:not(.bx-clone)').each(function() { return teasersW += $(this).width(); } );

							// only create teaser if, width of all teasers is bigger than the slider-wrapper
							if ( $(j).width() < teasersW ) {
								teaserSlider.push($(j).bxSlider(settings));
							}
						}

					});
				});
			} else {

				// settings for teaser with equal to or less than 3 elements
				var extendedSettings = $.extend({}, settings, {
					controls: false,
					infiniteLoop: false,
					wrapperClass: 'bx-wrapper bx-align-left',
					touchEnabled: false
				});

				// media MD
				$.each($(classes.join(", ").slice(0, -2)), function(k, v) {
					$(v).each (function(i, j) {
						if ($(j).find('.teaser').length > 3) {
							teaserSlider.push($(j).bxSlider(settings));
						} else {
							teaserSlider.push($(j).bxSlider(extendedSettings));
						}
					});
				});
			}

			// workaround
			// @see: https://github.com/stevenwanderski/bxslider-4/issues/560
			if ($('.bx-loading').length > 0) {
				$('.bx-loading').remove();
			}
		}

		loadSliders();

		var is = window.matchMedia("screen and (max-width: 600px)");
		var sm = window.matchMedia("screen and (max-width: 900px)");
		var md = window.matchMedia("screen and (max-width: 1024px)");

		if (md.matches) {
			var bxWrapper = $('.inhalt .bx-wrapper');
			var slideWidth = parseInt(($(bxWrapper).width() - 35) / 3);
			loadSliders(slideWidth);
		}

		if (is.matches || sm.matches) {
			loadSliders();
		}

	}

	/**
	 * Teaser as slick slider
	 */
	var initTeaserSlick = function() {
		var currentClassName = 'slick-current-slide';
		$('.teaser-slick').on({
			init:  function(event, slick){
				$(slick.$slides.get(0)).addClass(currentClassName);
			},
			beforeChange: function(event, slick, currentSlide, nextSlide){
				$(slick.$slides.get(currentSlide)).removeClass(currentClassName);
			},
			afterChange: function(event, slick, currentSlide){
				$(slick.$slides.get(currentSlide)).addClass(currentClassName);
			}
		}).slick({
			centerMode: true,
			slidesToShow: 3,
			centerPadding: '0px',
			responsive: [{
				breakpoint: 900,
				settings: {
					slidesToShow: 1,
					centerPadding: '0'
				}
			}]
		});
	};

	/**
	 * default slider
	 */
	var initDefaultSlider = function() {

		$('.outer-slider .grid-slider, .slider-average .grid-slider').bxSlider({
			minSlides: 1,
			maxSlides: 1,
			pager: false,
			nextText: '',
			prevText: ''
		});

	}

	var mediathekGallerySlider = function() {

		var slider = null;

		if ($('.mediathek-gallery').length == 0) {
			return 0;
		}

		var loadSlider = function() {

			// bxSlider is attached for .mediathek-detail in presse.js
			if ($('.mediathek-gallery').find('.mediathek-detail').length > 0) {
				return;
			}

			slider = $('.mediathek-gallery .bxslider').bxSlider({
				captions: true,
				video: true,
				pager: ($('.mediathek-gallery .bxslider li').length > 1),
				onSlideAfter: function($slideElement, oldIndex, newIndex) {

					// stop youtube videos on slide
					$('iframe[src*="https://www.youtube.com/embed/"]').each(function() {
						this.contentWindow.postMessage('{"event" : "command" , "func" : "pauseVideo", "args": ""}', '*');
					});

				}
			});

			// @todo : bxslider aborts loading (in ie9) if images are not loaded before
			if ($('.mediathek-detail .bxslider').length && $('html').hasClass('ie9')) {

				$('.mediathek-detail .bxslider li img').each(function(k, v) {
					var dataSrc = $(v).attr('data-src');
					$(v).removeAttr('data-src');
					$(v).attr('src', dataSrc);
					$(v).removeAttr('lazyload');
				});
			}

			$('.mediathek-detail .bxslider li').each(function(key, val) {
				$(val).find('a:not(.download-link)').attr('data-fancybox', 'media-lightbox' + key) ;
			});

			$('.mediathek-detail .bxslider li').find('a[data-fancybox]').fancybox({
				beforeLoad : function() {
					// add load animation
					$('.fancybox-inner').prepend("<div class='ajax-loading'></div>");
				},
				beforeShow: function() {
					$(".fancybox-inner").find("iframe").addClass("image-wrapper" );
				},
				afterShow : function () {
					$('.bg-overlay').show();
					$('.fancybox-inner .arrow-close').on('click', function() {
						$.fancybox.close();
					});

					// set width and height dynamically
					var w = $('.turntable-container input:hidden').first().attr('data-width');
					var h = $('.turntable-container input:hidden').first().attr('data-height');

					$('.turntable-container').width(w).height(h);

					turntable();

					$('.fancybox-inner .ajax-loading').remove();
				},
				afterClose : function () {
					$('.bg-overlay').hide();
				}
			});

		}

		loadSlider();

		$(window).resize(function() {
			if (slider != null) {
				if (typeof slider == 'object' && typeof slider.destroySlider == 'function') {
					slider.destroySlider();
				}
			}
			loadSlider();
		});
	}

	// jQuery quicklinks: berechnet , ob der text in den buttons ein- oder zweizeilig angezeigt wird
	var quicklinks = function() {
		if ($('.quicklinks .quicklinks-button').length > 0) {
			$('.quicklinks .quicklinks-button').on('click', function(e) {

				$link = $(this).find('a').first();
				if($link.attr('target')=='_blank'){
					window.open($link.attr('href'),$link.attr('target'));
				}else{
					location.href = $link.attr('href');
				}
			});
		}
	}

	/**
	 * fügt eine horizontale scrollbar hinzu, wenn der inhalt überlappt
	 */
	var hscrollbar = function() {

		var init = function() {
			if ($('.hscrollbar').prop('offsetWidth') < $('.hscrollbar').prop('scrollWidth')) {

				$('.hscrollbar').mCustomScrollbar("destroy");
				$('.hscrollbar').mCustomScrollbar({
					axis:"x",
					theme: 'inset'
				});
			} else {
				$('.hscrollbar').mCustomScrollbar("destroy");
			}
		}
		init();

		$(window).resize(function() {
			init();
		});
	}

	/**
	 * build all akkordeon elements
	 */
	var akkordeon = function() {
		$('.akkordeon').akkordeon();

		var apScrolling = function($target) {
			if ($target.length) {
				var $accordion = $target.closest('.akkordeon__plus');
				// open accordion
				if ($accordion.length) {
					var position = $target.offset().top;
					var offset = 200;

					if (WITTENSTEIN.isMobile()) {
						offset = 120;
					}

					var $headline = $target.find('h2.header');
					if ($headline.length && !$headline.hasClass('collapsed')) {
						$headline.click();
					}
				}

				$('html,body').animate({scrollTop: parseInt(position - offset)}, 1000);                        
			}
		}

		if ($('.akkordeon__plus').length) {
			// handle anchor links
			$.each($('a[data-accordion]'), function(index, link) {
				var anchor = $(link).attr('data-accordion').replace(/^#/, '?ap=')
				$(link).attr('href', $(link).attr('href') + anchor);

				$(link).click(function() {
					var $self = $(this);
					var $target = $($self.attr('data-accordion'));
					apScrolling($target);
					return false;
				});
			});

			var url = window.location.href;
			if (url.match(/\?ap=/)) {
				var selector = '#' + url.substring(url.indexOf("?ap=")).replace(/\?ap=/, '');
				setTimeout(function() {
					apScrolling($(selector));
				}, 750);
			}
		}
	}

	// build teaser blocks (M140)
	var teaserblocks = function() {
		$('.teaserblocks').teaserblocks();
	}

	// build tab navigation (M300)
	var tabNavigation = function() {
		$('.tab-navigation').find('table').addClass('table');

		$.each($('.tab-navigation').not('[data-mode]'), function(index, tabNavigation) {
			var $tabNavigation = $(tabNavigation);
			if(typeof $tabNavigation.attr('data-tabs') !== 'undefined' && $tabNavigation.attr('data-tabs') == 'product') {
				$tabNavigation.wrap('<div class="hscrollbar"></div>');
			} else {
				$tabNavigation.wrap('<div class="hscrollbar col-md-12"></div>');
			}
			$tabNavigation.tabnavigation();
		});
		$('.tab-navigation[data-mode]').tabs();
	}

	// WSEHR (M-04)
	var tabs2Accordion = function() {
		if ($('.tab-accordion').length && typeof $.fn.tabs2Accordion === 'function') {
			$('.tab-accordion').tabs2Accordion();

			var tabScrolling = function($target) {
				var position = $target.offset().top;
				var offset = 100;
				if (WITTENSTEIN.isMobile()) {
					offset = 60;
				}
				$('html,body').animate({scrollTop: parseInt(position - offset)}, 1000);
			}

			// handle anchor links
			$.each( $('a[data-tab]'), function(index, link) {
				var anchor = $(link).attr('data-tab').replace(/^#/, '?tab=')
				$(link).attr('href', $(link).attr('href') + anchor);
				
				$(link).click(function() {
					var $self = $(this);
					var $target = $($self.attr('data-tab'));
					tabScrolling($target);
					return false;
				});
			});
			
			var url = window.location.href;
			if (url.match(/\?tab=/)) {
				var selector = '#' + url.substring(url.indexOf("?tab=")).replace(/\?tab=/, '');
				setTimeout(function() {
					tabScrolling($(selector));
				}, 750);
			}			
		}
	}

	// raster layouts
	var layouts = function() {
		// wenn eine ueberschrift ueber dem bild angegeben ist, soll der text daneben auf gleicher höhe
		// mit dem bild anfangen
		$('.layout-84, .layout-48').layout({
			layout: 'layout-84'
		});

		$('.layout-714').layout({
			layout: 'layout-714'
		});

		$('.magazin').layout({
			layout: 'magazin'
		});

		if ($('.magazin').length == 0) {
			return;
		}

		// init slider in mobile view
		var magazinSlider = null;
		var loadSlider = function() {
			if (magazinSlider != null && typeof magazinSlider.destroySlider === 'function') {
				magazinSlider.destroySlider();
			}
			if (WITTENSTEIN.isMediaXS()) {
				magazinSlider = $('.magazin .bxslider').bxSlider({
					minSlides: 1,
					maxSlides: 1,
					pager: true,
					controls: false,
					adaptiveHeight: true
				});
			}
		}
		loadSlider();

		$(window).resize(function() {
			$('.magazin').layout({
				layout: 'magazin'
			});
			loadSlider();
		});
	}

	// init kompetenzen plugin
	var kompetenzen = function() {
		$('.kompetenzen').kompetenzen();
	}

	return {

		// called from hotspot
		initStandaloneTurntables : function() {
			standaloneTurntables();
		},

		initMediaSlider : function() {
			mediaElementSlider();
		},

		initTeaserSlider: function() {
			initTeaserSlider();
		},

		init : function() {
			// make teasers linked
			$('.teaser-big').teaserLink();
			initMoveSlider();
			initDefaultSlider();
			initTeaserSlider();
			initTeaserSlick();
			mediaElementSlider();
			quicklinks();
			akkordeon();
			teaserblocks();
			tabNavigation();
			tabs2Accordion();
			mediathekGallerySlider();
			layouts();
			kompetenzen();
		}
	}
})(jQuery);

/**
 * WITTENSTEIN Jobs
 */
var WITTENSTEIN = WITTENSTEIN || {};
WITTENSTEIN.jobs = (function($) {

    /**
     * @var XMLHttpRequest
     */
    var xhr;

    /**
     * Helper
     */
    var memory = [];

    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    /**
     * Show spinner
     */
    var showSpinner = function() {
        $('#job-results').prepend("<div class='ajax-loading' style='background-position: center 100px;'></div>");
    };

    /**
     * Hide spinner
     */
    var hideSpinner = function() {
        $('#job-results .ajax-loading').remove();
    };

    /**
     * Append Google Map in detail view
     */
    var locationMap = function()  {
        var $latitude = $('#geogrBreite');
        var $longitude = $('#geogrLaenge');

        if ($latitude.length && $longitude.length) {
            var map = new WITTENSTEIN.maps($latitude.val(), $longitude.val(),'standort-karte');
            map.init();
        }
    };

    /**
     * Append reset handler
     */
    var resetHandler = function() {

        $('.jobs-overview .akkordeon').akkordeon({
            elementClass : '.akkordeon-element',
            h2FirstHeader : '.category-header',
            collapseAll : true
        });

        $('.jobs-overview form #reset').on('click', function(e) {
            e.preventDefault();
            $('.jobs-overview form select option').removeAttr('selected');
            $('.jobs-overview form select option[value="0"]').attr('selected', 'selected');

            // reset dropdown
            $.each($('.jobs-overview form .dropdown li[data-value="0"]'), function(index, li) {
                $(li).siblings().removeClass('hover current isvisible').css({'display': 'none'}) 
                $(li).parent().children(':first').replaceWith( $(li).clone() );
                $(li).addClass('current').css({'display': 'block'})    
            });
            memory = [];
            $('.udgDropdown li').removeClass('disabled');
            updateResults();

            if (window.history.pushState) {
                window.history.pushState({}, null, window.location.pathname);
            }

            Cookies.remove('__memory');
        });

        if (Cookies.get('stageReferrer') == 1) {
            Cookies.remove('stageReferrer');
            $('form').reset();
        }
    };    

    /**
     * Search for jobs
     */
    var search = function($form, callback) {
        abortRequest();

        if (window.history.pushState && memory.length > 0) {
            Cookies.set('__memory', JSON.stringify(memory));
        }

        // guarantees that (hiden) selects and dropdown are equal 
        $.each($('#job-filter-form select'), function(index, select) {
            var $select = $(select);
            var $dropdown = $select.next();
            var listValue = $dropdown.find('li.current').attr('data-value');
            if (listValue != 0) {
                // copy values from dropdown to select
                // prevents errors in some cases where data is loaded from cookies
                $select.find('option[value="' + listValue + '"]').prop('selected', true);
            }
        });

        xhr = $.ajax({
            url: $form.attr('action'),
            method: $form.attr('method'),
            data: $form.serializeArray(),
            success: callback
        });
    };

    /**
     * Set new filter options
     *
     * @return void
     */
    var setNewFilterOptions = function() {
        // set filter according options
        if (memory.length > 0) {
            updateFilterOptions(FilterOptions);
        } else {
            // reset
            $('.udgDropdown li').removeClass('disabled');
        }
    };

    /**
     * Update filter, hide options which are not displayed
     */
    var updateFilterOptions = function(filterOptions) {

        if (typeof filterOptions === 'object') {
            for (var option in filterOptions) {
                var $dropdown = $('select[data-name="' + option + '"]').next();
                if ($.inArray(option, memory) == -1) {
                    $.each($('li', $dropdown), function(index, li) {
                        if( $(li).attr('data-value') && $(li).attr('data-value') != 0 ) {
                            var value = $(li).attr('data-value');
                            if (filterOptions[option][value]) {
                                $(li).removeClass('disabled');
                            } else {
                                $(li).addClass('disabled');
                                $(li).removeClass('current');
                            }
                        }
                    });
                    // fallback: show at least default li
                    if ($('li.current', $dropdown).length === 0) {
                        $('li[role="separator"]', $dropdown).next().addClass('current isvisible').show();
                    }
                } else {
                    $.each($('li', $dropdown), function(index, li) {
                        var value = $(li).attr('data-value');
                        if (filterOptions[option][value]) {
                            $(li).removeClass('disabled').hide();
                        }
                    });
                    $dropdown.find('li.current').show();
                }
            }
        }
    };

    /**
     * Show possible for selections with lower priority
     * 
     * @param   Object select
     * @return  void
     */
    var resetSelectionsWithLowerPriority = function(select) {
        var option = $(select).children("option:selected");
        var filter = $(select).attr('data-name');

        var index = memory.indexOf(filter);

        if (option.val() == 0 && index > -1) {
            memory.splice(index, 1);
        } else {
            if (index == -1) {
                memory.push(filter);    
            } else {
                // delete previous selections
                if (index + 1 < memory.length) {
                    var i = memory.length;
                    while (i != (index + 1)) {
                        var $select = $('select[data-name="'+memory.pop()+'"]');
                        var $dropdown = $select.next();

                        $select.children('option[value="0"]').prop('selected', true);
                        $('li', $dropdown).removeClass('current').css({'display': 'none'});
                        $('li:not(:first)[data-value="0"]', $dropdown).addClass('current').css({'display': 'block'});

                        i = memory.length;
                    }
                }
            }
        }
    };

    /**
     * Update job results
     */
    var updateResults = function() {
        showSpinner();
        search($('#job-filter-form'), function(data) {
            // show new resulst
            $('#job-results').replaceWith($('#job-results', data));
            // update filter
            setNewFilterOptions();
            // hide ajax spinner
            hideSpinner();
            // append detail listener
            handlePushState();
        });
    };

    /**
     * History push: save filter selection
     */
    var handlePushState = function() {
        $('#job-results a.button_4').click(function() {
            var selectedOptions = {};
            $.each($('#job-filter-form select'), function(index, select) {
                var $select = $(select);
                var $dropdown = $select.next();
                var listValue = $dropdown.find('li.current').attr('data-value');

                if (listValue != 0 ) {
                    selectedOptions[$select.attr('name')] = listValue;
                }
            });

            if (Object.entries(selectedOptions).length) {
                Cookies.set('__jo', selectedOptions);
                Cookies.set('__memory', JSON.stringify(memory));
            }
        });
    }

    /**
     * History pop: restore filter selection
     */
    var handlePopState = function() {
        var selectedOptions = Cookies.getJSON('__jo');
        if (typeof selectedOptions === 'object' && Object.entries(selectedOptions).length) {
            memory = Cookies.getJSON('__memory');
            $.each(selectedOptions, function(name, option) {
                $('select[name="' + name + '"] option[value="' + option + '"]').prop('selected', true);
            });
            updateResults();
            Cookies.remove('__jo');
            return true;
        }
        return false;
    }

    return {
        init : function() {
            var $overview = $('.jobs-overview');
            if ($overview.length) {

                handlePushState();
                $overview.on('change', '.filter-wrapper select', function(){
                    resetSelectionsWithLowerPriority($(this));
                    updateResults();
                });

                // replace selects with dropdowns
                $('.jobs-overview form select').addClass('dontsubmit').udgSelectDropdown();

                // reset
                resetHandler();
                var updateDropdowns = handlePopState();

                // set pre selected filter
                var $seletedOptions = $overview.find('form select option:selected');
                $.each($seletedOptions, function(index, option) {
                    if ($(option).val() != 0) {
                        resetSelectionsWithLowerPriority($(option).parent());
                        updateFilterOptions(PreSelectedResults);
                        return false;
                    }
                });

                if (updateDropdowns) {
                    $.each($seletedOptions, function(index, option) {
                        if ($(option).val() != 0) {
                            var $dropdown = $(option).parent().next();
                            var $current = $('li:not(:first)[data-value="' + $(option).val() + '"]', $dropdown);
                            $('li', $dropdown).removeClass('current').css({'display': 'none'});
                            $current.addClass('current isvisible').css({'display': 'block'});
                        }
                    });
                }

                // reset filter on language switch
                $('.languagemenu__item a').click(function(){
                    if ($(this).attr('href').match(/tx_udgjobs_pi/)) {
                        var url = $(this).attr('href').split('?')[0];
                        var parameters = $(this).attr('href').split('?')[1];
                        var newParameters = '';

                        $.each(parameters.split('&'), function(index, parameter) {
                            if(! parameter.match(/^tx_udgjobs_pi/) && ! parameter.match(/^cHash/)) {
                                newParameters += (index == 0 ? '&' : '') + parameter;
                            }
                        });

                        if (newParameters.length) {
                            newParameters = '?' + newParameters;
                        }

                        $(this).attr('href', url + newParameters);
                        Cookies.remove('__memory');
                        if (Cookies.get('stageReferrer') == 1) {
                            Cookies.remove('stageReferrer');
                            $('form').reset();
                        }
                    }
                });
            }

            if ($('.job-detail').length) {
                locationMap();
            }

            // Filter on stage
            if ($('.job-filter').length) {
                var url = $('#updateFilterUrl').val();
                var $form = $('.job-filter form');

                $('.job-filter select').udgSelectDropdown({change: function(select) {
                    resetSelectionsWithLowerPriority(select);
                    abortRequest();

                    var params = {
                        tx_udgjobs_pi1: {
                            audience : $form.find('.job-filter__audience').val(),
                            category : $form.find('.job-filter__category').val(),
                            location : $form.find('.job-filter__location').val(),
                        }
                    };

                    xhr = $.post(url, params, function(data) {
                        $('script[data-filter-options="1"]').replaceWith($('script[data-filter-options="1"]', data));
                        setNewFilterOptions();
                        $('.job-filter-wrapper .job-filter .ajax-loading').remove();

                        var href = $(data).find('#job-filter-submit').attr('href');
                        if (href.length > 0) {
                            $('#job-filter-submit').attr('href', href);
                        }
                    });

                }, scrollable: true});

                $('#job-filter-submit').on('click', function(e) {
                    $('#stage-referrer').val('1');
                    Cookies.set('__memory', JSON.stringify(memory));
                });
            }
        }
    }
})(jQuery);

/**
 * Servicebereich
 */
WITTENSTEIN.service = (function($) {

    "use strict";

    /****************************************************
     * Default Mode
     */

    var initDropdowns = function() {
        $('.udgDropdown').udgSelectDropdown({
            change: null
        });

        $('.services').on('change', '#dd-segment-type, #dd-segment, #dd-service', function(e) {

            e.stopImmediatePropagation();

            var url = $(this).parents('form').attr('action');
            var data = $(this).parents('form').serializeArray();

            var ajaxLoader = [
                              "<div class='ajax-container' style='height: 3.2em; position: relative;'>",
                              "<div class='ajax-loading lightgrey1' style='z-index: 1000;'></div>",
                              "</div>",
                              ];
            $('.services .segments h1').after(ajaxLoader.join(""));

            // ajax bei änderung in dropdowns
            $.post(
                    url,
                    data,
                    function(data) {
                        $('.services .services-tab-menu').replaceWith($(data).find('.services-tab-menu'));
                        $('.services .pre-after-sales-xs').replaceWith($(data).find('.pre-after-sales-xs'));
                        $('.services .service').replaceWith($(data).find('.service'));
                        $('.udgDropdown').udgSelectDropdown({
                            change: null
                        });
                        $('.services .segments .ajax-container').remove();
                    }
            );

            return false;
        });

    }

    /**
     * ajax aufruf bei klick auf segment
     */
    var serviceAjax = function() {

        $('.services .segment-button').on('click', function(e) {
            e.stopImmediatePropagation();
            var url = $(this).attr('href');
            $('.services .services-tab-menu, .services .service').prepend("<div class='ajax-loading' style='background-position: center 100px;'></div>");

            $.get(
                    url,
                    function(data) {
                        $('.services .services-tab-menu').replaceWith($(data).find('.services-tab-menu'));
                        $('.services .pre-after-sales-xs').replaceWith($(data).find('.pre-after-sales-xs'));
                        $('.services .service').replaceWith($(data).find('.service'));
                        $('.services .services-tab-menu .tab-navigation').tabnavigation();
                        $('.email a').spamprotection();
                    }
            );

            $('.services .segment-button').removeClass('active');
            $(this).addClass('active');

            return false;
        });
    }


    /****************************************************
     * Enumeration Mode
     */

    var $slickSlider =  $('.services-enum__container');
    var segmentSelector = '.services-enum__segment'; 
    var serviceSelector = '.services-enum__service--service a';
    var results = '.services-enum__tab-content';
    var activeClassName = 'active';

    /**
     * XMLHttpRequest
     */
    var xhr;

    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    /**
     * Listener for services
     */
    var serviceListener = function() {
        $(serviceSelector).click(function(){

            var position = $slickSlider.offset().top - 100;
            $('html,body').animate({scrollTop: position}, WITTENSTEIN.isMobileDevice() ? 0 : 350);

            if (typeof history.pushState != 'undefined') {
                history.pushState($(this).attr('id'), null, $(this).attr('href'));
            }
            showService($(this).attr('id'));
            return false;
        });
    }

    /**
     * Show services with given id
     */
    var showService = function(id) {
        var $element = $('#' + id);

        if ($element.length == 1) {
            $element.blur();
            abortRequest();
            $(results).addClass('ajax-loading');
            hideServices();
            $element.addClass(activeClassName);
            $element.closest(segmentSelector).addClass(activeClassName).siblings().removeClass(activeClassName);

            xhr = $.ajax({
                url: $element.attr('data-href'),
                method: 'get',
                success: function(response) {
                    $(results).removeClass('ajax-loading');
                    $(results).replaceWith($(response).find(results));
                }
            })              
        }
    }

    /**
     * Hide visible services
     */
    var hideServices = function() {
        $(results).children().remove();
        $(serviceSelector).removeClass(activeClassName);
        $(segmentSelector).removeClass(activeClassName);
    }

    /**
     * History pop
     */
    var popstateListener = function() {
        if (typeof history.pushState != 'undefined') {
            window.addEventListener('popstate', function(e){
                var service = e.state;
                if (service == null) {
                    hideServices();
                } else {
                    showService(service);
                }
            });
        }
    }

    /**
     * Resize listener
     */
    var resizeListener = function() {
        $(window).resize(function() {
            var $current = $(segmentSelector + '.'+activeClassName);
            if ($current.length > 0 && $current.attr('aria-hidden') === 'true') {
                var currentIndex = $(segmentSelector + '[aria-hidden="false"]').last().data('slick-index');
                $slickSlider.slick('slickGoTo', currentIndex, true);
            }
        });
    }

    /**
     * Initialize slider
     */
    var initEnumerationMode = function() {
        var initialSlide = 0;
        var $initialSegement = $(segmentSelector + '.'+activeClassName);

        if($initialSegement.length) {
            initialSlide = $initialSegement.index();
        }

        $slickSlider.on({
            init: function(event, slick){
                serviceListener();
                popstateListener();
                resizeListener();
            },
            beforeChange: function(event, slick, currentSlide, nextSlide){
                if (currentSlide != nextSlide) {
                    hideServices();
                }
            }
        }).slick({
            mobileFirst: true,
            dots: true,
            arrows: false,
            infinite: false,
            variableWidth: false,
            adaptiveHeight: false,
            slidesToShow: 1,
            initialSlide: initialSlide,
            accessibility: false,
            responsive: [{
                breakpoint: 600, // is
                settings: {
                    slidesToShow: 2
                }
            },{
                breakpoint: 900, // sm
                settings: {
                    slidesToShow: 3
                }
            },
            {
                breakpoint: 1024, // md
                settings: {
                    slidesToShow: 4,
                    dots: false
                }
            }]
        });
    }

    return {
        init: function() {
            if ($('.services').length) {
                initDropdowns();
                serviceAjax();
            }

            if ($slickSlider.length) {
                initEnumerationMode();
            }
        }
    }
})(jQuery);
/**
 * JavaScript für das Standort-Modul (udg_address)
 */
WITTENSTEIN.standort = (function($) {

    var ZOOM_LEVEL = 15;

    var map = null;

    // Url für den Routenplaner
    var URL_ROUTENPLANER = 'https://maps.google.com/maps?daddr=';

    // reset filter on click
    var resetfilter = function() {
        $('.udg-address-pi1 form #reset').off().on('click', function(e) {

            e.preventDefault();
            document.getElementById('region-selct').selectedIndex = -1;
            $('.address-filter select option').removeAttr('selected');

            var url = $(this).parents('form').attr('action');
            var data = $(this).parents('form').serializeArray();

            $('.udg-address-pi1').prepend("<div class='ajax-loading'></div>");

            $.post(
                    url,
                    data,
                    function(data) {

                        $('.udg-address-pi1 .filter-form').replaceWith($(data).find('.filter-form'));
                        $('.udg-address-pi1 #standort-karte').replaceWith($(data).find('#standort-karte'));
                        $('.udg-address-pi1 .hidden-fields').replaceWith($(data).find('.hidden-fields'));

                        if ($('.udg-address-pi1 .steckbrief').length) {
                            $('.udg-address-pi1 .steckbrief').replaceWith($(data).find('.steckbrief'));
                        } else {
                            $('.udg-address-pi1').append($(data).find('.steckbrief'));
                        }

                        // reinit
                        WITTENSTEIN.standort.init();
                        $('.udg-address-pi1 .ajax-loading').remove();
                    }
            );
        });
    }

    /**
     * reload data on filter change
     */
    var setfilter = function() {
        $('.udg-address-pi1').off().on('change', 'form select', function(e) {

            e.preventDefault();

            if ($(this).attr('id') == 'region-selct') {
                document.getElementById('address-selct').selectedIndex = -1;
                $('.address-filter').find('.dropdown li').removeClass('current isvisible');
                $('.address-filter').find('.dropdown li:first-child').addClass('current isvisible');
            }

            var url  = $(this).parents('form').attr('action');
            var data = $(this).parents('form').serializeArray();

            $('.udg-address-pi1').prepend("<div class='ajax-loading'></div>");

            $.post(
                    url,
                    data,
                    function(data) {

                        $('.udg-address-pi1 .filter-form').replaceWith($(data).find('.filter-form'));
                        $('.udg-address-pi1 #standort-karte').replaceWith($(data).find('#standort-karte'));
                        $('.udg-address-pi1 .hidden-fields').replaceWith($(data).find('.hidden-fields'));

                        if ($('.udg-address-pi1 .steckbrief').length) {
                            $('.udg-address-pi1 .steckbrief').replaceWith($(data).find('.steckbrief'));
                        } else {
                            $('.udg-address-pi1').append($(data).find('.steckbrief'));
                        }

                        // reinit
                        WITTENSTEIN.standort.init();

                        $('.udg-address-pi1 .ajax-loading').remove();

                        var address = [
                                       $('#address-street').text().trim(),
                                       $('#address-city').text().trim(),
                                       $('#address-country').text().trim(),
                                       ];

                        map.addInfoWindow([
                                           "<h3>" + $('#address-name').text() + "</h3>",
                                           "<p>" + $('#address-street').text() + "</p>",
                                           "<p>" + $('#address-city').text() + "</p>",
                                           "<a class='button_3' href='" + URL_ROUTENPLANER + encodeURIComponent(address.join(" ")) + "' target='_blank'>"+routeplanner+"</a>",
                                           ]);

                    }
            );
        });

    }

    /**
     * setmarkers
     */
    var setmarkers = function() {

        $('.coordinates .address').each(function(k, v) {
            var lat  = parseFloat($(this).find('.address-lat').val());
            var lon  = parseFloat($(this).find('.address-lon').val());
            var name = $(this).find('.address-name').val();
            var id   = $(this).find('.address-id').val();

            if (isNaN(lat) === false && isNaN(lon) === false) {

                map.setMapMarker(lat, lon, function(marker) {

                    google.maps.event.addListener(marker, 'click', function() {

                        $('.address-filter select').val(id);

                        var url = $('.udg-address-pi1 .filter-form form').attr('action');
                        var data = $('.udg-address-pi1 .filter-form form').serializeArray();

                        $('.udg-address-pi1 .steckbrief .standort').prepend("<div class='ajax-loading'></div>");

                        $.post(
                                url,
                                data,
                                function(data) {

                                    if ($('.udg-address-pi1 .steckbrief').length) {
                                        $('.udg-address-pi1 .steckbrief').replaceWith($(data).find('.steckbrief'));
                                    } else {
                                        $('.udg-address-pi1').append($(data).find('.steckbrief'));
                                    }

                                    $('.udg-address-pi1 .steckbrief .standort .ajax-loading').remove();

                                    var address = [
                                                   $('#address-street').text().trim(),
                                                   $('#address-city').text().trim(),
                                                   $('#address-country').text().trim(),
                                                   ];

                                    map.addInfoWindow([
                                                       "<h3>" + $('#address-name').text() + "</h3>",
                                                       "<p>" + $('#address-street').text() + "</p>",
                                                       "<p>" + $('#address-city').text() + "</p>",
                                                       "<a class='button_3' href='" + URL_ROUTENPLANER + encodeURIComponent(address.join(" ")) + "' target='_blank'>"+routeplanner+"</a>",
                                                       ]);
                                }
                        );

                    });
                });
            }

        });

    }

    /**
     * initialize google maps
     */
    var initMap = function() {

        var selectedAddr = $('.standort').length;
        var latitude = $('input[type="hidden"][name="latitude"]').val();
        var longitude = $('input[type="hidden"][name="longitude"]').val();

        // wenn keine adresse ausgewählt wurde, werden die koordinaten für die region genutzt
        if (selectedAddr == false) {
            latitude = $('input[type="hidden"][name="rlatitude"]').val();
        }

        if (selectedAddr == false) {
            longitude = $('input[type="hidden"][name="rlongitude"]').val();
        }

        map = new WITTENSTEIN.maps(
                latitude,
                longitude,
                'standort-karte',
                {
                    draggable : true,
                    scrollwheel: true
                }
        );

        map.showMarker(false);
        map.setZoom(ZOOM_LEVEL);

        if (selectedAddr == false) {
            map.setZoom(parseInt($('input[type="hidden"][name="rzoom"]').val()));
        }

        if (latitude == "" || longitude == "") {
            var address = $('input[type="hidden"][name="straddress"]').val() || $('input[type="hidden"][name="strregion"]').val();
            var region = "";

            // prevent search for strings like "Africa, Asia, Australia"
            if (address.match(/^[a-zßäöü\s]+$/i)) {
                var latlon = map.getLatLon(address, region, function() {
                    // do not init map until geo coordinates have been found
                    this.init();
                    this.zoomElement();

                    // set all other markers
                    setmarkers();

                });
                return ;
            }
        }

        map.init();
        map.zoomElement();
        // set all other markers
        setmarkers();

    }

    return {

        init : function() {
            if ($('.udg-address-pi1').length) {
                $('.udg-address-pi1 form .region-filter select').udgSelectDropdown({
                    'change' : null,
                    'scrollable' : true
                });
                $('.udg-address-pi1 form .address-filter select').udgSelectDropdown({
                    'change' : null
                });

                initMap();
                // resetfilter() ;
                setfilter();
            }
        }
    }
})(jQuery);
WITTENSTEIN.download = (function($) {

    /**
     * @var XMLHttpRequest
     */
    var xhr;


    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    /**
     * initialisiert die filter, bei änderungen wird ein ajax request abgesendet
     */
    var initFilters = function() {
        $('.download-filter select').udgSelectDropdown({change: false, scrollable: true});

        $('.downloads').on('change', '.download-filter select', function() {
            abortRequest();
        	var form = $('#download-form');
            var url = form.attr('action');

            // reset product selection on bu-switch
            if ($(this).attr('name') == 'tx_udgdownload_pi1[businessunit]') {
                form.find('select[name="tx_udgdownload_pi1[category]"]').val(0);
            	form.find('select[name="tx_udgdownload_pi1[product]"]').val(0);
            }
            
            if($(this).attr('name') == 'tx_udgdownload_pi1[category]') {
                form.find('select[name="tx_udgdownload_pi1[product]"]').val(0);
            }

            var params = form.find('select, input[type="hidden"]').serialize();
            // url += '&' + params;

            var formData = form.serializeArray();


            $('.downloads .download-liste .liste table').hide();
            $('.downloads .download-liste .liste').prepend("<div class='ajax-loading'></div>");

            xhr = $.post(
                url,
                formData,
                function(data) {
                    var noThumb = $('.downloads .download-liste table').hasClass('no-thumb');

                    //$('.downloads .download-filter').replaceWith($(data).find('.download-filter'));
                    $('.downloads .download-liste').replaceWith($(data).find('.download-liste'));

                    $('ul#document-type-tags').replaceWith($(data).find('ul#document-type-tags'));
                    replaceSelectBox($(data), 'select[name="tx_udgdownload_pi1[category]"]');
                    replaceSelectBox($(data), 'select[name="tx_udgdownload_pi1[product]"]');
                    replaceSelectBox($(data), 'select[name="tx_udgdownload_pi1[language]"]');
                    replaceSelectBox($(data), 'select[name="tx_udgdownload_pi1[businessunit]"]');


                    //$('.download-filter select').udgSelectDropdown({change: false, scrollable: true});
                   // $('.page-navigation').udgPaginate('destroy').udgPaginate();
                    $('.downloads .pagination').pagination({
                        jumpTo: '#downloads'
                    });

                    // einstellung der list optionen beibehalten
                    if (noThumb) {
                        $('.downloads .download-liste table').addClass('no-thumb');
                        $('.list-options .list-no-thumb').addClass('active');
                        $('.list-options .list-thumb').removeClass('active');
                    }
                }
            );
        });

        $('.download-filter').on('click', 'ul#document-type-tags li', function() {
            var $this = $(this);
            var currentValue = $this.data('value');
            var selectName = $this.parent().data('select');
            var $select = $('select[name="'+selectName+'"]');

            $this.toggleClass('current');

            if(typeof currentValue === 'number') {
                $select.find('option').each(function() {
                    if($(this).val() === currentValue.toString()) {
                        if ($this.hasClass('current')) {
                            $(this).attr('selected', true);
                        } else {
                            $(this).attr('selected', false);
                        }
                    }
                });
            } else if(typeof currentValue === 'undefined') {
                // default option has no value -> undefined data-value
                $select.find('option').each(function () {
                    $(this).attr('selected', false);
                });
                $select.find('option:first').attr('selected', true);
            }
            $select.trigger('change');
        });
    };



    /**
     * Replace any select box in download filter
     *
     * @params	Object	response
     * @params	String	selectbox selector
     * @return	void
     */
    var replaceSelectBox = function(data, selector) {
    	var newSelectBox = data.find(selector);
    	var parent = $('.downloads ' + selector).closest('.udgDropdown').parent();
    	var oldDropdown = parent.find('div.dropdown ');
    	var oldZIndex = oldDropdown.css('z-index');
    	parent.empty().append(newSelectBox);
    	newSelectBox.udgSelectDropdown({change: false, scrollable: true, zIndex: oldZIndex});
    };

    // ajax für paginierung
    var initPaginate = function() {
    	$('.downloads .pagination').pagination({
    		jumpTo: '#downloads'
    	});
        $('.downloads').on('click', '.pagination a', function(e) {

            e.preventDefault();

            var url = $(this).attr('href');

            $('.downloads .download-liste .liste table').hide();
            $('.downloads .download-liste .liste').prepend("<div class='ajax-loading'></div>");

            $.post(
                url ,
                $('#download-form').serializeArray(),
                function(data) {
                    var noThumb = $('.downloads .download-liste table').hasClass('no-thumb');

                    $('.downloads .download-filter').replaceWith($(data).find('.download-filter'));
                    $('.downloads .download-liste').replaceWith($(data).find('.download-liste'));

                    $('.download-filter select').udgSelectDropdown({change: false, scrollable: true});
                	$('.downloads .pagination').pagination({
                		jumpTo: '#downloads'
                	});

                    // einstellung der list optionen beibehalten
                    if (noThumb) {
                        $('.downloads .download-liste table').addClass('no-thumb');
                        $('.list-options .list-no-thumb').addClass('active');
                    }
                }
            );
        });
    }

    var initListOptions = function() {
        // wechselt die listenansicht mit und ohne thumbs
        $('.downloads').on('click', '.list-options .list-thumb', function(e) {
            e.preventDefault();

            $(this).addClass('active');
            $('.list-options .list-no-thumb').removeClass('active');

            $('.download-liste table').removeClass('no-thumb');
        });
        $('.downloads').on('click', '.list-options .list-no-thumb', function(e) {
            e.preventDefault();

            $(this).addClass('active');
            $('.list-options .list-thumb').removeClass('active');

            $('.download-liste table').removeClass('no-thumb').addClass('no-thumb');
        });
    }

    return {
        init : function() {
            if ($('.download-filter').length) {
                initFilters();
            }

            if ($('.download-liste').length) {
                initListOptions();
                initPaginate();
            }
        }
    }
})(jQuery);

/**
 * WITTENSTEIN education wall
 */
WITTENSTEIN.educationWall = (function($) {

    "use strict";

    /**
     * Helper
     */
    var _memory = {
        load: false,
        id: null,
        start: parseInt($('.education-wall .start').val()),
        offset: parseInt($('.education-wall .offset').val())
    };

    /**
     * XMLHttpRequest
     */
    var xhr;

    /**
     * Cancels the current HTTP request
     *
     * @return    void
     */
    var abortRequest = function() {
        if (xhr != null) {
            xhr.abort();
        }
    };

    /**
     * Scroll to given element
     * 
     * @var     Object  element
     * @var     Integer optional adjustment 
     * @return  void
     */
    var scrollTo = function(element, offset) {
        var position = $(element).offset().top  + (-offset|0);

        if (WITTENSTEIN.isMobile()) {
            $('html,body').scrollTop(position)
        } else {
            $('html,body').animate({scrollTop: position}, 100);
        }
    };

    /**
     * AJAX search function
     */
    var search = function(callback) {
        abortRequest();
        var $form = $('.education__filter');
        xhr = $.ajax({
            url: $form.attr('action'),
            method: $form.attr('method'),
            data: $form.serializeArray(),
            success: callback
        });
    }

    /**
     * History pop
     */
    var popstateListener = function() {
        var options = Cookies.getJSON('__edu');
        var clone = Object.assign({}, options);

        if (typeof options === 'object' && Object.entries(options).length) {
            $.each(options, function(uid, option) {
                var $education = $('.education-wall[data-uid="' + uid + '"]');             
                if ($education.length) {
                    if (Object.entries(option.selects).length) {
                        $.each(option.selects, function(name, value) {
                            var $element = $('[name="' + name + '"]');
                            if ($element.length) {
                                $element.val(value);
                            }
                        });
                        _memory.load = true;
                    }

                    if (parseInt(option.offset)) {
                        _memory.start = option.start;
                        _memory.offset = option.offset;
                        _memory.load = true;
                    }

                    if (typeof option.id === 'string') {
                        _memory.id = option.id;
                        _memory.load = true;
                    } 
                    delete clone[uid];
                }
            });

            if ($.isEmptyObject(clone)) {
                Cookies.remove('__edu');
            } else {
                Cookies.set('__edu', clone);
            }
        }
    }

    /**
     * History push: save filter selection
     */
    var handlePushState = function() {
        $('.education__job a').click(function() {
            var options = Cookies.getJSON('__edu');
            if ($.isEmptyObject(options)) {
                options = {};
            };

            var uid = $(this).closest('.education-wall').attr('data-uid');
            options[uid] = {
                selects: {},
                start: 0,
                offset: 0,
                id: null
            };

            var save = false;
            $.each($('.education__filter select'), function(index, select) {
                var $select = $(select);
                if ($(select).val() != 0) {
                    options[uid].selects[$select.attr('name')] = $(select).val();
                    save = true;
                }
            });

            var start = parseInt($('.education__filter .start').val());
            if (start > 0) {
                var offset = parseInt($('.education__filter .offset').val());
                options[uid].start = start;
                options[uid].offset = start + offset;
                save = true;
            }

            if (save) {
                options[uid].id = $(this).parent().attr('id');
                Cookies.set('__edu', options);
            }
        });
    }

    /**
     * Handler for dropdowns
     */
    var handleDropdowns = function() {
        var $selects = $('.education__filter select:not(.dontsubmit)');
        // replace selects with dropdowns
        $selects.addClass('dontsubmit').udgSelectDropdown();
        // save selection
        $.each($selects, function(index, select) {
            _memory[$(select).attr('name')] = $(select).val();
        });

        // reset z-index, needed after AJAX request
        var zIndex = 9999;
        $.each($('.education__filter .dropdown'), function(index, dropdown) {
            $(dropdown).attr('style', 'z-index:' + zIndex--);
        });

        $selects.on('change', function() {
            var $self = $(this);
            var key = $self.attr('name');

            // fire search only on changes
            if (_memory[key] != $self.val() || _memory.load) {
                _memory[key] = $self.val();
                var $form = $('.education__filter');
                $form.find('.start').val('0');
                var offset = $form.find('.offset').val();
                var ajaxClass = 'ajax-loading';
                $('.education__results').addClass(ajaxClass);

                if (_memory.load) {
                    $form.find('.offset').val(_memory.offset);
                }

                search(function(data) {
                    // replace dropdowns when result is not empty
                    if($(data).find('.education__job').length) {
                        var $selects = $form.find('select[name!="' + $self.attr('name') + '"]');
                        $.each($selects, function(index, select) {
                            $(select).off('change');
                            var selector = 'select[name="' + $(select).attr('name') + '"]';
                            var $parent = $(selector).closest('.udgDropdown').parent();
                            // delete old select and replace with new one
                            $parent.find('.udgDropdown').remove();
                            $parent.append($(data).find(selector));
                            // append listener
                            handleDropdowns();
                        });
                    }

                    // replace results
                    $('.education__results').removeClass(ajaxClass);
                    $('.education__results').replaceWith($(data).find('.education__results'));

                    // replace form data
                    var total = $(data).find('.education__filter .total').val();
                    $form.find('.total').val(total);

                    if (_memory.load) {
                        _memory.load = false;
                        $form.find('.offset').val(offset);
                        $form.find('.start').val(_memory.start);
                        var $element = $('#' + _memory.id)
                        if ($element.length) {
                            scrollTo($element, 200);
                        }
                    }                    

                    handleLoadMoreButton();
                    handlePushState();
                });
            }
        });
    }

    /**
     * Handler for loading mor educations
     */
    var handleLoadMoreButton = function() {
        $('.education__load').click(function() {
            var $self = $(this);
            var $form = $('.education__filter');
            var ajaxClass = 'education__load--ajax';
            var totalNumber = parseInt($form.find('.total').val());
            var offset = parseInt($form.find('.offset').val());
            var start = parseInt($form.find('.start').val()) + offset;

            $form.find('.start').val(start);
            $self.addClass(ajaxClass);

            search(function(response) {
                if ((start + offset) >= totalNumber) {
                    $self.unbind('click');
                    $self.remove();
                }
                $('.education__jobs').append($(response).find('.education__job'));
                handlePushState();
                $self.removeClass(ajaxClass);
            });
        });
    }

    /**
     * Change default values based on viewport
     */
    var setDefaults = function() {
        if (WITTENSTEIN.isPortable()) {
            var offset = parseInt($('.offset-mobile').val());
            var eq = parseInt(offset - 1);
            if ($('.education__job').length > eq) {
                _memory.offset = offset;
                $('.education-wall .offset').val(offset);
                $('.education__job:eq(' + eq + ')').nextAll().remove();
            }
        }
    }

    /**
     * Prevent reloading for deeplinks on the same page as the plugin
     */
    var handleDeeplinks = function() {
        var $deeplinks = $('.education__deeplink');
        if ($deeplinks.length) {
        	
            // scroll to plugin
        	var scrollToWall = function() {
                var offset = WITTENSTEIN.isPortable() ? 80 : 180;
                $('html,body').animate({
                    scrollTop: $('.education-wall').offset().top - offset
                }, 1000);
        	};
        	
            $.each($deeplinks, function(index, link) {
                // check if destination is equal
                if (link.hostname === location.hostname && link.pathname === location.pathname) {
    				$(link).attr('href', $(link).attr('href') + '&ew=1');

                    $(link).click(function() {
                        var $link = $(this);

                        // change filter
                        var trigger;
                        var names = ['category', 'profession'];

                        names.forEach(function(name) {
                            var value = parseInt($link.attr('data-education-' + name));
                            var $select = $('.education__filter select[name="tx_udgjobs_pi2[' + name + ']"]');
                            if ($select.length) {
                                $select.val(value);
                                var $dropdown = $select.siblings('.dropdown');
                                $dropdown.find('li').removeClass('current isvisible').hide();
                                var $current = $dropdown.find('li.divider').nextAll('li[data-value="' + value + '"]')
                                $current.addClass('current isvisible').show();
                                trigger = $select;
                            }
                        });

                        if (typeof trigger === 'object') {
                            trigger.change();
                        }

                        scrollToWall();
                        return false;
                    });
                }
            });
            
			var url = window.location.href;
			if (url.match(/[?&]ew=1/)) {
				setTimeout(scrollToWall, 750);
			}
        }
    }

    return {
        init: function() {
            var $container = $('.education-wall');
            if ($container.length) {
                setDefaults();

                // set data from cookies
                popstateListener();
                handleDropdowns();
                handleLoadMoreButton();
                handlePushState();

                // load data from cookies
                if (_memory.load) {
                    $container.find('select').first().change();
                }

                // handle deeplinks
                handleDeeplinks();
            }
        }
    }
})(jQuery);
/**
 * WITTENSTEIN education apply
 */
WITTENSTEIN.educationApply = (function($) {

    "use strict";

    var openClassName = 'open';

    /**
     * Close boxes and reset buttons
     */
    var close = function() {
        $('.education-apply__container .' + openClassName).removeClass(openClassName);
        var $buttons = $('.education-apply__link');
        $.each($buttons, function(index, button) {
            // reset text
            if($(button).attr('data-origin')) {
                $(button).text($(button).attr('data-origin'));
            }
            // reset href
            $(button).removeAttr('href');          
            $(button).removeClass('disabled');
        });
    }

    /**
     * Close all boxes
     */
    var handleClose = function() {
        $('.education-apply__box-close').click(close);
    }

    /**
     * Resize handler
     */
    var handleResize = function() {
        // close all boxes
        if (window.innerWidth > WITTENSTEIN.SCREEN_SM) {
            close();
        }
    }

    /**
     * Scrolling handler
     */
    var handleScrolling = function() {
        var $bar = $('.education-apply');        
        var $footer = $('footer .footer');

        if($bar.offset().top + $bar.outerHeight() >= $footer.offset().top - 20) {
            $bar.removeClass('fixed');
        }

        if($(document).scrollTop() + window.innerHeight < $footer.offset().top) {
            $bar.addClass('fixed');
        }
    }

    /**
     * Change selects on change
     */
    var handleSelects = function() {
        var $selects = $('.education-apply__container select:not(.dontsubmit)');

        // add dropdowns
        $selects.addClass('dontsubmit').udgSelectDropdown().change(function() {
            var $self = $(this);
            var $container = $self.closest('.education-apply__select-container');
            var $button = $('.education-apply__cta-link');
            var name = $self.attr('name') == 'entry' ? 'location' : 'entry';
            var $currentSelect =  $('.education-apply select[name="' + name + '"]');

            var $select = $('<select name="' + name + '" />');
            var $option = $('<option value="0">' + $currentSelect.find('option[value="0"]').text() + '</option>');
            $select.append($option);

            var _temp = [0];
            $.each(applyOptions, function(index, entry) {
                if (!_temp.includes(entry[name])) {
                    if ($self.val() == 0 || entry[$self.attr('name')] == $self.val()) {
                        var $option = $('<option value="' + entry[name] + '">' + entry[name] + '</option>');
                        if ($currentSelect.val() == entry[name]) {
                            $option.attr('selected', 'selected');
                        }
                        _temp.push(entry[name]);
                        $select.append($option);
                    }
                }
            });

            var $dropdown = $container.find('select[name="' + $select.attr('name') + '"]').parent();
            $dropdown.replaceWith($select);
            handleSelects();

            var resetButton = function($button) {
                $button.removeAttr('href');
                $button.text($button.attr('data-origin'));
                $button.addClass('disabled');
            };

            if ($select.val() != 0 && $self.val() != 0) {
                var link = '';
                $.each(applyOptions, function(index, element) {
                    if (element[$self.attr('name')] == $self.val() && element[$select.attr('name')] == $select.val()) {
                        link = element.link;
                        return false;
                    }
                });

                if (link.length) {
                    $button.text($button.attr('data-alt'));
                    $button.removeClass('disabled');
                    $button.attr('href', link);                    
                } else {
                    resetButton($button);
                }
            } else {
                resetButton($button);
            }
        });

        // reset z-index, needed after AJAX request
        var zIndex = 9999;
        $.each($('.education-apply .dropdown'), function(index, dropdown) {
            $(dropdown).attr('style', 'z-index:' + zIndex--);
        });
    };

    /**
     * Reset selects
     */
    var reset = function() {
        var $selects = $('.education-apply__container select');
        $.each($selects, function(index, select) {
            var name = $(select).attr('name');
            var $newSelect = $('<select name="' + name + '" />');
            var $option = $('<option value="0">' + $(select).find('option[value="0"]').text() + '</option>');
            $newSelect.append($option);
            var _temp = [0];
            $.each(applyOptions, function(index, entry) {
                if (!_temp.includes(entry[name])) {
                    var $option = $('<option value="' + entry[name] + '">' + entry[name] + '</option>');
                    _temp.push(entry[name]);
                    $newSelect.append($option);
                }
            });
            var $dropdown = $(select).parent();
            $dropdown.replaceWith($newSelect);
        });
        handleSelects();
    }

    /**
     * Handler for cta box
     */
    var handleCta = function() {
        var $selects = $('.education-apply__container select');
        handleSelects();

        // add click handler
        $('.education-apply__cta-link').click(function() {
            if($(this).attr('href')) {
                // open link and close this box
                window.open($(this).attr('href'), $(this).attr('target'));
                close();
                reset();
            } else {
                var $container  = $(this).closest('.education-apply__cta');
                var $box = $container.find('.education-apply__box');

                if (!$container.hasClass(openClassName)) {
                    // close other boxes
                    close();

                    // reset selects
                    $.each($selects, function(index, select) {
                        var $select = $(select);
                        $select.find('option').removeAttr('selected');
                        var $dropdown = $select.next();
                        $dropdown.find('li').removeClass('current isvisible').hide();
                        $dropdown.find('.divider').next().addClass('current isvisible').show();
                    });

                    $container.addClass(openClassName);

                    if ($box.find('select').length) {
                        $(this).addClass('disabled');
                    }

                    if (WITTENSTEIN.isGreaterThenMediaSM()) {
                        $box.css('top', -($box.outerHeight() + parseInt($('.education-apply').css('padding-top'))));
                    } else {
                        $box.css('top', 0);
                    }
                }
            }
        });
    }

    /**
     * Handler for question box
     */
    var handleQuestion = function() {
        // add click handler
        $('.education-apply__question-link').click(function() {
            // close other boxes
            close();

            var $container  = $(this).closest('.education-apply__question');
            var $box = $container.find('.education-apply__box');

            if (!$container.hasClass(openClassName)) {
                $container.addClass(openClassName);
                $box.css('top', -($box.outerHeight() + parseInt($('.education-apply').css('padding-top'))));
            }
        });
    }

    return {
        init: function() {
            var $container = $('.education-apply');
            if ($container.length) {
                handleScrolling();
                $container.show();
                handleCta();
                handleClose();
                handleQuestion();
                $(window).resize(handleResize);
                $(window).scroll(handleScrolling);
            }
        }
    }
})(jQuery);
/**
 * Suchergebnisseite
 */
WITTENSTEIN.suche = (function($) {

    return {
        init: function() {
            if ($('#solr-pagination ul').length) {
                $('#solr-pagination').udgPaginate('destroy').udgPaginate();
            }

            $('#tx-solr-search-form-pi-results .search_field').udgInputIcon();

        }
    }
})(jQuery);

/*!
 * JavaScript Cookie v2.1.3
 * https://github.com/js-cookie/js-cookie
 *
 * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
 * Released under the MIT license
 */
;(function (factory) {
    var registeredInModuleLoader = false;
    if (typeof define === 'function' && define.amd) {
        define(factory);
        registeredInModuleLoader = true;
    }
    if (typeof exports === 'object') {
        module.exports = factory();
        registeredInModuleLoader = true;
    }
    if (!registeredInModuleLoader) {
        var OldCookies = window.Cookies;
        var api = window.Cookies = factory();
        api.noConflict = function () {
            window.Cookies = OldCookies;
            return api;
        };
    }
}(function () {
    function extend () {
        var i = 0;
        var result = {};
        for (; i < arguments.length; i++) {
            var attributes = arguments[ i ];
            for (var key in attributes) {
                result[key] = attributes[key];
            }
        }
        return result;
    }

    function init (converter) {
        function api (key, value, attributes) {
            var result;
            if (typeof document === 'undefined') {
                return;
            }

            // Write

            if (arguments.length > 1) {
                attributes = extend({
                    path: '/'
                }, api.defaults, attributes);

                if (typeof attributes.expires === 'number') {
                    var expires = new Date();
                    expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
                    attributes.expires = expires;
                }

                // We're using "expires" because "max-age" is not supported by IE
                attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';

                try {
                    result = JSON.stringify(value);
                    if (/^[\{\[]/.test(result)) {
                        value = result;
                    }
                } catch (e) {}

                if (!converter.write) {
                    value = encodeURIComponent(String(value))
                        .replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
                } else {
                    value = converter.write(value, key);
                }

                key = encodeURIComponent(String(key));
                key = key.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent);
                key = key.replace(/[\(\)]/g, escape);

                var stringifiedAttributes = '';

                for (var attributeName in attributes) {
                    if (!attributes[attributeName]) {
                        continue;
                    }
                    stringifiedAttributes += '; ' + attributeName;
                    if (attributes[attributeName] === true) {
                        continue;
                    }
                    stringifiedAttributes += '=' + attributes[attributeName];
                }
                return (document.cookie = key + '=' + value + stringifiedAttributes);
            }

            // Read

            if (!key) {
                result = {};
            }

            // To prevent the for loop in the first place assign an empty array
            // in case there are no cookies at all. Also prevents odd result when
            // calling "get()"
            var cookies = document.cookie ? document.cookie.split('; ') : [];
            var rdecode = /(%[0-9A-Z]{2})+/g;
            var i = 0;

            for (; i < cookies.length; i++) {
                var parts = cookies[i].split('=');
                var cookie = parts.slice(1).join('=');

                if (cookie.charAt(0) === '"') {
                    cookie = cookie.slice(1, -1);
                }

                try {
                    var name = parts[0].replace(rdecode, decodeURIComponent);
                    cookie = converter.read ?
                        converter.read(cookie, name) : converter(cookie, name) ||
                        cookie.replace(rdecode, decodeURIComponent);

                    if (this.json) {
                        try {
                            cookie = JSON.parse(cookie);
                        } catch (e) {}
                    }

                    if (key === name) {
                        result = cookie;
                        break;
                    }

                    if (!key) {
                        result[name] = cookie;
                    }
                } catch (e) {}
            }

            return result;
        }

        api.set = api;
        api.get = function (key) {
            return api.call(api, key);
        };
        api.getJSON = function () {
            return api.apply({
                json: true
            }, [].slice.call(arguments));
        };
        api.defaults = {};

        api.remove = function (key, attributes) {
            api(key, '', extend(attributes, {
                expires: -1
            }));
        };

        api.withConverter = init;

        return api;
    }

    return init(function () {});
}));
/**
 * Udg Powermail
 */
var UdgPowermail = (function($) {

    /**
     * Append country <-> state validator for US
     * 
     * @return void
     */
    function usHandler() {
        var $states = $('#powermail_field_state');
        var $countries = $('#powermail_field_country');
        var $form = $('.powermail_form');

        var validateSelection = function(value, regex, $element) {
            if ( value.match(regex) ) {
                $element.closest('.powermail_fieldwrap').show();
            } else {
                $element.closest('.powermail_fieldwrap').hide();
            }
        };

        // country and state
        if ($countries.length && $states.length) {
            var countriesRegExp = new RegExp('United States', 'i');
            $countries.change(function() {
                validateSelection($(this).val(), countriesRegExp, $states);
            });
            validateSelection($countries.val(), countriesRegExp, $states);
        }

        // product category
        var $productcategories = $('#powermail_field_productcategory');
        var $gearheadOrders = $('#powermail_field_forgearheadordersdescribemotorbrandtype');
        if ($productcategories.length && $gearheadOrders.length) {
            var gearheadsRegExp = new RegExp('Gearheads', 'i');
            $productcategories.change(function() {
                validateSelection($(this).val(), gearheadsRegExp, $gearheadOrders);
            });
            validateSelection($productcategories.val(), gearheadsRegExp, $gearheadOrders);
        }

        if ($form.length) {
            $form.submit(function(event) {
                if ($states.closest('.powermail_fieldwrap').is(":hidden")) {
                    $states.val('');
                }
                if ($gearheadOrders.closest('.powermail_fieldwrap').is(":hidden")) {
                    $gearheadOrders.val('');
                }
            });
        }
    };

    return {
        /* Append listener */
        init : function() {
            usHandler();
        }
    }

})(jQuery);

jQuery(document).ready(function() {
    UdgPowermail.init();
});