
!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"),t.val(e(this).data("date-value"))}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_progress_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()});
/**
 * @preserve
 * Plugin Name: dflip
 * Description: dflip - 3D & 2D FlipBook
 *
 * Author: Deepak Ghimire
 * Author URI: http://codecanyon.net/user/deip?ref=deip
 */

'use strict';

var DFLIP = DFLIP || {};

// old fallback
// use DFLIP instead of PRESENTATION as of v 1.1
var PRESENTATION = DFLIP;

(function dFlip(DFLIP, $) {

  DFLIP.version = "1.4.31";

  DFLIP.PAGE_MODE = {SINGLE: 1, DOUBLE: 2, AUTO: null};
  DFLIP.SINGLE_PAGE_MODE = {ZOOM: 1, BOOKLET: 2, AUTO: null};
  DFLIP.CONTROLSPOSITION = {HIDDEN: 'hide', TOP: 'top', BOTTOM: 'bottom'};
  DFLIP.DIRECTION = {LTR: 1, RTL: 2};

  DFLIP.CORNERS = {TL: "tl", TR: "tr", BL: "bl", BR: "br", L: "l", R: "r", NONE: null};

  DFLIP.SOURCE_TYPE = {IMAGE: "image", PDF: "pdf", HTML: "html"};
  DFLIP.DISPLAY_TYPE = {WEBGL: "3D", HTML: "2D"};
  DFLIP.PAGE_SIZE = {AUTO: 0, SINGLE: 1, DOUBLEINTERNAL: 2};


  //defaults settings
  var defaults = DFLIP.defaults = {

    //sets if to use 3d or not (true|false)
    webgl: true,
    //if you want to turn of shadow in 3d set it to false
    webglShadow: true,

    // if enable sound at start (true|false)
    soundEnable: true,

    // height of the container
    // value(eg: 320) or percentage (eg: '50%')
    // calculaton limit: minimum 320, max window height
    height: '100%',

    // set to true to show outline on open (true|false)
    autoEnableOutline: false,

    // set to true to show thumbnail on open (true|false)
    autoEnableThumbnail: false,

    // set to true if PDF inbuilt outline is to be removed (true|false)
    overwritePDFOutline: false,

    // enableDownload of PDF files (true|false)
    enableDownload: true,

    // duration of page turn in milliseconds
    duration: 800,

    //direction of flipbook
    //DFLIP.DIRECTION.LTR or 1	for left to right(default),
    //DFLIP.DIRECTION.RTL or 2	for right to left,
    direction: DFLIP.DIRECTION.LTR,

    //set as
    //DFLIP.PAGE_MODE.AUTO	 				for auto-detect(default),
    //DFLIP.PAGE_MODE.SINGLE or 1 			for singleview,
    //DFLIP.PAGE_MODE.DOUBLE or 2 			for doubleview,
    pageMode: DFLIP.PAGE_MODE.AUTO,

    //set as
    //DFLIP.SINGLE_PAGE_MODE.AUTO	 				for auto-detect(default),
    //DFLIP.SINGLE_PAGE_MODE.ZOOM or 1 				for normal zoom single view,
    //DFLIP.SINGLE_PAGE_MODE.BOOKLET or 2 			for Booklet mode,
    singlePageMode: DFLIP.SINGLE_PAGE_MODE.AUTO,

    //color value in hexadecimal
    backgroundColor: "#fff",

    forceFit: true, //very rare usage leave it as true unless page are not fitting wrong...
    transparent: false, //true or false
    hard: "none", //possible values are "hard", "none", "cover"
    openPage: 1, //the pagenumber where the book should open

    annotationClass: "",

    autoPlay: false,
    autoPlayDuration: 5000,
    autoPlayStart: false,

    // texture settings
    maxTextureSize: 1600,	//max page size to be rendered. for pdf files only
    minTextureSize: 256,	//min page size to be rendered. for pdf files only
    rangeChunkSize: 524288,

    // icons for the buttons
    icons: {
      'altnext': 'ti-angle-right',
      'altprev': 'ti-angle-left',
      'next': 'ti-angle-right',
      'prev': 'ti-angle-left',
      'end': 'ti-angle-double-right',
      'start': 'ti-angle-double-left',
      'share': 'ti-sharethis',
      'help': 'ti-help-alt',
      'more': 'ti-more-alt',
      'download': 'ti-download',
      'zoomin': 'ti-zoom-in',
      'zoomout': 'ti-zoom-out',
      'fullscreen': 'ti-fullscreen',
      'fitscreen': 'ti-arrows-corner',
      'thumbnail': 'ti-layout-grid2',
      'outline': 'ti-menu-alt',
      'close': 'ti-close',
      'doublepage': 'ti-book',
      'singlepage': 'ti-file',
      'sound': 'ti-volume',
      'facebook': 'ti-facebook',
      'google': 'ti-google',
      'twitter': 'ti-twitter-alt',
      'mail': 'ti-email',
      'play': 'ti-control-play',
      'pause': 'ti-control-pause'
    },

    // TRANSLATION text to be displayed
    text: {

      toggleSound: "Turn on/off Sound",
      toggleThumbnails: "Toggle Thumbnails",
      toggleOutline: "Toggle Outline/Bookmark",
      previousPage: "Previous Page",
      nextPage: "Next Page",
      toggleFullscreen: "Toggle Fullscreen",
      zoomIn: "Zoom In",
      zoomOut: "Zoom Out",
      toggleHelp: "Toggle Help",

      singlePageMode: "Single Page Mode",
      doublePageMode: "Double Page Mode",
      downloadPDFFile: "Download PDF File",
      gotoFirstPage: "Goto First Page",
      gotoLastPage: "Goto Last Page",
      play: "Start AutoPlay",
      pause: "Pause AutoPlay",

      share: "Share"
    },

    //valid controlnames:
    //altPrev,pageNumber,altNext,outline,thumbnail,zoomIn,zoomOut,fullScreen,share
    //more,download,pageMode,startPage,endPage,sound
    allControls: "altPrev,pageNumber,altNext,play,outline,thumbnail,zoomIn,zoomOut,fullScreen,share,download,more,pageMode,startPage,endPage,sound",
    moreControls: "download,pageMode,startPage,endPage,sound",
    hideControls: "",

    controlsPosition: DFLIP.CONTROLSPOSITION.BOTTOM,
    paddingTop: 30,
    paddingLeft: 20,
    paddingRight: 20,
    paddingBottom: 30,

    //set if the zoom changes on mouse scroll (true|false)
    scrollWheel: true,

    // callbacks
    onCreate: function (flipBook) {
      // after flip book is created is fired
    },
    onCreateUI: function (flipBook) {
      // after ui created event is fired
    },
    onFlip: function (flipBook) {
      // after flip event is fired
    },
    beforeFlip: function (flipBook) {
      // before flip event is fired
    },
    onReady: function (flipBook) {
      // after flip book is completely loaded
    },

    zoomRatio: 1.5,
    pageSize: DFLIP.PAGE_SIZE.AUTO,

    /**
     * NON-OPTIONS AREA
     * These options are not supposed to be sent from options variable
     */
    /**
     * dependency URLS (NON-OPTION):
     * Do not set them as options,
     * Refer to advance-examples
     */
    //(NON-OPTION) source link for PDF.JS file
    // pdfjsSrc: "js/libs/pdf.min.js",
    pdfjsSrc: 'fileadmin/dflip/js/libs/pdf.min.js',
    //(NON-OPTION) source link for PDFcompatibility.JS file
    // pdfjsCompatibilitySrc: "js/libs/compatibility.js",
    pdfjsCompatibilitySrc: "fileadmin/dflip/js/libs/compatibility.js",
    //(NON-OPTION) source link for PDF.WORKER.JS file
    // pdfjsWorkerSrc: "js/libs/pdf.worker.min.js",
    pdfjsWorkerSrc: "fileadmin/dflip/js/libs/pdf.worker.min.js",
    //(NON-OPTION) source link for THREE.JS file
    // threejsSrc: "js/libs/three.min.js",
    threejsSrc: 'fileadmin/dflip/js/libs/three.min.js',
    //(NON-OPTION) source link for MOCKUP.JS file
    // mockupjsSrc: "js/libs/mockup.min.js",
    mockupjsSrc: "fileadmin/dflip/js/libs/mockup.min.js",
    //(NON-OPTION) File path to the trun sound
    // soundFile: "sound/turn2.mp3",
    soundFile: "fileadmin/dflip/sound/turn2.mp3",
    imagesLocation: "images",
    imageResourcesPath: "images/pdfjs/",
    cMapUrl: "cmaps/", //it's quite wierd how cmaps don't work properly with relative urls like others.. but is relative to pdf.min.js path

    //(NON-OPTION) developer parameters
    enableDebugLog: false,
    canvasToBlob: false,//as of 1.2.9 canvas are better optimized and secure
    enableAnnotation: true,
    pdfRenderQuality: 0.90,


    /**
     * Let them be, change at your risk
     */
    // if texture fallback override is required
    // note: if set to anything other than "blank" the first page is changed
    // recommended : "blank"
    textureLoadFallback: "blank", //"images/textures/white.jpg",
    // controls the flexibility of the paper more value for more flexiblilty
    stiffness: 3,
    // minTopOffset: 30,
    // link to the images file that you want as background.
    // supported files are jpgs,png. smaller files are preffered for performance
    backgroundImage: "",//"images/textures/el.jpg",
    // or any number like 5, 500. recommended: "auto"

    pageRatio: null, 		//equals to width/height

    pixelRatio: window.devicePixelRatio || 1,
    thumbElement: 'div',

    /*3D settings*/
    spotLightIntensity: 0.22,
    ambientLightColor: "#fff",
    ambientLightIntensity: 0.8,
    shadowOpacity: 0.15
  };

  var has3d = 'WebKitCSSMatrix' in window
      || (document.body && 'MozPerspective' in document.body.style),
    hasMouse = 'onmousedown' in window,
    hasTouch = 'ontouchstart' in window;

  var userAgent = navigator.userAgent;

  var utils = DFLIP.utils = {

    drag: {
      left: 0,
      right: 1,
      none: -1
    },
    mouseEvents: (hasMouse)
      ? {type: "mouse", start: "mousedown", move: "mousemove", end: "mouseup"}
      : {type: "touch", start: "touchstart", move: "touchmove", end: "touchend"},

    html: {
      div: "<div/>",
      img: "<img/>",
      a: "<a>",
      input: "<input type='text'/>"
    },
    //functions or so
    toRad: function (deg) {
      return deg * Math.PI / 180;
    },
    isset: function (check, fallback) {
      return check == null ? fallback : check;
    },
    isnull: function (variable) {
      return variable == null || variable == null;
    },
    toDeg: function (rad) {
      return rad * 180 / Math.PI;
    },

    transition: function (hasTransition, duration) {
      return hasTransition ? duration / 1000 + "s ease-out" : "0s none";
    },

    display: function (hasDisplay) {
      return hasDisplay ? "block" : "none";
    },

    resetTranslate: function () {
      return translateStr(0, 0);
    },

    translateStr: function (x, y) {
      return has3d ? ' translate3d(' + x + 'px,' + y + 'px, 0px) ' : ' translate(' + x + 'px, ' + y + 'px) ';
    },
    httpsCorrection: function (url) {
      var location = window.location;
      if (location.href.indexOf("https://") > -1 && url.indexOf(location.hostname) > -1) {
        url = url.replace("http://", "https://");
      }
      return url;
    },
    resetBoxShadow: function () {
      return "rgba(0, 0, 0, 0) 0px 0px 20px";
    },

    rotateStr: function (deg) {
      return ' rotateZ(' + deg + 'deg) ';
    },

    bg: function (src) {
      return '#fff' + bgImage(src);
    },

    bgImage: function (src) {
      return (src == null || src == "blank" ? '' : ' url(' + src + ')');
    },

    src: function (src) {
      return (src != null ? '' + src + '' : '');
    },

    limitAt: function (x, min, max) {
      return x < min ? min : x > max ? max : x;
    },

    distOrigin: function (x, y) {
      return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
    },

    distPoints: function (x1, y1, x2, y2) {
      return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    },
    calculateScale: function (startTouches, endTouches) {
      var startDistance = distPoints(startTouches[0].x, startTouches[0].y, startTouches[1].x, startTouches[1].y),
        endDistance = distPoints(endTouches[0].x, endTouches[0].y, endTouches[1].x, endTouches[1].y);
      return endDistance / startDistance;
    },
    /**
     * Calculates the average of multiple vectors (x, y values)
     */
    getVectorAvg: function (vectors) {
      return {
        x: vectors.map(function (v) {
          return v.x;
        }).reduce(utils.sum) / vectors.length,
        y: vectors.map(function (v) {
          return v.y;
        }).reduce(utils.sum) / vectors.length
      };
    },
    sum: function (a, b) {
      return a + b;
    },
    /**
     * Returns the touches of an event relative to the container offset
     * @param event
     * @return array touches
     */
    getTouches: function (event, position) {
      position = position || {left: 0, top: 0};
      return Array.prototype.slice.call(event.touches).map(function (touch) {
        return {
          x: touch.pageX - position.left,
          y: touch.pageY - position.top
        };
      });
    },

    angleByDistance: function (distance, fullWidth) {
      var h = fullWidth / 2;
      var d = limitAt(distance, 0, fullWidth);

      return d < h
        ? toDeg(Math.asin(d / h))
        : 90 + toDeg(Math.asin((d - h) / h));

    },

    log: function (args) {
      if (defaults.enableDebugLog == true && window.console)
        console.log(args);
    },
    lowerPowerOfTwo: function (value) {
      return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
    },
    nearestPowerOfTwo: function (value, max) {
      return Math.min(max || 2048, Math.pow(2, Math.ceil(Math.log(value) / Math.LN2)));
    },
    zoomStops: function (value, zoomRatio, ceil, min, max) {
      if (min == null) min = 256;
      if (max == null) max = 2048;
      //Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));

      var factor = Math.log(value / min) / Math.log(zoomRatio);

      return min * Math.pow(zoomRatio, ceil == null ? Math.round(factor) : (ceil == true ? Math.ceil(factor)
          : Math.floor(factor)));
    },

    extendOptions: function (defaults, options) {
      return $.extend(true, {}, defaults, options);
    },
    getFullscreenElement: function () {
      return document.fullscreenElement
        || document.mozFullScreenElement
        || document.webkitFullscreenElement
        || document.msFullscreenElement
    },
    hasFullscreenEnabled: function () {
      return document.fullscreenEnabled
        || document.mozFullScreenEnabled
        || document.webkitFullscreenEnabled
        || document.msFullscreenEnabled
    },
    getBasePage: function (pageNumber) {
      return Math.floor(pageNumber / 2) * 2;
    },

    loadResources: function loadResources(resourceTag, src, callback) {
      var doc = document,
        element = doc.createElement(resourceTag),
        refElement = doc.getElementsByTagName(resourceTag)[0];

      element.async = true;
      if (callback) {
        element.addEventListener('load', function (e) {
          callback(null, e);
        }, false);
      }

      element.src = src;

      refElement.parentNode.insertBefore(element, refElement);
    },
    getScript: function (source, callback, errorCallback) {
      var script = document.createElement('script');
      var prior = document.body.getElementsByTagName('script')[0];
      script.async = 1;
      script.setAttribute("data-cfasync", false);
      if (prior != null) {
        prior.parentNode.insertBefore(script, prior);
        prior = null;
      }
      else { //sometimes if script are loaded in head and no scripts are present in body
        document.body.appendChild(script);
      }

      function load(_, isAbort) {
        if (script != null) { //IE 10 doesn't regard
          if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
            //console.log("aborted loading :" + source);
            script.onload = script.onreadystatechange = null;
            script = null;
            script = null;
            if (!isAbort) {
              if (callback) callback();
              callback = null;
              errorCallback = null;
            }

          }
        }
      }

      script.addEventListener("load", load, false);
      script.addEventListener("readystatechange", load, false);
      script.addEventListener("complete", load, false);

      if (errorCallback) {
        script.addEventListener("error", errorCallback, false);
      }
      //script.onload = script.onreadystatechange = load;

      script.src = source + (prefix.dom == "MS" ? ("?" + Math.random(1)) : "");
    },
    isHardPage: function (config, pageNumber, pageCount, isBooklet) {
      if (config != null) {

        // var config = this.hardConfig;

        if (config == "cover") {
          return pageNumber == 0 || (isBooklet && pageNumber == 1)  //front cover is 0
            || pageNumber == (Math.floor(pageCount / (isBooklet ? 1 : 2)) - (isBooklet ? 0 : 1)); //start with 0 so 1 minus
        }
        else if (config == "all") {
          return true;
        }
        else {
          var baseTest = ("," + config + ",").indexOf("," + (pageNumber * 2 + 1) + ",") > -1;
          var nextTest = ("," + config + ",").indexOf("," + (pageNumber * 2 + 2) + ",") > -1;
          return baseTest || nextTest;

        }
      }
      return false;
    },
    fixMouseEvent: function (event) {


      if (event) {
        var originalEvent = event.originalEvent || event;

        //noinspection JSUnresolvedVariable
        if (originalEvent.changedTouches && originalEvent.changedTouches.length > 0) {
          var _event = $.event.fix(event);
          //noinspection JSUnresolvedVariable
          var touch = originalEvent.changedTouches[0];
          _event.clientX = touch.clientX;
          _event.clientY = touch.clientY;
          _event.pageX = touch.pageX;
          _event.touches = originalEvent.touches;
          _event.pageY = touch.pageY;
          _event.movementX = touch.movementX;
          _event.movementY = touch.movementY;
          return _event;
        }
        else {
          return event;
        }
      }
      else {
        return event;
      }

    },

    //self Execution
    hasWebgl: (function () {
      try {
        var canvas = document.createElement('canvas');
        //noinspection JSUnresolvedVariable
        return !!( window.WebGLRenderingContext && ( canvas.getContext('webgl') || canvas.getContext('experimental-webgl') ) );
      } catch (e) {
        return false;
      }
    })(),
    isBookletMode: function (book) {
      return book.pageMode == DFLIP.PAGE_MODE.SINGLE && book.singlePageMode == DFLIP.SINGLE_PAGE_MODE.BOOKLET
    },
    isRTLMode: function (book) {
      return book.direction == DFLIP.DIRECTION.RTL
    },
    isMobile: (function () {
      var check = false;
      (function (a) {
        if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true
      })(userAgent || navigator.vendor || window.opera);
      return check;
    })(),
    isIOS: /(iPad|iPhone|iPod)/g.test(userAgent),
    isSafari: /constructor/i.test(window.HTMLElement) || (function (p) {
      return p.toString() === "[object SafariRemoteNotification]";
    })(!window['safari'] || safari.pushNotification),
    prefix: (function () {
      var styles = window.getComputedStyle(document.documentElement, ''),
        pre = (Array.prototype.slice
          .call(styles)
          .join('')
          .match(/-(moz|webkit|ms)-/))[1],
        dom = ('WebKit|Moz|MS').match(new RegExp('(' + pre + ')', 'i'))[1];
      return {
        dom: dom,
        lowercase: pre,
        css: '-' + pre + '-',
        js: pre[0].toUpperCase() + pre.substr(1)
      };
    })(),

    __extends: function (child, parent) {
      for (var key in parent)
        if (parent.hasOwnProperty(key)) child[key] = parent[key];
      function Ctor() {
        this.constructor = child;
      }

      Ctor.prototype = parent.prototype;
      child.prototype = new Ctor();
      child.__super = parent.prototype;
      return child;
    }

  };

  //caching the utils

  var SOURCE_TYPE = DFLIP.SOURCE_TYPE,
    DISPLAY_TYPE = DFLIP.DISPLAY_TYPE,

    drag = utils.drag,
    mouseEvents = utils.mouseEvents,
    html = utils.html,
    isset = utils.isset,
    isnull = utils.isnull,

    toRad = utils.toRad,
    toDeg = utils.toDeg,
    transition = utils.transition,
    translateStr = utils.translateStr,
    resetBoxShadow = utils.resetBoxShadow,
    rotateStr = utils.rotateStr,

    bg = utils.bg,
    bgImage = utils.bgImage,
    src = utils.src,

    limitAt = utils.limitAt,
    distOrigin = utils.distOrigin,
    distPoints = utils.distPoints,
    angleByDistance = utils.angleByDistance,
    log = utils.log,
    nearestPowerOfTwo = utils.nearestPowerOfTwo,
    extendOptions = utils.extendOptions,
    getBasePage = utils.getBasePage,
    getScript = utils.getScript,
    fixMouseEvent = utils.fixMouseEvent,
    prefix = utils.prefix,
    isBookletMode = utils.isBookletMode,
    isRTLMode = utils.isRTLMode,
    isMobile = utils.isMobile,
    hasWebgl = utils.hasWebgl,
    isSafari = utils.isSafari,
    isIOS = utils.isIOS,
    __extends = utils.__extends;

  // Support: IE<11, Chrome<21, Android<4.4, Safari<6
  (function checkSetPresenceInImageData() {
    // IE < 11 will use window.CanvasPixelArray which lacks set function.
    if (window.CanvasPixelArray) {
      if (typeof window.CanvasPixelArray.prototype.set !== 'function') {
        window.CanvasPixelArray.prototype.set = function (arr) {
          for (var i = 0, ii = this.length; i < ii; i++) {
            this[i] = arr[i];
          }
        };
      }
    } else {
      // Old Chrome and Android use an inaccessible CanvasPixelArray prototype.
      // Because we cannot feature detect it, we rely on user agent parsing.
      var polyfill = false, versionMatch;
      if (isSafari) {
        versionMatch = userAgent.match(/Version\/([0-9]+)\.([0-9]+)\.([0-9]+) Safari\//);
        // Safari < 6 lacks the set function.
        polyfill = versionMatch && parseInt(versionMatch[1]) < 6;
      }

      if (polyfill) {
        var contextPrototype = window.CanvasRenderingContext2D.prototype;
        var createImageData = contextPrototype.createImageData;
        contextPrototype.createImageData = function (w, h) {
          var imageData = createImageData.call(this, w, h);
          imageData.data.set = function (arr) {
            for (var i = 0, ii = this.length; i < ii; i++) {
              this[i] = arr[i];
            }
          };
          return imageData;
        };
        // this closure will be kept referenced, so clear its vars
        contextPrototype = null;
      }
    }
  })();

  // Support: IE<10, Android<4.0, iOS
  (function checkRequestAnimationFrame() {
    function fakeRequestAnimationFrame(callback) {
      window.setTimeout(callback, 20);
    }

    if ('requestAnimationFrame' in window) {
      return;
    }
    window.requestAnimationFrame =
      window.mozRequestAnimationFrame ||
      window.webkitRequestAnimationFrame ||
      fakeRequestAnimationFrame;
  })();

  // Checking if the typed arrays are supported
  // Support: iOS<6.0 (subarray), IE<10, Android<4.0
  (function checkTypedArrayCompatibility() {
    if (typeof Uint8Array !== 'undefined') {
      // Support: iOS<6.0
      if (typeof Uint8Array.prototype.subarray === 'undefined') {
        Uint8Array.prototype.subarray = function subarray(start, end) {
          return new Uint8Array(this.slice(start, end));
        };
        Float32Array.prototype.subarray = function subarray(start, end) {
          return new Float32Array(this.slice(start, end));
        };
      }

      // Support: Android<4.1
      if (typeof Float64Array === 'undefined') {
        window.Float64Array = Float32Array;
      }
      return;
    }

    function subarray(start, end) {
      return new TypedArray(this.slice(start, end));
    }

    function setArrayOffset(array, offset) {
      if (arguments.length < 2) {
        offset = 0;
      }
      for (var i = 0, n = array.length; i < n; ++i, ++offset) {
        this[offset] = array[i] & 0xFF;
      }
    }

    function TypedArray(arg1) {
      var result, i, n;
      if (typeof arg1 === 'number') {
        result = [];
        for (i = 0; i < arg1; ++i) {
          result[i] = 0;
        }
      } else if ('slice' in arg1) {
        result = arg1.slice(0);
      } else {
        result = [];
        for (i = 0, n = arg1.length; i < n; ++i) {
          result[i] = arg1[i];
        }
      }

      result.subarray = subarray;
      result.buffer = result;
      result.byteLength = result.length;
      result.set = setArrayOffset;

      if (typeof arg1 === 'object' && arg1.buffer) {
        result.buffer = arg1.buffer;
      }
      return result;
    }

    window.Uint8Array = TypedArray;
    window.Int8Array = TypedArray;

    // we don't need support for set, byteLength for 32-bit array
    // so we can use the TypedArray as well
    window.Uint32Array = TypedArray;
    window.Int32Array = TypedArray;
    window.Uint16Array = TypedArray;
    window.Float32Array = TypedArray;
    window.Float64Array = TypedArray;
  })();

  var extendDFlipOptions = function (options) {
    return $.extend(true, {}, defaults, options);
  };

  //Creates ui for the flipbook
  var createUI = function (container, object) {

      var uiClass = "df-ui";
      var wrapperClass = "df-ui-wrapper";
      var buttonClass = uiClass + "-" + "btn";
      var ui = object.ui = $(html.div, {'class': uiClass});
      var options = object.options;

      ui.dispose = function () {
        container.find("." + buttonClass).each(function () {
          $(this).off();
        });
        help.off();
        next.off();
        prev.off();
        play.off();
        zoom.off();
        zoomIn.off();
        zoomOut.off();
        page.off();
        sound.off();
        more.off();
        fullScreen.off();
        fit.off();
        share.off();
        start.off();
        end.off();
        pageModeButton.off();
        altPrev.off();
        altNext.off();
        thumbnail.off();
        outline.off();

        controls.remove();
        sizeControls.remove();
        prev.remove();
        next.remove();
        zoom.remove();
        if (ui.shareBox) {
          if (ui.shareBox.dispose)
            ui.shareBox.dispose();
          ui.shareBox = null;
        }
        document.removeEventListener('keyup', onKeyUp, false);
        window.removeEventListener('click', closeMoreOptions, false);
        ui.update = null;
        object = null;
      };

      var validPage = function (pageNumber) {

        if (isNaN(pageNumber)) pageNumber = object.target._activePage;
        else if (pageNumber < 1) pageNumber = 1;
        else if (pageNumber > object.target.pageCount) pageNumber = object.target.pageCount;
        return pageNumber;

      };

      var next = ui.next = $(html.div, {

        class: buttonClass + " " + uiClass + "-next " + options.icons['next'],
        title: options.text.nextPage,
        html: "<span>" + options.text.nextPage + "</span>"

      }).on("click", function () {
        object.next();
      });

      var prev = ui.prev = $(html.div, {

        class: buttonClass + " " + uiClass + "-prev " + options.icons['prev'],
        title: options.text.previousPage,
        html: "<span>" + options.text.previousPage + "</span>"

      }).on("click", function () {

        object.prev();

      });
      var play = $(html.div, {

        class: buttonClass + " " + uiClass + "-play " + options.icons['play'],
        title: options.text.play,
        html: "<span>" + options.text.play + "</span>"

      }).on("click", function () {
        var el = $(this);
        object.setAutoPlay(!el.hasClass(options.icons['pause']));

      });
      if (options.autoPlay == true) {
        ui.play = play;
        object.setAutoPlay(options.autoPlayStart);
      }
      var zoom = $(html.div, {
        class: wrapperClass + " " + uiClass + "-zoom"
      });

      var zoomIn = ui.zoomIn = $(html.div, {

        class: buttonClass + " " + uiClass + "-zoomin " + options.icons['zoomin'],
        title: options.text.zoomIn,
        html: "<span>" + options.text.zoomIn + "</span>"

      }).on("click", function () {

        object.zoom(1);
        ui.update();
        if (object.target.startPoint && object.target.pan)
          object.target.pan(object.target.startPoint);

      });

      var zoomOut = ui.zoomOut = $(html.div, {

        class: buttonClass + " " + uiClass + "-zoomout " + options.icons['zoomout'],
        title: options.text.zoomOut,
        html: "<span>" + options.text.zoomOut + "</span>"

      }).on("click", function () {
        object.zoom(-1);
        ui.update();
        if (object.target.startPoint && object.target.pan)
          object.target.pan(object.target.startPoint);
      });
      zoom.append(zoomIn).append(zoomOut);

      var page = ui.pageNumber = $(html.div, {

        class: buttonClass + " " + uiClass + "-page",

      }).on("change", function () {

        var pageNumber = parseInt((ui.pageInput.val()), 10);

        pageNumber = validPage(pageNumber);
        object.gotoPage(pageNumber);

      }).on("keyup", function (event) {

        if (event.keyCode == 13) {
          var pageNumber = parseInt((ui.pageInput.val()), 10);

          pageNumber = validPage(pageNumber);
          if (pageNumber !== validPage(object.target._activePage || object._activePage))
            object.gotoPage(pageNumber);
        }

      });

      ui.pageInput = $('<input id="df_book_page_number" type="text"/>').appendTo(page);
      ui.pageLabel = $('<label for="df_book_page_number"/>').appendTo(page);

      var sizeControls = $(html.div, {
        class: wrapperClass + " " + uiClass + "-size"
      });

      var help = $(html.div, {
        class: buttonClass + " " + uiClass + "-help " + options.icons['help'],
        title: options.text.toggleHelp,
        html: "<span>" + options.text.toggleHelp + "</span>"
      }).on("click", function () {

      });


      //Sound Button
      var sound = ui.sound = $(html.div, {

        class: buttonClass + " " + uiClass + "-sound " + options.icons['sound'],
        title: options.text.toggleSound,
        html: "<span>" + options.text.toggleSound + "</span>"

      }).on("click", function () {

        options.soundEnable = !options.soundEnable;
        ui.updateSound();

      });

      //Updates sound on click of sound button
      ui.updateSound = function () {

        if (options.soundEnable == false || options.soundEnable == 'false')
          sound.addClass("disabled");
        else
          sound.removeClass("disabled");

      };

      //immediate check
      ui.updateSound();


      //More button
      var more = ui.more = $(html.div, {

        class: buttonClass + " " + uiClass + "-more " + options.icons['more']

      }).on("click", function (event) {
        if (!more.hasClass("df-active")) {
          $(this).addClass("df-active");
          event.stopPropagation();
        }
      });

      //closes moreoptions container
      function closeMoreOptions(event) {
        more.removeClass("df-active");
      }

      //register a click event on window to close the moreoptions
      window.addEventListener('click', closeMoreOptions, false);

      //more container that holds the moreoptions
      var moreContainer = $(html.div, {
        class: "more-container"
      });
      more.append(moreContainer);

      if (typeof options.source == 'string' && options.enableDownload == true) {
        var downloadClass = buttonClass + " " + uiClass + "-download " + options.icons['download'];
        var download = ui.download = $('<a download target="_blank" class="' + downloadClass + '"><span>' + options.text.downloadPDFFile + '</span></a>');
        download.attr("href", options.source).attr("title", options.text.downloadPDFFile);
        //moreContainer.append(download);
      }

      var fullscreenEnabled = utils.hasFullscreenEnabled();

      if (!fullscreenEnabled) {
        container.addClass("df-custom-fullscreen");
      }

      ui.switchFullscreen = function () {

        var fullscreenElement = utils.getFullscreenElement();

        var container = object.container[0];

        if (ui.isFullscreen != true) {

          object.container.addClass("df-fullscreen");
          if (container.requestFullscreen) {
            container.requestFullscreen();
          } else if (container.msRequestFullscreen) {
            container.msRequestFullscreen();
          } else if (container.mozRequestFullScreen) {
            container.mozRequestFullScreen();
          } else if (container.webkitRequestFullscreen) {
            container.webkitRequestFullscreen();
          }

          ui.isFullscreen = true

        }
        else {

          object.container.removeClass("df-fullscreen");
          ui.isFullscreen = false;

          if (document.exitFullscreen) {
            document.exitFullscreen();
          } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
          } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
          } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
          }

        }

        if (!utils.hasFullscreenEnabled()) {
          setTimeout(function () {
            object.resize();
          }, 50);
        }
      };

      var fullScreen = ui.fullScreen = $(html.div, {

        class: buttonClass + " " + uiClass + "-fullscreen " + options.icons['fullscreen'],
        title: options.text.toggleFullscreen,
        html: "<span>" + options.text.toggleFullscreen + "</span>"

      }).on("click", ui.switchFullscreen);

      var fit = ui.fit = $(html.div, {

        class: buttonClass + " " + uiClass + "-fit " + options.icons['fitscreen']

      }).on("click", function () {

        $(this).toggleClass("df-button-fit-active");

      });
      sizeControls.append(fullScreen);

      var controls = $(html.div, {
        class: wrapperClass + " " + uiClass + "-controls"
      });

      var shareBox = ui.shareBox = new DFLIP.Share(container, options);

      var share = ui.share = $(html.div, {

        class: buttonClass + " " + uiClass + "-share " + options.icons['share'],
        title: options.text.share,
        html: "<span>" + options.text.share + "</span>"

      }).on("click", function (event) {
        if (ui.shareBox.isOpen == true)
          ui.shareBox.close();
        else {
          ui.shareBox.update(object.getURLHash());
          ui.shareBox.show();
        }
      });

      var start = ui.startPage = $(html.div, {

        class: buttonClass + " " + uiClass + "-start " + options.icons['start'],
        title: options.text.gotoFirstPage,
        html: "<span>" + options.text.gotoFirstPage + "</span>"

      }).on("click", function () {

        object.start();

      });


      var end = ui.endPage = $(html.div, {

        class: buttonClass + " " + uiClass + "-end " + options.icons['end'],
        title: options.text.gotoLastPage,
        html: "<span>" + options.text.gotoLastPage + "</span>"

      }).on("click", function () {

        object.end();

      });

      var pageModeButton = ui.pageMode = $(html.div, {

        class: buttonClass + " " + uiClass + "-pagemode " + options.icons['singlepage'],
        html: "<span>" + options.text.singlePageMode + "</span>"

      }).on("click", function () {

        var el = $(this);
        object.setPageMode(!el.hasClass(options.icons['doublepage']));

      });


      object.setPageMode(object.target.pageMode == DFLIP.PAGE_MODE.SINGLE)
      //moreContainer.append(pageModeButton).append(start).append(end).append(sound);

      var altPrev = ui.altPrev = $(html.div, {

        class: buttonClass + " " + uiClass + "-prev" + " " + uiClass + "-alt " + options.icons['prev'],
        title: options.text.previousPage,
        html: "<span>" + options.text.previousPage + "</span>"

      }).on("click", function () {
        object.prev();
      });

      var altNext = ui.altNext = $(html.div, {

        class: buttonClass + " " + uiClass + "-next" + " " + uiClass + "-alt " + options.icons['next'],
        title: options.text.nextPage,
        html: "<span>" + options.text.nextPage + "</span>"

      }).on("click", function () {
        object.next();
      });

      var thumbnail = ui.thumbnail = $(html.div, {

        class: buttonClass + " " + uiClass + "-thumbnail " + options.icons['thumbnail'],
        title: options.text.toggleThumbnails,
        html: "<span>" + options.text.toggleThumbnails + "</span>"

      }).on("click", function () {
        var $this = $(this);
        if (object.target.thumbContainer) {
          var thumbContainer = object.target.thumbContainer;
          thumbContainer.toggleClass("df-sidemenu-visible");
          $this.toggleClass("df-active");
        }
        else {
          object.contentProvider.initThumbs();
          $this.toggleClass("df-active");
        }
        if ($this.hasClass("df-active")) {
          $this.siblings(".df-active").trigger("click");
        }
        ui.update(true);
      });

      var outline = ui.outline = $(html.div, {

        class: buttonClass + " " + uiClass + "-outline " + options.icons['outline'],
        title: options.text.toggleOutline,
        html: "<span>" + options.text.toggleOutline + "</span>"

      }).on("click", function () {
        var $this = $(this);
        if (object.target.outlineContainer) {
          var outlineContainer = object.target.outlineContainer;
          $this.toggleClass("df-active");
          outlineContainer.toggleClass("df-sidemenu-visible");
          if ($this.hasClass("df-active")) {
            $this.siblings(".df-active").trigger("click");
          }
          ui.update(true);
        }
      });

      /**
       * Controls position and pplace ment is determined by options.moreControls and options.hideControls
       */
      var allControls = options.allControls.replace(/ /g, '').split(','),
        moreControls = "," + options.moreControls.replace(/ /g, '') + ",",
        hideControls = "," + options.hideControls.replace(/ /g, '') + ",";

      var moreControlsArray = moreControls.split(',');

      for (var controlCount = 0; controlCount < allControls.length; controlCount++) {
        //if hidden skip
        var controlName = allControls[controlCount];
        if (hideControls.indexOf("," + controlName + ",") < 0) { //not found in hide list
          var control = ui[controlName];
          if (control != null) {
            if (moreControls.indexOf("," + controlName + ",") > -1 && controlName !== 'more' && controlName !== 'pageNumber') {//found in more controls
              moreContainer.append(control);
            }
            else {
              controls.append(control);
            }
          }
        }
      }

      container.append(controls).append(prev).append(next).append(zoom);

      var ctrlDown = false, shiftDown = false, altDown = false;
      var shiftKey = 16, ctrlKey = 17, altKey = 18, sKey = 83, vKey = 86, cKey = 67, eKey = 69, gKey = 71, nKey = 78,
        oKey = 79, deleteKey = 46, rightKey = 39, leftKey = 37, escKey = 27;

      document.addEventListener('keyup', onKeyUp, false);

      function onKeyUp(event) {
        switch (event.keyCode) {
          case escKey:
            if (ui.isFullscreen == true) ui.fullScreen.trigger("click");
            break;
          case shiftKey:
            shiftDown = false;
            break;
          case ctrlKey:
            ctrlDown = false;
            break;
          case altKey:
            altDown = false;
            break;
          case leftKey:
            object.prev();
            break;
          case rightKey:
            object.next();
            break;
          default:
            break;
        }
        //log(event.keyCode);
      }

      ui.update = function (resize) {
        log("ui update");
        var target = object.target;

        var pageNumber = validPage(target._activePage || object._activePage);
        var pageCount = target.pageCount || object.pageCount;

        var isRTL = target.direction == DFLIP.DIRECTION.RTL,
          isStart = (pageNumber == 1 || pageNumber == 0),
          isEnd = pageNumber == pageCount;

        ui.next.show();
        ui.prev.show();
        ui.altNext.removeClass("disabled");
        ui.altPrev.removeClass("disabled");

        if ((isStart && !isRTL) || (isEnd && isRTL)) {
          ui.prev.hide();
          ui.altPrev.addClass("disabled");
        }
        if ((isEnd && !isRTL) || (isStart && isRTL)) {
          ui.next.hide();
          ui.altNext.addClass("disabled");
        }

        ui.pageInput.val(pageNumber);
        ui.pageLabel.html((pageNumber) + "/" + pageCount);


        if (container.find(".df-sidemenu-visible").length > 0) {
          container.addClass("df-sidemenu-open");
        }
        else {
          container.removeClass("df-sidemenu-open");
        }
        if (resize == true)
          object.resize();

        if (target.contentProvider.zoomScale == target.contentProvider.maxZoom) {
          ui.zoomIn.addClass("disabled");
        }
        else {
          ui.zoomIn.removeClass("disabled");
        }

        if (target.contentProvider.zoomScale == 1) {
          ui.zoomOut.addClass("disabled");
        }
        else {
          ui.zoomOut.removeClass("disabled");
        }

      };

      if (object.target != null) {
        object.target.ui = ui;
      }

      if (options.onCreateUI != null)
        options.onCreateUI(object);
    }
  ;

  var PreviewStage = null;
  //later updated via RegisterMockupObjects in case 3d is requested

  //Registers necessary mockup object when required
  function RegisterMockupObjects() {

    PreviewStage = (function (_super) {
      __extends(PreviewStage, _super);
      function PreviewStage(parameters) {
        parameters = parameters || {};
        var _this = this;
        _super.call(this, parameters);
        _this.options = parameters;
        _this.canvas = $(_this.renderer.domElement).addClass("df-3dcanvas");
        _this.container = parameters.container;
        _this.container.append(_this.canvas);
        //_this.container.height(parameters.height);
        _this.type = "PreviewStage";
        _this.mouse = new THREE.Vector2();
        _this.raycaster = new THREE.Raycaster();

        _this.camera.position.set(0, 20, 600);
        _this.camera.lookAt(new THREE.Vector3(0, 0, 0));

        //shadows are zigzap due to shadow camera position
        _this.spotLight.position.set(-220, 330, 550);

        _this.spotLight.castShadow = isMobile ? false : parameters.webglShadow;
        //_this.spotLight.shadowDarkness = 0.6;
        if (_this.spotLight.shadow) {
          _this.spotLight.shadow.bias = -0.0008;
        }
        _this.spotLight.intensity = isset(parameters.spotLightIntensity, defaults.spotLightIntensity);
        _this.ambientLight.color = new THREE.Color(isset(parameters.ambientLightColor, defaults.ambientLightColor));
        _this.ambientLight.intensity = isset(parameters.ambientLightIntensity, defaults.ambientLightIntensity);

        var material = new THREE.ShadowMaterial();
        material.opacity = isset(parameters.shadowOpacity, defaults.shadowOpacity);

        _this.ground.material = material;
        _this.ground.position.z = -2;

        _this.orbitControl.maxAzimuthAngle = 0.4;
        _this.orbitControl.minAzimuthAngle = -0.4;
        _this.orbitControl.minPolarAngle = 1.4;
        _this.orbitControl.maxPolarAngle = 2.2;

        //_this.orbitControl.maxPolarAngle = 10;
        _this.orbitControl.mouseButtons.ORBIT = THREE.MOUSE.RIGHT;
        _this.orbitControl.mouseButtons.PAN = -1;
        _this.orbitControl.maxDistance = 5000;
        _this.orbitControl.minDistance = 50;
        _this.orbitControl.noZoom = true;

        _this.selectiveRendering = true;

        _this.orbitControl.zoomSpeed = 5;

        _this.orbitControl.keyPanSpeed = 0;
        _this.orbitControl.center.set(0, 0, 0);
        _this.orbitControl.update();

        _this.swipe_threshold = isMobile ? 15 : 20;

        var cssRenderer = _this.cssRenderer = new THREE.CSS3DRenderer();
        $(cssRenderer.domElement).css({
          position: "absolute",
          top: 0,
          pointerEvents: "none"
        }).addClass("df-3dcanvas df-csscanvas");
        _this.container[0].appendChild(cssRenderer.domElement);

        var cssScene = _this.cssScene = new THREE.Scene();

        var divLeftDOM = document.createElement("div");
        divLeftDOM.className = "df-page-content df-page-content-left";

        var divRightDOM = document.createElement("div");
        divRightDOM.className = "df-page-content df-page-content-right";

        var divLeft = cssScene.divLeft = new THREE.CSS3DObject(divLeftDOM);
        var divRight = cssScene.divRight = new THREE.CSS3DObject(divRightDOM);
        cssScene.add(divLeft);
        cssScene.add(divRight);

        _this.resizeCallback = function () {
          cssRenderer.setSize(_this.canvas.width(), _this.canvas.height());
        };

        function requestRender() {
          _this.renderRequestPending = true;
        }

        window.addEventListener(mouseEvents.move, requestRender, false);

        window.addEventListener('keyup', requestRender, false);


        _this.dispose = function () {

          _this.clearChild();
          _this.render();

          window.removeEventListener(mouseEvents.move, requestRender, false);

          if (_this.options.scrollWheel == true) {
            _this.renderer.domElement.removeEventListener('mousewheel', onMouseWheel, false);
            _this.renderer.domElement.removeEventListener('DOMMouseScroll', onMouseWheel, false); // firefox
          }

          window.removeEventListener('keyup', requestRender, false);

          _this.renderer.domElement.removeEventListener("mousemove", editor_mouseMove, false);
          _this.renderer.domElement.removeEventListener("touchmove", editor_mouseMove, false);

          _this.renderer.domElement.removeEventListener("mousedown", editor_mouseDown, false);
          _this.renderer.domElement.removeEventListener("touchstart", editor_mouseDown, false);
          _this.renderer.domElement.removeEventListener("mouseup", editor_mouseUp, false);
          _this.renderer.domElement.removeEventListener("touchend", editor_mouseUp, false);


          _this.canvas.remove();

          cssRenderer.domElement.parentNode.removeChild(cssRenderer.domElement);

          cssRenderer = null;

          _this.renderCallback = null;
          _this.renderCallback = null;
          _this.orbitControl.dispose();
          _this.orbitControl = null;


          _this.renderer.dispose();

          _this.cancelRAF();
        };

        _this.renderCallback = function () {
          if (TWEEN.getAll().length > 0)
            _this.renderRequestPending = true;
          TWEEN.update();
          cssRenderer.render(cssScene, _this.camera)
        };

        var onMouseWheel = function (event) {
          var delta = 0;

          if (event.wheelDelta != null) { // WebKit / Opera / Explorer 9

            delta = event.wheelDelta;

          } else if (event.detail != null) { // Firefox

            delta = -event.detail;

          }
          if (delta) {
            var currentZoom = _this.previewObject.contentProvider.zoomScale;
            if ((delta > 0 && currentZoom == 1)
              || (delta < 0 && currentZoom > 1)) {
              event.preventDefault();
            }
            _this.previewObject.zoom(delta > 0 ? 1 : -1);
          }

          requestRender();
        };

        var editor_mouseMove = function (event) {

          _this.renderRequestPending = true;
          event = fixMouseEvent(event);
          if (_this.isMouseDown && event.movementX != 0 && event.movementY != 0) {
            _this.isMouseMoving = true;
          }
          if (event.touches != null && event.touches.length == 2 && _this.startTouches != null) {
            //return;
            // _this.startTouches = event.touches;
            _this.zoomDirty = true;
            var touchCenter = utils.getVectorAvg(utils.getTouches(event, _this.container.offset())),
              newScale = utils.calculateScale(_this.startTouches, utils.getTouches(event)),
              scale = newScale / _this.lastScale;

            var zoom = _this.previewObject.contentProvider.zoomScale,
              x = touchCenter.x,
              y = touchCenter.y;

            _this.camera.position.z = _this.originalZ / (newScale);
            _this.lastScale = newScale;

            _this.lastZoomCenter = touchCenter;
            event.preventDefault();
            return;
          }
          if (_this.isMouseDown == true && _this.previewObject.contentProvider.zoomScale == 1) {
            //check if swipe has happened

            var swipe_dist = event.pageX - _this.lastPos,
              swipe_time = performance.now() - _this.lastTime;

            //$("body > p").html(swipe_dist);

            if (Math.abs(swipe_dist) > _this.swipe_threshold) {
              //swipe has triggered
              //_this.dragPage.pendingPoint = point;
              if (swipe_dist < 0) {
                _this.target.next();
              }
              else {
                _this.target.prev();
              }
              event.preventDefault();
              _this.isMouseDown = false;
            }
            _this.lastPos = event.pageX;
            _this.lastTime = performance.now();

          }
        };

        var editor_mouseDown = function (event) {
          event = fixMouseEvent(event);
          if (event.touches != null && event.touches.length == 2 && _this.startTouches == null) {
            _this.startTouches = utils.getTouches(event);
            _this.lastScale = 1;
            _this.originalZ = _this.camera.position.z * 1;
          }
          document.activeElement.blur();
          _this.mouseValue = event.pageX + "," + event.pageY;
          _this.isMouseMoving = false;
          _this.isMouseDown = true;
          _this.lastPos = event.pageX;
          _this.lastTime = performance.now();
        };

        var editor_click = function (event) {
          _this.isMouseDown = false;
          //bail out if it's not left click
          if (event.button !== 0) return this;
          var mouseValue = event.pageX + "," + event.pageY;

          if (_this.isMouseMoving) {

          }
          else if (mouseValue == _this.mouseValue) {
            event = event || window.event;
            event = $.event.fix(event);

            var mouse = _this.mouse, raycaster = _this.raycaster;
            mouse.x = ( (event.offsetX) / _this.canvas.innerWidth() ) * 2 - 1;
            mouse.y = 1 - ( (event.offsetY ) / _this.canvas.innerHeight() ) * 2;

            raycaster.setFromCamera(mouse, _this.camera);

            var intersects = raycaster.intersectObjects(_this.target instanceof MOCKUP.Bundle
              ? _this.target.children : [_this.target], true);

            if (intersects.length > 0) {

              var object, objectCount = 0;
              do {
                object = intersects[objectCount] != null ? intersects[objectCount].object : null;
                //bookStage.clickFace = intersects[objectCount].face;
                objectCount++;
              } while ((object instanceof THREE.BoxHelper || !(object instanceof MOCKUP.Paper) || object.isFlipping == true) && objectCount < intersects.length);

              //if (object.parent instanceof  MOCKUP.Bundle) {
              //    object = object.parent;
              //}

              if (object.userData.object != null) {

                // helper

                //bookStage.selectObject(object.userData.object);

              } else {

                if (object.angles[1] > 90) {
                  if (object.isEdge != true) _this.target.next();
                }
                else {
                  if (object.isEdge != true) _this.target.prev();
                }

              }

            } else {

              //bookStage.selectObject(null);

            }
          }
          //bookStage.stage.render();
        };

        var editor_mouseUp = function (event) {
          event = fixMouseEvent(event);
          if (event.touches != null && event.touches.length == 0) {
            var zoom = _this.previewObject.contentProvider.zoomScale;
            if (_this.zoomDirty == true) {
              _this.previewObject.contentProvider.zoomScale =
                utils.limitAt(_this.previewObject.contentProvider.zoomScale * _this.lastScale,
                  1, _this.previewObject.contentProvider.maxZoom);
              _this.previewObject.zoomValue = _this.previewObject.contentProvider.zoomScale * 1;
              //_this.previewObject.zoom(_this.lastScale < 1 ? -1 : 1);
              //console.log(_this.previewObject.contentProvider.zoomScale * _this.lastScale,_this.previewObject.contentProvider.maxZoom)
              //_this.previewObject.pendingZoom = true;
              _this.previewObject.resize();
              _this.zoomDirty = false;
            }

            _this.lastScale = null;
            _this.startTouches = null;
          }
          if (event.touches != null && event.touches.length > 1) return;
          editor_click(event);
        };
        //if (MOCKUP.mode !== MOCKUP.MODE.PLUGIN) {

        //_this.renderer.domElement.addEventListener('click', editor_click, false);
        //bookStage.renderer.domElement.addEventListener('dblclick', editor_dblclick, false);
        _this.renderer.domElement.addEventListener("mousemove", editor_mouseMove, false);
        _this.renderer.domElement.addEventListener("touchmove", editor_mouseMove, false);

        _this.renderer.domElement.addEventListener("mousedown", editor_mouseDown, false);
        _this.renderer.domElement.addEventListener("touchstart", editor_mouseDown, false);
        _this.renderer.domElement.addEventListener("mouseup", editor_mouseUp, false);
        _this.renderer.domElement.addEventListener("touchend", editor_mouseUp, false);
        if (_this.options.scrollWheel == true) {
          _this.renderer.domElement.addEventListener('mousewheel', onMouseWheel, false);
          _this.renderer.domElement.addEventListener('DOMMouseScroll', onMouseWheel, false); // firefox
        }

        //}

        $(_this.renderer.domElement).css({display: "block"});

        $(window).trigger("resize");

        return this;
      }

      PreviewStage.prototype.width = function () {
        return this.container.width();
      };

      PreviewStage.prototype.height = function () {
        return this.container.height();
      };

      return PreviewStage;

    })(MOCKUP.Stage);
    MOCKUP.PreviewStage = PreviewStage;

    var BookPaper = (function (_super) {
      __extends(BookPaper, _super);
      function BookPaper(parameters, stage) {
        parameters = parameters || {};
        parameters.folds = 1;
        _super.call(this, parameters, stage);
        this.angle = 0;
        this.isFlipping = false;
        this.material.materials[5].transparent = true;
        this.material.materials[4].transparent = true;
        this.type = "BookPaper";
      }

      BookPaper.prototype.tween = function (oldAngle, newAngle) {
        var page = this;
        var epsilon = 0.00001;
        page.originalStiff = page.stiffness;
        var oldTarget = page.newStiffness;
        var isBooklet = isBookletMode(page.parent);
        //console.log(page.stiffness);
        var diff = newAngle - oldAngle;//170 -5 == 165 :  5-170 = -165

        var isRight = oldAngle > 90;
        var isRTL = page.parent.direction == DFLIP.DIRECTION.RTL;
        page.init = {
          angle: oldAngle,
          angle2: (oldAngle < 90 ? 0 : 180),
          stiff: page.originalStiff,
          index: (isRight && !isRTL) || (!isRight && isRTL) ? 1 : 0
        };
        page.first = {
          angle: oldAngle + diff / 4,
          angle2: (oldAngle < 90 ? 90 : 90),
          stiff: page.originalStiff,
          index: (isRight && !isRTL) || (!isRight && isRTL) ? 1 : 0.25
        };
        page.mid = {
          angle: oldAngle + diff * 2 / 4,
          angle2: (oldAngle < 90 ? 135 : 45),
          stiff: page.newStiffness,
          index: (isRight && !isRTL) || (!isRight && isRTL) ? 0.5 : 0.5
        };
        page.mid2 = {
          angle: oldAngle + diff * 3 / 4,
          angle2: (oldAngle < 90 ? 180 : 0),
          stiff: page.newStiffness,
          index: (isRight && !isRTL) || (!isRight && isRTL) ? 0.25 : 1
        };
        page.end = {
          angle: newAngle,
          angle2: (oldAngle < 90 ? 180 : 0),
          stiff: page.newStiffness,
          index: (isRight && !isRTL) || (!isRight && isRTL) ? 0 : 1
        };

        //console.log(page.init, page.first, page.mid, page.end);
        page.isFlipping = true;

        var update = function (tween, event) {

          page.angles[1] = tween.angle;
          page.angles[4] = page.isHard ? tween.angle : tween.angle2;
          if (page.isHard == true) {
            page.stiffness = 0;
          } else {
            page.stiffness = tween.stiff / (oldTarget + epsilon) * (page.newStiffness + epsilon);
            page.stiffness = isNaN(page.stiffness) ? 0 : tween.stiff;
          }
          if (isBooklet) {
            page.material.materials[5].opacity = page.material.materials[4].opacity = tween.index;
            page.castShadow = (isRight && !isRTL) || (!isRight && isRTL) ? tween.index > 0.5 : tween.index > 0.5;
          }
          //check if any sibling is flipping and their stiff is more that this

          page.updateAngle(true);

        };

        if (isBooklet && ((!isRight && !isRTL) || (isRight && isRTL))) {
          page.material.materials[5].opacity = page.material.materials[4].opacity = 0;
          page.castShadow = false;
        }

        page.currentTween = new TWEEN.Tween(page.init)
          .to({
            angle: [page.first.angle, page.mid.angle, page.mid2.angle, page.end.angle],
            angle2: [page.first.angle2, page.mid.angle2, page.mid2.angle2, page.end.angle2],
            stiff: [page.first.stiff, page.mid.stiff, page.mid2.stiff, page.end.stiff],
            index: [page.first.index, page.mid.index, page.mid2.index, page.end.index]
          }, page.parent.duration)
          .onUpdate(function (event) {
            update(this, event);
          }).easing(TWEEN.Easing.Sinusoidal.Out)
          .onComplete(function (event) {
            page.stiffness = page.newStiffness;
            page.updateAngle();
            page.material.materials[5].opacity = page.material.materials[4].opacity = 1;
            page.castShadow = true;
            page.isFlipping = false;
            if (page.parent && page.parent.refresh)
              page.parent.refresh();
            //console.log(page.stiffness);
          }).start();

      };

      return BookPaper;
    })(MOCKUP.FlexBoxPaper);
    MOCKUP.BookPaper = BookPaper;

    var Book = (function (_super) {
      __extends(Book, _super);

      function Book(parameters, stage) {

        parameters = parameters || {};
        parameters.segments = parameters.segments || 50;
        this.pageCount = parameters.pageCount;

        this.height = parameters.height;
        this.width = parameters.width;

        //correcting page count as multiple of 2
        this.pageCount = (this.pageCount == 1 ? this.pageCount : Math.ceil(this.pageCount / 2) * 2);

        this.direction = parameters.direction || DFLIP.DIRECTION.LTR;

        this.startPage = 1;
        this.endPage = this.pageCount;

        this.stackCount = parameters.stackCount || 6;// = 15;
        this.materials = [];

        _super.call(this, parameters, stage);
        this.angles = [0, 0, 0, 0, 0, 0];
        this.stiffness = parameters.stiffness == null ? 1.5 : parameters.stiffness; //so that 0 can be set
        this.hardConfig = parameters.hard; //hard is not that good in 3d
        this._activePage = parameters.openPage || this.startPage;

        this.createStack(parameters);
        this.pageMode = parameters.pageMode || ((isMobile || this.pageCount <= 2) ? DFLIP.PAGE_MODE.SINGLE
            : DFLIP.PAGE_MODE.DOUBLE);

        this.singlePageMode = parameters.singlePageMode || (isMobile ? DFLIP.SINGLE_PAGE_MODE.BOOKLET
            : DFLIP.SINGLE_PAGE_MODE.ZOOM);


        this.type = "Book";

      }

      Book.prototype.getPageByNumber = function (pageNumber) {
        var relativePageNumber = isBookletMode(this) ? (isRTLMode(this) ? pageNumber + 1 : pageNumber)
          : Math.floor((pageNumber - 1) / 2);
        return this.getObjectByName(relativePageNumber.toString());
      };

      Book.prototype.isPageHard = function (pageNumber) {

        return utils.isHardPage(this.hardConfig, pageNumber, this.pageCount);

      };

      Book.prototype.activePage = function (pageNumber) {
        if (pageNumber == null) return this._activePage;
        this.gotoPage(pageNumber);
      };

      Book.prototype.gotoPage = function (pageNumber) {
        pageNumber = parseInt(pageNumber, 10);
        this._activePage = pageNumber;
        if (this.autoPlay == true) {
          this.previewObject.setAutoPlay(this.autoPlay);
        }
        this.updatePage(pageNumber);
        if (this && this.thumblist && this.thumblist.review)
          this.thumblist.review();
      };


      Book.prototype.moveBy = function (step) {
        var nextPage = this._activePage + step;
        nextPage = limitAt(nextPage, this.startPage, this.endPage);

        this.gotoPage(nextPage);
      };

      Book.prototype.next = function (step) {
        if (step == null)
          step =
            (this.direction == DFLIP.DIRECTION.RTL)
              ? -this.pageMode : this.pageMode;

        this.moveBy(step);
      };

      Book.prototype.prev = function (step) {
        if (step == null)
          step =
            (this.direction == DFLIP.DIRECTION.RTL)
              ? this.pageMode : -this.pageMode;

        this.moveBy(step);
      };

      Book.prototype.updateAngle = function () {

        var startAngle = this.angles[1];
        var endAngle = this.angles[4];

        var spreadAngle = endAngle - startAngle;
        var stacks = this.stackCount;

        for (var _stackCount = 0; _stackCount < stacks; _stackCount++) {
          var clone = this.children[_stackCount];
          //start from angle[1] and end at angles[4]
          clone.angles[1] = startAngle + _stackCount * spreadAngle / (stacks * 100);
          clone.stiffness = this.stiffness;//_stackCount/stacks;
          clone.updateAngle();
        }

      };

      Book.prototype.refresh = function () {
        this.updatePage(this._activePage);
        if (this.flipCallback != null) this.flipCallback();
      };


      Book.prototype.updatePage = function (pageNumber) {
        // this.contentProvider.setLoading(pageNumber, true);
        var isRTL = (this.direction == DFLIP.DIRECTION.RTL),
          isBooklet = isBookletMode(this),
          newBaseNumber = getBasePage(pageNumber);

        var pageDivisor = isBooklet ? 1 : 2;

        pageNumber = Math.floor((pageNumber / pageDivisor));

        if (isRTL) pageNumber = this.pageCount / pageDivisor - pageNumber;

        var oldBaseNumber = this.oldBaseNumber || 0;
        var pageCount = this.pageCount / pageDivisor;
        var stackCount = this.stackCount;
        var angleShift = 0.02;
        var depth = 0.4;
        var stiffFactor = isBooklet ? 0
          : (0.5 - Math.abs(pageCount / 2 - pageNumber) / pageCount) / this.stiffness;
        var positionFactor = 1;//(stiffFactor +width);
        // var centre = Math.floor(stackCount / 2);
        var midPoint = Math.floor(stackCount / 2);//pageNumber < centre ? pageNumber //starting center pages
        // : ((pageCount - pageNumber > centre) ? centre //other pages
        //: (pageNumber + centre - pageCount)) ;//remainig center page
        //console.log(midPoint);

        //var targetIndex = midPoint;
        //if(midPoint == centre) {
        /*This sitaution is good when there is icrement or decrement by 1*/
        var isLeft = false;
        if (oldBaseNumber > pageNumber) {
          isLeft = true;
          this.children[stackCount - 1].skipFlip = true;
          this.children.unshift(this.children.pop());

          // this.contentProvider.setLoading(pageNumber, true);
        }
        else if (oldBaseNumber < pageNumber) {
          this.children[0].skipFlip = true;
          this.children.push(this.children.shift());

          // this.contentProvider.setLoading(pageNumber, true);
        }

        var remainingPages = (pageCount - pageNumber);
        var stackDepth = (5) / pageCount;
        var leftDepth = stackDepth * pageNumber / 2;
        var rightDepth = stackDepth * remainingPages / 2;
        var maxDepth = (leftDepth < rightDepth ? rightDepth : leftDepth);
        //maxDepth = maxDepth > 5 ? 5: maxDepth;
        for (var _pageCount = 0; _pageCount < stackCount; _pageCount++) {
          var page = this.children[_pageCount];//this.getObjectByName("page"+_pageCount);//this.children[_pageCount];

          var color = page.color;
          var oldAngle = page.angles[1];
          var newAngle;
          var relativePageNumber = pageNumber - midPoint + _pageCount;
          if (isRTL) relativePageNumber = isBooklet ? this.pageCount - relativePageNumber
            : Math.floor(this.pageCount / 2) - relativePageNumber - 1;

          var isHard = page.isHard = this.isPageHard(relativePageNumber);
          var oldName = page.name;


          //Sizing
          page.isEdge = false; //true;
          if (_pageCount == 0) {
            page.depth = leftDepth < depth ? depth : leftDepth;
          }
          else if (_pageCount == stackCount - 1) {
            page.depth = rightDepth < depth ? depth : rightDepth;
          }
          else {
            page.depth = depth;
            page.isEdge = false;
          }
          if (page.isFlipping == true) {
            page.depth = depth;
          }
          page.position.x = 0;

          var leftAngle = angleShift * _pageCount,
            rightAngle = 180 - angleShift * (_pageCount - midPoint) + angleShift * _pageCount;

          if (_pageCount < midPoint) {
            page.newStiffness = isHard || this.stiffness == 0 ? 0 : stiffFactor / (pageNumber / pageCount) / 4;
            newAngle = leftAngle;
            page.position.z = maxDepth - ( -_pageCount + midPoint) * depth;//(pageNumber < pageCount / 2)
            if (isLeft == true) page.position.z -= depth;

          }
          else {
            newAngle = rightAngle;
            page.newStiffness = isHard || this.stiffness == 0 ? 0
              : stiffFactor / (Math.abs(pageCount - pageNumber) / pageCount) / 4;
            page.position.z = (maxDepth - (-stackCount + _pageCount + midPoint + 1) * depth) - page.depth;//(pageNumber < pageCount / 2)

          }

          if (page.isFlipping == false) {

            if (Math.abs(oldAngle - newAngle) > 20 && page.skipFlip == false) {
              page.depth = depth;
              //we need predicted stiffness so that there is no overlap issues
              var predicted = page.stiffness;

              if (oldAngle > newAngle) {//left
                predicted = stiffFactor / (Math.abs(pageCount - pageNumber) / pageCount) / 4;
              }
              else {//right
                predicted = stiffFactor / (pageNumber / pageCount) / 4;
              }
              page.position.z += depth;//((_pageCount < midPoint) ? 0 : depth) * 2;/// 2;

              page.stiffness = isNaN(predicted) ? page.stiffness : predicted;
              page.updateAngle(true);
              page.targetStiffness = isHard ? 0 : (_pageCount < pageNumber)
                ? stiffFactor / (Math.abs(pageCount - pageNumber) / pageCount) / 4
                : stiffFactor / (pageNumber / pageCount) / 4;

              page.targetStiffness = isHard ? 0 : (isNaN(page.targetStiffness) ? page.stiffness : page.targetStiffness);

              page.isFlipping = true;

              page.tween(oldAngle, newAngle);

              if (this.preFlipCallback != null)
                this.preFlipCallback();
            } else {
              page.skipFlip = false;
              page.newStiffness = isNaN(page.newStiffness) ? 0 : page.newStiffness;
              if (page.angles[1] != newAngle || page.stiffness != page.newStiffness || page.depth != page.oldDepth) {
                page.angles[1] = page.angles[4] = newAngle;
                page.stiffness = page.newStiffness;
                page.updateAngle(true);
              }
              else {
                //console.log("skipped");
              }
            }
          }

          page.visible = isBooklet
            ? (isRTL

              ? (_pageCount < midPoint || page.isFlipping)
              : (_pageCount >= midPoint || page.isFlipping))

            : ((relativePageNumber >= 0 && relativePageNumber < pageCount) || (isBooklet && relativePageNumber == pageCount));


          if (this.requestPage != null && page.visible == true) {
            page.name = relativePageNumber.toString();
            if (page.name != oldName) {

              page.textureLoaded = false;
              page.frontImage(defaults.textureLoadFallback);
              page.frontPageStamp = "-1";
              page.frontTextureLoaded = false;
              page.thumbLoaded = false;

              // if (!isBooklet) {
              page.backImage(defaults.textureLoadFallback);
              page.backPageStamp = "-1";
              page.backTextureLoaded = false;
              // }
              this.requestPage();
            }
          }

          //if (isBooklet && _pageCount < midPoint && page.isFlipping == false)
          //	page.visible = false;

          page.oldDepth = page.depth;
          var xPos = Math.abs(page.geometry.boundingBox.max.x) < Math.abs(page.geometry.boundingBox.min.x)
            ? page.geometry.boundingBox.max.x : page.geometry.boundingBox.min.x;
          page.position.x = (page.isEdge == true && page.isFlipping == false ) ? ((_pageCount < midPoint)
            ? xPos : -xPos) : 0;
        }
        //$(".quick-hint").html(pageNumber);
        //console.log("leftDepth:" + leftDepth, "rightDepth:" + rightDepth, "midPoint:" + midPoint, "oldBaseNumber:" + oldBaseNumber, "pageNumber:" + pageNumber);
        this.oldBaseNumber = pageNumber;

        if (this.updatePageCallback != null)
          this.updatePageCallback();

      };
      //if (window.flipBook != null)flipBook.book.refresh();
      //book.activePage(book.activePage());
      Book.prototype.createCover = function (parameters) {
        parameters.width = parameters.width * 2;
        this.cover = new MOCKUP.BiFold(parameters);
        this.add(this.cover);
      };

      Book.prototype.createStack = function (parameters) {

        var colors = "red,green,blue,yellow,orange,black".split(",");

        for (var _stackCount = 0; _stackCount < this.stackCount; _stackCount++) {
          parameters.angles = [, this.stackCount - _stackCount];//[1] = (this.stackCount - _stackCount);
          parameters.stiffness = (this.stackCount - _stackCount) / 100;

          var clone = new MOCKUP.BookPaper(parameters);
          clone.angles[1] = 180;
          //clone.name = "page" + _stackCount;
          clone.index = _stackCount;
          clone.updateAngle();
          clone.textureReady = false;
          clone.textureRequested = false;
          this.add(clone);
          clone.color = colors[_stackCount];
          //for (var _count = 0; _count < 4; _count++) {
          //    clone.material.materials[_count].color = new THREE.Color(THREE.ColorKeywords[colors[_stackCount]]);
          //}
          clone.position.z = -1 * _stackCount;// * (this.mainObject.depth * 1.05);
        }
      };


      Book.prototype.shininess = function (shininess) {
        if (shininess == null) {
          return this.mainObject.shininess();
        }
        else {
          this.mainObject.shininess(shininess);
        }
      };

      Book.prototype.bumpScale = function (bumpScale) {
        if (bumpScale == null) {
          return this.mainObject.bumpScale();
        }
        else {
          this.mainObject.bumpScale(bumpScale);
        }
      };


      Book.prototype.frontImage = function (frontImage) {
        if (frontImage == null) {
          return this.mainObject.frontImage();
        }
        else {
          this.mainObject.frontImage(frontImage);
        }
      };


      Book.prototype.backImage = function (backImage) {
        if (backImage == null) {
          return this.mainObject.backImage();
        }
        else {
          this.mainObject.backImage(backImage);
        }
      };

      return Book;
    })(MOCKUP.Bundle);
    MOCKUP.Book = Book;

  }

  //base object of flipbook or other trifold objects
  var PreviewObject = (function (_super) {

    function PreviewObject(parameters) {
      parameters = parameters || {};
      //_super.call(this, parameters);
      this.type = "PreviewObject";
      var _this = this;

      _this.zoomValue = 1;
      function resizeDelay() {
        setTimeout(function () {
          _this.resize()
        }, 50);
      }

      window.addEventListener("resize", resizeDelay, false);

      this.sound = document.createElement("audio");
      this.sound.setAttribute("src", parameters.soundFile + "?ver=" + DFLIP.version);
      this.sound.setAttribute("type", "audio/mpeg");

      this.autoPlayFunction = function () {
        if (_this && _this.target.autoPlay) {
          if (_this.target.direction == DFLIP.DIRECTION.RTL)
            _this.target.prev();
          else
            _this.target.next();
        }
      };
      //this.pageMode = DFLIP.PAGE_MODE.DOUBLE;
      this.dispose = function () {

        clearInterval(this.autoPlayTimer);
        this.autoPlayTimer = null;
        this.autoPlayFunction = null;

        //complete any tweens left.
        if (this.target && this.target.children) {
          for (var count = 0; count < this.target.children.length; count++) {
            var page = this.target.children[count];
            if (page && page.currentTween) page.currentTween.stop();
          }
        }
        //first dispose internal objects
        if (this.zoomTween) {
          if (this.zoomTween.stop) this.zoomTween.stop();
          this.zoomTween = null;
        }
        if (this.container && this.container.info && this.container.info.remove)
          this.container.info.remove();

        if (this.target && this.target.dispose)
          this.target.dispose();
        this.target = null;

        if (this.stage && this.stage.dispose)
          this.stage.dispose();
        this.stage = null;

        //if (this.target && this.target.outlineContainer) this.target.outlineContainer.remove();

        if (this.ui && this.ui.dispose)
          this.ui.dispose();
        this.ui = null;

        if (this.contentProvider && this.contentProvider.dispose)
          this.contentProvider.dispose();
        this.contentProvider = null;

        window.removeEventListener("resize", resizeDelay);

      };
    }

    PreviewObject.prototype = {

      start: function () {

        this.target.gotoPage(this.target.startPage);

      },

      end: function () {
        this.target.gotoPage(this.target.endPage);
      },

      next: function () {

      },

      prev: function () {

      },

      zoom: function (delta) {

        this.pendingZoom = true;
        this.zoomDelta = delta;

        this.resize();
        this.ui.update();
      },

      resize: function () {

        var _this = this;

        if (_this.target == null ||
          _this.target.ui == null ||
          _this.target.contentProvider == null ||
          _this.target.contentProvider.viewport == null ||
          _this.target.stage == null)
          return;

        if (this.ui && this.ui.isFullscreen == true && utils.hasFullscreenEnabled() == true && utils.getFullscreenElement() == null) {
          this.ui.switchFullscreen();
        }

        //Variable Caches
        var target = _this.target,
          container = _this.container,
          options = _this.options,
          stage = target.stage,
          contentProvider = target.contentProvider,
          pageRatio = contentProvider.pageRatio,
          zoomViewport = contentProvider.zoomViewport,
          isRTL = isRTLMode(target),
          is3d = target.mode !== "css",
          isLandScape = contentProvider.pageRatio > 1,
          isWide, height, width, cameraZ, fov, zoom, maxZoom,
          sideShift = container.hasClass("df-sidemenu-open") ? 220 : 0,
          isSingle = this.target.pageMode == DFLIP.PAGE_MODE.SINGLE;

        /*SIZE CALCULATION*/
        //checking if the container height is more than the window height
        container.height(options.height);
        var containerHeight = Math.min(container.height(), $(window).height());
        container.height(containerHeight);//setting twice for failsafe


        //checking if the responsive width according to container
        var containerWidth = container.width();
        if (containerWidth < 400) {//rather than responsive lets use
          _this.container.addClass("df-xs");
        } else {
          _this.container.removeClass("df-xs");
        }

        var controlsHeight = container.find(".df-ui-controls").height();
        var paddingTop = options.paddingTop + (options.controlsPosition == DFLIP.CONTROLSPOSITION.TOP
              ? controlsHeight : 0),
          paddingRight = options.paddingRight,
          paddingBottom = options.paddingBottom + (options.controlsPosition == DFLIP.CONTROLSPOSITION.BOTTOM
              ? controlsHeight : 0),
          paddingLeft = options.paddingLeft;

        paddingTop = isNaN(paddingTop) ? 0 : limitAt(paddingTop, 0, paddingTop),
          paddingBottom = isNaN(paddingBottom) ? 0 : limitAt(paddingBottom, 0, paddingBottom),
          paddingLeft = isNaN(paddingLeft) ? 0 : limitAt(paddingLeft, 0, paddingLeft),
          paddingRight = isNaN(paddingRight) ? 0 : limitAt(paddingRight, 0, paddingRight);

        //containerHeight, containerWidth, controlsHeight above
        var stageWidth = containerWidth - sideShift, //if sideMenu for thumbnails is open?
          stageHeight = containerHeight;
        var paddingHeight = paddingTop + paddingBottom,
          paddingWidth = paddingLeft + paddingRight;

        var stageInnerWidth = stageWidth - paddingWidth,
          stageInnerHeight = stageHeight - paddingHeight;

        width = Math.floor(isSingle ? stageInnerWidth : stageInnerWidth / 2);
        height = Math.floor(width / pageRatio);

        //check if book fits by width
        isWide = height > stageInnerHeight;
        if (isWide) {
          height = stageInnerHeight;
          width = height * pageRatio;
        }

        /*ZOOM CALCULATION*/
        //update maxZoom for current Stage Dimension
        maxZoom = contentProvider.maxZoom = contentProvider.zoomViewport.height / height;

        //set to 1 if unset initally
        if (_this.zoomValue == null) _this.zoomValue = 1;
        if (contentProvider.zoomScale == null) contentProvider.zoomScale = 1;

        if (_this.pendingZoom == true && _this.zoomDelta != null) {

          var delta = _this.zoomDelta, predictedIndex, currentMaxDimension = Math.max(height, width);

          _this.zoomValue = _this.zoomDelta > 0 ? _this.zoomValue * _this.options.zoomRatio
            : _this.zoomValue / _this.options.zoomRatio;
          _this.zoomValue = limitAt(_this.zoomValue, 1, maxZoom);

          if (_this.zoomValue == 1) {
            contentProvider.zoomScale = 1;
          } else {
            predictedIndex = height * _this.zoomValue;
            //zoomStops matches the contentProvider internal calcuation and prediction stops so that the texture size won't differ
            predictedIndex = utils.zoomStops(predictedIndex, _this.options.zoomRatio, _this.zoomDelta > 0, Math.max(width, height));
            contentProvider.zoomScale = limitAt(predictedIndex / currentMaxDimension, 1, maxZoom);
          }

        }

        zoom = contentProvider.zoomScale;

        //Update Image CacheSize Index
        contentProvider.checkViewportSize(width, height, zoom);

        if (contentProvider.contentSourceType == SOURCE_TYPE.PDF) {
          //recalculation is required for pixel shift issue only if the source is PDF
          width = contentProvider.imageViewport.width / zoom;
          height = contentProvider.imageViewport.height / zoom;
        }

        if (contentProvider.zoomScale != 1) {
          this.target.container.addClass("df-zoom-enabled");
        }

        var zoomWidth = target.zoomWidth = Math.floor(width * zoom),
          zoomHeight = target.zoomHeight = Math.floor(height * zoom);
        var zoomFullWidth = zoomWidth * 2;

        if (is3d) {

          //zoomHeight is equal to target.height (normally 300) so relative calculation is required
          var proportion = zoomHeight / target.height,
            aspect = stageWidth / stageHeight;
          var relativeHeight = zoom * (height + paddingHeight) / proportion,
            relativeWidth = zoom * (width * (isSingle ? 1 : 2) + paddingWidth) / proportion;

          var focusSize = isWide ? relativeHeight : relativeWidth / aspect;
          stage.resizeCanvas(stageWidth, stageHeight);

          cameraZ = 1 / ( 2 * Math.tan(Math.PI * stage.camera.fov * 0.5 / 180) / (focusSize / zoom)) + 2.2;

          stage.camera.updateProjectionMatrix();

          stage.renderRequestPending = true;

          //pixel value to stage position value

          var shift = (paddingTop - paddingBottom) * ( target.height / height) / zoom / 2;

          //put a check if the existing gap is enough
          // _this.target.position.y = shift;
          // stage.cssScene.position.y = _this.target.position.y;

          var _reset = contentProvider.zoomScale == 1;
          if (stage.camera.position.z !== cameraZ && _this.pendingZoom == true) { //avoid recreating the tween if the target is same as before
            if (_this.zoomTween != null)
              _this.zoomTween.stop();
            _this.zoomTween = new TWEEN.Tween({
              campos: stage.camera.position.z,
              otx: stage.orbitControl.target.x,
              oty: stage.orbitControl.target.y,
              otz: stage.orbitControl.target.z
            }).delay(0)
              .to({
                  campos: cameraZ,
                  otx: 0,
                  oty: shift,
                  otz: 0
                },
                100)
              .onUpdate(function () {
                stage.camera.position.z = this.campos;
                if (_reset) {
                  stage.camera.position.y = this.oty;
                  stage.orbitControl.target = new THREE.Vector3(this.otx, this.oty, this.otz);
                }
                stage.orbitControl.update();
              }).easing(TWEEN.Easing.Linear.None)
              .onComplete(function () {
                stage.camera.position.z = cameraZ;
                if (contentProvider.zoomScale == 1) {
                  stage.camera.position.set(0, shift, cameraZ);
                  stage.orbitControl.target = new THREE.Vector3(0, shift, 0);
                }
                stage.orbitControl.update();
              })
              .start();
          }
          else {
            if (contentProvider.zoomScale == 1) {
              stage.camera.position.set(0, shift, cameraZ);
              stage.orbitControl.target = new THREE.Vector3(0, shift, 0);
            }
            /*else {
              stage.camera.position.z = cameraZ;
            }*/
            stage.orbitControl.update();
          }

          stage.orbitControl.update();
          stage.orbitControl.mouseButtons.ORBIT = zoom != 1 ? -1 : THREE.MOUSE.RIGHT;
          stage.orbitControl.mouseButtons.PAN = zoom != 1 ? THREE.MOUSE.LEFT : -1;

        }
        else {

          target.pageWidth = Math.round(width);
          target.fullWidth = target.pageWidth * 2;
          target.height = Math.round(height);

          var shiftHeight = target.shiftHeight = Math.round(limitAt((zoomHeight - stageHeight + paddingHeight) / 2, 0, zoomHeight)),
            shiftWidth = target.shiftWidth = Math.round(limitAt((zoomFullWidth - stageWidth + paddingWidth ) / 2, 0, zoomFullWidth));

          if (zoom == 1) {
            target.left = 0;
            target.top = 0;
          }
          target.stage.css({
            top: -shiftHeight,
            bottom: -shiftHeight,
            right: -shiftWidth + (isRTL ? sideShift : 0),
            left: -shiftWidth + (isRTL ? 0 : sideShift),
            paddingTop: paddingTop,
            paddingRight: paddingRight,
            paddingBottom: paddingBottom,
            paddingLeft: paddingLeft,
            transform: "translate3d(" + target.left + "px," + target.top + "px,0)"
          });
          target.stageHeight = stage.height();

          target.wrapper.css({
            width: zoomFullWidth,
            height: zoomHeight,
            marginTop: (containerHeight - zoomHeight - paddingHeight ) > 0
              ? (containerHeight - paddingHeight - zoomHeight) / 2
              : 0
          });

          var wrapperSize = Math.floor((distOrigin(width, height)) * zoom);

          target.stage.find(".df-page-wrapper").width(wrapperSize).height(wrapperSize);

          target.stage.find(".df-book-page, .df-page-front , .df-page-back, .df-page-fold-inner-shadow").height(zoomHeight).width(zoomWidth);

        }

        _this.checkCenter({type: "resize"});

        if (contentProvider.zoomScale == 1) {
          this.target.container.removeClass("df-zoom-enabled");
        }

        if (target.thumblist) {
          target.thumblist.reset($(target.thumblist.container).height());
        }

        _this.pendingZoom = false;

      },

      playSound: function () {
        try {
          if (this.options && this.options.soundEnable == true) {
            this.sound.currentTime = 0;
            this.sound.play();
          }
        } catch (error) {

        }
      },

      setPageMode: function (isSingle) {
        if (isSingle == true) {
          this.ui.pageMode.addClass(this.options.icons['doublepage']);
          this.ui.pageMode.html("<span>" + this.options.text.doublePageMode + "</span>");
          this.ui.pageMode.attr("title", this.options.text.doublePageMode);
          this.target.pageMode = DFLIP.PAGE_MODE.SINGLE;
        }
        else {
          this.ui.pageMode.removeClass(this.options.icons['doublepage']);
          this.ui.pageMode.html("<span>" + this.options.text.singlePageMode + "</span>");
          this.ui.pageMode.attr("title", this.options.text.singlePageMode);
          this.target.pageMode = DFLIP.PAGE_MODE.DOUBLE;
        }

        if (this.target && this.target.singlePageMode == DFLIP.SINGLE_PAGE_MODE.BOOKLET) {
          this.target.reset();
        }

        this.resize();
      },
      setAutoPlay: function (isPlay) {
        if (this.options.autoPlay) {
          isPlay = isPlay == true;
          var text = isPlay ? this.options.text.pause : this.options.text.play;
          this.ui.play.toggleClass(this.options.icons['pause'], isPlay);
          this.ui.play.html("<span>" + text + "</span>");
          this.ui.play.attr("title", text);

          clearInterval(this.autoPlayTimer);
          if (isPlay) {
            this.autoPlayTimer = setInterval(this.autoPlayFunction, this.options.autoPlayDuration);
          }

          this.target.autoPlay = isPlay;
        }
      },
      height: function (height) {
        if (height == null) {
          return this.container.height();
        } else {
          this.options.height = height;
          this.container.height(height);
          this.resize();
        }
      },
      /**
       *checks whether the book is closed and needs to be centered
       */
      checkCenter: function (options) {

        options = options == null ? {} : options;
        this.centerType = this.centerType || "start";
        var target = this.target;
        var singleShift = 0, left = 0, right = 0;
        var basePage = utils.getBasePage(target._activePage);
        var isEven = target._activePage % 2 == 0;
        var isRTL = target.direction == DFLIP.DIRECTION.RTL;
        var isSingle = target.pageMode == DFLIP.PAGE_MODE.SINGLE,
          isBooklet = isSingle && target.singlePageMode == DFLIP.SINGLE_PAGE_MODE.BOOKLET;
        var stageWidth = target.stage.width(),
          width;

        if (target.mode == 'css') {
          width = target.wrapper.width();
          //calculate the excess shift required for correction in case width is too small
          singleShift = Math.max((width - stageWidth) / 2, 0);

          left = -width / 4;
          right = width / 4;

          if (basePage == 0 || isBooklet) {
            target.wrapper.css({
              left: isSingle
                ? isRTL ? right - singleShift : left - singleShift
                : isRTL ? right : left
            });
            target.shadow.css({width: '50%', left: isRTL ? 0 : '50%', transitionDelay: ''});
          }
          else if (basePage == target.pageCount) {
            target.wrapper.css({
              left: isSingle
                ? isRTL ? left - singleShift : right - singleShift
                : isRTL ? left : right
            });
            target.shadow.css({width: '50%', left: isRTL ? '50%' : 0, transitionDelay: ''});
          }
          else {
            target.wrapper.css({
              left: isSingle
                ? isRTL
                      ? (isEven ? left - singleShift : right - singleShift )
                      : (isEven ? right - singleShift : left - singleShift )
                : 0
            });
            target.shadow.css({
              width: '100%',
              left: 0,
              transitionDelay: (parseInt(target.duration, 10) + 50) + 'ms'
            });
          }

          target.wrapper.css({transition: options.type == "resize" ? "none" : ""});

        }
        else if (target.stage != null) {
          var init = target.position.x, end;
          singleShift = target.width / 4;
          width = target.width;
          left = -width / 2;
          right = width / 2;

          if (basePage == 0 || isBooklet) {
            end = isRTL ? right : left;
          }
          else if (basePage == target.pageCount) {
            end = isRTL ? left : right;
          }
          else {
            end = isSingle
              ? isRTL
                    ? (isEven ? left : right )
                    : (isEven ? right : left )
              : 0;
          }
          //create a centertween
          if (end !== this.centerEnd) { //avoid recreating the tween if the target is same as before
            this.centerTween = new TWEEN.Tween({x: init}).delay(0)
              .to({x: end}, target.duration)
              .onUpdate(function () {
                target.position.x = this.x;
                target.stage.cssScene.position.x = this.x;
              }).easing(target.ease)
              .start();
            this.centerEnd = end;

          }
        }
        // log("checkcenter at : " + left);
      },

      width: function (width) {
        if (width == null) {
          return this.container.width();
        } else {
          this.options.width = width;
          this.container.width(width);
          this.resize();
        }
      }

    };

    return PreviewObject;

  })({});

  DFLIP.PreviewObject = PreviewObject;

  //contentprovider that handles the source of book
  var ContentProvider = (function (_super) {
    __extends(ContentProvider, _super);


    function ContentProvider(contentSource, callback, parameters, flipbook) {

      parameters = parameters || {};

      var _this = this;

      _this.contentRawSource = contentSource || [defaults.textureLoadFallback];
      _this.contentSource = _this.contentRawSource;
      _this.contentSourceType = null;
      _this.minDimension = parameters.minTextureSize || 256;
      _this.maxDimension = parameters.maxTextureSize || 2048;
      _this.pdfRenderQuality = parameters.pdfRenderQuality || DFLIP.defaults.pdfRenderQuality;
      _this.flipbook = flipbook;
      _this.waitPeriod = 50;
      _this.maxLength = 297;
      _this.enableDebug = false;
      _this.zoomScale = 1;
      _this.maxZoom = 2;
      _this.options = parameters;
      _this.outline = parameters.outline;
      _this.links = parameters.links;
      _this.html = parameters.html;
      _this.isCrossOrigin = parameters.isCrossOrigin;

      _this.normalViewport = {
        height: 297,
        width: 210,
        scale: 1
      };
      _this.viewport = {
        height: 297,
        width: 210,
        scale: 1
      };
      _this.imageViewport = {
        height: 297,
        width: 210,
        scale: 1
      };
      _this.bookSize = {
        height: 297,
        width: 210
      }
      _this.zoomViewport = {
        height: 297,
        width: 210
      };

      _this.thumbsize = 128;
      _this.cacheIndex = 256; //index of bigger dimension height or width
      _this.cache = [];

      _this.pageRatio = parameters.pageRatio || _this.viewport.width / _this.viewport.height;

      //texture load control so that it wont delay the transition
      _this.textureLoadTimeOut = null;

      _this.type = "TextureLibrary";

      if (Array === _this.contentSource.constructor || Array.isArray(_this.contentSource) || _this.contentSource instanceof Array) {

        //case of images and html content
        _this.contentSourceType = SOURCE_TYPE.IMAGE;
        _this.pageCount = _this.contentSource.length;

        //_this.setLoading(1, true);

        // Make in memory copy of image to avoid css issues
        $("<img/>")
          .attr("src", _this.contentSource[0])
          .on('load', (function () {
            _this.viewport.height = this.height;
            _this.viewport.width = this.width;

            _this.pageRatio = _this.viewport.width / _this.viewport.height;
            _this.bookSize = {
              width: (_this.pageRatio > 1 ? 1 : _this.pageRatio) * _this.maxLength,
              height: _this.maxLength / (_this.pageRatio < 1 ? 1 : _this.pageRatio)
            };
            _this.zoomViewport = {
              width: (_this.pageRatio > 1 ? 1 : _this.pageRatio) * _this.maxDimension,
              height: _this.maxDimension / (_this.pageRatio < 1 ? 1 : _this.pageRatio)
            };

            _this.linkService = new PDFLinkService();

            $(this).off();

            if (_this.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL) {
              _this.pageCount = _this.contentSource.length * 2 - 2;
              if (_this.options.webgl == true)
                _this.requiresImageTextureScaling = true;
            }

            if (callback != null) {
              callback(_this);
              callback = null;
            }
            //_this.setLoading(1);

            //console.log(_this.zoomViewport);
            log(this.height + ":" + this.width);
            //pic_real_width = this.width;   // Note: $(this).width() will not
            //pic_real_height = this.height; // work for in memory images.
            //moved to set target function
            //_this.
            // ();


          }));

      }
      else if (typeof _this.contentSource == 'string' || _this.contentSource instanceof String) { //case of link to pdf file

        var processSource = function () {
          if (_this) {
            //configurePDFJS(PDFJS);
            PDFJS.workerSrc = defaults.pdfjsWorkerSrc;

            _this.contentSourceType = SOURCE_TYPE.PDF;
            //PDFJS.disableWorker = true;
            PDFJS.disableAutoFetch = true;
            PDFJS.disableStream = true;
            if (isSafari || isIOS || _this.options.disableFontFace == true) {
              PDFJS.disableFontFace = isSafari || isIOS || _this.options.disableFontFace == true;
            }
            PDFJS.imageResourcesPath = defaults.imageResourcesPath;
            PDFJS.cMapUrl = defaults.cMapUrl;
            PDFJS.cMapPacked = !0;
            PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK;

            var loading = _this.loading = PDFJS.getDocument(_this.options.docParameters ? _this.options.docParameters
              : {
                url: utils.httpsCorrection(contentSource),
                rangeChunkSize: isNaN(DFLIP.defaults.rangeChunkSize) ? 524288 : DFLIP.defaults.rangeChunkSize
              });

            loading.then(function sourceLoaded(pdf) {

                _this.pdfDocument = pdf;
                pdf.getPage(1).then(function (page) {
                  _this.normalViewport = page.getViewport(1);
                  _this.viewport = page.getViewport(1);
                  _this.viewport.height = _this.viewport.height / 10;
                  _this.viewport.width = _this.viewport.width / 10;

                  _this.pageRatio = _this.viewport.width / _this.viewport.height;

                  _this.bookSize = {
                    width: (_this.pageRatio > 1 ? 1 : _this.pageRatio) * _this.maxLength,
                    height: _this.maxLength / (_this.pageRatio < 1 ? 1 : _this.pageRatio)
                  };

                  _this.zoomViewport = {
                    width: (_this.pageRatio > 1 ? 1 : _this.pageRatio) * _this.maxDimension,
                    height: _this.maxDimension / (_this.pageRatio < 1 ? 1 : _this.pageRatio)
                  };

                  _this.refPage = page;

                  //console.log(_this.zoomViewport);

                  //check if intenal pages are of double sizes.
                  if (pdf.numPages > 1) {
                    pdf.getPage(2).then(function (page) {
                      if (_this.options.pageSize == DFLIP.PAGE_SIZE.AUTO) {
                        var _viewport = page.getViewport(1);
                        //Update: doing width check gives false alarm if the internal pages are of different sizes yet follow same aspect ratio
                        //if (_viewport.width > _this.normalViewport.width * 1.5) {
                        var _pageRatio = _viewport.width / _viewport.height;
                        if (_pageRatio > _this.pageRatio * 1.5) {
                          _this.options.pageSize = DFLIP.PAGE_SIZE.DOUBLEINTERNAL;
                          _this.pageCount = pdf.numPages * 2 - 2;
                        }
                        else {
                          _this.options.pageSize = DFLIP.PAGE_SIZE.SINGLE;
                        }
                      }
                      if (callback != null) {
                        callback(_this);
                        callback = null;
                      }
                    });
                  } else {
                    if (callback != null) {
                      callback(_this);
                      callback = null;
                    }
                  }

                });
                _this.linkService = new PDFLinkService();
                _this.linkService.setDocument(pdf, null);

                //moved to set target function
                //_this.initThumbs();
                _this.pageCount = pdf.numPages;
                _this.contentSource = pdf;

              },
              function loadingError(error) {
                if (_this) {
                  var cors = "", tmp = document.createElement('a');
                  tmp.href = _this.contentSource;

                  if (tmp.hostname !== window.location.hostname)
                    cors = "CROSS ORIGIN!! ";

                  _this.updateInfo(cors + "Cannot access file!  " + _this.contentSource);
                }
              });

            loading.onProgress = function getDocumentProgress(progressData) {
              if (_this) {
                var percentage = 100 * progressData.loaded / progressData.total;
                if (isNaN(percentage)) {
                  if (progressData && progressData.loaded) {
                    _this.updateInfo("Loading PDF " + (Math.ceil(progressData.loaded / 10000) / 100).toString() + "MB ...");
                  } else {
                    _this.updateInfo("Loading PDF ...");
                  }
                } else {
                  _this.updateInfo("Loading PDF " + percentage.toString().split(".")[0] + "% ...");
                }
              }
            };
          }
        };
        var checkCORS = function () {
          if (_this) {
            defaults.pdfjsWorkerSrc += "?ver=" + DFLIP.version;

            _this.updateInfo("Loading PDF Worker ...");
            var tmp = document.createElement('a');
            tmp.href = defaults.pdfjsWorkerSrc;

            if (tmp.hostname !== window.location.hostname) {
              _this.updateInfo("Loading PDF Worker CORS ...");
              $.ajax({
                url: defaults.pdfjsWorkerSrc,
                cache: true,
                success: function (data) {
                  defaults.pdfjsWorkerSrc = DFLIP.createObjectURL(data, "text/javascript");
                  processSource();
                }
              });
            }
            else {
              processSource();
            }
          }
        };
        if (window.PDFJS == null) {
          if (_this) {
            _this.updateInfo("Loading PDF Service ...");
            //getScript(defaults.pdfjsCompatibilitySrc + "?ver=" + DFLIP.version, function () {

            getScript(defaults.pdfjsSrc + "?ver=" + DFLIP.version, function () {

              if (typeof define === 'function' && define.amd) {
                _this.updateInfo("Loading PDF Service (require) ...");
                require.config({paths: {'pdfjs-dist/build/pdf.worker': defaults.pdfjsWorkerSrc.replace(".js", "")}});
                require(['pdfjs-dist/build/pdf'], function (pdf) {
                  checkCORS();
                });
              } else {
                checkCORS();
              }
            }, function () {
              _this.updateInfo("Unable to load PDF service..");
            });
            //});
          }
        }
        else {

          processSource();
        }

      }
      else {
        console.error("Unknown source type. Please check documentation for help");
      }

      this.dispose = function () {
        if (_this.loading && _this.loading.destroy) {
          _this.loading.destroy();
        }
        _this.loading = null;
        if (_this.textureLoadTimeOut) {
          clearTimeout(_this.textureLoadTimeOut);
          _this.textureLoadTimeOut = null;
        }
        if (this.targetObject) {
          if (this.targetObject.thumbContainer && this.targetObject.thumbContainer.remove)
            this.targetObject.thumbContainer.remove();
          if (this.targetObject.outlineContainer && this.targetObject.outlineContainer.remove)
            this.targetObject.outlineContainer.remove();
          if (this.targetObject.dispose) this.targetObject.dispose();
          this.targetObject.processPage = null;
          this.targetObject.requestPage = null;
          if (this.targetObject.container && this.targetObject.container.off)
            this.targetObject.container.off();

        }
        if (this.pdfDocument && this.pdfDocument.destroy) this.pdfDocument.destroy();
        if (this.linkService && this.linkService.dispose) this.linkService.dispose();
        if (this.outlineViewer && this.outlineViewer.dispose) this.outlineViewer.dispose();
        if (this.thumblist && this.thumblist.dispose) {
          this.thumblist.review = null;
          this.thumblist.dispose();
        }

        this.activeThumb = null;
        this.targetObject = null;
        this.pdfDocument = null;
        this.linkService = null;
        this.outlineViewer = null;
        this.thumblist = null;
        _this = null;
      };
      return this;
    }

    ContentProvider.prototype.updateInfo = function (info) {
      if (this.flipbook && this.flipbook.updateInfo) {
        this.flipbook.updateInfo(info);
      }
    };

    ContentProvider.prototype.initThumbs = function () {

      var _this = this;
      if (_this.cache[_this.thumbsize] == null) _this.cache[_this.thumbsize] = [];
      var thumbLoadTimeOut;
      var review = function () {
        clearTimeout(thumbLoadTimeOut);
        thumbLoadTimeOut = setTimeout(function () {

          thumbLoadTimeOut = setTimeout(reviewThumbs, _this.waitPeriod / 2);

        }, _this.waitPeriod);
      };

      var reviewThumbs = function () {
        var requestCount = 0;
        if (Date.now() - _this.thumblist.lastScrolled < 100) {
          requestCount = 1;
        } else {
          _this.targetObject.container.find(".df-thumb-container .df-vrow").each(function () {
            var thumb = $(this);
            if (!thumb.hasClass("df-thumb-loaded")) {
              requestCount++;
              var id = $(this).attr("id").replace("df-thumb", "");
              _this.getPage(id, review, true);
              thumb.addClass("df-thumb-loaded");
              return false;
            }
          });
          if (requestCount == 0) {
            clearTimeout(thumbLoadTimeOut);
          }
        }

        if (requestCount > 0) {
          review();
        }
        //move to thumb if thumb is on
        if (_this.activeThumb != _this.targetObject._activePage) {
          var thumbVisible = _this.targetObject.thumbContainer != null && _this.targetObject.thumbContainer.hasClass("df-sidemenu-visible");

          if (thumbVisible) {
            var wrapper = _this.thumblist.container;
            var cScroll = wrapper.scrollTop,
              cHeight = wrapper.getBoundingClientRect().height;

            var thumb = _this.targetObject.thumbContainer.find("#df-thumb" + _this.targetObject._activePage);
            if (thumb.length > 0) {//TODO direct jumps won't work..
              _this.targetObject.thumbContainer.find(".df-selected").removeClass("df-selected");
              thumb.addClass("df-selected");
              //js calculation
              thumb = thumb[0];


              if (cScroll + cHeight < thumb.offsetTop + thumb.scrollHeight)
                thumb.scrollIntoView(false);
              else if (cScroll > thumb.offsetTop)
                thumb.scrollIntoView();

              _this.activeThumb = _this.targetObject._activePage;
            }
            else {
              $(wrapper).scrollTop(_this.targetObject._activePage * 124);
              review();
            }
          }
        }
      };

      _this.thumblist = _this.targetObject.thumblist = new ThumbList({
        //w: 128 * _this.viewport.width/_this.viewport.height,
        h: 500,
        addFn: function (row) {

        },
        scrollFn: review,
        itemHeight: 128,
        totalRows: _this.pageCount,
        generatorFn: function (row) {
          var el = document.createElement("div");
          var pageNumber = row + 1;
          el.id = "df-thumb" + pageNumber;
          var elText = document.createElement("div");
          elText.innerHTML = pageNumber;
          el.appendChild(elText);
          //el.style.position = "absolute";
          //el.callback = function_this.getPage(pageNumber,null,true);
          return el;
        }
      });

      _this.thumblist.lastScrolled = Date.now();
      _this.thumblist.review = review;
      review();

      //_this.thumblist.container.classList.add('thumb-container');
      var thumbContainer = $('<div>').addClass("df-thumb-container df-sidemenu-visible df-sidemenu");
      thumbContainer.append($(_this.thumblist.container).addClass("df-thumb-wrapper"));
      _this.targetObject.thumbContainer = thumbContainer;
      _this.targetObject.container.append(thumbContainer);

      var sideMenuClose = $(html.div, {
        class: "df-ui-btn df-ui-sidemenu-close ti-close"
      });
      thumbContainer.append(sideMenuClose);
      _this.thumblist.reset($(_this.thumblist.container).height());
      _this.targetObject.container.on('click', '.df-thumb-container .df-vrow', function (e) {
        e.stopPropagation();
        var id = $(this).attr("id").replace("df-thumb", "");
        _this.targetObject.gotoPage(parseInt(id, 10));
      });
    };

    ContentProvider.prototype.initOutline = function () {
      var _this = this;
      var outlineContainer = $('<div>').addClass("df-outline-container df-sidemenu");
      var outlineWrapper = $('<div>').addClass("df-outline-wrapper");

      var sideMenuClose = $(html.div, {
        class: "df-ui-btn df-ui-sidemenu-close ti-close"
      });

      outlineContainer.append(sideMenuClose).append(outlineWrapper);
      _this.targetObject.container.append(outlineContainer);
      _this.targetObject.outlineContainer = outlineContainer;

      _this.outlineViewer = new BookMarkViewer({
        container: outlineWrapper[0],
        linkService: _this.linkService,
        outlineItemClass: "df-outline-item",
        outlineToggleClass: "df-outline-toggle",
        outlineToggleHiddenClass: "df-outlines-hidden"
      });

      function processOutline(outline) {

        if (_this.options.overwritePDFOutline == true) {
          outline = [];
        }
        outline = outline || [];

        if (_this.outline) {
          for (var count = 0; count < _this.outline.length; count++) {
            _this.outline[count].custom = true;
            if (outline) outline.push(_this.outline[count]);
          }
          /*                    _this.outline.forEach(function(v) {
           //v.custom = true;
           this.push(v);
           }, this);
           outline.push(_this.outline)*/
        }

        _this.outlineViewer.render({outline: outline});
      }

      if (_this.pdfDocument) {
        _this.pdfDocument.getOutline().then(function (outline) {
          processOutline(outline);
        });
      }
      else {
        processOutline([]);
      }

      if (_this.options.autoEnableOutline == true) {
        _this.targetObject.ui.outline.trigger("click");
      }

      if (_this.options.autoEnableThumbnail == true) {
        _this.targetObject.ui.thumbnail.trigger("click");
      }

    };

    ContentProvider.prototype.checkViewportSize = function (width, height, zoom) {
      var _this = this;
      var target = _this.targetObject;
      var zoomWidth = width * zoom,
        zoomHeight = height * zoom;

      var oldCacheSize = _this.cacheIndex;

      /*            var height = target.mode == "css"
       ? (target.container.height() - (target.stage.innerWidth() - target.stage.width()) )
       : target.stage.height();

       var width = height * _this.normalViewport.width / _this.normalViewport.height;*/

      //var zoom = _this.zoomScale != 1;

      if (_this.contentSourceType == SOURCE_TYPE.PDF) {


        /*                _this.viewport.height = height;
         _this.viewport.width = width;*/
        _this.cacheIndex = Math.ceil(Math.max(zoomWidth, zoomHeight));

        // if (zoom !== 1) {

        _this.cacheIndex = Math.floor(Math.max(zoomWidth, zoomHeight));// * _this.zoomScale;//nearestPowerOfTwo(Math.max(_this.viewport.width,_this.viewport.height));
        // _this.cacheIndex = Math.floor(utils.zoomStops(Math.max(zoomWidth, zoomHeight), _this.options.zoomRatio, oldCacheSize < _this.cacheIndex, Math.max(width, height)));

        // }

        _this.cacheIndex = limitAt(_this.cacheIndex * defaults.pixelRatio, _this.minDimension, _this.maxDimension);
        //removed to force internal page size fit incase the internal pages are of different sizes.
        // _this.cacheScale = _this.cacheIndex / Math.max(_this.normalViewport.width, _this.normalViewport.height);

        if (_this.cache[_this.cacheIndex] == null) _this.cache[_this.cacheIndex] = [];

        if (oldCacheSize !== _this.cacheIndex) {
          for (var pageCount = 0; pageCount < target.children.length; pageCount++) {
            var page = target.children[pageCount];
            //page.name = '-2';
          }
          target.refresh();
        }

        //if(zoom !==1){
        //	zoomHeight = height> width ? _this.cacheIndex : _this.cacheIndex * _this.pageRatio;
        //}
        _this.imageViewport = _this.refPage.getViewport(zoomHeight / _this.normalViewport.height);
        _this.viewport = (target.mode == "css") ? _this.imageViewport
          : _this.refPage.getViewport(_this.bookSize.height / _this.normalViewport.height);

        log(_this.cacheIndex);

        var div = target.container.find(".linkAnnotation"),
          viewportClone = _this.viewport.clone({dontFlip: true});
        div.css({
          transform: 'matrix(' + viewportClone.transform.join(',') + ')'
        });
        //_this.zoomScale = (zoom == true) ? _this.normalViewport.height * _this.viewport.scale / _this.viewport.height : 1;

      }
      else {
        if (_this.cache[_this.cacheIndex] == null) _this.cache[_this.cacheIndex] = [];
        /*                _this.cacheIndex = _this.zoomScale == 1 ? limitAt(_this.cacheIndex, _this.minDimension, _this.maxDimension) : _this.maxDimension;*/

        //_this.zoomScale = (zoom == true) ? _this.zoomViewport.height / height : 1;
      }

      //_this.zoomScale = (zoom == true) ? _this.zoomViewport.height / height : 1;
    };

    ContentProvider.prototype.getCache = function (index, isThumb) {
      return (isThumb == true)
        ? this.cache[this.thumbsize] == null ? null : this.cache[this.thumbsize][index]
        : this.cache[this.cacheIndex] == null ? null : this.cache[this.cacheIndex][index];
    };

    ContentProvider.prototype.setCache = function (index, src, isThumb, cacheIndexSize) {
      if (isThumb == true) {
        if (this.cache[this.thumbsize] != null) this.cache[this.thumbsize][index] = src;
      }
      else {
        var cacheIndex = cacheIndexSize == null ? this.cacheIndex : cacheIndexSize;
        if (this.cache[cacheIndex] != null)
          this.cache[cacheIndex][index] = src;
      }

    };

    ContentProvider.prototype.setTarget = function (targetObject) {
      var _this = this;
      if (targetObject == null) {
        return this.targetObject;
      }
      else {
        this.targetObject = targetObject;
        targetObject.contentProvider = this;

        targetObject.container.removeClass("df-loading df-init");

        //_this.initThumbs();

        if (_this.linkService != null) {
          _this.linkService.setViewer(targetObject);

          _this.initOutline();
        }

        targetObject.processPage = function (pageNumber, callback) {
          if (pageNumber > 0 && pageNumber <= _this.pageCount) {
            //log("Loading page :" + pageNumber);
            _this.getPage(pageNumber, callback);
          }
          else {
            _this.setPage(pageNumber, defaults.textureLoadFallback, callback);
            //log("Invalid PageNumber :" + pageNumber);
          }
        };

        targetObject.requestPage = function () {

          _this.review("Request");

        };

        if (targetObject.resize != null)
          targetObject.resize();

      }
    };

    ContentProvider.prototype.review = function (message) {
      var _this = this;
      message = message || "timer review";
      clearTimeout(_this.textureLoadTimeOut);
      _this.textureLoadTimeOut = setTimeout(function () {

        _this.textureLoadTimeOut = setTimeout(_this.reviewPages, _this.waitPeriod / 2, _this, message);

      }, _this.waitPeriod);
    };

    ContentProvider.prototype.reviewPages = function (_this, message) {
      _this = _this || this;
      var target = _this.targetObject;

      if (target == null) return;

      var isBooklet = isBookletMode(target);
      if (message != null) log(message);
      var requiresRevisit = false;
      var pageCount, page;

      for (pageCount = 0; pageCount < _this.targetObject.children.length; pageCount++) {
        page = target.children[pageCount];
        if (page.isFlipping == true) { //requires revisit
          requiresRevisit = true;
          break;
        }
      }
      if (requiresRevisit == false) {

        var pageLength = target.children.length > 3 ? 3 : target.children.length;
        var midPoint = pageLength / 2;

        var basePage = isBooklet ? target._activePage : getBasePage(target._activePage);
        _this.baseNumber = basePage;

        if (_this.zoomScale > 1) {
          pageLength = 1;
        }

        for (pageCount = 0; pageCount < pageLength; pageCount++) {

          var dividend = Math.floor(pageCount / 2);
          var diff = pageCount % 2 == 0
            ? -dividend * (isBooklet ? 1 : 2)
            : (dividend == 0 ? 1 : dividend) * (isBooklet ? 1 : 2);

          var frontPageNumber = basePage + diff,
            backPageNumber = basePage + diff + 1;

          var page1 = target.getPageByNumber(frontPageNumber),
            page2 = target.getPageByNumber(backPageNumber),
            reqFrontPageStamp = frontPageNumber + "|" + _this.cacheIndex,
            reqBackPageStamp = backPageNumber + "|" + _this.cacheIndex;


          var requestCount = 0;
          if (page1 != null && page1.frontPageStamp != reqFrontPageStamp && page1.visible == true) {
            page1.frontTextureLoaded = false;
            target.processPage(frontPageNumber, function () {
              _this.review("Batch Call");
            });
            page1.frontPageStamp = reqFrontPageStamp;
            requestCount++;
          }
          if (page2 != null && page2.backPageStamp != reqBackPageStamp && page2.visible == true && !isBooklet) {
            page2.backTextureLoaded = false;
            target.processPage(backPageNumber, function () {
              _this.review("Batch Call");
            });
            page2.backPageStamp = reqBackPageStamp;
            requestCount++;
          }

          //diff is 0 only at the open pages
          if (diff == 0 && _this.annotedPage !== basePage) {// && target.mode !== "css") {
            _this.getAnnotations(frontPageNumber);
            if (!isBooklet) _this.getAnnotations(backPageNumber);
            _this.annotedPage = basePage;
          }

          if (requestCount > 0) {
            break;
          }
        }
        if (requestCount == 0) {
          if (target.mode !== "css") {
            _this.setLoading(basePage);
          }
          else {
            // _this.setLoading(basePage);
            // _this.setLoading(basePage + 1);
          }
        }
      }
      else {
        _this.review("Revisit request");
        if (_this.annotedPage != null && target.mode !== "css") {
          var baseActive = getBasePage(target._activePage);
          $(target.getContentLayer(baseActive)).html("");
          $(target.getContentLayer(baseActive + 1)).html("");
          _this.annotedPage = null;
        }
      }

    };

    ContentProvider.prototype.getPage = function (pageNumber, callbackFunction, isThumb) {
      var _this = this;

      pageNumber = parseInt(pageNumber, 10);
      var _pageNumber = pageNumber;
      var source = _this.contentSource;
      if (pageNumber <= 0 && pageNumber >= _this.pageCount) {
        _this.setPage(pageNumber, defaults.textureLoadFallback, callbackFunction, isThumb);
      }
      else {
        if (_this.contentSourceType == SOURCE_TYPE.PDF) {
          if (_this.getCache(pageNumber, isThumb) != null) {
            _this.setPage(pageNumber, _this.getCache(pageNumber, isThumb), callbackFunction, isThumb);
            log("Page " + pageNumber + " loaded from cache");
          }
          else {
            if (isThumb !== true) _this.setLoading(pageNumber, true);

            if (_this.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL && pageNumber > 2) {
              _pageNumber = Math.ceil((pageNumber - 1) / 2) + 1;
            }
            source.getPage(_pageNumber, isThumb).then(function (page) {
              renderPage(page, pageNumber, callbackFunction, isThumb);
            });
          }
        }
        else if (_this.contentSourceType == SOURCE_TYPE.IMAGE || _this.contentSourceType == SOURCE_TYPE.HTML) {
          if (_this.getCache(pageNumber, isThumb) != null) {
            _this.setPage(pageNumber, _this.getCache(pageNumber, isThumb), callbackFunction, isThumb);
            log("Page " + pageNumber + " loaded from cache");
          }
          else {
            if (isThumb !== true) _this.setLoading(pageNumber, true);

            if (_this.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL && pageNumber > 2) {
              _pageNumber = Math.ceil((pageNumber - 1) / 2) + 1;
            }

            //if (_this.isCrossOrigin == null) {
            //
            //	_this.setCache(pageNumber, source[_pageNumber - 1], isThumb, _this.cacheIndex);
            //	_this.setPage(pageNumber, source[_pageNumber - 1], callbackFunction, isThumb);
            //
            //	if (callbackFunction != null) callbackFunction();
            //
            //} else {
            loadImage(source[_pageNumber - 1], function (src) {

              _this.setCache(pageNumber, src, isThumb, _this.cacheIndex);
              _this.setPage(pageNumber, src, callbackFunction, isThumb);

              if (callbackFunction != null) callbackFunction();

            }, _this.isCrossOrigin);
            //}
          }

          //_this.setPage(pageNumber, source[pageNumber - 1], callbackFunction, isThumb);
        }
      }

      function loadImage(src, callback, isCrossOrigin) {

        var img = new Image;

        img.crossOrigin = "Anonymous";

        img.onload = function () {

          if (isCrossOrigin == true) {
            var canvas = document.createElement("canvas"),
              ctx = canvas.getContext("2d");
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img, 0, 0);
            //localStorage.setItem( "savedImageData", canvas.toDataURL("image/png") );

            if (defaults.canvasToBlob == true) {
              canvas.toBlob(function (blob) {
                var src = DFLIP.createObjectURL(blob, "image/jpeg");

                if (callback != null) callback(src);

              }, "image/jpeg", 0.85)


            }
            else {
              if (callback != null) callback(canvas);
            }
          }
          else {
            if (callback != null) callback(src);
          }
          //$(this).off();
          img.onload = null;
          img = null;

        };

        img.src = src;

        // make sure the load event fires for cached images too
        if (img.complete || img.complete === undefined) {
          img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
          img.src = src;
        }

      }

      function renderPage(page, pageNumber, callbackFunction, isThumb) {


        var forceFit = _this.options.forceFit;
        var isDoublePage = _this.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL && pageNumber > 1 && pageNumber < _this.pageCount;
        var widthFix = isDoublePage && forceFit ? 2 : 1;

        /*                var heightScale = _this.pageRatio < 1
         ? _this.cacheScale
         : _this.cacheScale / _this.pageRatio;*/
        //_this.cacheScale = _this.cacheIndex / Math.max(_this.normalViewport.width, _this.normalViewport.height);
        //scales are calculated based on perpage in case per page fitting is required.
        var viewport = forceFit ? page.getViewport(1) : _this.normalViewport;

        var scale = _this.cacheIndex / Math.max(viewport.width / widthFix, viewport.height);//heightScale /_this.normalViewport.height;
        if (_this.webgl == true) {
          scale = nearestPowerOfTwo(_this.cacheIndex) / (_this.pageRatio > 1
              ? viewport.width / widthFix : viewport.height);
        }

        var canvas = document.createElement('canvas');
        var start = performance.now();

        var requestedCacheSize = _this.cacheIndex;

        var context = canvas.getContext('2d');

        // scale = scale * defaults.pixelRatio;

        if (isThumb == true) {
          scale = _this.thumbsize / _this.normalViewport.height;
        }

        canvas.height = Math.round(viewport.height * scale); //causes fluctuation in value like 22.99999 as 22
        canvas.width = Math.round(viewport.width / widthFix * scale);

        if (_this.targetObject.mode == 'css' && Math.abs(_this.targetObject.zoomHeight - canvas.height) < 2) {
          canvas.height = _this.targetObject.zoomHeight + 0; //causes fluctuation in value like 22.99999 as 22
          canvas.width = _this.targetObject.zoomWidth + 0;
        }

        viewport = page.getViewport(scale);
        log("rendering " + pageNumber + " at " + canvas.width + "x" + canvas.height);

        if (isDoublePage) {
          if (isRTLMode(_this.targetObject)) {
            if (pageNumber % 2 == 0) {
              viewport.transform[4] = -canvas.width;
            }
          } else {
            if (pageNumber % 2 == 1) {
              viewport.transform[4] = -canvas.width;
            }
          }
        }
        var renderContext = {
          canvasContext: context,
          viewport: viewport
        };

        page.cleanupAfterRender = true;
        var pageRendering = page.render(renderContext);

        pageRendering.promise.then(
          function () {

            log(performance.now() - start);
            start = performance.now();
            if (isThumb == true || (_this.options.canvasToBlob == true && _this.webgl !== true)) {
              canvas.toBlob(function (blob) {
                var src = DFLIP.createObjectURL(blob, "image/jpeg");
                log(performance.now() - start);
                _this.setCache(pageNumber, src, isThumb, requestedCacheSize);
                _this.setPage(pageNumber, src, callbackFunction, isThumb);

                //canvas.width = canvas.height = 1;
                //context.clearRect( 0, 0, canvas.width, canvas.height );

                //page.cleanup();
              }, "image/jpeg", _this.pdfRenderQuality)
            }
            else {
              log("Setting Page " + pageNumber);
              _this.setPage(pageNumber, canvas, callbackFunction, isThumb);
            }
            renderContext = null;
          });

      }

    };

    ContentProvider.prototype.getTargetPage = function (pageNumber) {

    };

    ContentProvider.prototype.setLoading = function (pageNumber, show) {
      if (this.targetObject != null) {
        if (this.webgl == true) {
          var container = this.targetObject.container;
          if (show == true) {
            if (container.isLoading !== true) {
              container.addClass("df-loading");
              container.isLoading = true;
              log("Loading icon at " + pageNumber + " as " + show);
            }
          }
          else {
            if (container.isLoading != null) {
              container.removeClass("df-loading");
              container.isLoading = null;
              log("Loading icon at " + pageNumber + " as " + show);
            }
          }
        } else {
          var contentLayer = $(this.targetObject.getContentLayer(pageNumber));
          if (contentLayer != null) {
            if (show == true) contentLayer.addClass("df-page-loading");
            else contentLayer.removeClass("df-page-loading");
            log("Loading icon at " + pageNumber + " as " + show);
          }
        }
      }
    };

    ContentProvider.prototype.getAnnotations = function (pageNumber) {
      var _this = this;

      if (_this.options.enableAnnotation == false) return;

      var target = _this.targetObject;

      pageNumber = parseInt(pageNumber, 10);
      var source = _this.contentSource;
      var contentLayer = $(target.getContentLayer(pageNumber));
      contentLayer.empty();
      if (pageNumber > 0 && pageNumber <= _this.pageCount) {


        if (_this.contentSourceType == SOURCE_TYPE.PDF) {
          var basePage = getBasePage(pageNumber);

          var _pageNumber = pageNumber;
          if (_this.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL && pageNumber > 2) {
            _pageNumber = Math.ceil((pageNumber - 1) / 2) + 1;
          }

          source.getPage(_pageNumber).then(function (page) {

            if (contentLayer != null && contentLayer.length > 0) {
              _this.setupAnnotations(page, _this.viewport, contentLayer, pageNumber);

              /*                            //it's just resizing nothing to do with annotation fetch
               if (target.mode != "css") {

               var page3d = target.getPageByNumber(pageNumber);
               if (page3d != null) {
               var isLeft = (pageNumber % 2 == 0);
               var width = Math.abs(page3d.geometry.boundingBox.max.x - page3d.geometry.boundingBox.min.x);
               var height = Math.abs(page3d.geometry.boundingBox.max.z - page3d.geometry.boundingBox.min.z);

               var div3d = isLeft ? target.parent.cssScene.divLeft : target.parent.cssScene.divRight;
               if (div3d != null) {
               div3d.rotation.y = (isLeft ? -1 : 1 ) * Math.atan2(height, width) * 0.9;
               div3d.position.z = height * 0.8;
               div3d.position.x = (isLeft ? 1 : -1 ) * height / 2.5;
               $(div3d.element).css({
               width: width,
               left: isLeft ? -width / 2 : width / 2
               });

               }
               }
               }*/
            }
          });
        }

        //render any custom liks available for page.

        if (_this.links != null && _this.links[pageNumber] != null) {
          var pageLinks = _this.links[pageNumber];
          for (var index = 0; index < pageLinks.length; index++) {
            var pageLink = pageLinks[index];

            var annotation;
            if (pageLink.dest && pageLink.dest.indexOf && pageLink.dest.indexOf('[html]') == 0) {
              annotation = document.createElement('div');
              annotation.innerHTML = pageLink.dest.substr(6);
              annotation.className = "customHtmlAnnotation";
            } else {
              annotation = document.createElement('a');
              annotation.setAttribute("dest", pageLink.dest);
              annotation.className = "customLinkAnnotation";
              annotation.href = "#" + pageLink.dest;
              annotation.onclick = function () {
                var dest = this.getAttribute("dest");
                if (dest) {
                  _this.linkService.customNavigateTo(dest);
                }
                return false;
              };

            }
            annotation.style.left = pageLink.x + "%";
            annotation.style.top = pageLink.y + "%";

            annotation.style.width = pageLink.w + "%";
            annotation.style.height = pageLink.h + "%";
            contentLayer[0].appendChild(annotation);
          }
        }

        //render any html available for page.

        if (_this.html != null && _this.html[pageNumber] != null) {
          var pageHTML = _this.html[pageNumber];
          contentLayer.append($("<div class='customHTMLAnnotation'>").html(pageHTML));
        }
      }
    };

    ContentProvider.prototype.setPage = function (pageNumber, textureSrc, callbackFunction, isThumb) {
      var _this = this;
      var target = _this.targetObject;
      var isRTL = isRTLMode(target);
      var isBooklet = isBookletMode(target);
      if (isThumb == true) {
        var page = _this.targetObject.container.find("#df-thumb" + pageNumber);
        //log("setting:" + pageNumber + " " + bgImage(textureSrc));
        page.css({
          backgroundImage: bgImage(textureSrc)
        });
      }
      else {

        if (textureSrc == defaults.textureLoadFallback) {
          log("Fallback on " + pageNumber);
        }

        var bookPage = target.getPageByNumber(pageNumber);
        if (bookPage != null) {
          if (
            (pageNumber % 2 != 0 && !isRTL) ||
            (pageNumber % 2 != 1 && isRTL && !isBooklet) || (isBooklet && !isRTL)
          ) {
            log(pageNumber + "rendered to back of " + bookPage.color);
            bookPage.backImage(textureSrc, function (object, texture) {
              bookPage.backTextureLoaded = true;
              _this.setLoading(pageNumber);
              if (_this.requiresImageTextureScaling && texture && pageNumber != 1 && pageNumber != _this.pageCount) {
                texture.repeat.x = 0.5;
                texture.offset.x = 0.5;
              }
              if (callbackFunction != null) callbackFunction();
            });

          }
          else {
            log(pageNumber + "rendered to front of " + bookPage.color);
            bookPage.frontImage(textureSrc, function (object, texture) {
              bookPage.frontTextureLoaded = true;
              _this.setLoading(pageNumber);
              if (_this.requiresImageTextureScaling && texture && pageNumber != 1 && pageNumber != _this.pageCount) {
                texture.repeat.x = 0.5;
              }
              if (callbackFunction != null) callbackFunction();
            });
            //}
          }
        }
        else {
          log("Invalid set request on Page " + pageNumber);
        }
      }
    };

    ContentProvider.prototype.setupAnnotations = function (page, viewport, pageDiv, pageNumber) {
      if (pageDiv == null || $(pageDiv).length == 0) return;
      var _this = this;
      return page.getAnnotations().then(function (annotationsData) {
        viewport = viewport.clone({
          dontFlip: true
        });

        if (_this.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL && pageNumber > 2 && pageNumber % 2 == 1) {
          //viewport.transform[4]= -viewport.scale * page.view[2]/2;

        }
        else if (pageNumber == 1) {

        }
        if (pageDiv == null) {
          return;
        }
        pageDiv = $(pageDiv);
        if (pageDiv.find(".annotationDiv").length == 0) {
          pageDiv.append($("<div class='annotationDiv'>"));
        }
        var div = pageDiv.find(".annotationDiv");
        div.empty();
        if (_this.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL && pageNumber > 2 && pageNumber % 2 == 1) {
          //viewport.transform[4]= -viewport.scale * page.view[2]/2;
          div.css({left: '-100%'});
        }
        else if (pageNumber == 1) {
          div.css({left: ''});
        }
        /*                div.css({
         transform:'matrix(' + _this.viewport.transform.join(',') + ')'
         });*/

        PDFJS.AnnotationLayer.render({
          annotations: annotationsData,
          div: div[0],
          page: page,
          viewport: viewport,
          linkService: _this.linkService
        });

        if (_this.options.annotationClass && _this.options.annotationClass !== "") {
          div.find(" > section").addClass(_this.options.annotationClass);
        }
        // div.find(" > section").addClass("someclass");
        /*				page.getTextContent().then(function(textContent){
         console.log( textContent );
         var textLayer = new DFLIP.TextLayerBuilder({
         textLayerDiv :div[0],
         pageIndex : null,
         viewport : viewport.clone({
         dontFlip: false
         })
         });

         textLayer.setTextContent(textContent);
         textLayer.render();
         });*/

      });

    };

    return ContentProvider;
  })({});

  var PageCSS = (function () {
    function PageCSS(parameters) {
      this.angles = parameters.angles || [0, 0, 0, 0, 0, 0];
      this.stiffness = parameters.angles || 0.1;
      this.segments = parameters.segments || 1;
      this.canvasMode = parameters.contentSourceType !== SOURCE_TYPE.IMAGE && parameters.canvasToBlob == false;
      this.initDOM();
    }

    function createInternals(pageSide) {
      var contentLayer = pageSide.contentLayer = $(html.div, {
        class: "df-page-content"
      });
      pageSide.append(contentLayer);
    }

    PageCSS.prototype = {
      initDOM: function () {
        var element = this.element = $(html.div, {
          class: "df-book-page"
        });
        var wrapper = this.wrapper = $(html.div, {
          class: "df-page-wrapper"
        });
        var front = this.front = $(html.div, {
          class: "df-page-front"
        });
        var back = this.back = $(html.div, {
          class: "df-page-back"
        });
        var foldInnerShadow = this.foldInnerShadow = $(html.div, {
          class: "df-page-fold-inner-shadow"
        });
        var foldOuterShadow = this.foldOuterShadow = $(html.div, {
          class: "df-page-fold-outer-shadow"
        });
        this.frontIMG = new Image();
        this.backIMG = new Image();

        createInternals(front, this.segments, true);
        createInternals(back, this.segments, false);
        element.append(wrapper).append(foldOuterShadow);
        wrapper.append(front).append(back).append(foldInnerShadow);

      },

      updatePoint: function (point) {

        if (point == null) return;

        //detect the current page
        var page = this.parent.dragPage != null ? this.parent.dragPage
          : point.page != null ? point.page : this;

        //get the pageWidth and pageHeight
        var pageWidth = page.element.width(),
          pageHeight = page.element.height();

        //the corner where the drag started
        var corner = this.parent.corner != null ? this.parent.corner : point.corner,
          corners = DFLIP.CORNERS;

        var
          isRight = page.side == drag.right,
          isBottom = (corner == corners.BL) || (corner == corners.BR);

        point.rx = (isRight == true)
          ? pageWidth * 2 - point.x
          : point.x;

        point.ry = (isBottom == true)
          ? pageHeight - point.y
          : point.y;

        var radAngle = Math.atan2(point.ry, point.rx);

        radAngle = Math.PI / 2 - limitAt(radAngle, 0, toRad(90));

        var correctionX = isRight
            ? point.x / 2
            : pageWidth - point.x / 2,

          correctionY = point.ry / 2,

          refLength = Math.max(0,
            Math.sin(radAngle - Math.atan2(correctionY, correctionX)) * distOrigin(correctionX,
              correctionY)),

          foldLength = 0.5 * distOrigin(point.rx, point.ry);

        var x = Math.round(pageWidth - refLength * Math.sin(radAngle)),
          y = Math.round(refLength * Math.cos(radAngle)),

          angle = toDeg(radAngle);

        var angle1 = isBottom
          ? isRight ? 180 + ( 90 - angle) : 180 + angle
          : isRight ? angle : 90 - angle;

        var angle2 = isBottom
            ? isRight ? 180 + ( 90 - angle) : angle
            : isRight ? angle + 180 : angle1,
          angleS = isBottom
            ? isRight ? 90 - angle : angle + 90
            : isRight ? angle1 - 90 : angle1 + 180,
          x1 = isRight ? pageWidth - x : x,
          y1 = isBottom ? pageHeight + y : -y,
          x2 = isRight ? -x : x - pageWidth,
          y2 = isBottom ? -pageHeight - y : y;

        var opacity = limitAt(point.distance * 0.5 / pageWidth, 0, 0.5);
        var foldOpacity = limitAt((pageWidth * 2 - point.rx) * 0.5 / pageWidth, 0.05, 0.3);

        page.element.addClass("df-folding");

        var front = isRight ? page.back : page.front;
        var back = isRight ? page.front : page.back;
        var outerShadow = page.foldOuterShadow;
        var innerShadow = page.foldInnerShadow;
        page.wrapper.css({
          transform: translateStr(x1, y1) + rotateStr(angle1)
        });

        front.css({
          transform: rotateStr(-angle1) + translateStr(-x1, -y1)
        });

        back.css({
          transform: rotateStr(angle2) + translateStr(x2, y2),
          boxShadow: "rgba(0, 0, 0, " + opacity + ") 0px 0px 20px"
        });

        innerShadow.css({
          transform: rotateStr(angle2) + translateStr(x2, y2),
          opacity: foldOpacity / 2,
          backgroundImage: prefix.css + "linear-gradient( " + angleS + "deg, rgba(0, 0, 0, 0.25) , rgb(0, 0, 0) " + foldLength * 0.7 + "px, rgb(255, 255, 255) " + foldLength + "px)"
        });

        outerShadow.css({
          //transform: rotateStr(angle - (isRight ? -180 : 0)) + translateStr(isRight ? -x : x - pageWidth, y),
          opacity: foldOpacity / 2,
          left: isRight ? "auto" : 0,
          right: isRight ? 0 : "auto",
          backgroundImage: prefix.css + "linear-gradient( " + (-angleS + 180) + "deg, rgba(0, 0, 0,0) " + foldLength / 3 + "px, rgb(0, 0, 0) " + foldLength + "px)"
        });

        //$("body > p").html(JSON.stringify({
        //	x: Math.round(point.rx),
        //	y: Math.round(point.ry),
        //	a: Math.round(angle),
        //	a1: Math.round(angle1),
        //	cx: Math.round(correctionX),
        //	cy: Math.round(correctionY),
        //	dx: Math.round(x),
        //	dy: Math.round(y),
        //	ref: Math.round(refLength),
        //	dis: Math.round(distOrigin(point.x, point.y))
        //}));
      },

      updateAngle: function (angle, isRight) {

        var width = this.element.width() * 5;

        //if(prefix.dom!=='MS') {
        this.wrapper.css({
          perspective: width,
          perspectiveOrigin: isRight == true ? "0% 50%" : "100% 50%"
        });
        //}

        this.front.css({
          display: (isRight == true ? (angle <= -90 ? 'block' : 'none') : (angle < 90 ? 'block' : 'none')),
          transform: (prefix.dom !== 'MfS' ? "" : "perspective(" + width + "px) ")
          + (isRight == true ? "translateX(-100%) " : "" )
          + "rotateY(" + ((isRight == true ? 180 : 0 ) + angle) + "deg)"
        });
        this.back.css({
          display: (isRight == true ? (angle > -90 ? 'block' : 'none') : (angle >= 90 ? 'block' : 'none')),
          transform: (prefix.dom !== 'MSd' ? "" : "perspective(" + width + "px) ")
          + (isRight == false ? "translateX(100%) " : "" )
          + "rotateY(" + ((isRight == false ? -180 : 0 ) + angle) + "deg)"
        });
        //$("body > p").html(JSON.stringify({
        //	a: Math.round(angle)
        //}));
        return;
        /*if(this.angles[1] != null) {
         var segsb = this.back.segments;
         var segsf = this.front.segments;
         var width = this.element.width();
         var angle1 = this.angles[1];
         var angle2 = this.angles[4]/segsb.length;
         var step = Math.floor(width/segsb.length);

         for (var count = 0; count < segsb.length; count++) {
         var segb = segsb[count];
         var segf = segsf[count];
         segb.css({
         transform: "rotate3d(0,1,0," + (count == 0 ? angle1 : angle2) + "deg)",
         //backgroundPositionX: -step * count,
         //backgroundSize: width + "px 100%"
         });

         segf.css({
         transform: "rotate3d(0,1,0," + (count == 0 ? 180 + angle1 : angle2) + "deg)",
         //backgroundPositionX: step * (count + 1),
         //backgroundSize: width + "px 100%"
         });
         }
         }
         else{
         this.element.find(".bg-segment").css({
         transform: "translate3d(0px,0,0) rotate3d(0,1,0,0deg)"
         });
         }*/

      },

      tween: function (point) {
        var page = this;
        if (page == null || page.parent == null) return;
        var isBooklet = isBookletMode(page.parent);
        var isRight = page.side == drag.right;
        var isRTL = page.parent.direction == DFLIP.DIRECTION.RTL;
        var isBottom = page.parent.corner == DFLIP.CORNERS.BL || page.parent.corner == DFLIP.CORNERS.BR;
        var isMagnetic = page.magnetic == true;
        var travelY = isBottom ? page.parent.height : 0;

        var init, first, mid, angle = 0;

        var end = page.end = (page && page.animateToReset == true)
          ? {x: isRight ? page.parent.fullWidth : 0, y: travelY}
          : {x: isRight ? 0 : page.parent.fullWidth, y: travelY};

        page.ease = page.isHard ? TWEEN.Easing.Quadratic.InOut : TWEEN.Easing.Linear.None;

        var tempDuration = page.parent.duration;

        if (page.isHard == true) {

          if (point != null) {
            angle = angleByDistance(point.distance, point.fullWidth);
          }

          init = page.init = {angle: angle * (isRight ? -1 : 1)};
          end = page.end = (page && page.animateToReset == true)
            ? {angle: isRight ? 0 : -0}
            : {angle: isRight ? -180 : 180};

        } else {

          if (point == null) {

            init = page.init = (page && page.animateToReset == true)
              ? {x: isRight ? 0 : page.parent.fullWidth, y: 0}
              : {x: isRight ? page.parent.fullWidth : 0, y: 0};

            first = page.first = {
              x: (isRight ? 3 : 1 ) * page.parent.fullWidth / 4,
              y: 0
            };

            mid = page.mid = {x: (isRight ? 1 : 3 ) * page.parent.fullWidth / 4, y: 0};

          }
          else {

            init = page.init = {x: point.x, y: point.y, opacity: 1};
            first = page.first = {x: point.x * 3 / 4, y: point.y * 3 / 4, opacity: 1};
            mid = page.mid = {x: point.x / 4, y: point.y / 4, opacity: 1};

            tempDuration = page.parent.duration * distPoints(init.x, init.y, end.x, end.y) / page.parent.fullWidth;

            tempDuration = limitAt(tempDuration, page.parent.duration / 3, page.parent.duration);

          }
        }
        init.index = 0;
        // first.index = 0;
        // mid.index = 0;
        end.index = 1;
        page.isFlipping = true;

        var update = function (tween) {

          if (page.isHard == true) {
            page.updateAngle(tween.angle, isRight);
            page.angle = tween.angle;
          } else {
            page.updatePoint({
              x: tween.x,
              y: tween.y
            });
            page.x = tween.x;
            page.y = tween.y;
          }
          if (isBooklet && !isMagnetic)
            page.element[0].style.opacity = (isRight && !isRTL) || (!isRight && isRTL)
              ? tween.index > 0.5 ? 2 * (1 - tween.index) : 1
              : tween.index < 0.5 ? 2 * tween.index : 1;

        };

        if (isBooklet && ((!isRight && !isRTL) || (isRight && isRTL)))
          page.element[0].style.opacity = 0;

        var completeTween = page.completeTween = page.completeTween || function (skipRefresh) {
            page.isFlipping = false;

            if (page.isHard == true) {

              page.updateAngle(page.end.angle);
              page.back.css({display: "block"});
              page.front.css({display: "block"});

            }
            else {

              page.updatePoint({
                x: page.end.x,
                y: page.end.y
              });

            }

            page.element[0].style.opacity = 1;

            if (page.animateToReset !== true) {
              page.side = page.side == drag.right ? drag.left : drag.right;
            }
            else
              page.animateToReset = null;

            page.currentTween = null;
            page.pendingPoint = null;
            page.magnetic = false;
            page.parent.dragPage = null;
            page.parent.corner = DFLIP.CORNERS.NONE;

            if (skipRefresh != true)
              page.parent.refresh();


            //log("Tween Completed");
          };
        if (page.isHard == true) {
          page.currentTween = new TWEEN.Tween(init).delay(0)
            .to(end, page.parent.duration)
            .onUpdate(function () {
              update(this);
            }).easing(page.ease)
            .onComplete(page.completeTween)
            .start();
        } else {
          if (point == null) {
            page.currentTween = new TWEEN.Tween(init).delay(0)
              .to(end, page.parent.duration)
              .onUpdate(function () {
                update(this);
              }).easing(TWEEN.Easing.Sinusoidal.Out)
              .onComplete(page.completeTween)
              .start();
          }
          else {
            page.currentTween = new TWEEN.Tween(init).delay(0)
              .to(end, tempDuration)
              .onUpdate(function () {
                update(this);
              }).easing(TWEEN.Easing.Sinusoidal.Out)
              .onComplete(page.completeTween);
            page.currentTween.start();
          }
        }
        //page.currentTween.parent= page;

      },
      frontImage: function (texture, callback) {
        var _this = this;

        function completed() {
          _this.front.css({
            backgroundImage: bgImage(texture)
          });
          if (callback != null) callback();
        }

        if (_this.canvasMode == true) {
          _this.front.find(">canvas").remove();
          if (texture !== defaults.textureLoadFallback) {
            _this.front.append($(texture));
          }
          if (callback != null) callback();
        }
        else {
          if (texture == defaults.textureLoadFallback) {
            completed();
          } else {
            _this.frontIMG.onload = completed;
            _this.frontIMG.src = texture;
          }
        }
      },
      backImage: function (texture, callback) {
        var _this = this;

        function completed() {
          _this.back.css({
            backgroundImage: bgImage(texture)
          });
          if (callback != null) callback();
        }

        if (_this.canvasMode == true) {
          _this.back.find(">canvas").remove();
          if (texture !== defaults.textureLoadFallback) {
            _this.back.append($(texture));
          }
          if (callback != null) callback();
        }
        else {
          if (texture == defaults.textureLoadFallback) {
            completed();
          } else {
            _this.backIMG.onload = completed;
            _this.backIMG.src = texture;
          }
        }

      },
      updateCSS: function (css) {
        this.element.css(css);
      },
      resetCSS: function () {
        this.wrapper.css({
          transform: ''
        });

        this.front.css({
          transform: '',
          boxShadow: ''
        });

        this.back.css({
          transform: '',
          boxShadow: ''
        });
      },
      clearTween: function (skipRefresh) {
        this.currentTween.stop();
        this.completeTween(skipRefresh == true);
        this.resetCSS();
      }

    };

    return PageCSS;
  })();

  var BookCSS = (function (_super) {
    __extends(BookCSS, _super);

    function updateFolding(dragPage) {
      dragPage.parent.container.find(".df-folding").removeClass("df-folding");
      dragPage.element.addClass("df-folding");
    }

    function hasFlipping(book) {
      var hasFlipping = false;
      for (var pageCount = 0; pageCount < book.pages.length; pageCount++) {
        var page = book.pages[pageCount];
        if (page.isFlipping == true) {
          hasFlipping = true;
          break;
        }
      }
      return hasFlipping;
    }

    function BookCSS(parameters, container) {
      //parameters = extendOptions(parameters);

      //_super.call(this, parameters, stage);
      var _this = this;
      _this.type = "BookCSS";
      _this.images = parameters.images || [];
      _this.pageCount = parameters.pageCount || 2;
      //_this.segments = parameters.segments = 5;

      _this.foldSense = 50;

      _this.stackCount = 4;
      _this.mode = "css";
      _this.pages = [];
      _this.duration = parameters.duration;

      _this.container = $(container);
      _this.options = parameters;
      _this.drag = drag.none;
      _this.pageCount = (_this.pageCount == 1 ? _this.pageCount : Math.ceil(_this.pageCount / 2) * 2);
      _this.pageMode = parameters.pageMode || ((isMobile || _this.pageCount <= 2) ? DFLIP.PAGE_MODE.SINGLE
          : DFLIP.PAGE_MODE.DOUBLE);

      _this.singlePageMode = parameters.singlePageMode || (isMobile ? DFLIP.SINGLE_PAGE_MODE.BOOKLET
          : DFLIP.SINGLE_PAGE_MODE.ZOOM);

      _this.swipe_threshold = isMobile ? 15 : 50;

      _this.direction = parameters.direction || DFLIP.DIRECTION.LTR;

      _this.startPage = 1;
      _this.endPage = _this.pageCount;

      _this._activePage = parameters.openPage || _this.startPage;

      _this.hardConfig = parameters.hard;
      //var foldTime = null;
      has3d = 'WebKitCSSMatrix' in window || (document.body && 'MozPerspective' in document.body.style);

      _this.animateF = function () {
        if (TWEEN.getAll().length > 0)
          TWEEN.update();
        else
          clearInterval(_this.animate);
      };

      _this.init(parameters);

      _this.skipDrag = false;

      function checkPage(point) {
        if (_this.dragPage != point.page && point.page.visible == true) {
          _this.dragPage.clearTween(true);
          _this.dragPage = point.page;
          _this.corner = point.corner;
          _this.dragPage.pendingPoint = point;
        }
      }

      var mouseMove = function (event) {
          //event.preventDefault();
          var point = _this.eventToPoint(event);
          if (event.touches != null && event.touches.length == 2 && _this.startTouches != null) {
            //return;
            // _this.startTouches = event.touches;
            _this.zoomDirty = true;
            var touchCenter = utils.getVectorAvg(utils.getTouches(event, _this.container.offset())),
              newScale = utils.calculateScale(_this.startTouches, utils.getTouches(event)),
              scale = newScale / _this.lastScale;

            var zoom = _this.contentProvider.zoomScale,
              x = touchCenter.x,
              y = touchCenter.y;

            _this.stage.css({
              transform: "translate3d(" + _this.left + "px," + _this.top + "px,0) scale3d(" + newScale + "," + newScale + ",1)"
            });

            _this.lastScale = newScale;

            _this.lastZoomCenter = touchCenter;
            event.preventDefault();
          }

          if ((event.touches != null && event.touches.length > 1) || _this.startPoint == null || _this.startTouches != null) return;

          var targetPage = _this.dragPage || point.page;

          if (_this.contentProvider.zoomScale !== 1) {
            if ((event.touches != null || _this.isPanning == true)) {
              _this.pan(point);
              event.preventDefault();
            }
          }
          else {
            if (_this.skipDrag !== true) {
              //if (_this.cancelMouse != true) {

              var distance = point.distance;//_this.getDistance(event);//point.x < _this.pageWidth ? point.x : _this.fullWidth - point.x;

              if (!hasFlipping(_this)) {


                if ((_this.dragPage != null ) || (point.isInside == true)) {
                  //$(".quick-hint").html(distance);
                  if (_this.dragPage != null) {
                    log("set mouse down move");
                  }
                  else {
                    point.y = limitAt(point.y, 1, _this.height - 1);
                    point.x = limitAt(point.x, 1, point.fullWidth - 1);
                  }

                  var corner = _this.corner || point.corner;
                  if (targetPage.isHard) {
                    var isRight = corner == DFLIP.CORNERS.BR || corner == DFLIP.CORNERS.TR;

                    var angle = angleByDistance(point.distance, point.fullWidth);

                    targetPage.updateAngle(angle * (isRight ? -1 : 1), isRight);

                  }
                  else {
                    targetPage.updatePoint(point, _this);
                  }

                  targetPage.magnetic = true;
                  targetPage.magneticCorner = point.corner;
                  event.preventDefault();
                  //point.page.updatePoint(point);
                }

                if (_this.dragPage == null && targetPage != null && point.isInside == false && targetPage.magnetic == true) {
                  targetPage.pendingPoint = point;
                  targetPage.animateToReset = true;
                  _this.corner = targetPage.magneticCorner;
                  _this.animatePage(targetPage);
                  targetPage.pendingPoint = null;
                  targetPage.magnetic = false;
                  targetPage.magneticCorner = null;
                }

                if (_this.isPanning == true && _this.dragPage == null && _this.contentProvider.zoomScale == 1) {
                  //check if swipe has happened
                  //console.log(_this.lastPos - point.x,performance.now()-_this.lastTime);
                  var swipe_dist = point.x - _this.lastPos,
                    swipe_time = performance.now() - _this.lastTime;
                  if (Math.abs(swipe_dist) > _this.swipe_threshold) {
                    //swipe has triggered
                    //_this.dragPage.pendingPoint = point;
                    if (swipe_dist < 0) {
                      _this.next();
                    }
                    else {
                      _this.prev();
                    }
                    _this.drag = drag.none;
                    _this.isPanning = false;
                    event.preventDefault();
                  }
                  _this.lastPos = point.x;
                  _this.lastTime = performance.now();

                }
              }
            }
          }

        },
        mouseUp = function (event) {
          if (event.touches != null && event.touches.length == 0) {
            var zoom = _this.contentProvider.zoomScale;
            if (_this.zoomDirty == true) {
              _this.previewObject.contentProvider.zoomScale =
                utils.limitAt(_this.previewObject.contentProvider.zoomScale * _this.lastScale,
                  1, _this.previewObject.contentProvider.maxZoom);
              _this.previewObject.zoomValue = _this.previewObject.contentProvider.zoomScale * 1;
              //_this.previewObject.zoom(_this.lastScale < 1 ? -1 : 1);
              //console.log(_this.previewObject.contentProvider.zoomScale * _this.lastScale,_this.previewObject.contentProvider.maxZoom)
              //_this.previewObject.pendingZoom = true;
              _this.previewObject.resize();
              _this.zoomDirty = false;
            }
            _this.wrapper.css({
              transform: ""
            });
            _this.lastScale = null;
            _this.startTouches = null;
          }
          _this.isPanning = false;
          if (event.touches != null && event.touches.length > 1) return;
          if (_this.skipDrag !== true) {
            //completeFold();
            var point = _this.eventToPoint(event);
            if (_this.dragPage) {
              event.preventDefault();

              /*							if (_this.animate != null) {
               clearInterval(_this.animate);
               }

               _this.animate = setInterval(_this.animateF, 30);

               _this.dragPage.tween(point);*/

              //use something like pending point
              // detect the next page anbd call the updatepage
              //will be better

              _this.dragPage.pendingPoint = point;
              if (point.x == _this.startPoint.x && point.y == _this.startPoint.y && point.isInside == true) {

                if (_this.corner == DFLIP.CORNERS.BR || _this.corner == DFLIP.CORNERS.TR) {
                  checkPage(point);
                  if (_this.dragPage.isFlipping !== true)
                    _this.next();
                }
                else if (_this.corner == DFLIP.CORNERS.BL || _this.corner == DFLIP.CORNERS.TL) {
                  checkPage(point);
                  if (_this.dragPage.isFlipping !== true)
                    _this.prev();
                }
              }
              else if (_this.dragPage.isFlipping !== true) {
                if (point.distance > point.fullWidth / 2) {
                  if (point.x > point.fullWidth / 2)
                    _this.prev();
                  else
                    _this.next();
                }
                else {
                  _this.dragPage.animateToReset = true;
                  _this.animatePage(_this.dragPage);
                }
              }
              //_this.dragPage.animateToReset = true;
              if (_this.dragPage) {
                _this.dragPage.pendingPoint = null;
                _this.dragPage.magnetic = false;
              }
            } else {
              //detect click
              /*if(_this.wrapper[0].contains(event.target) && _this.contentProvider.zoomScale == 1 && point.x == _this.startPoint.x && point.y == _this.startPoint.y && point.isInsidePage && _this.startPoint.page == point.page && !point.page.isFlipping && event.srcElement.nodeName!=="A"){
               if(_this.startPoint.page.side ==0){
               _this.prev();
               _this.startPoint.page = null;
               }
               else{
               _this.next();
               _this.startPoint.page = null;
               }
               }*/
            }

            _this.drag = drag.none;

            //_this.dragPage = null;
            //_this.corner = DFLIP.CORNERS.NONE;
            //log("set mouse up");
          }

        },
        mouseClick = function (event) {

          var point = _this.eventToPoint(event);

          var element = event.srcElement || event.originalTarget;

          if (_this.dragPage && _this.dragPage.magnetic) return;

          if (_this.wrapper[0].contains(event.target) && _this.contentProvider.zoomScale == 1 && point.x == _this.startPoint.x && point.y == _this.startPoint.y && point.isInsidePage && _this.startPoint.page == point.page && !point.page.isFlipping && element.nodeName !== "A") {

            if (_this.startPoint.page.side == 0) {
              _this.corner = DFLIP.CORNERS.TL;
              _this.prev();
              _this.startPoint.page = null;
            }
            else {
              _this.corner = DFLIP.CORNERS.TR;
              _this.next();
              _this.startPoint.page = null;
            }
            _this.isPanning = false;
          }

        },
        mouseDown = function (event) {
          if (event.touches != null && event.touches.length == 2 && _this.startTouches == null) {
            _this.startTouches = utils.getTouches(event);
            _this.lastScale = 1;
          }
          if ((event.touches != null && event.touches.length > 1) || (event.touches == null && event.button !== 0)) return;
          var point = _this.eventToPoint(event);
          _this.startPoint = point;
          _this.left = _this.left || 0;
          _this.top = _this.top || 0;
          _this.isPanning = true;
          _this.lastPos = point.x;
          _this.lastTime = performance.now();

          if (_this.skipDrag !== true) {

            if (point.isInside == true && !hasFlipping(_this)) {
              _this.startPoint = point;
              _this.drag = point.drag;
              _this.dragPage = point.page;

              _this.corner = point.corner;

              log(_this.corner);

              updateFolding(_this.dragPage);
              //log("set mouse down");
              if (point.page.isHard) {

              }
              else {
                point.page.updatePoint(point, _this);
              }
              if (point.page.name == "0") {
                _this.shadow.css({
                  width: '50%',
                  left: _this.direction == DFLIP.DIRECTION.RTL ? 0 : '50%',
                  transitionDelay: ''
                });
              } else if (point.page.name == Math.ceil(_this.pageCount / 2) - 1) {
                _this.shadow.css({
                  width: '50%',
                  left: _this.direction == DFLIP.DIRECTION.RTL ? '50%' : 0,
                  transitionDelay: ''
                });
              }
            }
          }
        },
        onMouseWheel = function (event) {
          var delta = 0;

          //var zoom = _this.contentProvider.zoomScale > 1;
          if (event.wheelDelta != null) { // WebKit / Opera / Explorer 9

            delta = event.wheelDelta / 120;

          } else if (event.detail != null) { // Firefox

            delta = -event.detail / 3;

          }

          var zoom1 = _this.contentProvider.zoomScale,
            maxZoom = _this.contentProvider.maxZoom;

          if (delta) {

            if ((delta > 0 && zoom1 < maxZoom) || (delta < 0 && zoom1 > 1)) {

              event.stopPropagation();
              event.preventDefault();

              var pointOld = _this.eventToPoint(event);
              var pointNew = _this.eventToPoint(event);

              var origin = {x: _this.container.width() / 2, y: -23 + _this.container.height() / 2};

              _this.previewObject.zoom(delta);

              var zoom2 = _this.contentProvider.zoomScale;
              if (zoom1 !== zoom2) {
                var dz = (zoom2 / zoom1);

                //fix zoom to previous center
                if (zoom2 == 1) {
                  _this.left = 0;
                  _this.top = 0;
                } else {
                  _this.left *= dz;
                  _this.top *= dz;
                }

                //fix zoom to previous pointer
                var dx = (pointOld.raw.x - origin.x ) * dz,
                  dy = (pointOld.raw.y - origin.y ) * dz;

                pointNew.raw.x = origin.x + dx;// origin.x + dz * (point.x-origin.x);
                pointNew.raw.y = origin.y + dy;// origin.y + dz * (point.y-origin.y);

                _this.startPoint = pointNew;
                //console.log(pointOld.raw.x - origin.x,dx,pointOld.raw.y - origin.y,dy,pointNew.raw,_this.startPoint.raw);
                _this.pan(pointOld);

                var targetPage = _this.dragPage || pointOld.page;
                if (_this.dragPage == null && targetPage != null && pointOld.isInside == true && targetPage.magnetic == true) {
                  targetPage.pendingPoint = pointOld;
                  targetPage.animateToReset = true;
                  _this.corner = targetPage.magneticCorner;
                  _this.animatePage(targetPage);
                  targetPage.pendingPoint = null;
                  targetPage.magnetic = false;
                  targetPage.magneticCorner = null;
                }
              }

            }
          }

        };

      var containerDom = _this.container[0];
      var stageDom = _this.stage[0];
      if (containerDom) {
        stageDom.addEventListener("mousemove", mouseMove, false);
        stageDom.addEventListener("touchmove", mouseMove, false);

        stageDom.addEventListener("mousedown", mouseDown, false);
        stageDom.addEventListener("click", mouseClick, false);
        stageDom.addEventListener("mouseup", mouseUp, false);
        stageDom.addEventListener("touchend", mouseUp, false);
        stageDom.addEventListener("touchstart", mouseDown, false);

        if (_this.options.scrollWheel == true) {
          //lets not trigger scroll when in outline or another
          stageDom.addEventListener('mousewheel', onMouseWheel, false);
          stageDom.addEventListener('DOMMouseScroll', onMouseWheel, false); // firefox
        }
      }

      this.dispose = function () {
        stageDom.removeEventListener("mousemove", mouseMove, false);
        stageDom.removeEventListener("touchmove", mouseMove, false);

        stageDom.removeEventListener("mousedown", mouseDown, false);
        stageDom.removeEventListener("click", mouseClick, false);
        stageDom.removeEventListener("mouseup", mouseUp, false);
        stageDom.removeEventListener("touchend", mouseUp, false);
        stageDom.removeEventListener("touchstart", mouseDown, false);

        if (_this.options.scrollWheel == true) {
          stageDom.removeEventListener('mousewheel', onMouseWheel, false);
          stageDom.removeEventListener('DOMMouseScroll', onMouseWheel, false); // firefox
        }
        _this.updatePageCallback = null;
        _this.flipCallback = null;
        _this.animateF = null;
        _this.stage.remove();

      };
    }

    BookCSS.prototype = {
      add: function (object) {
        if (object instanceof PageCSS)
          this.container.append($(object.element));
        else
          this.container.append($(object));
      },
      pan: function (point) {
        var origin = this.startPoint;
        var scale = this.contentProvider.zoomScale;

        var left = (this.left + (point.raw.x - origin.raw.x)),
          top = (this.top + (point.raw.y - origin.raw.y));

        //round removes blur due to decimal value in transform.
        this.left = Math.round(limitAt(left, -this.shiftWidth, this.shiftWidth));
        this.top = Math.round(limitAt(top, -this.shiftHeight, this.shiftHeight));

        if (scale == 1) {
          this.left = 0;
          this.top = 0;
        }

        this.startPoint = point;

        //console.log(point, origin);
        this.stage.css({
          transform: "translate3d(" + this.left + "px," + this.top + "px,0)"
        });

        //var a = book.wrapper.height();
      },
      getPageByNumber: function (pageNumber) {
        var relativePageNumber = isBookletMode(this) ? (isRTLMode(this) ? pageNumber + 1 : pageNumber)
          : Math.floor((pageNumber - 1) / 2);
        var page;
        for (var count = 0; count < this.pages.length; count++) {
          if (relativePageNumber == parseInt(this.pages[count].name, 10))
            page = this.pages[count];
        }
        return page;
      },
      getPageSide: function (pageNumber) {

        var isRTL = this.direction == DFLIP.DIRECTION.RTL;

        var page = this.getPageByNumber(pageNumber);
        if (page == null) return;
        if (isBookletMode(this)) return isRTL ? page.front : page.back;
        if (pageNumber % 2 == 0)
          return isRTL ? page.back : page.front;
        else
          return isRTL ? page.front : page.back;
      },
      getContentLayer: function (pageNumber) {
        var pageSide = this.getPageSide(pageNumber);
        return pageSide == null ? null : pageSide.contentLayer;
      }
    };

    BookCSS.prototype.init = function (parameters) {
      var _this = this;
      _this.stage = $(html.div, {
        class: "df-book-stage"
      });
      _this.wrapper = $(html.div, {
        class: "df-book-wrapper"
      });
      _this.shadow = $(html.div, {
        class: "df-book-shadow"
      });
      //_this.resize();
      _this.container.append(_this.stage);
      _this.stage.append(_this.wrapper);
      _this.wrapper.append(_this.shadow);
      /*			_this.nextButton = $(html.div, {
       class: "df-book-next-button df-book-side-buttons " + parameters.icons['altnext']
       }).appendTo(_this.wrapper).on("click", function () {
       _this.next();
       });
       _this.prevButton = $(html.div, {
       class: "df-book-prev-button df-book-side-buttons " + parameters.icons['altprev']
       }).appendTo(_this.wrapper).on("click", function () {
       _this.prev();
       });*/


      //_this.container.height(parameters.height);

      _this.createStack(parameters);
    };

    BookCSS.prototype.createStack = function (parameters) {

      var colors = "red,green,blue,yellow,orange,black".split(",");

      for (var _stackCount = 0; _stackCount < this.stackCount; _stackCount++) {
        parameters.angles = [, this.stackCount - _stackCount];//[1] = (this.stackCount - _stackCount);
        parameters.stiffness = (this.stackCount - _stackCount) / 100;

        var clone = new PageCSS(parameters);
        clone.angles[1] = 180;
        clone.index = _stackCount;
        clone.parent = this;
        clone.textureReady = false;
        clone.textureRequested = false;
        this.wrapper.append(clone.element);
        clone.isFlipping = false;
        this.pages.push(clone);
        clone.color = colors[_stackCount];
        //for (var _count = 0; _count < 4; _count++) {
        //    clone.element.css({
        //        backgroundColor : colors[_stackCount]
        //    });
        //}
      }

      this.children = this.pages;
    };

    BookCSS.prototype.isPageHard = function (pageNumber) {

      return utils.isHardPage(this.hardConfig, pageNumber, this.pageCount, isBookletMode(this));

    };

    BookCSS.prototype.setDuration = function (_duration) {
      this.duration = _duration;
    };

    BookCSS.prototype.moveBy = function (step) {
      var nextPage = this._activePage + step;

      nextPage = limitAt(nextPage, this.startPage, this.endPage);

      this.gotoPage(nextPage);
    };

    BookCSS.prototype.next = function (step) {
      if (step == null)
        step =
          (this.direction == DFLIP.DIRECTION.RTL)
            ? -this.pageMode : this.pageMode;

      this.moveBy(step);
    };

    BookCSS.prototype.prev = function (step) {
      if (step == null)
        step =
          (this.direction == DFLIP.DIRECTION.RTL)
            ? this.pageMode : -this.pageMode;

      this.moveBy(step);
    };
    BookCSS.prototype.eventToPoint = function (event) {

      event = fixMouseEvent(event);

      var wrapper = this.wrapper,
        pages = this.pages,
        pageWidth = this.pageWidth,
        fullWidth = this.fullWidth,
        height = this.height,
        win = $(window),
        point = {x: event.clientX, y: event.clientY};

      var left = point.x - wrapper[0].getBoundingClientRect().left;// + win['scrollLeft']();

      var top = point.y - wrapper[0].getBoundingClientRect().top;// + win['scrollTop']();

      point.x = point.x - this.container[0].getBoundingClientRect().left;
      point.y = point.y - this.container[0].getBoundingClientRect().top;

      var distance = (this.drag == drag.none)
        ? left < pageWidth ? left : fullWidth - left
        : this.drag == drag.left ? left : fullWidth - left;

      var page = //((left >= 0 && left <= fullWidth)?
        (left < pageWidth ? pages[this.stackCount / 2 - 1] : pages[this.stackCount / 2]);

      var pageDrag = left < this.foldSense ? drag.left
        : (left > fullWidth - this.foldSense) ? drag.right : drag.none;

      //determine the corner
      var x = left,
        y = top,
        h = height,
        w = fullWidth,
        delta = this.foldSense,
        corners = DFLIP.CORNERS,
        corner;

      if (x >= 0 && x < delta) {
        if (y >= 0 && y <= delta)
          corner = corners.TL;
        else if (y >= h - delta && y <= h)
          corner = corners.BL;
        else if (y > delta && y < h - delta)
          corner = corners.L;
        else
          corner = corners.NONE;
      }
      else if (x >= w - delta && x <= w) {
        if (y >= 0 && y <= delta)
          corner = corners.TR;
        else if (y >= h - delta && y <= h)
          corner = corners.BR;
        else if (y > delta && y < h - delta)
          corner = corners.R;
        else
          corner = corners.NONE;
      }
      else
        corner = corners.NONE;

      return {
        isInsidePage: x >= 0 && x <= w && y >= 0 && y <= h,
        isInside: corner !== corners.NONE && corner !== corners.L && corner !== corners.R,
        x: left,
        y: top,
        fullWidth: fullWidth,
        rawDistance: fullWidth - left,
        distance: distance,
        page: page,
        drag: pageDrag,
        foldSense: this.foldSense,
        event: event,
        raw: point,
        corner: corner
      };
    };

    BookCSS.prototype.gotoPage = function (pageNumber) {
      pageNumber = parseInt(pageNumber, 10);
      this._activePage = pageNumber;

      if (this.autoPlay == true) {
        this.previewObject.setAutoPlay(this.autoPlay);
      }
      this.updatePage(pageNumber);
      if (this && this.thumblist && this.thumblist.review)
        this.thumblist.review();
    };

    BookCSS.prototype.refresh = function () {
      this.updatePage(this._activePage);
      if (this.flipCallback != null) this.flipCallback();
    };

    BookCSS.prototype.updatePage = function (pageNumber) {

      var isRTL = (this.direction == DFLIP.DIRECTION.RTL),
        isBooklet = isBookletMode(this),
        newBaseNumber = getBasePage(pageNumber);

      var pageDivisor = isBooklet ? 1 : 2;

      pageNumber = Math.floor((pageNumber / pageDivisor));

      if (isRTL) pageNumber = this.pageCount / pageDivisor - pageNumber;

      var oldBaseNumber = this.oldBaseNumber || 0;
      var pageCount = this.pageCount / pageDivisor;
      var stackCount = this.stackCount;

      var midPoint = Math.floor(stackCount / 2);

      if (oldBaseNumber > pageNumber) {
        this.children[stackCount - 1].skipFlip = true;
        this.children.unshift(this.children.pop());
      }
      else if (oldBaseNumber < pageNumber) {
        this.children[0].skipFlip = true;
        this.children.push(this.children.shift());
      }

      for (var _pageCount = 0; _pageCount < stackCount; _pageCount++) {
        var page = this.children[_pageCount];

        if (oldBaseNumber !== pageNumber) {
          if (page.currentTween != null) {
            page.clearTween(true);
            //page.currentTween.stop();
            //page.completeTween(true);
            //page.resetCSS();
            //page.currentTween = null;
          }
        }

        var oldSide = page.side;
        var newSide;
        var relativePageNumber = pageNumber - midPoint + _pageCount;
        if (isRTL) relativePageNumber = isBooklet ? this.pageCount - relativePageNumber
          : Math.floor(this.pageCount / 2) - relativePageNumber - 1;

        var oldName = page.name;

        page.isHard = this.isPageHard(relativePageNumber);
        if (page.isHard) {
          page.element.addClass("df-hard-page");
        } else {
          page.element.removeClass("df-hard-page");
          page.front.css({display: "block"});
          page.back.css({display: "block"});
        }
        if (relativePageNumber == 0 || relativePageNumber == pageCount) {
          page.element.addClass("df-cover-page");
        } else {
          page.element.removeClass("df-cover-page");
        }

        var oldPageNumber = $(page.element).attr("pageNumber");
        if (oldPageNumber != relativePageNumber) {
          page.front.contentLayer.empty();
          page.back.contentLayer.empty();
        }
        $(page.element).attr("pageNumber", relativePageNumber);


        //Sizing
        page.isEdge = false; //true;
        if (_pageCount == 0) {

        }
        else if (_pageCount == stackCount - 1) {

        }
        else {

          page.isEdge = false;
        }


        if (_pageCount < midPoint) {
          newSide = drag.left;
        }
        else {
          newSide = drag.right;
        }


        if (page.isFlipping == false) {

          if (newSide !== oldSide && page.skipFlip == false) {

            this.animatePage(page);

            if (this.preFlipCallback != null)
              this.preFlipCallback();

          } else {
            page.skipFlip = false;
            page.element.removeClass("df-flipping df-quick-turn df-folding df-left-side df-right-side");
            page.element.addClass((_pageCount < midPoint) ? "df-left-side" : "df-right-side");
            page.side = newSide;
          }
        }

        page.visible = isBooklet
          ? (isRTL

            ? (_pageCount < midPoint || page.isFlipping)
            : (_pageCount >= midPoint || page.isFlipping))

          : ((relativePageNumber >= 0 && relativePageNumber < pageCount) || (isBooklet && relativePageNumber == pageCount));

        if (this.requestPage != null && page.visible == true) {

          page.name = relativePageNumber.toString();
          if (page.name != oldName) {

            page.backTextureLoaded = false;
            page.frontTextureLoaded = false;
            page.backPageStamp = "-1";
            page.frontPageStamp = "-1";
            page.thumbLoaded = false;
            page.front.contentLayer.html("");
            page.back.contentLayer.html("");
            //if (oldName !== '-2') {
            //canvas clearing
            page.frontImage(defaults.textureLoadFallback);
            page.backImage(defaults.textureLoadFallback);
            //}
            this.requestPage();

          }
        }

        page.oldDepth = page.depth;
        page.updateCSS({
          display: page.visible == true ? "block" : "none",
          zIndex: 6 + (_pageCount < midPoint ? (_pageCount - midPoint) : (midPoint - _pageCount)),
          transform: ''
        });

        if (page.pendingPoint == null && page.isFlipping == false) {
          page.resetCSS();
        }
      }

      if (TWEEN.getAll().length == 0) {
        clearInterval(this.animate);
      }
      $(".quick-hint").html(pageNumber);

      this.oldBaseNumber = pageNumber;

      if (this.updatePageCallback)
        this.updatePageCallback();

    };

    BookCSS.prototype.animatePage = function (page) {
      page.element.addClass("df-flipping");
      page.isFlipping = true;

      if (this.animate != null) {
        clearInterval(this.animate);
      }

      this.animate = setInterval(this.animateF, 30);

      page.tween(page.pendingPoint);
    };

    return BookCSS;
  })
  ({});

  var FlipBook = (function (_super) {

    __extends(FlipBook, _super);

    function FlipBook(container, source, parameters) {
      _super.call(this, parameters);
      var _this = this;

      _this.type = "FlipBook";
      _this.container = container;
      _this.options = parameters;
      _this.options.source = source;
      _this.contentSource = source;

      if (parameters.height != null && parameters.height.toString().indexOf('%') < 0) {
        _this.container.height(Math.min(parameters.height, $(window).height()));
      } else {
        _this.container.height(parameters.height);
      }

      if (_this.options.isLightBox) {
        window.dfLightBox.closeButton.addClass(_this.options.icons['close']);
      }
      if (_this.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL) {
        //currently booklet version cannot handle double sized image pages
        if (Array === _this.contentSource.constructor || Array.isArray(_this.contentSource) || _this.contentSource instanceof Array) {
          _this.options.singlePageMode = DFLIP.SINGLE_PAGE_MODE.ZOOM;
        }
        _this.container.addClass("df-double-internal");
      }
      if (!_this.options.isLightBox && _this.container.attr("id") != null) {
        _this.options.id = _this.container.attr("id");
      }

      if (_this.options.parsed !== true && _this.options.links != null) {
        DFLIP.parseLinks(_this.options.links);
      }
      var webgl = _this.webgl = parameters.webgl == true && hasWebgl == true;

      container.addClass("df-container df-loading df-init df-floating" + " df-controls-" + _this.options.controlsPosition);

      if (_this.options.transparent == true) {
        container.addClass("df-transparent");
      }
      if (_this.options.direction == DFLIP.DIRECTION.RTL) {
        container.addClass("df-rtl");
      }
      _this.container.info = $(html.div, {
        class: "loading-info"
      }).appendTo(_this.container).html("Loading...");

      if (userAgent.indexOf('MSIE') !== -1
        || navigator.appVersion.indexOf('Trident/') > 0 || (isSafari && !isIOS)) {
        _this.options.webgl = false; //IE 11
      }

      if (!!userAgent.match(/msie\s[5-9]/i)) {
        _this.container.info.html("Your browser (Internet Explorer) is out of date to run DFlip Flipbook Plugin. <br><a href='http://browsehappy.com/'>Upgrade to a new one</a>").addClass("df-old-browser");
        container.removeClass("df-loading");
        return _this;
      }

      var backgroundImage = parameters.backgroundImage == null || parameters.backgroundImage == '' ? ''
        : "url('" + parameters.backgroundImage + "')";

      _this.container.css({
        position: "relative",
        overflow: "hidden",
        backgroundColor: parameters.backgroundColor,
        backgroundImage: backgroundImage
      });

      _this.init(webgl, source);

      if (_this.options.onCreate != null)
        _this.options.onCreate(_this);

      return _this;

    }

    FlipBook.prototype.init = function (webgl) {
      var _this = this;
      var book = _this.target;

      var options = _this.options;

      if (webgl == true) {

        var updateMockupJs = function (callback) {

            var process3d = function () {
              MOCKUP.defaults.anisotropy = 0;
              MOCKUP.defaults.groundTexture = "blank";
              THREE.skipPowerOfTwo = true;

              RegisterMockupObjects();

              if (callback != null) callback();
            };

            if (window.MOCKUP == null) {
              _this.updateInfo("Loading WEBGL 3D ...");

              if (typeof define === 'function' && define.amd) {
                requirejs.config({
                  "paths": {
                    "three": defaults.threejsSrc.replace(".js", "")
                  },
                  shim: {
                    'three': {
                      exports: 'THREE'
                    }
                  }
                });
                require(['three'], function (THREE) {
                  window.THREE = THREE;
                  getScript(defaults.mockupjsSrc + "?ver=" + DFLIP.version, function () {
                    process3d();
                  });
                  return THREE;
                });
              }
              else {
                getScript(defaults.threejsSrc + "?ver=" + DFLIP.version, function () {
                  //_this.updateInfo("Loading 3D Pages ..."); this was retainnng _this and not releasing memory
                  getScript(defaults.mockupjsSrc + "?ver=" + DFLIP.version, function () {
                    process3d();
                  });
                });
              }
            }
            else {
              process3d();
            }
          }
        ;

        updateMockupJs(function () {

          //Todo: ability to use anisotropy

          _this.container.css({
            minHeight: 300,
            minWidth: 300
          });

          _this.stage = new PreviewStage(extendOptions(_this.options, {container: _this.container}));
          _this.stage.previewObject = _this;

          _this.contentProvider = new ContentProvider(_this.contentSource, function (contentProvider) {
            // _this.pageCount = contentProvider.pageCount = utils.limitAt(contentProvider.pageCount, 1, 2 * 5);
            var options = {
              pageCount: contentProvider.pageCount,//Math.ceil(contentProvider.pageCount / 2) * 2,
              stackCount: 6,
              segments: 20,
              width: contentProvider.bookSize.width,
              height: contentProvider.bookSize.height
            };

            _this.checkOpenPage();
            _this.target = book = _this.stage.target = new MOCKUP.Book(extendOptions(_this.options, options), _this.stage);
            _this.extendtarget();
            createUI(_this.container, _this);

            //bookStage.setTarget(_this.target);
            book.ui = _this.ui;
            book.container = _this.container;
            contentProvider.webgl = webgl;
            contentProvider.setTarget(_this.target);

            book.getContentLayer = function (pageNumber) {

              var isRTL = book.direction == DFLIP.DIRECTION.RTL,
                left = _this.stage.cssScene.divLeft.element,
                right = _this.stage.cssScene.divRight.element;

              var baseActive = getBasePage(book._activePage);

              //if(isRTL){
              //	if(pageNumber == 0 || pageNumber == 1) return right;
              //	if(pageNumber == book.pageCount) return left;
              //}

              if (isBookletMode(book)) return isRTL ? left : right;

              if (pageNumber % 2 == 0)
                return isRTL ? right : left;
              else
                return isRTL ? left : right;
              //else
              //	return null;
            };
            book.stage = _this.stage;

            book.flipCallback = function () {
              if (_this.contentProvider) {
                _this.contentProvider.review("flipCallback");

                var baseActive = getBasePage(book._activePage);

                var width, height;
                var pageLeft = book.getPageByNumber(baseActive),
                  pageRight = book.getPageByNumber(baseActive + 1);
                //if (page3d != null) {
                //    var isLeft = (pageNumber % 2 == 0);
                var divLeft = book.parent.cssScene.divLeft,
                  divRight = book.parent.cssScene.divRight;

                var isSingle = book.pageMode == DFLIP.PAGE_MODE.SINGLE;
                var isRTL = book.direction == DFLIP.DIRECTION.RTL;

                if (pageLeft != null && divLeft != null) {
                  width = Math.abs(pageLeft.geometry.boundingBox.max.x - pageLeft.geometry.boundingBox.min.x);
                  height = Math.abs(pageLeft.geometry.boundingBox.max.z - pageLeft.geometry.boundingBox.min.z);

                  divLeft.rotation.y = -Math.atan2(height, width) * 0.9;
                  divLeft.position.z = height * 0.8;
                  divLeft.position.x = height / 2.5;
                  $(divLeft.element).css({
                    width: width,
                    left: -width / 2//baseActive == 0 && isRTL == true? width
                    //: baseActive == book.pageCount && isRTL == true ? 0 : -width / 2
                  });

                }

                if (pageRight != null && divRight != null) {
                  width = Math.abs(pageRight.geometry.boundingBox.max.x - pageRight.geometry.boundingBox.min.x);
                  height = Math.abs(pageRight.geometry.boundingBox.max.z - pageRight.geometry.boundingBox.min.z);

                  divRight.rotation.y = Math.atan2(height, width) * 0.9;
                  divRight.position.z = height * 0.8;
                  divRight.position.x = -height / 2.5;
                  $(divRight.element).css({
                    width: width,
                    left: width / 2// == 0 && isRTL == true ? 0
                    //: baseActive == book.pageCount && isRTL == true ? -width : width / 2
                  });

                }

                if (_this.options.onFlip != null)
                  _this.options.onFlip(_this);
              }
            };

            book.resize = function () {
              _this.resize();
            }();

            book.updatePageCallback = function () {
              _this.ui.update();
              _this.checkCenter();
              _this.stage.renderRequestPending = true;
            };

            var divLeft = $(_this.stage.cssScene.divLeft.element);
            var divRight = $(_this.stage.cssScene.divRight.element);

            book.preFlipCallback = function () {
              divLeft.empty();
              divRight.empty();
              if (_this.options.beforeFlip != null)
                _this.options.beforeFlip(_this);

              _this.playSound();
            };

            $(window).trigger("resize");

            divLeft.css({
              width: contentProvider.bookSize.width,
              height: contentProvider.bookSize.height,
              left: -contentProvider.bookSize.width / 2
            });

            divRight.css({
              width: contentProvider.bookSize.width,
              height: contentProvider.bookSize.height,
              left: contentProvider.bookSize.width / 2
            });

            book.ease = TWEEN.Easing.Cubic.InOut;
            //book.ease = TWEEN.Easing.Quadratic.InOut;
            book.contentProvider = contentProvider;
            book.duration = _this.options.duration;
            book.gotoPage(book._activePage);
            book.flipCallback();

            if (_this.options.onReady != null)
              _this.options.onReady(_this);

          }, options, _this);
        });
      }
      else {

        _this.contentProvider = new ContentProvider(_this.contentSource, function (contentProvider) {
          // _this.pageCount = contentProvider.pageCount = utils.limitAt(contentProvider.pageCount, 1, 2 * 5);
          var options = {
            pageCount: contentProvider.pageCount,//Math.ceil(contentProvider.pageCount / 2) * 2,
            contentSourceType: contentProvider.contentSourceType
          };

          _this.checkOpenPage();
          _this.target = book = new BookCSS(extendOptions(_this.options, options), _this.container);
          _this.target.previewObject = _this;
          _this.extendtarget();
          createUI(_this.container, _this);
          contentProvider.webgl = webgl;
          contentProvider.setTarget(_this.target);
          contentProvider.waitPeriod = 2;
          book.ease = TWEEN.Easing.Quadratic.InOut;
          book.duration = _this.options.duration;

          /*					_this.ui.prev.hide();
           _this.ui.next.hide();

           _this.ui.prev = book.prevButton;
           _this.ui.next = book.nextButton;*/

          book.container = _this.container;
          book.updatePageCallback = function () {
            _this.ui.update();
            _this.checkCenter();
          };

          book.resize = function () {
            _this.resize();
          }();

          $(window).trigger("resize");

          book.flipCallback = function () {
            if (_this.contentProvider) {
              _this.contentProvider.review("flipCallback");

              if (_this.options.onFlip != null)
                _this.options.onFlip(_this);
            }
          };

          book.preFlipCallback = function () {
            if (_this.options.beforeFlip != null)
              _this.options.beforeFlip(_this);

            _this.playSound();
          };
          book.gotoPage(book._activePage);
          book.flipCallback();

          if (_this.options.onReady != null)
            _this.options.onReady(_this);

        }, options, _this);

      }


    }
    ;

    FlipBook.prototype.extendtarget = function () {
      var _this = this;
      _this.target.previewObject = _this;
      _this.target.reset = function () {
        for (var pageCount = 0; pageCount < _this.target.children.length; pageCount++) {
          var page = _this.target.children[pageCount];
          page.skipFlip = true;
          page.name = '-2';
        }
        _this.contentProvider.annotedPage = '-2';
        _this.target.refresh();

      }
    };

    FlipBook.prototype.getURLHash = function () {
      if (this.options.id != null) {
        var hash = "dflip-" + (this.options.slug != null ? this.options.slug : this.options.id) + "/";
        if (this.target != null && this.target._activePage != null) {
          hash += this.target._activePage + "/";
        }
        window.location.hash = hash;
      }
      return window.location.href;
    };

    FlipBook.prototype.checkOpenPage = function () {
      //options value is overridden by attribute
      if (this.options.id != null) {
        var book = $("#" + this.options.id);
        if (book.length > 0 && book.data("page") != null) {
          var pageNumber = parseInt(book.data("page"), 10);
          if (!isNaN(pageNumber))
            this.options.openPage = pageNumber;
        }
      }
    };

    FlipBook.prototype.end = function () {

      this.target.gotoPage(this.target.endPage);

    };

    FlipBook.prototype.gotoPage = function (pageNumber) {

      this.target.gotoPage(pageNumber);
      if (this.ui != null) this.ui.update();
    };

    FlipBook.prototype.prev = function () {

      this.target.prev();

    };

    FlipBook.prototype.next = function () {

      this.target.next();

    };

    FlipBook.prototype.updateInfo = function (info) {
      if (this.container && this.container.info && this.container.info.html)
        this.container.info.html(info);
    }
    return FlipBook;

  })(PreviewObject);

  $.fn.extend({

    shelf: function () {

    },
    flipBook: function (source, options) {
      return new FlipBook($(this), source, extendDFlipOptions(options));
    }
  });

})
(DFLIP, jQuery);


//Polyfills

/**
 * Blob.js Polyfill
 * A Blob implementation.
 * 2014-07-24
 *
 * By Eli Grey, http://eligrey.com
 * By Devin Samarin, https://github.com/dsamarin
 * License: X11/MIT
 */
(function (view) {
  "use strict";

  view.URL = view.URL || view.webkitURL;

  if (view.Blob && view.URL) {
    try {
      new Blob;
      return;
    } catch (e) {
    }
  }

  // Internally we use a BlobBuilder implementation to base Blob off of
  // in order to support older browsers that only have BlobBuilder
  var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || (function (view) {
      var
        get_class = function (object) {
          return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
        }, FakeBlobBuilder = function BlobBuilder() {
          this.data = [];
        }, FakeBlob = function Blob(data, type, encoding) {
          this.data = data;
          this.size = data.length;
          this.type = type;
          this.encoding = encoding;
        }, FBB_proto = FakeBlobBuilder.prototype, FB_proto = FakeBlob.prototype, FileReaderSync = view.FileReaderSync,
        FileException = function (type) {
          this.code = this[this.name = type];
        }, file_ex_codes = (
          "NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
          + "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
        ).split(" "), file_ex_code = file_ex_codes.length, real_URL = view.URL || view.webkitURL || view,
        real_create_object_URL = real_URL.createObjectURL, real_revoke_object_URL = real_URL.revokeObjectURL,
        URL = real_URL, btoa = view.btoa, atob = view.atob, ArrayBuffer = view.ArrayBuffer,
        Uint8Array = view.Uint8Array, origin = /^[\w-]+:\/*\[?[\w\.:-]+\]?(?::[0-9]+)?/
      ;
      FakeBlob.fake = FB_proto.fake = true;
      while (file_ex_code--) {
        FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
      }
      // Polyfill URL
      if (!real_URL.createObjectURL) {
        URL = view.URL = function (uri) {
          var
            uri_info = document.createElementNS("http://www.w3.org/1999/xhtml", "a"), uri_origin
          ;
          uri_info.href = uri;
          if (!("origin" in uri_info)) {
            if (uri_info.protocol.toLowerCase() === "data:") {
              uri_info.origin = null;
            } else {
              uri_origin = uri.match(origin);
              uri_info.origin = uri_origin && uri_origin[1];
            }
          }
          return uri_info;
        };
      }
      URL.createObjectURL = function (blob) {
        var
          type = blob.type, data_URI_header
        ;
        if (type === null) {
          type = "application/octet-stream";
        }
        if (blob instanceof FakeBlob) {
          data_URI_header = "data:" + type;
          if (blob.encoding === "base64") {
            return data_URI_header + ";base64," + blob.data;
          } else if (blob.encoding === "URI") {
            return data_URI_header + "," + decodeURIComponent(blob.data);
          }
          if (btoa) {
            return data_URI_header + ";base64," + btoa(blob.data);
          } else {
            return data_URI_header + "," + encodeURIComponent(blob.data);
          }
        } else if (real_create_object_URL) {
          return real_create_object_URL.call(real_URL, blob);
        }
      };
      URL.revokeObjectURL = function (object_URL) {
        if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
          real_revoke_object_URL.call(real_URL, object_URL);
        }
      };
      FBB_proto.append = function (data/*, endings*/) {
        var bb = this.data;
        // decode data to a binary string
        if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
          var
            str = "", buf = new Uint8Array(data), i = 0, buf_len = buf.length
          ;
          for (; i < buf_len; i++) {
            str += String.fromCharCode(buf[i]);
          }
          bb.push(str);
        } else if (get_class(data) === "Blob" || get_class(data) === "File") {
          if (FileReaderSync) {
            var fr = new FileReaderSync;
            bb.push(fr.readAsBinaryString(data));
          } else {
            // async FileReader won't work as BlobBuilder is sync
            throw new FileException("NOT_READABLE_ERR");
          }
        } else if (data instanceof FakeBlob) {
          if (data.encoding === "base64" && atob) {
            bb.push(atob(data.data));
          } else if (data.encoding === "URI") {
            bb.push(decodeURIComponent(data.data));
          } else if (data.encoding === "raw") {
            bb.push(data.data);
          }
        } else {
          if (typeof data !== "string") {
            data += ""; // convert unsupported types to strings
          }
          // decode UTF-16 to binary string
          bb.push(unescape(encodeURIComponent(data)));
        }
      };
      FBB_proto.getBlob = function (type) {
        if (!arguments.length) {
          type = null;
        }
        return new FakeBlob(this.data.join(""), type, "raw");
      };
      FBB_proto.toString = function () {
        return "[object BlobBuilder]";
      };
      FB_proto.slice = function (start, end, type) {
        var args = arguments.length;
        if (args < 3) {
          type = null;
        }
        return new FakeBlob(
          this.data.slice(start, args > 1 ? end : this.data.length), type, this.encoding
        );
      };
      FB_proto.toString = function () {
        return "[object Blob]";
      };
      FB_proto.close = function () {
        this.size = 0;
        delete this.data;
      };
      return FakeBlobBuilder;
    }(view));

  view.Blob = function (blobParts, options) {
    var type = options ? (options.type || "") : "";
    var builder = new BlobBuilder();
    if (blobParts) {
      for (var i = 0, len = blobParts.length; i < len; i++) {
        if (Uint8Array && blobParts[i] instanceof Uint8Array) {
          builder.append(blobParts[i].buffer);
        }
        else {
          builder.append(blobParts[i]);
        }
      }
    }
    var blob = builder.getBlob(type);
    if (!blob.slice && blob.webkitSlice) {
      blob.slice = blob.webkitSlice;
    }
    return blob;
  };

  var getPrototypeOf = Object.getPrototypeOf || function (object) {
      return object.__proto__;
    };
  view.Blob.prototype = getPrototypeOf(new view.Blob());
}(window));

/**
 * canvas-toBlob.js Polyfill
 * A canvas.toBlob() implementation.
 * 2013-12-27
 *
 * By Eli Grey, http://eligrey.com and Devin Samarin, https://github.com/eboyjr
 * License: X11/MIT
 *   See https://github.com/eligrey/canvas-toBlob.js/blob/master/LICENSE.md
 */
(function (view) {
  "use strict";
  var
    Uint8Array = view.Uint8Array, HTMLCanvasElement = view.HTMLCanvasElement,
    canvas_proto = HTMLCanvasElement && HTMLCanvasElement.prototype, is_base64_regex = /\s*;\s*base64\s*(?:;|$)/i,
    to_data_url = "toDataURL", base64_ranks, decode_base64 = function (base64) {
      var
        len = base64.length, buffer = new Uint8Array(len / 4 * 3 | 0), i = 0, outptr = 0, last = [0, 0], state = 0,
        save = 0, rank, code;
      while (len--) {
        code = base64.charCodeAt(i++);
        rank = base64_ranks[code - 43];
        if (rank !== 255 && rank != null) {
          last[1] = last[0];
          last[0] = code;
          save = (save << 6) | rank;
          state++;
          if (state === 4) {
            buffer[outptr++] = save >>> 16;
            if (last[1] !== 61 /* padding character */) {
              buffer[outptr++] = save >>> 8;
            }
            if (last[0] !== 61 /* padding character */) {
              buffer[outptr++] = save;
            }
            state = 0;
          }
        }
      }
      // 2/3 chance there's going to be some null bytes at the end, but that
      // doesn't really matter with most image formats.
      // If it somehow matters for you, truncate the buffer up outptr.
      return buffer;
    }
  ;
  if (Uint8Array) {
    base64_ranks = new Uint8Array([
      62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
    ]);
  }
  if (HTMLCanvasElement && !canvas_proto.toBlob) {
    canvas_proto.toBlob = function (callback, type /*, ...args*/) {
      if (!type) {
        type = "image/png";
      }
      if (this.mozGetAsFile) {
        callback(this.mozGetAsFile("canvas", type));
        return;
      }
      if (this.msToBlob && /^\s*image\/png\s*(?:$|;)/i.test(type)) {
        callback(this.msToBlob());
        return;
      }

      var
        args = Array.prototype.slice.call(arguments, 1),
        dataURI = this[to_data_url].apply(this, args),
        header_end = dataURI.indexOf(","),
        data = dataURI.substring(header_end + 1),
        is_base64 = is_base64_regex.test(dataURI.substring(0, header_end)),
        blob
      ;
      if (Blob.fake) {
        // no reason to decode a data: URI that's just going to become a data URI again
        blob = new Blob;
        if (is_base64) {
          blob.encoding = "base64";
        } else {
          blob.encoding = "URI";
        }
        blob.data = data;
        blob.size = data.length;
      } else if (Uint8Array) {
        if (is_base64) {
          blob = new Blob([decode_base64(data)], {type: type});
        } else {
          blob = new Blob([decodeURIComponent(data)], {type: type});
        }
      }
      callback(blob);
    };

    if (canvas_proto.toDataURLHD) {
      canvas_proto.toBlobHD = function () {
        to_data_url = "toDataURLHD";
        var blob = this.toBlob();
        to_data_url = "toDataURL";
        return blob;
      }
    } else {
      canvas_proto.toBlobHD = canvas_proto.toBlob;
    }
  }
}(window));

/**
 * performance.now polyfill
 **/
(function PerformanceNowPolyfill() {

  if ('performance' in window === false) {
    window.performance = {};
  }

  // IE 8
  Date.now = (Date.now || function () {
    return new Date().getTime();
  });

  if ('now' in window.performance === false) {
    var offset = window.performance.timing && window.performance.timing.navigationStart
      ? window.performance.timing.navigationStart
      : Date.now();

    window.performance.now = function () {
      return Date.now() - offset;
    };
  }

})();

/**
 * Tween.js - Licensed under the MIT license
 * https://github.com/tweenjs/tween.js
 */
(function TweenJs() {
  var TWEEN = TWEEN || (function () {

      var _tweens = [];

      return {

        getAll: function () {

          return _tweens;

        },

        removeAll: function () {

          _tweens = [];

        },

        add: function (tween) {

          _tweens.push(tween);

        },

        remove: function (tween) {

          var i = _tweens.indexOf(tween);

          if (i !== -1) {
            _tweens.splice(i, 1);
          }

        },

        update: function (time) {

          if (_tweens.length === 0) {
            return false;
          }

          var i = 0;

          time = time != null ? time : window.performance.now();

          while (i < _tweens.length) {

            if (_tweens[i].update(time)) {
              i++;
            } else {
              _tweens.splice(i, 1);
            }

          }

          return true;

        }
      };

    })();

  TWEEN.Tween = function (object) {

    var _object = object;
    var _valuesStart = {};
    var _valuesEnd = {};
    var _valuesStartRepeat = {};
    var _duration = 1000;
    var _repeat = 0;
    var _yoyo = false;
    var _isPlaying = false;
    var _reversed = false;
    var _delayTime = 0;
    var _startTime = null;
    var _easingFunction = TWEEN.Easing.Linear.None;
    var _interpolationFunction = TWEEN.Interpolation.Linear;
    var _chainedTweens = [];
    var _onStartCallback = null;
    var _onStartCallbackFired = false;
    var _onUpdateCallback = null;
    var _onCompleteCallback = null;
    var _onStopCallback = null;

    // Set all starting values present on the target object
    for (var field in object) {
      _valuesStart[field] = parseFloat(object[field], 10);
    }

    this.to = function (properties, duration) {

      if (duration != null) {
        _duration = duration;
      }

      _valuesEnd = properties;

      return this;

    };

    this.start = function (time) {

      TWEEN.add(this);

      _isPlaying = true;

      _onStartCallbackFired = false;

      _startTime = time != null ? time : window.performance.now();
      _startTime += _delayTime;

      for (var property in _valuesEnd) {

        // Check if an Array was provided as property value
        if (_valuesEnd[property] instanceof Array) {

          if (_valuesEnd[property].length === 0) {
            continue;
          }

          // Create a local copy of the Array with the start value at the front
          _valuesEnd[property] = [_object[property]].concat(_valuesEnd[property]);

        }

        // If `to()` specifies a property that doesn't exist in the source object,
        // we should not set that property in the object
        if (_valuesStart[property] === null) {
          continue;
        }

        _valuesStart[property] = _object[property];

        if ((_valuesStart[property] instanceof Array) === false) {
          _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
        }

        _valuesStartRepeat[property] = _valuesStart[property] || 0;

      }

      return this;

    };

    this.stop = function () {

      if (!_isPlaying) {
        return this;
      }

      TWEEN.remove(this);
      _isPlaying = false;

      if (_onStopCallback !== null) {
        _onStopCallback.call(_object);
      }

      this.stopChainedTweens();
      return this;

    };

    this.stopChainedTweens = function () {

      for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
        _chainedTweens[i].stop();
      }

    };

    this.complete = function () {
      if (!_isPlaying) {
        return this;
      }

      TWEEN.remove(this);
      _isPlaying = false;

      if (_onCompleteCallback !== null) {
        _onCompleteCallback.call(_object);
      }

      this.completeChainedTweens();
      return this;
    };

    this.completeChainedTweens = function () {

      for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
        _chainedTweens[i].complete();
      }

    };

    this.delay = function (amount) {

      _delayTime = amount;
      return this;

    };

    this.repeat = function (times) {

      _repeat = times;
      return this;

    };

    this.yoyo = function (yoyo) {

      _yoyo = yoyo;
      return this;

    };


    this.easing = function (easing) {

      _easingFunction = easing == null ? _easingFunction : easing;
      return this;

    };

    this.interpolation = function (interpolation) {

      _interpolationFunction = interpolation;
      return this;

    };

    this.chain = function () {

      _chainedTweens = arguments;
      return this;

    };

    this.onStart = function (callback) {

      _onStartCallback = callback;
      return this;

    };

    this.onUpdate = function (callback) {

      _onUpdateCallback = callback;
      return this;

    };

    this.onComplete = function (callback) {

      _onCompleteCallback = callback;
      return this;

    };

    this.onStop = function (callback) {

      _onStopCallback = callback;
      return this;

    };

    this.update = function (time) {

      var property;
      var elapsed;
      var value;

      if (time < _startTime) {
        return true;
      }

      if (_onStartCallbackFired === false) {

        if (_onStartCallback !== null) {
          _onStartCallback.call(_object);
        }

        _onStartCallbackFired = true;

      }

      elapsed = (time - _startTime) / _duration;
      elapsed = elapsed > 1 ? 1 : elapsed;

      value = _easingFunction(elapsed);

      for (property in _valuesEnd) {

        // Don't update properties that do not exist in the source object
        if (_valuesStart[property] === null) {
          continue;
        }

        var start = _valuesStart[property] || 0;
        var end = _valuesEnd[property];

        if (end instanceof Array) {

          _object[property] = _interpolationFunction(end, value);

        } else {

          // Parses relative end values with start as base (e.g.: +10, -3)
          if (typeof (end) === 'string') {

            if (end.startsWith('+') || end.startsWith('-')) {
              end = start + parseFloat(end, 10);
            } else {
              end = parseFloat(end, 10);
            }
          }

          // Protect against non numeric properties.
          if (typeof (end) === 'number') {
            _object[property] = start + (end - start) * value;
          }

        }

      }

      if (_onUpdateCallback !== null) {
        _onUpdateCallback.call(_object, value);
      }

      if (elapsed === 1) {

        if (_repeat > 0) {

          if (isFinite(_repeat)) {
            _repeat--;
          }

          // Reassign starting values, restart by making startTime = now
          for (property in _valuesStartRepeat) {

            if (typeof (_valuesEnd[property]) === 'string') {
              _valuesStartRepeat[property] = _valuesStartRepeat[property] + parseFloat(_valuesEnd[property], 10);
            }

            if (_yoyo) {
              var tmp = _valuesStartRepeat[property];

              _valuesStartRepeat[property] = _valuesEnd[property];
              _valuesEnd[property] = tmp;
            }

            _valuesStart[property] = _valuesStartRepeat[property];

          }

          if (_yoyo) {
            _reversed = !_reversed;
          }

          _startTime = time + _delayTime;

          return true;

        } else {

          if (_onCompleteCallback !== null) {
            _onCompleteCallback.call(_object);
          }

          for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
            // Make the chained tweens start exactly at the time they should,
            // even if the `update()` method was called way past the duration of the tween
            _chainedTweens[i].start(_startTime + _duration);
          }

          return false;

        }

      }

      return true;

    };

  };

  TWEEN.Easing = {

    Linear: {

      None: function (k) {

        return k;

      }

    },

    Quadratic: {

      In: function (k) {

        return k * k;

      },

      Out: function (k) {

        return k * (2 - k);

      },

      InOut: function (k) {

        if ((k *= 2) < 1) {
          return 0.5 * k * k;
        }

        return -0.5 * (--k * (k - 2) - 1);

      }

    },
    Quartic: {

      In: function (k) {

        return k * k * k * k;

      },

      Out: function (k) {

        return 1 - (--k * k * k * k);

      },

      InOut: function (k) {

        if ((k *= 2) < 1) {
          return 0.5 * k * k * k * k;
        }

        return -0.5 * ((k -= 2) * k * k * k - 2);

      }

    },
    Sinusoidal: {

      In: function (k) {

        return 1 - Math.cos(k * Math.PI / 2);

      },

      Out: function (k) {

        return Math.sin(k * Math.PI / 2);

      },

      InOut: function (k) {

        return 0.5 * (1 - Math.cos(Math.PI * k));

      }

    },
    Cubic: {

      In: function (k) {

        return k * k * k;

      },

      Out: function (k) {

        return --k * k * k + 1;

      },

      InOut: function (k) {

        if ((k *= 2) < 1) {
          return 0.5 * k * k * k;
        }

        return 0.5 * ((k -= 2) * k * k + 2);

      }

    }

  };

  TWEEN.Interpolation = {

    Linear: function (v, k) {

      var m = v.length - 1;
      var f = m * k;
      var i = Math.floor(f);
      var fn = TWEEN.Interpolation.Utils.Linear;

      if (k < 0) {
        return fn(v[0], v[1], f);
      }

      if (k > 1) {
        return fn(v[m], v[m - 1], m - f);
      }

      return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);

    },

    Bezier: function (v, k) {

      var b = 0;
      var n = v.length - 1;
      var pw = Math.pow;
      var bn = TWEEN.Interpolation.Utils.Bernstein;

      for (var i = 0; i <= n; i++) {
        b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
      }

      return b;

    },

    Utils: {

      Linear: function (p0, p1, t) {

        return (p1 - p0) * t + p0;

      },

      Bernstein: function (n, i) {

        var fc = TWEEN.Interpolation.Utils.Factorial;

        return fc(n) / fc(i) / fc(n - i);

      },

      Factorial: (function () {

        var a = [1];

        return function (n) {

          var s = 1;

          if (a[n]) {
            return a[n];
          }

          for (var i = n; i > 1; i--) {
            s *= i;
          }

          a[n] = s;
          return s;

        };

      })(),

      CatmullRom: function (p0, p1, p2, p3, t) {

        var v0 = (p2 - p0) * 0.5;
        var v1 = (p3 - p1) * 0.5;
        var t2 = t * t;
        var t3 = t * t2;

        return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;

      }

    }
  };

  window.TWEEN = TWEEN;
})();

DFLIP.createBlob = function createBlob(data, contentType) {
  if (typeof Blob !== 'undefined') {
    return new Blob([data], {type: contentType});
  }
  // Blob builder is deprecated in FF14 and removed in FF18.
  var bb = new MozBlobBuilder();
  bb.append(data);
  return bb.getBlob(contentType);
};

DFLIP.createObjectURL = (function createObjectURLClosure() {
  // Blob/createObjectURL is not available, falling back to data schema.
  var digits =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

  return function createObjectURL(data, contentType) {
    if (typeof URL !== 'undefined' && URL.createObjectURL) {
      var blob = DFLIP.createBlob(data, contentType);
      return URL.createObjectURL(blob);
    }

    var buffer = 'data:' + contentType + ';base64,';
    for (var i = 0, ii = data.length; i < ii; i += 3) {
      var b1 = data[i] & 0xFF;
      var b2 = data[i + 1] & 0xFF;
      var b3 = data[i + 2] & 0xFF;
      var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
      var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
      var d4 = i + 2 < ii ? (b3 & 0x3F) : 64;
      buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
    }
    return buffer;
  };
})();

var ThumbList = (function ThumbListClosure() {
  function ThumbList(config) {
    var width = (config && config.w + 'px') || '100%';
    var height = (config && config.h + 'px') || '100%';
    var itemHeight = this.itemHeight = config.itemHeight;

    this.items = config.items;
    this.generatorFn = config.generatorFn;
    this.totalRows = config.totalRows || (config.items && config.items.length);

    this.addFn = config.addFn;
    this.scrollFn = config.scrollFn;

    var scroller = ThumbList.createScroller(itemHeight * this.totalRows);
    this.container = ThumbList.createContainer(width, height);
    this.container.appendChild(scroller);

    this.screenItemsLen = Math.ceil(config.h / itemHeight);
    this.offsetItems = this.screenItemsLen;
    // Cache 4 times the number of items that fit in the container viewport
    this.cachedItemsLen = this.screenItemsLen + this.offsetItems * 2;
    this._renderChunk(this.container, 0);

    var self = this;
    self.lastRepaintY = 0;
    var maxBuffer = this.screenItemsLen * itemHeight;
    var lastScrolled = 0;

    var requestInterval;

    function onScroll(e) {
      var scrollTop = e.target.scrollTop; // Triggers reflow
      if (!self.lastRepaintY || Math.abs(scrollTop - self.lastRepaintY) >= (self.offsetItems * self.itemHeight)) {
        var first = parseInt(scrollTop / itemHeight, 10) - self.offsetItems;
        self._renderChunk(self.container, first < 0 ? 0 : first);
        self.lastRepaintY = scrollTop;
      }

      self.lastScrolled = lastScrolled = Date.now();

      if (self.scrollFn != null) {
        self.scrollFn();
      }

      e.preventDefault && e.preventDefault();
    }

    self.dispose = function () {
      if (self.container) {
        if (self.container.parentNode) {
          self.container.parentNode.removeChild(self.container);
        }
      }

      self.container.removeEventListener('scroll', onScroll);
    };

    self.container.addEventListener('scroll', onScroll);
  }

  ThumbList.prototype.reset = function (height) {

    //container.find(".df-vrow").remove();
    this.screenItemsLen = Math.ceil(height / this.itemHeight);
    this.cachedItemsLen = this.screenItemsLen + this.offsetItems * 2;
    var first = parseInt(this.lastRepaintY / this.itemHeight, 10) - this.offsetItems;
    //this.lastRepaintY = 0;
    this.needReset = true;
    this._renderChunk(this.container, Math.max(first, 0));
  };

  ThumbList.prototype.createRow = function (i) {
    var item;
    if (this.generatorFn) {
      item = this.generatorFn(i);
      item.classList.add('df-vrow');
      item.style.position = 'absolute';
      item.style.top = (i * this.itemHeight) + 'px';
      item.setAttribute("index", i);
    }
    return item;
  };

  /**
   * Renders a particular, consecutive chunk of the total rows in the list. To
   * keep acceleration while scrolling, we mark the nodes that are candidate for
   * deletion instead of deleting them right away, which would suddenly stop the
   * acceleration. We delete them once scrolling has finished.
   *
   * @param {Node} node Parent node where we want to append the children chunk.
   * @param {Number} from Starting position, i.e. first children index.
   * @return {void}
   */
  ThumbList.prototype._renderChunk = function (node, from) {
    var isEmpty = this.range == null;
    this.range = this.range || {min: 0, max: this.cachedItemsLen};
    var range = this.range;

    var min = range.min, max = range.max;

    var isAdd = isEmpty ? true : from >= min;

    if (!isEmpty && from == min && this.needReset == false) return;

    var countVar;

    var start = isEmpty ? min : isAdd ? max : from;// - this.cachedItemsLen/3;

    start = start > this.totalRows ? this.totalRows
      : start < 0 ? 0 : start;

    var end = from + this.cachedItemsLen;//this.cachedItemsLen/3);

    end = end > this.totalRows ? this.totalRows : end;

    for (countVar = start; countVar < end; countVar++) {
      if (isAdd)
        node.appendChild(this.createRow(countVar));
      else
        node.insertBefore(this.createRow(countVar), node.childNodes[1 + countVar - start]);
      if (this.addFn != null) {
        this.addFn(countVar);
      }
    }
    var difference = Math.abs(from - min);
    this.needReset = false;
    if (!isEmpty && node.childNodes.length > (this.cachedItemsLen + 1)) {
      // Hide and mark obsolete nodes for deletion.
      var delStart = isAdd ? 1 : 1 + this.cachedItemsLen,
        delEnd = delStart + (end - start);

      for (var j = delEnd; j > delStart; j--) {
        if (node.childNodes[delStart])
          this.container.removeChild(node.childNodes[delStart]);
      }
    }
    this.range.min = from;
    this.range.max = end;
  };

  ThumbList.createContainer = function (w, h) {
    var c = document.createElement('div');
    c.style.width = w;
    c.style.height = h;
    c.style.overflow = 'auto';
    c.style.position = 'relative';
    c.style.padding = 0;
    //c.style.border = '1px solid black';
    return c;
  };

  ThumbList.createScroller = function (h) {
    var scroller = document.createElement('div');
    scroller.style.opacity = 0;
    scroller.style.position = 'absolute';
    scroller.style.top = 0;
    scroller.style.left = 0;
    scroller.style.width = '1px';
    scroller.style.height = h + 'px';
    return scroller;
  };
  return ThumbList;
})();


/**
 * @typedef {Object} BookMarkViewerOptions
 * @property {HTMLDivElement} container - The viewer element.
 * @property {IPDFLinkService} linkService - The navigation/linking service.
 */

/**
 * @typedef {Object} BookMarkViewerRenderParameters
 * @property {Array|null} outline - An array of outline objects.
 */

/**
 * @class
 */
var BookMarkViewer = (function BookMarkViewerClosure() {
  /**
   * @constructs BookMarkViewer
   * @param {BookMarkViewerOptions} options
   */
  function BookMarkViewer(options) {
    this.outline = null;
    this.lastToggleIsShow = true;
    this.container = options.container;
    this.linkService = options.linkService;
    this.outlineItemClass = options.outlineItemClass || "outlineItem";
    this.outlineToggleClass = options.outlineToggleClass || "outlineItemToggler";
    this.outlineToggleHiddenClass = options.outlineToggleHiddenClass || "outlineItemsHidden";
  }

  BookMarkViewer.prototype = {

    dispose: function () {
      if (this.container) {
        if (this.container.parentNode) {
          this.container.parentNode.removeChild(this.container);
        }
      }
      this.linkService = null;

    },
    reset: function BookMarkViewer_reset() {
      this.outline = null;
      this.lastToggleIsShow = true;

      var container = this.container;
      while (container.firstChild) {
        container.removeChild(container.firstChild);
      }
    },

    /**
     * @private
     */
    _dispatchEvent: function BookMarkViewer_dispatchEvent(outlineCount) {
      var event = document.createEvent('CustomEvent');
      event.initCustomEvent('outlineloaded', true, true, {
        outlineCount: outlineCount
      });
      this.container.dispatchEvent(event);
    },

    /**
     * @private
     */
    _bindLink: function BookMarkViewer_bindLink(element, item) {
      var linkService = this.linkService;
      if (item.custom == true) {
        element.href = linkService.getCustomDestinationHash(item.dest);
        element.onclick = function goToDestination(e) {
          linkService.customNavigateTo(item.dest);
          return false;
        };
      }
      else {
        if (item.url) {
          PDFJS.addLinkAttributes(element, {url: item.url});
          return;
        }

        element.href = linkService.getDestinationHash(item.dest);
        element.onclick = function goToDestination(e) {
          linkService.navigateTo(item.dest);
          return false;
        };
      }
    },

    /**
     * Prepend a button before an outline item which allows the user to toggle
     * the visibility of all outline items at that level.
     *
     * @private
     */
    _addToggleButton: function BookMarkViewer_addToggleButton(div) {
      var toggler = document.createElement('div');
      toggler.className = this.outlineToggleClass + " " + this.outlineToggleHiddenClass;
      toggler.onclick = function (event) {
        event.stopPropagation();
        toggler.classList.toggle(this.outlineToggleHiddenClass);

        if (event.shiftKey) {
          var shouldShowAll = !toggler.classList.contains(this.outlineToggleHiddenClass);
          this._toggleOutlineItem(div, shouldShowAll);
        }
      }.bind(this);
      div.insertBefore(toggler, div.firstChild);
    },

    /**
     * Toggle the visibility of the subtree of an outline item.
     *
     * @param {Element} root - the root of the outline (sub)tree.
     * @param {boolean} show - whether to show the outline (sub)tree. If false,
     *   the outline subtree rooted at |root| will be collapsed.
     *
     * @private
     */
    _toggleOutlineItem: function BookMarkViewer_toggleOutlineItem(root, show) {
      this.lastToggleIsShow = show;
      var togglers = root.querySelectorAll('.' + this.outlineToggleClass);
      for (var i = 0, ii = togglers.length; i < ii; ++i) {
        togglers[i].classList[show ? 'remove' : 'add'](this.outlineToggleHiddenClass);
      }
    },

    /**
     * Collapse or expand all subtrees of the outline.
     */
    toggleOutlineTree: function BookMarkViewer_toggleOutlineTree() {
      if (!this.outline) {
        return;
      }
      this._toggleOutlineItem(this.container, !this.lastToggleIsShow);
    },

    /**
     * @param {BookMarkViewerRenderParameters} params
     */
    render: function BookMarkViewer_render(params) {
      var outline = (params && params.outline) || null;
      var outlineCount = 0;

      if (this.outline) {
        this.reset();
      }
      this.outline = outline;

      if (!outline) {
        //this._dispatchEvent(outlineCount);
        return;
      }

      var fragment = document.createDocumentFragment();
      var queue = [{parent: fragment, items: this.outline}];
      var hasAnyNesting = false;
      while (queue.length > 0) {
        var levelData = queue.shift();
        var isCustom = levelData.custom;
        for (var i = 0, len = levelData.items.length; i < len; i++) {
          var item = levelData.items[i];

          var div = document.createElement('div');
          div.className = this.outlineItemClass;

          var element = document.createElement('a');
          if (item.custom == null && isCustom != null)
            item.custom = isCustom;

          this._bindLink(element, item);
          //element.
          element.textContent = item.title.replace(/\x00/g, '');
          //PDFJS.removeNullCharacters(item.title) || "Untitled Bookmark";

          div.appendChild(element);

          if (item.items && item.items.length > 0) {
            hasAnyNesting = true;
            this._addToggleButton(div);

            var itemsDiv = document.createElement('div');
            itemsDiv.className = this.outlineItemClass + "s";
            div.appendChild(itemsDiv);
            queue.push({parent: itemsDiv, custom: item.custom, items: item.items});
          }

          levelData.parent.appendChild(div);
          outlineCount++;
        }
      }
      if (hasAnyNesting) {
        if (this.container.classList != null) {
          this.container.classList.add(this.outlineItemClass + "s");
        }
        else if (this.container.className != null) {
          this.container.className += " picWindow";
        }
      }

      this.container.appendChild(fragment);

      this._dispatchEvent(outlineCount);
    }

  };

  return BookMarkViewer;
})();
//PDFJS.PDFOutlineViewer = PDFOutlineViewer;

var DFLightBox = (function DFLightBoxClosure($) {
  /**
   * @constructs DFLightBox
   * @param closeCallback callBack function required to dispose object properly when lighbox is closed
   */
  function DFLightBox(closeCallback, options) {

    this.duration = 300;

    //cache this
    var _this = this;
    //lightbox wrapper div
    _this.lightboxWrapper = $("<div>").addClass("df-lightbox-wrapper");

    //lightbox container
    _this.container = $("<div>").addClass("df-container").appendTo(_this.lightboxWrapper);
    //lightbox controls
    _this.controls = $("<div>").addClass("df-lightbox-controls").appendTo(_this.lightboxWrapper);

    //lightbox close button
    _this.closeButton = $("<div>").addClass("df-lightbox-close df-ui-btn")
      .on("click", function () {
        _this.close(closeCallback);
      })
      .appendTo(_this.controls);

    _this.lightboxWrapper.append(_this.container);

    return _this;
  }

  DFLightBox.prototype.show = function (callback) {

    if (this.lightboxWrapper.parent().length == 0)
      $("body").append(this.lightboxWrapper);

    this.lightboxWrapper.fadeIn(this.duration, callback);

    return this;
  };

  DFLightBox.prototype.close = function (callback) {

    this.lightboxWrapper.fadeOut(this.duration);
    setTimeout(callback, this.duration);

    return this;
  };

  return DFLightBox;
})(jQuery);

DFLIP.Share = (function ShareClosure($) {

  function Share(container, options) {
    var _this = this;
    var htmlDiv = '<div>';
    var shareButtonClass = "df-share-button";
    var windowParameters = "width=500,height=400";
    _this.isOpen = false;
    _this.shareUrl = "";
    _this.wrapper = $('<div class="df-share-wrapper" style="display: none;">')
      .on("click", function (e) {
        _this.close();
      });
    _this.box = $('<div class="df-share-box">')
      .on("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
      }).appendTo(_this.wrapper).html('<span class="df-share-title">' + options.text.share + '</span>');
    _this.urlInput = $('<textarea class="df-share-url">').on("click", function () {
      $(this).select();
    });

    _this.facebook = $(htmlDiv, {
      class: shareButtonClass + " df-share-facebook " + options.icons['facebook']
    }).on("click", function (e) {
      window.open('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(_this.shareUrl), "Sharer", windowParameters);
    });
    _this.google = $(htmlDiv, {
      class: shareButtonClass + " df-share-google " + options.icons['google']
    }).on("click", function (e) {
      window.open('https://plus.google.com/share?url=' + encodeURIComponent(_this.shareUrl), "Sharer", windowParameters);
    });
    _this.twitter = $(htmlDiv, {
      class: shareButtonClass + " df-share-twitter " + options.icons['twitter']
    }).on("click", function (e) {
      window.open('http://twitter.com/share?url=' + encodeURIComponent(_this.shareUrl), "Sharer", windowParameters);
    });
    _this.mail = $('<a>', {
      class: shareButtonClass + " df-share-mail " + options.icons['mail'],
      href: 'mailto:?subject=I wanted you to see this FlipBook&body=Check out this site ' + encodeURIComponent(_this.shareUrl),
      target: '_blank'
    }).on("click", function (e) {
      $(this).attr('href', 'mailto:?subject=I wanted you to see this FlipBook&body=Check out this site ' + encodeURIComponent(_this.shareUrl));
      e.stopPropagation();//so the default event is not cancelled by parent element
    });

    _this.box.append(_this.urlInput).append(_this.facebook).append(_this.google).append(_this.twitter).append(_this.mail);
    $(container).append(_this.wrapper);

  }

  Share.prototype.show = function () {
    this.wrapper.fadeIn(300);
    this.urlInput.val(this.shareUrl);
    this.urlInput.trigger("click");
    this.isOpen = true;
  }

  Share.prototype.dispose = function () {
    var _this = this;
    _this.box.off();
    _this.google.off();
    _this.twitter.off();
    _this.facebook.off();
    _this.mail.off();
    _this.urlInput.off();
    _this.wrapper.off().remove();
  }

  Share.prototype.close = function () {
    this.wrapper.fadeOut(300);
    this.isOpen = false;
  }

  Share.prototype.update = function (url) {
    this.shareUrl = url;
  }

  return Share;
})(jQuery);
DFLIP.Popup = (function PopupClosure($) {

  function Popup(container, options) {
    var _this = this;
    var htmlDiv = '<div>';
    var windowParameters = "width=500,height=400";
    _this.isOpen = false;
    _this.wrapper = $('<div class="df-popup-wrapper" style="display: none;">')
      .on("click", function (e) {
        _this.close();
      });
    _this.box = $('<div class="df-popup-box">')
      .on("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
      }).appendTo(_this.wrapper);

    $(container).append(_this.wrapper);

  }

  Popup.prototype.show = function () {
    this.wrapper.fadeIn(300);
    this.isOpen = true;
  }

  Popup.prototype.dispose = function () {
    var _this = this;
    _this.box.off();
    _this.wrapper.off().remove();
  }

  Popup.prototype.close = function () {
    this.wrapper.fadeOut(300);
    this.isOpen = false;
  }

  return Popup;
})(jQuery);

/**
 * Performs navigation functions inside PDF, such as opening specified page,
 * or destination.
 * @class
 * @implements {IPDFLinkService}
 */
var PDFLinkService = (function () {
  /**
   * @constructs PDFLinkService
   */
  function PDFLinkService() {
    this.baseUrl = null;
    this.pdfDocument = null;
    this.pdfViewer = null;
    this.pdfHistory = null;

    this._pagesRefCache = null;
  }

  PDFLinkService.prototype = {
    dispose: function () {
      this.baseUrl = null;
      this.pdfDocument = null;
      this.pdfViewer = null;
      this.pdfHistory = null;

      this._pagesRefCache = null;
    },
    setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
      this.baseUrl = baseUrl;
      this.pdfDocument = pdfDocument;
      this._pagesRefCache = Object.create(null);
    },

    setViewer: function PDFLinkService_setViewer(pdfViewer) {
      this.pdfViewer = pdfViewer;
    },

    setHistory: function PDFLinkService_setHistory(pdfHistory) {
      this.pdfHistory = pdfHistory;
    },

    /**
     * @returns {number}
     */
    get pagesCount() {
      return this.pdfDocument.numPages;
    },

    /**
     * @returns {number}
     */
    get page() {
      return this.pdfViewer.currentPageNumber;
    },

    /**
     * @param {number} value
     */
    set page(value) {
      this.pdfViewer.currentPageNumber = value;
    },

    /**
     * @param dest - The PDF destination object.
     */
    navigateTo: function PDFLinkService_navigateTo(dest) {
      var destString = '';
      var self = this;

      var goToDestination = function (destRef) {
        // dest array looks like that: <page-ref> </XYZ|FitXXX> <args..>
        var pageNumber = destRef instanceof Object ? self._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R']
          : (destRef + 1);
        if (pageNumber) {
          //case double internal
          if (self.pdfViewer.contentProvider.options.pageSize == DFLIP.PAGE_SIZE.DOUBLEINTERNAL && pageNumber > 2) {
            pageNumber = pageNumber * 2 - 1;
          }

          if (pageNumber > self.pdfViewer.pageCount) {
            pageNumber = self.pdfViewer.pageCount;
          }
          self.pdfViewer.gotoPage(pageNumber);
          // self.pdfViewer.scrollPageIntoView(pageNumber, dest);

          if (self.pdfHistory) {
            // Update the browsing history.
            self.pdfHistory.push({
              dest: dest,
              hash: destString,
              page: pageNumber
            });
          }
        } else {
          self.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
            var pageNum = pageIndex + 1;
            var cacheKey = destRef.num + ' ' + destRef.gen + ' R';
            self._pagesRefCache[cacheKey] = pageNum;
            goToDestination(destRef);
          });
        }
      };

      var destinationPromise;
      if (typeof dest === 'string') {
        destString = dest;
        destinationPromise = this.pdfDocument.getDestination(dest);
      } else {
        destinationPromise = Promise.resolve(dest);
      }
      destinationPromise.then(function (destination) {
        dest = destination;
        if (!(destination instanceof Array)) {
          return; // invalid destination
        }
        goToDestination(destination[0]);
      });
    },


    /**
     * @param dest - The PDF destination object.
     */
    customNavigateTo: function PDFLinkService_navigateTo(dest) {
      if (dest == '' || dest == null || dest == 'null') return;
      var pageNumber = null;
      if (!isNaN(Math.round(dest))) {
        pageNumber = dest;
      }
      else if (typeof dest === 'string') {
        pageNumber = parseInt(dest.replace("#", ""), 10);
        if (isNaN(pageNumber)) {
          window.open(dest);
          return;
        }
      }

      if (pageNumber != null)
        this.pdfViewer.gotoPage(pageNumber);

    },

    /**
     * @param dest - The PDF destination object.
     * @returns {string} The hyperlink to the PDF object.
     */
    getDestinationHash: function PDFLinkService_getDestinationHash(dest) {
      if (typeof dest === 'string') {
        return this.getAnchorUrl('#' + escape(dest));
      }
      if (dest instanceof Array) {
        var destRef = dest[0]; // see navigateTo method for dest format
        var pageNumber = destRef instanceof Object ? this._pagesRefCache[destRef.num + ' ' + destRef.gen + ' R']
          : (destRef + 1);
        if (pageNumber) {
          var pdfOpenParams = this.getAnchorUrl('#page=' + pageNumber);
          var destKind = dest[1];
          if (typeof destKind === 'object' && 'name' in destKind &&
            destKind.name === 'XYZ') {
            var scale = (dest[4] || this.pdfViewer.currentScaleValue);
            var scaleNumber = parseFloat(scale);
            if (scaleNumber) {
              scale = scaleNumber * 100;
            }
            pdfOpenParams += '&zoom=' + scale;
            if (dest[2] || dest[3]) {
              pdfOpenParams += ',' + (dest[2] || 0) + ',' + (dest[3] || 0);
            }
          }
          return pdfOpenParams;
        }
      }
      return this.getAnchorUrl('');
    },

    /**
     * @param dest - The PDF destination object.
     * @returns {string} The hyperlink to the PDF object.
     */
    getCustomDestinationHash: function PDFLinkService_getCustomDestinationHash(dest) {
      //if (typeof dest === 'string') {
      return '#' + escape(dest);
      //}
      //return this.getAnchorUrl('');
    },


    /**
     * Prefix the full url on anchor links to make sure that links are resolved
     * relative to the current URL instead of the one defined in <base href>.
     * @param {String} anchor The anchor hash, including the #.
     * @returns {string} The hyperlink to the PDF object.
     */
    getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
      return (this.baseUrl || '') + anchor;
    },

    /**
     * @param {string} hash
     */
    setHash: function PDFLinkService_setHash(hash) {
      if (hash.indexOf('=') >= 0) {
        var params = parseQueryString(hash);
        // borrowing syntax from "Parameters for Opening PDF Files"
        if ('nameddest' in params) {
          if (this.pdfHistory) {
            this.pdfHistory.updateNextHashParam(params.nameddest);
          }
          this.navigateTo(params.nameddest);
          return;
        }
        var pageNumber, dest;
        if ('page' in params) {
          pageNumber = (params.page | 0) || 1;
        }
        if ('zoom' in params) {
          // Build the destination array.
          var zoomArgs = params.zoom.split(','); // scale,left,top
          var zoomArg = zoomArgs[0];
          var zoomArgNumber = parseFloat(zoomArg);

          if (zoomArg.indexOf('Fit') === -1) {
            // If the zoomArg is a number, it has to get divided by 100. If it's
            // a string, it should stay as it is.
            dest = [null, {name: 'XYZ'},
              zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null,
              zoomArgs.length > 2 ? (zoomArgs[2] | 0) : null,
              (zoomArgNumber ? zoomArgNumber / 100 : zoomArg)];
          } else {
            if (zoomArg === 'Fit' || zoomArg === 'FitB') {
              dest = [null, {name: zoomArg}];
            } else if ((zoomArg === 'FitH' || zoomArg === 'FitBH') ||
              (zoomArg === 'FitV' || zoomArg === 'FitBV')) {
              dest = [null, {name: zoomArg},
                zoomArgs.length > 1 ? (zoomArgs[1] | 0) : null];
            } else if (zoomArg === 'FitR') {
              if (zoomArgs.length !== 5) {
                console.error('PDFLinkService_setHash: ' +
                  'Not enough parameters for \'FitR\'.');
              } else {
                dest = [null, {name: zoomArg},
                  (zoomArgs[1] | 0), (zoomArgs[2] | 0),
                  (zoomArgs[3] | 0), (zoomArgs[4] | 0)];
              }
            } else {
              console.error('PDFLinkService_setHash: \'' + zoomArg +
                '\' is not a valid zoom value.');
            }
          }
        }
        if (dest) {
          this.pdfViewer.scrollPageIntoView(pageNumber || this.page, dest);
        } else if (pageNumber) {
          this.page = pageNumber; // simple page
        }
        if ('pagemode' in params) {
          var event = document.createEvent('CustomEvent');
          event.initCustomEvent('pagemode', true, true, {
            mode: params.pagemode
          });
          this.pdfViewer.container.dispatchEvent(event);
        }
      } else if (/^\d+$/.test(hash)) { // page number
        this.page = hash;
      } else { // named destination
        if (this.pdfHistory) {
          this.pdfHistory.updateNextHashParam(unescape(hash));
        }
        this.navigateTo(unescape(hash));
      }
    },

    /**
     * @param {string} action
     */
    executeNamedAction: function PDFLinkService_executeNamedAction(action) {
      // See PDF reference, table 8.45 - Named action
      switch (action) {
        case 'GoBack':
          if (this.pdfHistory) {
            this.pdfHistory.back();
          }
          break;

        case 'GoForward':
          if (this.pdfHistory) {
            this.pdfHistory.forward();
          }
          break;

        case 'NextPage':
          this.page++;
          break;

        case 'PrevPage':
          this.page--;
          break;

        case 'LastPage':
          this.page = this.pagesCount;
          break;

        case 'FirstPage':
          this.page = 1;
          break;

        default:
          break; // No action according to spec
      }

      var event = document.createEvent('CustomEvent');
      event.initCustomEvent('namedaction', true, true, {
        action: action
      });
      this.pdfViewer.container.dispatchEvent(event);
    },

    /**
     * @param {number} pageNum - page number.
     * @param {Object} pageRef - reference to the page.
     */
    cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
      var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
      this._pagesRefCache[refStr] = pageNum;
    }
  };

  return PDFLinkService;
})();
//PDFJS.PDFLinkService = PDFLinkService;

/**
 * @typedef {Object} TextLayerBuilderOptions
 * @property {HTMLDivElement} textLayerDiv - The text layer container.
 * @property {EventBus} eventBus - The application event bus.
 * @property {number} pageIndex - The page index.
 * @property {PageViewport} viewport - The viewport of the text layer.
 * @property {PDFFindController} findController
 * @property {boolean} enhanceTextSelection - Option to turn on improved
 *   text selection.
 */

/**
 * TextLayerBuilder provides text-selection functionality for the PDF.
 * It does this by creating overlay divs over the PDF text. These divs
 * contain text that matches the PDF text they are overlaying. This object
 * also provides a way to highlight text that is being searched for.
 * @class
 */
DFLIP.TextLayerBuilder = (function TextLayerBuilderClosure() {
  function TextLayerBuilder(options) {
    this.textLayerDiv = options.textLayerDiv;
    this.renderingDone = false;
    this.divContentDone = false;
    this.pageIdx = options.pageIndex;
    this.pageNumber = this.pageIdx + 1;
    this.matches = [];
    this.viewport = options.viewport;
    this.textDivs = [];
    this.findController = options.findController || null;
    this.textLayerRenderTask = null;
    this.enhanceTextSelection = options.enhanceTextSelection;
    this._bindMouse();
  }

  TextLayerBuilder.prototype = {
    _finishRendering: function TextLayerBuilder_finishRendering() {
      this.renderingDone = true;

      if (!this.enhanceTextSelection) {
        var endOfContent = document.createElement('div');
        endOfContent.className = 'endOfContent';
        this.textLayerDiv.appendChild(endOfContent);
      }

      /*			this.eventBus.dispatch('textlayerrendered', {
       source: this,
       pageNumber: this.pageNumber
       });*/
    },

    /**
     * Renders the text layer.
     * @param {number} timeout (optional) if specified, the rendering waits
     *   for specified amount of ms.
     */
    render: function TextLayerBuilder_render(timeout) {
      if (!this.divContentDone || this.renderingDone) {
        return;
      }

      if (this.textLayerRenderTask) {
        this.textLayerRenderTask.cancel();
        this.textLayerRenderTask = null;
      }

      this.textDivs = [];
      var textLayerFrag = document.createDocumentFragment();
      this.textLayerRenderTask = PDFJS.renderTextLayer({
        textContent: this.textContent,
        container: textLayerFrag,
        viewport: this.viewport,
        textDivs: this.textDivs,
        timeout: timeout,
        enhanceTextSelection: this.enhanceTextSelection,
      });
      this.textLayerRenderTask.promise.then(function () {
        this.textLayerDiv.appendChild(textLayerFrag);
        this._finishRendering();
        this.updateMatches();
      }.bind(this), function (reason) {
        // canceled or failed to render text layer -- skipping errors
      });
    },

    setTextContent: function TextLayerBuilder_setTextContent(textContent) {
      if (this.textLayerRenderTask) {
        this.textLayerRenderTask.cancel();
        this.textLayerRenderTask = null;
      }
      this.textContent = textContent;
      this.divContentDone = true;
    },

    convertMatches: function TextLayerBuilder_convertMatches(matches,
                                                             matchesLength) {
      var i = 0;
      var iIndex = 0;
      var bidiTexts = this.textContent.items;
      var end = bidiTexts.length - 1;
      var queryLen = (this.findController === null ? 0 : this.findController.state.query.length);
      var ret = [];
      if (!matches) {
        return ret;
      }
      for (var m = 0, len = matches.length; m < len; m++) {
        // Calculate the start position.
        var matchIdx = matches[m];

        // Loop over the divIdxs.
        while (i !== end && matchIdx >= (iIndex + bidiTexts[i].str.length)) {
          iIndex += bidiTexts[i].str.length;
          i++;
        }

        if (i === bidiTexts.length) {
          console.error('Could not find a matching mapping');
        }

        var match = {
          begin: {
            divIdx: i,
            offset: matchIdx - iIndex
          }
        };

        // Calculate the end position.
        if (matchesLength) { // multiterm search
          matchIdx += matchesLength[m];
        } else { // phrase search
          matchIdx += queryLen;
        }

        // Somewhat the same array as above, but use > instead of >= to get
        // the end position right.
        while (i !== end && matchIdx > (iIndex + bidiTexts[i].str.length)) {
          iIndex += bidiTexts[i].str.length;
          i++;
        }

        match.end = {
          divIdx: i,
          offset: matchIdx - iIndex
        };
        ret.push(match);
      }

      return ret;
    },

    renderMatches: function TextLayerBuilder_renderMatches(matches) {
      // Early exit if there is nothing to render.
      if (matches.length === 0) {
        return;
      }

      var bidiTexts = this.textContent.items;
      var textDivs = this.textDivs;
      var prevEnd = null;
      var pageIdx = this.pageIdx;
      var isSelectedPage = (this.findController === null ? false : (pageIdx === this.findController.selected.pageIdx));
      var selectedMatchIdx = (this.findController === null ? -1 : this.findController.selected.matchIdx);
      var highlightAll = (this.findController === null ? false : this.findController.state.highlightAll);
      var infinity = {
        divIdx: -1,
        offset: undefined
      };

      function beginText(begin, className) {
        var divIdx = begin.divIdx;
        textDivs[divIdx].textContent = '';
        appendTextToDiv(divIdx, 0, begin.offset, className);
      }

      function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
        var div = textDivs[divIdx];
        var content = bidiTexts[divIdx].str.substring(fromOffset, toOffset);
        var node = document.createTextNode(content);
        if (className) {
          var span = document.createElement('span');
          span.className = className;
          span.appendChild(node);
          div.appendChild(span);
          return;
        }
        div.appendChild(node);
      }

      var i0 = selectedMatchIdx, i1 = i0 + 1;
      if (highlightAll) {
        i0 = 0;
        i1 = matches.length;
      } else if (!isSelectedPage) {
        // Not highlighting all and this isn't the selected page, so do nothing.
        return;
      }

      for (var i = i0; i < i1; i++) {
        var match = matches[i];
        var begin = match.begin;
        var end = match.end;
        var isSelected = (isSelectedPage && i === selectedMatchIdx);
        var highlightSuffix = (isSelected ? ' selected' : '');

        if (this.findController) {
          this.findController.updateMatchPosition(pageIdx, i, textDivs,
            begin.divIdx);
        }

        // Match inside new div.
        if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
          // If there was a previous div, then add the text at the end.
          if (prevEnd !== null) {
            appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
          }
          // Clear the divs and set the content until the starting point.
          beginText(begin);
        } else {
          appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
        }

        if (begin.divIdx === end.divIdx) {
          appendTextToDiv(begin.divIdx, begin.offset, end.offset,
            'highlight' + highlightSuffix);
        } else {
          appendTextToDiv(begin.divIdx, begin.offset, infinity.offset,
            'highlight begin' + highlightSuffix);
          for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
            textDivs[n0].className = 'highlight middle' + highlightSuffix;
          }
          beginText(end, 'highlight end' + highlightSuffix);
        }
        prevEnd = end;
      }

      if (prevEnd) {
        appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
      }
    },

    updateMatches: function TextLayerBuilder_updateMatches() {
      // Only show matches when all rendering is done.
      if (!this.renderingDone) {
        return;
      }

      // Clear all matches.
      var matches = this.matches;
      var textDivs = this.textDivs;
      var bidiTexts = this.textContent.items;
      var clearedUntilDivIdx = -1;

      // Clear all current matches.
      for (var i = 0, len = matches.length; i < len; i++) {
        var match = matches[i];
        var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
        for (var n = begin, end = match.end.divIdx; n <= end; n++) {
          var div = textDivs[n];
          div.textContent = bidiTexts[n].str;
          div.className = '';
        }
        clearedUntilDivIdx = match.end.divIdx + 1;
      }

      if (this.findController === null || !this.findController.active) {
        return;
      }

      // Convert the matches on the page controller into the match format
      // used for the textLayer.
      var pageMatches, pageMatchesLength;
      if (this.findController !== null) {
        pageMatches = this.findController.pageMatches[this.pageIdx] || null;
        pageMatchesLength = (this.findController.pageMatchesLength)
          ? this.findController.pageMatchesLength[this.pageIdx] || null : null;
      }

      this.matches = this.convertMatches(pageMatches, pageMatchesLength);
      this.renderMatches(this.matches);
    },

    /**
     * Fixes text selection: adds additional div where mouse was clicked.
     * This reduces flickering of the content if mouse slowly dragged down/up.
     * @private
     */
    _bindMouse: function TextLayerBuilder_bindMouse() {
      var div = this.textLayerDiv;
      var self = this;
      div.addEventListener('mousedown', function (e) {
        if (self.enhanceTextSelection && self.textLayerRenderTask) {
          self.textLayerRenderTask.expandTextDivs(true);
          return;
        }
        var end = div.querySelector('.endOfContent');
        if (!end) {
          return;
        }
        // On non-Firefox browsers, the selection will feel better if the height
        // of the endOfContent div will be adjusted to start at mouse click
        // location -- this will avoid flickering when selections moves up.
        // However it does not work when selection started on empty space.
        var adjustTop = e.target !== div;
        adjustTop = adjustTop && window.getComputedStyle(end).getPropertyValue('-moz-user-select') !== 'none';
        if (adjustTop) {
          var divBounds = div.getBoundingClientRect();
          var r = Math.max(0, (e.pageY - divBounds.top) / divBounds.height);
          end.style.top = (r * 100).toFixed(2) + '%';
        }
        end.classList.add('active');
      });
      div.addEventListener('mouseup', function (e) {
        if (self.enhanceTextSelection && self.textLayerRenderTask) {
          self.textLayerRenderTask.expandTextDivs(false);
          return;
        }
        var end = div.querySelector('.endOfContent');
        if (!end) {
          return;
        }
        end.style.top = '';
        end.classList.remove('active');
      });
    },
  };
  return TextLayerBuilder;
})();

DFLIP.ConvertPageLinks = function () {

  var w = arguments[0] / 100, h = arguments[1] / 100;

  var toPercent = function (_x, _y, _w, _h, _dest) {
    return {
      x: _x / w,
      y: _y / h,
      w: _w / w,
      h: _h / h,
      dest: _dest
    };
  };

  var percents = [];
  var input;

  for (var index = 2; index < arguments.length; index++) {
    input = arguments[index];
    percents[index - 2] = toPercent.apply(this, input);
  }

  return percents;
};

DFLIP.parseLinks = function (links) {
  var _links;
  if (links != null && links.length > 0) {
    for (var index = 0; index < links.length; index++) {
      _links = links[index];

      if (_links != null && _links[0] != null && _links[0].dest == null) {

        _links = DFLIP.ConvertPageLinks.apply(this, _links);
        links[index] = _links;
      }
    }
  }
  return links;
};

/**
 * DFLIP.parseBooks
 */
(function ($) {

  //php and javascript interpret booleans differently so we use string checks
  function isTrue(val) {
    return val == "true" || val == true;
  }

  function checkValues(options) {

    //boolean values
    if (options.webgl != null) options.webgl = isTrue(options.webgl);
    if (options.enableDownload != null) options.enableDownload = isTrue(options.enableDownload);
    if (options.scrollWheel != null) options.scrollWheel = isTrue(options.scrollWheel);
    if (options.autoEnableOutline != null) options.autoEnableOutline = isTrue(options.autoEnableOutline);
    if (options.autoEnableThumbnail != null) options.autoEnableThumbnail = isTrue(options.autoEnableThumbnail);
    if (options.transparent != null) options.transparent = isTrue(options.transparent);
    if (options.overwritePDFOutline != null) options.overwritePDFOutline = isTrue(options.overwritePDFOutline);
    if (options.soundEnable != null) options.soundEnable = isTrue(options.soundEnable);
    if (options.forceFit != null) options.forceFit = isTrue(options.forceFit);
    if (options.enableAnnotation != null) options.enableAnnotation = isTrue(options.enableAnnotation);
    if (options.webglShadow != null) options.webglShadow = isTrue(options.webglShadow);
    if (options.autoPlay != null) options.autoPlay = isTrue(options.autoPlay);
    if (options.autoPlayStart != null) options.autoPlayStart = isTrue(options.autoPlayStart);

    //integer value
    if (options.paddingTop != null) options.paddingTop = parseInt(options.paddingTop, 10);
    if (options.paddingRight != null) options.paddingRight = parseInt(options.paddingRight, 10);
    if (options.paddingBottom != null) options.paddingBottom = parseInt(options.paddingBottom, 10);
    if (options.paddingLeft != null) options.paddingLeft = parseInt(options.paddingLeft, 10);
    if (options.zoomRatio != null) options.zoomRatio = parseFloat(options.zoomRatio, 10);
    if (options.stiffness != null) options.stiffness = parseFloat(options.stiffness, 10);
    if (options.autoPlayDuration != null) options.autoPlayDuration = parseInt(options.autoPlayDuration, 10);

    if (options.pageMode == 0 || options.pageMode == "0")
      options.pageMode = null;
    if (options.singlePageMode == 0 || options.singlePageMode == "0")
      options.singlePageMode = null;
  }

  function parseOptions(options) {

    //bail out if already parsed or failed
    if (options.parsed == true) return;

    options.parsed = true;
    //options.links are in json format
    //{"1":[]}
    //convert them to array format
    var links = [];
    checkValues(options);

    if (typeof dFlipWPGlobal !== 'undefined' && options.wpOptions == 'true') {

      try {
        for (var key in options.links) {
          var _pagelinks = options.links[key];
          var pagelink = [100, 100];
          for (var l = 0; l < _pagelinks.length; l++) {
            var _link = _pagelinks[l];
            var _values = _link.substr(1).slice(0, -1).split(",");
            var _linkarr = [];
            for (var v = 0; v < 5; v++) {
              _linkarr[v] = _values[v];
            }
            pagelink.push(_linkarr);
          }
          links[parseInt(key, 10) + 1] = pagelink;
        }
      }
      catch (error) {
        console.error(error.stack);
      }
      options.links = DFLIP.parseLinks(links);

    } else {
      options.links = DFLIP.parseLinks(options.links);
    }

  }

  DFLIP.getOptions = function (book) {

    book = $(book);

    var book_id = book.attr("id");

    var options = "option_" + book_id,
      source = book.attr("source") || book.attr("df-source");

    //verify and optimize the values
    options = options == null || options == "" || window[options] == null ? {} : window[options];

    options.source = source == null || source == "" ? options.source : source;

    /*As of 1.2.6 attribute values are also considered as options in some cases*/
    var attrOptions = {
      webgl: book.attr("webgl"),
      height: book.attr("height"),
      soundEnable: book.attr("sound"),
      transparent: book.attr("transparent"),
      enableDownload: book.attr("download"),
      duration: book.attr("duration"),
      hard: book.attr("hard"),
      pageMode: book.attr("pagemode"),
      direction: book.attr("direction"),
      backgroundColor: book.attr("backgroundcolor"),
      scrollWheel: book.attr("scrollwheel"),
      backgroundImage: book.attr("backgroundimage"),
      paddingTop: book.attr("paddingtop"),
      paddingRight: book.attr("paddingright"),
      paddingBottom: book.attr("paddingbottom"),
      paddingLeft: book.attr("paddingleft"),
      wpOptions: book.attr("wpoptions")
    };

    options = $.extend(true, {}, options, attrOptions);

    parseOptions(options);

    return options;
  }

  DFLIP.parseBooks = function () {

    $('._df_button, ._df_thumb, ._df_custom, ._df_book').each(function () {

      var book = $(this);

      //fetch any existing values
      var parsed = book.attr("parsed") || book.attr("df-parsed");

      //skip if already parsed or failed
      if (parsed !== "true") {
        book.attr("df-parsed", "true")

        if (book.hasClass("_df_book")) {

          var book_id = book.attr("id"),
            slug = book.attr("slug");
          var options = DFLIP.getOptions(book);
          options.id = book_id;
          if (slug != null)
            options.slug = slug;
          if (book_id) {
            window[book_id.toString()] = $(book).flipBook(options.source, options);
          }
          else {
            $(book).flipBook(options.source, options);
          }

        }
        else {

          if (book.hasClass("_df_thumb")) {
            var wrapper = $("<div class='_df_book-cover'>");

            var text = book.html().trim();
            book.html("");
            var title = $("<span class='_df_book-title'>").html(text).appendTo(wrapper);

            var thumb = book.attr("thumb") || book.attr("df-thumb"),
              thumbType = book.attr("thumbtype") || DFLIP.defaults.thumbElement || "div",
              tags = book.attr("tags") || book.attr("df-tags");

            if (tags) {
              tags = tags.split(",");

              if (tags.length > 0) {
                for (var tagcount = 0; tagcount < tags.length; tagcount++) {
                  book.append("<span class='_df_book-tag'>" + tags[tagcount] + "</span>");
                }
              }
            }

            if (thumb != null && thumb.toString().trim() != '') {
              if (thumbType == 'img') {
                wrapper.append('<img src="' + thumb + '" alt="' + text + '"/>');
                book.attr("thumb-type", "img");
              } else {
                wrapper.css({
                  backgroundImage: "url(" + thumb + ")"
                });
              }
            } else {
              wrapper.addClass("_df_thumb-not-found");
            }

            book.append(wrapper);
          }

        }

      }
    });

  };

  $(document).ready(function () {

    //Autodetection if the folder structure is copied properly
    if (typeof dFlipLocation == 'undefined' && DFLIP.autoDetectLocation != false) {
      $("script").each(function () {
        var src = $(this)[0].src;
        if ((src.indexOf("/dflip.js") > -1 || src.indexOf("/dflip.min.js") > -1 )
          && (src.indexOf("https://") > -1 || src.indexOf("http://") > -1 ) && src.indexOf("js/dflip.") > -1) {
          var splits = src.split("/");
          window.dFlipLocation = splits.slice(0, -2).join("/");
        }
      });
    }

    if (typeof dFlipLocation !== 'undefined') {

      //add ending forward slash trail for safety
      if (dFlipLocation.length > 2 && dFlipLocation.slice(-1) !== "/") {
        window.dFlipLocation += "/";
      }

      //PRESENTATION.defaults.backgroundImage = "blank"; "images/textures/white.jpg";
      //PRESENTATION.defaults.textureLoadFallback = dFlipLocation + "images/textures/white.jpg";
      DFLIP.defaults.mockupjsSrc = dFlipLocation + "js/libs/mockup.min.js";
      DFLIP.defaults.pdfjsSrc = dFlipLocation + "js/libs/pdf.min.js";
      DFLIP.defaults.pdfjsCompatibilitySrc = dFlipLocation + "js/libs/compatibility.js";
      DFLIP.defaults.threejsSrc = dFlipLocation + "js/libs/three.min.js";
      DFLIP.defaults.pdfjsWorkerSrc = dFlipLocation + "js/libs/pdf.worker.min.js";
      DFLIP.defaults.soundFile = dFlipLocation + "sound/turn2.mp3";
      DFLIP.defaults.imagesLocation = dFlipLocation + "images";
      DFLIP.defaults.imageResourcesPath = dFlipLocation + "images/pdfjs/";
      DFLIP.defaults.cMapUrl = dFlipLocation + "js/libs/cmaps/";

      if (typeof dFlipWPGlobal !== 'undefined') {

        checkValues(dFlipWPGlobal);

        $.extend(DFLIP.defaults, dFlipWPGlobal);
      }
    }

    DFLIP.preParseHash = window.location.hash;
    DFLIP.parseBooks();

    $('body').on('click', '._df_button, ._df_thumb, ._df_custom', function (event) {
      event.preventDefault();
      //cache the book element
      var book = $(this);

      if (!window.dfLightBox) {
        window.dfLightBox = new DFLightBox(function () {

          if (window.location.hash.indexOf("#dflip-") == 0)
            window.location.hash = "#_";
          window.dfActiveLightBoxBook.dispose();
          window.dfActiveLightBoxBook = null;
        });
      }

      window.dfLightBox.duration = 500;

      if (window.dfActiveLightBoxBook && window.dfActiveLightBoxBook.dispose) {
        window.dfActiveLightBoxBook.dispose();

      } else {
        window.dfLightBox.show(
          function () {
            //                            $("body").addClass("df-no-scroll");
            var options = DFLIP.getOptions(book);
            options.transparent = false;
            options.id = book.attr("id");
            var slug = book.attr("slug");
            if (slug != null)
              options.slug = slug;
            options.isLightBox = true;
            window.dfActiveLightBoxBook = $(window.dfLightBox.container).flipBook(options.source, options);
          }
        );
      }


    });

    if (DFLIP.utils.isSafari || DFLIP.utils.isIOS) {
      $('body').addClass("df-webkit");
    }
    //parse hash and check if any exists
    if (DFLIP.preParseHash && DFLIP.preParseHash.indexOf('dflip-') >= 0) {
      var id = DFLIP.preParseHash.split('dflip-')[1].split('/')[0];
      var page = DFLIP.preParseHash.split('dflip-')[1].split('/')[1];
      if (page != null) {
        page = page.split('/')[0];
      }
      var book;
      //first check for slug pattern
      book = $("[slug=" + id + "]");
      //then id pattern
      if (book.length == 0) book = $('#' + id);

      if (book.length > 0) {

        //var oldHash = window.location.hash;
        //window.location.hash = id;
        //window.location.hash = DFLIP.preParseHash;

        if (page != null) {
          book.data("page", page)
        }

        if (book.is('._df_button, ._df_thumb, ._df_custom')) {
          book.trigger("click");
        }
      }
    }

    $('body').on('click', '.df-ui-sidemenu-close', function () {
      var $this = $(this);
      $this.closest(".df-container").find(".df-ui-outline.df-active , .df-ui-thumbnail.df-active").trigger("click");
    });


  });

})(jQuery);

/* Modernizr 2.5.3 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-fontface-borderradius-boxshadow-opacity-rgba-cssgradients-shiv-cssclasses-teststyles-testprop-testallprops-prefixes-domprefixes-load
 */
;window.Modernizr=function(a,b,c){function z(a){j.cssText=a}function A(a,b){return z(m.join(a+";")+(b||""))}function B(a,b){return typeof a===b}function C(a,b){return!!~(""+a).indexOf(b)}function D(a,b){for(var d in a)if(j[a[d]]!==c)return b=="pfx"?a[d]:!0;return!1}function E(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:B(f,"function")?f.bind(d||b):f}return!1}function F(a,b,c){var d=a.charAt(0).toUpperCase()+a.substr(1),e=(a+" "+o.join(d+" ")+d).split(" ");return B(b,"string")||B(b,"undefined")?D(e,b):(e=(a+" "+p.join(d+" ")+d).split(" "),E(e,b,c))}var d="2.5.3",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m=" -webkit- -moz- -o- -ms- ".split(" "),n="Webkit Moz O ms",o=n.split(" "),p=n.toLowerCase().split(" "),q={},r={},s={},t=[],u=t.slice,v,w=function(a,c,d,e){var f,i,j,k=b.createElement("div"),l=b.body,m=l?l:b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),k.appendChild(j);return f=["&#173;","<style>",a,"</style>"].join(""),k.id=h,(l?k:m).innerHTML+=f,m.appendChild(k),l||(m.style.background="",g.appendChild(m)),i=c(k,a),l?k.parentNode.removeChild(k):m.parentNode.removeChild(m),!!i},x={}.hasOwnProperty,y;!B(x,"undefined")&&!B(x.call,"undefined")?y=function(a,b){return x.call(a,b)}:y=function(a,b){return b in a&&B(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=u.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(u.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(u.call(arguments)))};return e});var G=function(a,c){var d=a.join(""),f=c.length;w(d,function(a,c){var d=b.styleSheets[b.styleSheets.length-1],g=d?d.cssRules&&d.cssRules[0]?d.cssRules[0].cssText:d.cssText||"":"",h=a.childNodes,i={};while(f--)i[h[f].id]=h[f];e.fontface=/src/i.test(g)&&g.indexOf(c.split(" ")[0])===0},f,c)}(['@font-face {font-family:"font";src:url("https://")}'],["fontface"]);q.rgba=function(){return z("background-color:rgba(150,255,150,.5)"),C(j.backgroundColor,"rgba")},q.borderradius=function(){return F("borderRadius")},q.boxshadow=function(){return F("boxShadow")},q.opacity=function(){return A("opacity:.55"),/^0.55$/.test(j.opacity)},q.cssgradients=function(){var a="background-image:",b="gradient(linear,left top,right bottom,from(#9f9),to(white));",c="linear-gradient(left top,#9f9, white);";return z((a+"-webkit- ".split(" ").join(b+a)+m.join(c+a)).slice(0,-a.length)),C(j.backgroundImage,"gradient")},q.fontface=function(){return e.fontface};for(var H in q)y(q,H)&&(v=H.toLowerCase(),e[v]=q[H](),t.push((e[v]?"":"no-")+v));return z(""),i=k=null,function(a,b){function g(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function h(){var a=k.elements;return typeof a=="string"?a.split(" "):a}function i(a){var b={},c=a.createElement,e=a.createDocumentFragment,f=e();a.createElement=function(a){var e=(b[a]||(b[a]=c(a))).cloneNode();return k.shivMethods&&e.canHaveChildren&&!d.test(a)?f.appendChild(e):e},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+h().join().replace(/\w+/g,function(a){return b[a]=c(a),f.createElement(a),'c("'+a+'")'})+");return n}")(k,f)}function j(a){var b;return a.documentShived?a:(k.shivCSS&&!e&&(b=!!g(a,"article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio{display:none}canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden]{display:none}audio[controls]{display:inline-block;*display:inline;*zoom:1}mark{background:#FF0;color:#000}")),f||(b=!i(a)),b&&(a.documentShived=b),a)}var c=a.html5||{},d=/^<|^(?:button|form|map|select|textarea)$/i,e,f;(function(){var a=b.createElement("a");a.innerHTML="<xyz></xyz>",e="hidden"in a,f=a.childNodes.length==1||function(){try{b.createElement("a")}catch(a){return!0}var c=b.createDocumentFragment();return typeof c.cloneNode=="undefined"||typeof c.createDocumentFragment=="undefined"||typeof c.createElement=="undefined"}()})();var k={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:j};a.html5=k,j(b)}(this,b),e._version=d,e._prefixes=m,e._domPrefixes=p,e._cssomPrefixes=o,e.testProp=function(a){return D([a])},e.testAllProps=F,e.testStyles=w,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+t.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return o.call(a)=="[object Function]"}function e(a){return typeof a=="string"}function f(){}function g(a){return!a||a=="loaded"||a=="complete"||a=="uninitialized"}function h(){var a=p.shift();q=1,a?a.t?m(function(){(a.t=="c"?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){a!="img"&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l={},o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};y[c]===1&&(r=1,y[c]=[],l=b.createElement(a)),a=="object"?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),a!="img"&&(r||y[c]===2?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i(b=="c"?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),p.length==1&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&o.call(a.opera)=="[object Opera]",l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return o.call(a)=="[object Array]"},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,i){var j=b(a),l=j.autoCallback;j.url.split(".").pop().split("?").shift(),j.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]||h),j.instead?j.instead(a,e,f,g,i):(y[j.url]?j.noexec=!0:y[j.url]=1,f.load(j.url,j.forceCSS||!j.forceJS&&"css"==j.url.split(".").pop().split("?").shift()?"c":c,j.noexec,j.attrs,j.timeout),(d(e)||d(l))&&f.load(function(){k(),e&&e(j.origUrl,i,g),l&&l(j.origUrl,i,g),y[j.url]=2})))}function i(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var j,l,m=this.yepnope.loader;if(e(a))g(a,0,m,0);else if(w(a))for(j=0;j<a.length;j++)l=a[j],e(l)?g(l,0,m,0):w(l)?B(l):Object(l)===l&&i(l,m);else Object(a)===a&&i(a,m)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,b.readyState==null&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
/*
 * jQuery FlexSlider v2.1
 * Copyright 2012 WooThemes
 * Contributing Author: Tyler Smith
 */
;(function(d){d.flexslider=function(i,k){var a=d(i),c=d.extend({},d.flexslider.defaults,k),e=c.namespace,p="ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch,t=p?"touchend":"click",l="vertical"===c.direction,m=c.reverse,h=0<c.itemWidth,r="fade"===c.animation,s=""!==c.asNavFor,f={};d.data(i,"flexslider",a);f={init:function(){a.animating=!1;a.currentSlide=c.startAt;a.animatingTo=a.currentSlide;a.atEnd=0===a.currentSlide||a.currentSlide===a.last;a.containerSelector=c.selector.substr(0,
 c.selector.search(" "));a.slides=d(c.selector,a);a.container=d(a.containerSelector,a);a.count=a.slides.length;a.syncExists=0<d(c.sync).length;"slide"===c.animation&&(c.animation="swing");a.prop=l?"top":"marginLeft";a.args={};a.manualPause=!1;var b=a,g;if(g=!c.video)if(g=!r)if(g=c.useCSS)a:{g=document.createElement("div");var n=["perspectiveProperty","WebkitPerspective","MozPerspective","OPerspective","msPerspective"],e;for(e in n)if(void 0!==g.style[n[e]]){a.pfx=n[e].replace("Perspective","").toLowerCase();
 a.prop="-"+a.pfx+"-transform";g=!0;break a}g=!1}b.transitions=g;""!==c.controlsContainer&&(a.controlsContainer=0<d(c.controlsContainer).length&&d(c.controlsContainer));""!==c.manualControls&&(a.manualControls=0<d(c.manualControls).length&&d(c.manualControls));c.randomize&&(a.slides.sort(function(){return Math.round(Math.random())-0.5}),a.container.empty().append(a.slides));a.doMath();s&&f.asNav.setup();a.setup("init");c.controlNav&&f.controlNav.setup();c.directionNav&&f.directionNav.setup();c.keyboard&&
 (1===d(a.containerSelector).length||c.multipleKeyboard)&&d(document).bind("keyup",function(b){b=b.keyCode;if(!a.animating&&(39===b||37===b))b=39===b?a.getTarget("next"):37===b?a.getTarget("prev"):!1,a.flexAnimate(b,c.pauseOnAction)});c.mousewheel&&a.bind("mousewheel",function(b,g){b.preventDefault();var d=0>g?a.getTarget("next"):a.getTarget("prev");a.flexAnimate(d,c.pauseOnAction)});c.pausePlay&&f.pausePlay.setup();c.slideshow&&(c.pauseOnHover&&a.hover(function(){!a.manualPlay&&!a.manualPause&&a.pause()},
 function(){!a.manualPause&&!a.manualPlay&&a.play()}),0<c.initDelay?setTimeout(a.play,c.initDelay):a.play());p&&c.touch&&f.touch();(!r||r&&c.smoothHeight)&&d(window).bind("resize focus",f.resize);setTimeout(function(){c.start(a)},200)},asNav:{setup:function(){a.asNav=!0;a.animatingTo=Math.floor(a.currentSlide/a.move);a.currentItem=a.currentSlide;a.slides.removeClass(e+"active-slide").eq(a.currentItem).addClass(e+"active-slide");a.slides.click(function(b){b.preventDefault();var b=d(this),g=b.index();
 !d(c.asNavFor).data("flexslider").animating&&!b.hasClass("active")&&(a.direction=a.currentItem<g?"next":"prev",a.flexAnimate(g,c.pauseOnAction,!1,!0,!0))})}},controlNav:{setup:function(){a.manualControls?f.controlNav.setupManual():f.controlNav.setupPaging()},setupPaging:function(){var b=1,g;a.controlNavScaffold=d('<ol class="'+e+"control-nav "+e+("thumbnails"===c.controlNav?"control-thumbs":"control-paging")+'"></ol>');if(1<a.pagingCount)for(var n=0;n<a.pagingCount;n++)g="thumbnails"===c.controlNav?
 '<img src="'+a.slides.eq(n).attr("data-thumb")+'"/>':"<a>"+b+"</a>",a.controlNavScaffold.append("<li>"+g+"</li>"),b++;a.controlsContainer?d(a.controlsContainer).append(a.controlNavScaffold):a.append(a.controlNavScaffold);f.controlNav.set();f.controlNav.active();a.controlNavScaffold.delegate("a, img",t,function(b){b.preventDefault();var b=d(this),g=a.controlNav.index(b);b.hasClass(e+"active")||(a.direction=g>a.currentSlide?"next":"prev",a.flexAnimate(g,c.pauseOnAction))});p&&a.controlNavScaffold.delegate("a",
 "click touchstart",function(a){a.preventDefault()})},setupManual:function(){a.controlNav=a.manualControls;f.controlNav.active();a.controlNav.live(t,function(b){b.preventDefault();var b=d(this),g=a.controlNav.index(b);b.hasClass(e+"active")||(g>a.currentSlide?a.direction="next":a.direction="prev",a.flexAnimate(g,c.pauseOnAction))});p&&a.controlNav.live("click touchstart",function(a){a.preventDefault()})},set:function(){a.controlNav=d("."+e+"control-nav li "+("thumbnails"===c.controlNav?"img":"a"),
 a.controlsContainer?a.controlsContainer:a)},active:function(){a.controlNav.removeClass(e+"active").eq(a.animatingTo).addClass(e+"active")},update:function(b,c){1<a.pagingCount&&"add"===b?a.controlNavScaffold.append(d("<li><a>"+a.count+"</a></li>")):1===a.pagingCount?a.controlNavScaffold.find("li").remove():a.controlNav.eq(c).closest("li").remove();f.controlNav.set();1<a.pagingCount&&a.pagingCount!==a.controlNav.length?a.update(c,b):f.controlNav.active()}},directionNav:{setup:function(){var b=d('<ul class="'+
 e+'direction-nav"><li><a class="'+e+'prev" href="#">'+c.prevText+'</a></li><li><a class="'+e+'next" href="#">'+c.nextText+"</a></li></ul>");a.controlsContainer?(d(a.controlsContainer).append(b),a.directionNav=d("."+e+"direction-nav li a",a.controlsContainer)):(a.append(b),a.directionNav=d("."+e+"direction-nav li a",a));f.directionNav.update();a.directionNav.bind(t,function(b){b.preventDefault();b=d(this).hasClass(e+"next")?a.getTarget("next"):a.getTarget("prev");a.flexAnimate(b,c.pauseOnAction)});
 p&&a.directionNav.bind("click touchstart",function(a){a.preventDefault()})},update:function(){var b=e+"disabled";1===a.pagingCount?a.directionNav.addClass(b):c.animationLoop?a.directionNav.removeClass(b):0===a.animatingTo?a.directionNav.removeClass(b).filter("."+e+"prev").addClass(b):a.animatingTo===a.last?a.directionNav.removeClass(b).filter("."+e+"next").addClass(b):a.directionNav.removeClass(b)}},pausePlay:{setup:function(){var b=d('<div class="'+e+'pauseplay"><a></a></div>');a.controlsContainer?
 (a.controlsContainer.append(b),a.pausePlay=d("."+e+"pauseplay a",a.controlsContainer)):(a.append(b),a.pausePlay=d("."+e+"pauseplay a",a));f.pausePlay.update(c.slideshow?e+"pause":e+"play");a.pausePlay.bind(t,function(b){b.preventDefault();d(this).hasClass(e+"pause")?(a.manualPause=!0,a.manualPlay=!1,a.pause()):(a.manualPause=!1,a.manualPlay=!0,a.play())});p&&a.pausePlay.bind("click touchstart",function(a){a.preventDefault()})},update:function(b){"play"===b?a.pausePlay.removeClass(e+"pause").addClass(e+
 "play").text(c.playText):a.pausePlay.removeClass(e+"play").addClass(e+"pause").text(c.pauseText)}},touch:function(){function b(b){j=l?d-b.touches[0].pageY:d-b.touches[0].pageX;p=l?Math.abs(j)<Math.abs(b.touches[0].pageX-e):Math.abs(j)<Math.abs(b.touches[0].pageY-e);if(!p||500<Number(new Date)-k)b.preventDefault(),!r&&a.transitions&&(c.animationLoop||(j/=0===a.currentSlide&&0>j||a.currentSlide===a.last&&0<j?Math.abs(j)/q+2:1),a.setProps(f+j,"setTouch"))}function g(){i.removeEventListener("touchmove",
 b,!1);if(a.animatingTo===a.currentSlide&&!p&&null!==j){var h=m?-j:j,l=0<h?a.getTarget("next"):a.getTarget("prev");a.canAdvance(l)&&(550>Number(new Date)-k&&50<Math.abs(h)||Math.abs(h)>q/2)?a.flexAnimate(l,c.pauseOnAction):r||a.flexAnimate(a.currentSlide,c.pauseOnAction,!0)}i.removeEventListener("touchend",g,!1);f=j=e=d=null}var d,e,f,q,j,k,p=!1;i.addEventListener("touchstart",function(j){a.animating?j.preventDefault():1===j.touches.length&&(a.pause(),q=l?a.h:a.w,k=Number(new Date),f=h&&m&&a.animatingTo===
 a.last?0:h&&m?a.limit-(a.itemW+c.itemMargin)*a.move*a.animatingTo:h&&a.currentSlide===a.last?a.limit:h?(a.itemW+c.itemMargin)*a.move*a.currentSlide:m?(a.last-a.currentSlide+a.cloneOffset)*q:(a.currentSlide+a.cloneOffset)*q,d=l?j.touches[0].pageY:j.touches[0].pageX,e=l?j.touches[0].pageX:j.touches[0].pageY,i.addEventListener("touchmove",b,!1),i.addEventListener("touchend",g,!1))},!1)},resize:function(){!a.animating&&a.is(":visible")&&(h||a.doMath(),r?f.smoothHeight():h?(a.slides.width(a.computedW),
 a.update(a.pagingCount),a.setProps()):l?(a.viewport.height(a.h),a.setProps(a.h,"setTotal")):(c.smoothHeight&&f.smoothHeight(),a.newSlides.width(a.computedW),a.setProps(a.computedW,"setTotal")))},smoothHeight:function(b){if(!l||r){var c=r?a:a.viewport;b?c.animate({height:a.slides.eq(a.animatingTo).height()},b):c.height(a.slides.eq(a.animatingTo).height())}},sync:function(b){var g=d(c.sync).data("flexslider"),e=a.animatingTo;switch(b){case "animate":g.flexAnimate(e,c.pauseOnAction,!1,!0);break;case "play":!g.playing&&
 !g.asNav&&g.play();break;case "pause":g.pause()}}};a.flexAnimate=function(b,g,n,i,k){s&&1===a.pagingCount&&(a.direction=a.currentItem<b?"next":"prev");if(!a.animating&&(a.canAdvance(b,k)||n)&&a.is(":visible")){if(s&&i)if(n=d(c.asNavFor).data("flexslider"),a.atEnd=0===b||b===a.count-1,n.flexAnimate(b,!0,!1,!0,k),a.direction=a.currentItem<b?"next":"prev",n.direction=a.direction,Math.ceil((b+1)/a.visible)-1!==a.currentSlide&&0!==b)a.currentItem=b,a.slides.removeClass(e+"active-slide").eq(b).addClass(e+
 "active-slide"),b=Math.floor(b/a.visible);else return a.currentItem=b,a.slides.removeClass(e+"active-slide").eq(b).addClass(e+"active-slide"),!1;a.animating=!0;a.animatingTo=b;c.before(a);g&&a.pause();a.syncExists&&!k&&f.sync("animate");c.controlNav&&f.controlNav.active();h||a.slides.removeClass(e+"active-slide").eq(b).addClass(e+"active-slide");a.atEnd=0===b||b===a.last;c.directionNav&&f.directionNav.update();b===a.last&&(c.end(a),c.animationLoop||a.pause());if(r)p?(a.slides.eq(a.currentSlide).css({opacity:0,
 zIndex:1}),a.slides.eq(b).css({opacity:1,zIndex:2}),a.animating=!1,a.currentSlide=a.animatingTo):(a.slides.eq(a.currentSlide).fadeOut(c.animationSpeed,c.easing),a.slides.eq(b).fadeIn(c.animationSpeed,c.easing,a.wrapup));else{var q=l?a.slides.filter(":first").height():a.computedW;h?(b=c.itemWidth>a.w?2*c.itemMargin:c.itemMargin,b=(a.itemW+b)*a.move*a.animatingTo,b=b>a.limit&&1!==a.visible?a.limit:b):b=0===a.currentSlide&&b===a.count-1&&c.animationLoop&&"next"!==a.direction?m?(a.count+a.cloneOffset)*
 q:0:a.currentSlide===a.last&&0===b&&c.animationLoop&&"prev"!==a.direction?m?0:(a.count+1)*q:m?(a.count-1-b+a.cloneOffset)*q:(b+a.cloneOffset)*q;a.setProps(b,"",c.animationSpeed);if(a.transitions){if(!c.animationLoop||!a.atEnd)a.animating=!1,a.currentSlide=a.animatingTo;a.container.unbind("webkitTransitionEnd transitionend");a.container.bind("webkitTransitionEnd transitionend",function(){a.wrapup(q)})}else a.container.animate(a.args,c.animationSpeed,c.easing,function(){a.wrapup(q)})}c.smoothHeight&&
 f.smoothHeight(c.animationSpeed)}};a.wrapup=function(b){!r&&!h&&(0===a.currentSlide&&a.animatingTo===a.last&&c.animationLoop?a.setProps(b,"jumpEnd"):a.currentSlide===a.last&&(0===a.animatingTo&&c.animationLoop)&&a.setProps(b,"jumpStart"));a.animating=!1;a.currentSlide=a.animatingTo;c.after(a)};a.animateSlides=function(){a.animating||a.flexAnimate(a.getTarget("next"))};a.pause=function(){clearInterval(a.animatedSlides);a.playing=!1;c.pausePlay&&f.pausePlay.update("play");a.syncExists&&f.sync("pause")};
 a.play=function(){a.animatedSlides=setInterval(a.animateSlides,c.slideshowSpeed);a.playing=!0;c.pausePlay&&f.pausePlay.update("pause");a.syncExists&&f.sync("play")};a.canAdvance=function(b,g){var d=s?a.pagingCount-1:a.last;return g?!0:s&&a.currentItem===a.count-1&&0===b&&"prev"===a.direction?!0:s&&0===a.currentItem&&b===a.pagingCount-1&&"next"!==a.direction?!1:b===a.currentSlide&&!s?!1:c.animationLoop?!0:a.atEnd&&0===a.currentSlide&&b===d&&"next"!==a.direction?!1:a.atEnd&&a.currentSlide===d&&0===
 b&&"next"===a.direction?!1:!0};a.getTarget=function(b){a.direction=b;return"next"===b?a.currentSlide===a.last?0:a.currentSlide+1:0===a.currentSlide?a.last:a.currentSlide-1};a.setProps=function(b,g,d){var e,f=b?b:(a.itemW+c.itemMargin)*a.move*a.animatingTo;e=-1*function(){if(h)return"setTouch"===g?b:m&&a.animatingTo===a.last?0:m?a.limit-(a.itemW+c.itemMargin)*a.move*a.animatingTo:a.animatingTo===a.last?a.limit:f;switch(g){case "setTotal":return m?(a.count-1-a.currentSlide+a.cloneOffset)*b:(a.currentSlide+
 a.cloneOffset)*b;case "setTouch":return b;case "jumpEnd":return m?b:a.count*b;case "jumpStart":return m?a.count*b:b;default:return b}}()+"px";a.transitions&&(e=l?"translate3d(0,"+e+",0)":"translate3d("+e+",0,0)",d=void 0!==d?d/1E3+"s":"0s",a.container.css("-"+a.pfx+"-transition-duration",d));a.args[a.prop]=e;(a.transitions||void 0===d)&&a.container.css(a.args)};a.setup=function(b){if(r)a.slides.css({width:"100%","float":"left",marginRight:"-100%",position:"relative"}),"init"===b&&(p?a.slides.css({opacity:0,
 display:"block",webkitTransition:"opacity "+c.animationSpeed/1E3+"s ease",zIndex:1}).eq(a.currentSlide).css({opacity:1,zIndex:2}):a.slides.eq(a.currentSlide).fadeIn(c.animationSpeed,c.easing)),c.smoothHeight&&f.smoothHeight();else{var g,n;"init"===b&&(a.viewport=d('<div class="'+e+'viewport"></div>').css({overflow:"hidden",position:"relative"}).appendTo(a).append(a.container),a.cloneCount=0,a.cloneOffset=0,m&&(n=d.makeArray(a.slides).reverse(),a.slides=d(n),a.container.empty().append(a.slides)));
 c.animationLoop&&!h&&(a.cloneCount=2,a.cloneOffset=1,"init"!==b&&a.container.find(".clone").remove(),a.container.append(a.slides.first().clone().addClass("clone")).prepend(a.slides.last().clone().addClass("clone")));a.newSlides=d(c.selector,a);g=m?a.count-1-a.currentSlide+a.cloneOffset:a.currentSlide+a.cloneOffset;l&&!h?(a.container.height(200*(a.count+a.cloneCount)+"%").css("position","absolute").width("100%"),setTimeout(function(){a.newSlides.css({display:"block"});a.doMath();a.viewport.height(a.h);
 a.setProps(g*a.h,"init")},"init"===b?100:0)):(a.container.width(200*(a.count+a.cloneCount)+"%"),a.setProps(g*a.computedW,"init"),setTimeout(function(){a.doMath();a.newSlides.css({width:a.computedW,"float":"left",display:"block"});c.smoothHeight&&f.smoothHeight()},"init"===b?100:0))}h||a.slides.removeClass(e+"active-slide").eq(a.currentSlide).addClass(e+"active-slide")};a.doMath=function(){var b=a.slides.first(),d=c.itemMargin,e=c.minItems,f=c.maxItems;a.w=a.width();a.h=b.height();a.boxPadding=b.outerWidth()-
 b.width();h?(a.itemT=c.itemWidth+d,a.minW=e?e*a.itemT:a.w,a.maxW=f?f*a.itemT:a.w,a.itemW=a.minW>a.w?(a.w-d*e)/e:a.maxW<a.w?(a.w-d*f)/f:c.itemWidth>a.w?a.w:c.itemWidth,a.visible=Math.floor(a.w/(a.itemW+d)),a.move=0<c.move&&c.move<a.visible?c.move:a.visible,a.pagingCount=Math.ceil((a.count-a.visible)/a.move+1),a.last=a.pagingCount-1,a.limit=1===a.pagingCount?0:c.itemWidth>a.w?(a.itemW+2*d)*a.count-a.w-d:(a.itemW+d)*a.count-a.w-d):(a.itemW=a.w,a.pagingCount=a.count,a.last=a.count-1);a.computedW=a.itemW-
 a.boxPadding};a.update=function(b,d){a.doMath();h||(b<a.currentSlide?a.currentSlide+=1:b<=a.currentSlide&&0!==b&&(a.currentSlide-=1),a.animatingTo=a.currentSlide);if(c.controlNav&&!a.manualControls)if("add"===d&&!h||a.pagingCount>a.controlNav.length)f.controlNav.update("add");else if("remove"===d&&!h||a.pagingCount<a.controlNav.length)h&&a.currentSlide>a.last&&(a.currentSlide-=1,a.animatingTo-=1),f.controlNav.update("remove",a.last);c.directionNav&&f.directionNav.update()};a.addSlide=function(b,e){var f=
 d(b);a.count+=1;a.last=a.count-1;l&&m?void 0!==e?a.slides.eq(a.count-e).after(f):a.container.prepend(f):void 0!==e?a.slides.eq(e).before(f):a.container.append(f);a.update(e,"add");a.slides=d(c.selector+":not(.clone)",a);a.setup();c.added(a)};a.removeSlide=function(b){var e=isNaN(b)?a.slides.index(d(b)):b;a.count-=1;a.last=a.count-1;isNaN(b)?d(b,a.slides).remove():l&&m?a.slides.eq(a.last).remove():a.slides.eq(b).remove();a.doMath();a.update(e,"remove");a.slides=d(c.selector+":not(.clone)",a);a.setup();
 c.removed(a)};f.init()};d.flexslider.defaults={namespace:"flex-",selector:".slides > li",animation:"fade",easing:"swing",direction:"horizontal",reverse:!1,animationLoop:!0,smoothHeight:!1,startAt:0,slideshow:!0,slideshowSpeed:7E3,animationSpeed:600,initDelay:0,randomize:!1,pauseOnAction:!0,pauseOnHover:!1,useCSS:!0,touch:!0,video:!1,controlNav:!0,directionNav:!0,prevText:"Previous",nextText:"Next",keyboard:!0,multipleKeyboard:!1,mousewheel:!1,pausePlay:!1,pauseText:"Pause",playText:"Play",controlsContainer:"",
 manualControls:"",sync:"",asNavFor:"",itemWidth:0,itemMargin:0,minItems:0,maxItems:0,move:0,start:function(){},before:function(){},after:function(){},end:function(){},added:function(){},removed:function(){}};d.fn.flexslider=function(i){void 0===i&&(i={});if("object"===typeof i)return this.each(function(){var a=d(this),c=a.find(i.selector?i.selector:".slides > li");1===c.length?(c.fadeIn(400),i.start&&i.start(a)):void 0===a.data("flexslider")&&new d.flexslider(this,i)});var k=d(this).data("flexslider");
 switch(i){case "play":k.play();break;case "pause":k.pause();break;case "next":k.flexAnimate(k.getTarget("next"),!0);break;case "prev":case "previous":k.flexAnimate(k.getTarget("prev"),!0);break;default:"number"===typeof i&&k.flexAnimate(i,!0)}}})(jQuery);
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='&shy;<style media="'+h+'"> #mq-test-1 { width: 42px; }</style>';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document);

/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs  */
(function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B<y;B++){A=D[B],z=A.href,C=A.media,x=A.rel&&A.rel.toLowerCase()==="stylesheet";if(!!z&&x&&!o[z]){if(A.styleSheet&&A.styleSheet.rawCssText){m(A.styleSheet.rawCssText,z,C);o[z]=true}else{if((!/^([a-zA-Z:]*\/\/)/.test(z)&&!g)||z.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:z,media:C})}}}}u()},u=function(){if(d.length){var x=d.shift();n(x.href,function(y){m(y,x.href,x.media);o[x.href]=true;u()})}},m=function(I,x,z){var G=I.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),J=G&&G.length||0,x=x.substring(0,x.lastIndexOf("/")),y=function(K){return K.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+x+"$2$3")},A=!J&&z,D=0,C,E,F,B,H;if(x.length){x+="/"}if(A){J=1}for(;D<J;D++){C=0;if(A){E=z;k.push(y(I))}else{E=G[D].match(/@media *([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&y(RegExp.$2))}B=E.split(",");H=B.length;for(;C<H;C++){F=B[C];i.push({media:F.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/)&&RegExp.$2||"all",rules:k.length-1,hasquery:F.indexOf("(")>-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l<h){clearTimeout(r);r=setTimeout(j,h);return}else{l=z}for(var E in i){var K=i[E],C=K.minw,J=K.maxw,A=C===null,L=J===null,y="em";if(!!C){C=parseFloat(C)*(C.indexOf(y)>-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this);
/*! fancyBox v2.1.4 fancyapps.com | fancyapps.com/fancybox/#license */
(function(C,z,f,r){var q=f(C),n=f(z),b=f.fancybox=function(){b.open.apply(this,arguments)},H=navigator.userAgent.match(/msie/),w=null,s=z.createTouch!==r,t=function(a){return a&&a.hasOwnProperty&&a instanceof f},p=function(a){return a&&"string"===f.type(a)},F=function(a){return p(a)&&0<a.indexOf("%")},l=function(a,d){var e=parseInt(a,10)||0;d&&F(a)&&(e*=b.getViewport()[d]/100);return Math.ceil(e)},x=function(a,b){return l(a,b)+"px"};f.extend(b,{version:"2.1.4",defaults:{padding:15,margin:20,width:800,
    height:600,minWidth:100,minHeight:100,maxWidth:9999,maxHeight:9999,autoSize:!0,autoHeight:!1,autoWidth:!1,autoResize:!0,autoCenter:!s,fitToView:!0,aspectRatio:!1,topRatio:0.5,leftRatio:0.5,scrolling:"auto",wrapCSS:"",arrows:!0,closeBtn:!0,closeClick:!1,nextClick:!1,mouseWheel:!0,autoPlay:!1,playSpeed:3E3,preload:3,modal:!1,loop:!0,ajax:{dataType:"html",headers:{"X-fancyBox":!0}},iframe:{scrolling:"auto",preload:!0},swf:{wmode:"transparent",allowfullscreen:"true",allowscriptaccess:"always"},keys:{next:{13:"left",
        34:"up",39:"left",40:"up"},prev:{8:"right",33:"down",37:"right",38:"down"},close:[27],play:[32],toggle:[70]},direction:{next:"left",prev:"right"},scrollOutside:!0,index:0,type:null,href:null,content:null,title:null,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'+
                                                                                                                                                                                                                                                                                                                                                                                                                                                                  (H?' 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>'},openEffect:"fade",openSpeed:250,openEasing:"swing",openOpacity:!0,
    openMethod:"zoomIn",closeEffect:"fade",closeSpeed:250,closeEasing:"swing",closeOpacity:!0,closeMethod:"zoomOut",nextEffect:"elastic",nextSpeed:250,nextEasing:"swing",nextMethod:"changeIn",prevEffect:"elastic",prevSpeed:250,prevEasing:"swing",prevMethod:"changeOut",helpers:{overlay:!0,title:!0},onCancel:f.noop,beforeLoad:f.noop,afterLoad:f.noop,beforeShow:f.noop,afterShow:f.noop,beforeChange:f.noop,beforeClose:f.noop,afterClose:f.noop},group:{},opts:{},previous:null,coming:null,current:null,isActive:!1,
    isOpen:!1,isOpened:!1,wrap:null,skin:null,outer:null,inner:null,player:{timer:null,isActive:!1},ajaxLoad:null,imgPreload:null,transitions:{},helpers:{},open:function(a,d){if(a&&(f.isPlainObject(d)||(d={}),!1!==b.close(!0)))return f.isArray(a)||(a=t(a)?f(a).get():[a]),f.each(a,function(e,c){var k={},g,h,j,m,l;"object"===f.type(c)&&(c.nodeType&&(c=f(c)),t(c)?(k={href:c.data("fancybox-href")||c.attr("href"),title:c.data("fancybox-title")||c.attr("title"),isDom:!0,element:c},f.metadata&&f.extend(!0,k,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     c.metadata())):k=c);g=d.href||k.href||(p(c)?c:null);h=d.title!==r?d.title:k.title||"";m=(j=d.content||k.content)?"html":d.type||k.type;!m&&k.isDom&&(m=c.data("fancybox-type"),m||(m=(m=c.prop("class").match(/fancybox\.(\w+)/))?m[1]:null));p(g)&&(m||(b.isImage(g)?m="image":b.isSWF(g)?m="swf":"#"===g.charAt(0)?m="inline":p(c)&&(m="html",j=c)),"ajax"===m&&(l=g.split(/\s+/,2),g=l.shift(),l=l.shift()));j||("inline"===m?g?j=f(p(g)?g.replace(/.*(?=#[^\s]+$)/,""):g):k.isDom&&(j=c):"html"===m?j=g:!m&&(!g&&
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      k.isDom)&&(m="inline",j=c));f.extend(k,{href:g,type:m,content:j,title:h,selector:l});a[e]=k}),b.opts=f.extend(!0,{},b.defaults,d),d.keys!==r&&(b.opts.keys=d.keys?f.extend({},b.defaults.keys,d.keys):!1),b.group=a,b._start(b.opts.index)},cancel:function(){var a=b.coming;a&&!1!==b.trigger("onCancel")&&(b.hideLoading(),b.ajaxLoad&&b.ajaxLoad.abort(),b.ajaxLoad=null,b.imgPreload&&(b.imgPreload.onload=b.imgPreload.onerror=null),a.wrap&&a.wrap.stop(!0,!0).trigger("onReset").remove(),b.coming=null,b.current||
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     b._afterZoomOut(a))},close:function(a){b.cancel();!1!==b.trigger("beforeClose")&&(b.unbindEvents(),b.isActive&&(!b.isOpen||!0===a?(f(".fancybox-wrap").stop(!0).trigger("onReset").remove(),b._afterZoomOut()):(b.isOpen=b.isOpened=!1,b.isClosing=!0,f(".fancybox-item, .fancybox-nav").remove(),b.wrap.stop(!0,!0).removeClass("fancybox-opened"),b.transitions[b.current.closeMethod]())))},play:function(a){var d=function(){clearTimeout(b.player.timer)},e=function(){d();b.current&&b.player.isActive&&(b.player.timer=
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    setTimeout(b.next,b.current.playSpeed))},c=function(){d();f("body").unbind(".player");b.player.isActive=!1;b.trigger("onPlayEnd")};if(!0===a||!b.player.isActive&&!1!==a){if(b.current&&(b.current.loop||b.current.index<b.group.length-1))b.player.isActive=!0,f("body").bind({"afterShow.player onUpdate.player":e,"onCancel.player beforeClose.player":c,"beforeLoad.player":d}),e(),b.trigger("onPlayStart")}else c()},next:function(a){var d=b.current;d&&(p(a)||(a=d.direction.next),b.jumpto(d.index+1,a,"next"))},
    prev:function(a){var d=b.current;d&&(p(a)||(a=d.direction.prev),b.jumpto(d.index-1,a,"prev"))},jumpto:function(a,d,e){var c=b.current;c&&(a=l(a),b.direction=d||c.direction[a>=c.index?"next":"prev"],b.router=e||"jumpto",c.loop&&(0>a&&(a=c.group.length+a%c.group.length),a%=c.group.length),c.group[a]!==r&&(b.cancel(),b._start(a)))},reposition:function(a,d){var e=b.current,c=e?e.wrap:null,k;c&&(k=b._getPosition(d),a&&"scroll"===a.type?(delete k.position,c.stop(!0,!0).animate(k,200)):(c.css(k),e.pos=f.extend({},
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 e.dim,k)))},update:function(a){var d=a&&a.type,e=!d||"orientationchange"===d;e&&(clearTimeout(w),w=null);b.isOpen&&!w&&(w=setTimeout(function(){var c=b.current;c&&!b.isClosing&&(b.wrap.removeClass("fancybox-tmp"),(e||"load"===d||"resize"===d&&c.autoResize)&&b._setDimension(),"scroll"===d&&c.canShrink||b.reposition(a),b.trigger("onUpdate"),w=null)},e&&!s?0:300))},toggle:function(a){b.isOpen&&(b.current.fitToView="boolean"===f.type(a)?a:!b.current.fitToView,s&&(b.wrap.removeAttr("style").addClass("fancybox-tmp"),
            b.trigger("onUpdate")),b.update())},hideLoading:function(){n.unbind(".loading");f("#fancybox-loading").remove()},showLoading:function(){var a,d;b.hideLoading();a=f('<div id="fancybox-loading"><div></div></div>').click(b.cancel).appendTo("body");n.bind("keydown.loading",function(a){if(27===(a.which||a.keyCode))a.preventDefault(),b.cancel()});b.defaults.fixed||(d=b.getViewport(),a.css({position:"absolute",top:0.5*d.h+d.y,left:0.5*d.w+d.x}))},getViewport:function(){var a=b.current&&b.current.locked||
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     !1,d={x:q.scrollLeft(),y:q.scrollTop()};a?(d.w=a[0].clientWidth,d.h=a[0].clientHeight):(d.w=s&&C.innerWidth?C.innerWidth:q.width(),d.h=s&&C.innerHeight?C.innerHeight:q.height());return d},unbindEvents:function(){b.wrap&&t(b.wrap)&&b.wrap.unbind(".fb");n.unbind(".fb");q.unbind(".fb")},bindEvents:function(){var a=b.current,d;a&&(q.bind("orientationchange.fb"+(s?"":" resize.fb")+(a.autoCenter&&!a.locked?" scroll.fb":""),b.update),(d=a.keys)&&n.bind("keydown.fb",function(e){var c=e.which||e.keyCode,k=
            e.target||e.srcElement;if(27===c&&b.coming)return!1;!e.ctrlKey&&(!e.altKey&&!e.shiftKey&&!e.metaKey&&(!k||!k.type&&!f(k).is("[contenteditable]")))&&f.each(d,function(d,k){if(1<a.group.length&&k[c]!==r)return b[d](k[c]),e.preventDefault(),!1;if(-1<f.inArray(c,k))return b[d](),e.preventDefault(),!1})}),f.fn.mousewheel&&a.mouseWheel&&b.wrap.bind("mousewheel.fb",function(d,c,k,g){for(var h=f(d.target||null),j=!1;h.length&&!j&&!h.is(".fancybox-skin")&&!h.is(".fancybox-wrap");)j=h[0]&&!(h[0].style.overflow&&
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  "hidden"===h[0].style.overflow)&&(h[0].clientWidth&&h[0].scrollWidth>h[0].clientWidth||h[0].clientHeight&&h[0].scrollHeight>h[0].clientHeight),h=f(h).parent();if(0!==c&&!j&&1<b.group.length&&!a.canShrink){if(0<g||0<k)b.prev(0<g?"down":"left");else if(0>g||0>k)b.next(0>g?"up":"right");d.preventDefault()}}))},trigger:function(a,d){var e,c=d||b.coming||b.current;if(c){f.isFunction(c[a])&&(e=c[a].apply(c,Array.prototype.slice.call(arguments,1)));if(!1===e)return!1;c.helpers&&f.each(c.helpers,function(d,
            e){e&&(b.helpers[d]&&f.isFunction(b.helpers[d][a]))&&(e=f.extend(!0,{},b.helpers[d].defaults,e),b.helpers[d][a](e,c))});f.event.trigger(a+".fb")}},isImage:function(a){return p(a)&&a.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp)((\?|#).*)?$)/i)},isSWF:function(a){return p(a)&&a.match(/\.(swf)((\?|#).*)?$/i)},_start:function(a){var d={},e,c;a=l(a);e=b.group[a]||null;if(!e)return!1;d=f.extend(!0,{},b.opts,e);e=d.margin;c=d.padding;"number"===f.type(e)&&(d.margin=[e,e,e,e]);"number"===f.type(c)&&
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    (d.padding=[c,c,c,c]);d.modal&&f.extend(!0,d,{closeBtn:!1,closeClick:!1,nextClick:!1,arrows:!1,mouseWheel:!1,keys:null,helpers:{overlay:{closeClick:!1}}});d.autoSize&&(d.autoWidth=d.autoHeight=!0);"auto"===d.width&&(d.autoWidth=!0);"auto"===d.height&&(d.autoHeight=!0);d.group=b.group;d.index=a;b.coming=d;if(!1===b.trigger("beforeLoad"))b.coming=null;else{c=d.type;e=d.href;if(!c)return b.coming=null,b.current&&b.router&&"jumpto"!==b.router?(b.current.index=a,b[b.router](b.direction)):!1;b.isActive=
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               !0;if("image"===c||"swf"===c)d.autoHeight=d.autoWidth=!1,d.scrolling="visible";"image"===c&&(d.aspectRatio=!0);"iframe"===c&&s&&(d.scrolling="scroll");d.wrap=f(d.tpl.wrap).addClass("fancybox-"+(s?"mobile":"desktop")+" fancybox-type-"+c+" fancybox-tmp "+d.wrapCSS).appendTo(d.parent||"body");f.extend(d,{skin:f(".fancybox-skin",d.wrap),outer:f(".fancybox-outer",d.wrap),inner:f(".fancybox-inner",d.wrap)});f.each(["Top","Right","Bottom","Left"],function(a,b){d.skin.css("padding"+b,x(d.padding[a]))});b.trigger("onReady");
        if("inline"===c||"html"===c){if(!d.content||!d.content.length)return b._error("content")}else if(!e)return b._error("href");"image"===c?b._loadImage():"ajax"===c?b._loadAjax():"iframe"===c?b._loadIframe():b._afterLoad()}},_error:function(a){f.extend(b.coming,{type:"html",autoWidth:!0,autoHeight:!0,minWidth:0,minHeight:0,scrolling:"no",hasError:a,content:b.coming.tpl.error});b._afterLoad()},_loadImage:function(){var a=b.imgPreload=new Image;a.onload=function(){this.onload=this.onerror=null;b.coming.width=
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      this.width;b.coming.height=this.height;b._afterLoad()};a.onerror=function(){this.onload=this.onerror=null;b._error("image")};a.src=b.coming.href;!0!==a.complete&&b.showLoading()},_loadAjax:function(){var a=b.coming;b.showLoading();b.ajaxLoad=f.ajax(f.extend({},a.ajax,{url:a.href,error:function(a,e){b.coming&&"abort"!==e?b._error("ajax",a):b.hideLoading()},success:function(d,e){"success"===e&&(a.content=d,b._afterLoad())}}))},_loadIframe:function(){var a=b.coming,d=f(a.tpl.iframe.replace(/\{rnd\}/g,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  (new Date).getTime())).attr("scrolling",s?"auto":a.iframe.scrolling).attr("src",a.href);f(a.wrap).bind("onReset",function(){try{f(this).find("iframe").hide().attr("src","//about:blank").end().empty()}catch(a){}});a.iframe.preload&&(b.showLoading(),d.one("load",function(){f(this).data("ready",1);s||f(this).bind("load.fb",b.update);f(this).parents(".fancybox-wrap").width("100%").removeClass("fancybox-tmp").show();b._afterLoad()}));a.content=d.appendTo(a.inner);a.iframe.preload||b._afterLoad()},_preloadImages:function(){var a=
            b.group,d=b.current,e=a.length,c=d.preload?Math.min(d.preload,e-1):0,f,g;for(g=1;g<=c;g+=1)f=a[(d.index+g)%e],"image"===f.type&&f.href&&((new Image).src=f.href)},_afterLoad:function(){var a=b.coming,d=b.current,e,c,k,g,h;b.hideLoading();if(a&&!1!==b.isActive)if(!1===b.trigger("afterLoad",a,d))a.wrap.stop(!0).trigger("onReset").remove(),b.coming=null;else{d&&(b.trigger("beforeChange",d),d.wrap.stop(!0).removeClass("fancybox-opened").find(".fancybox-item, .fancybox-nav").remove());b.unbindEvents();
        e=a.content;c=a.type;k=a.scrolling;f.extend(b,{wrap:a.wrap,skin:a.skin,outer:a.outer,inner:a.inner,current:a,previous:d});g=a.href;switch(c){case "inline":case "ajax":case "html":a.selector?e=f("<div>").html(e).find(a.selector):t(e)&&(e.data("fancybox-placeholder")||e.data("fancybox-placeholder",f('<div class="fancybox-placeholder"></div>').insertAfter(e).hide()),e=e.show().detach(),a.wrap.bind("onReset",function(){f(this).find(e).length&&e.hide().replaceAll(e.data("fancybox-placeholder")).data("fancybox-placeholder",
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            !1)}));break;case "image":e=a.tpl.image.replace("{href}",g);break;case "swf":e='<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="'+g+'"></param>',h="",f.each(a.swf,function(a,b){e+='<param name="'+a+'" value="'+b+'"></param>';h+=" "+a+'="'+b+'"'}),e+='<embed src="'+g+'" type="application/x-shockwave-flash" width="100%" height="100%"'+h+"></embed></object>"}(!t(e)||!e.parent().is(a.inner))&&a.inner.append(e);b.trigger("beforeShow");
        a.inner.css("overflow","yes"===k?"scroll":"no"===k?"hidden":k);b._setDimension();b.reposition();b.isOpen=!1;b.coming=null;b.bindEvents();if(b.isOpened){if(d.prevMethod)b.transitions[d.prevMethod]()}else f(".fancybox-wrap").not(a.wrap).stop(!0).trigger("onReset").remove();b.transitions[b.isOpened?a.nextMethod:a.openMethod]();b._preloadImages()}},_setDimension:function(){var a=b.getViewport(),d=0,e=!1,c=!1,e=b.wrap,k=b.skin,g=b.inner,h=b.current,c=h.width,j=h.height,m=h.minWidth,u=h.minHeight,n=h.maxWidth,
            v=h.maxHeight,s=h.scrolling,q=h.scrollOutside?h.scrollbarWidth:0,y=h.margin,p=l(y[1]+y[3]),r=l(y[0]+y[2]),z,A,t,D,B,G,C,E,w;e.add(k).add(g).width("auto").height("auto").removeClass("fancybox-tmp");y=l(k.outerWidth(!0)-k.width());z=l(k.outerHeight(!0)-k.height());A=p+y;t=r+z;D=F(c)?(a.w-A)*l(c)/100:c;B=F(j)?(a.h-t)*l(j)/100:j;if("iframe"===h.type){if(w=h.content,h.autoHeight&&1===w.data("ready"))try{w[0].contentWindow.document.location&&(g.width(D).height(9999),G=w.contents().find("body"),q&&G.css("overflow-x",
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  "hidden"),B=G.height())}catch(H){}}else if(h.autoWidth||h.autoHeight)g.addClass("fancybox-tmp"),h.autoWidth||g.width(D),h.autoHeight||g.height(B),h.autoWidth&&(D=g.width()),h.autoHeight&&(B=g.height()),g.removeClass("fancybox-tmp");c=l(D);j=l(B);E=D/B;m=l(F(m)?l(m,"w")-A:m);n=l(F(n)?l(n,"w")-A:n);u=l(F(u)?l(u,"h")-t:u);v=l(F(v)?l(v,"h")-t:v);G=n;C=v;h.fitToView&&(n=Math.min(a.w-A,n),v=Math.min(a.h-t,v));A=a.w-p;r=a.h-r;h.aspectRatio?(c>n&&(c=n,j=l(c/E)),j>v&&(j=v,c=l(j*E)),c<m&&(c=m,j=l(c/E)),j<u&&
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    (j=u,c=l(j*E))):(c=Math.max(m,Math.min(c,n)),h.autoHeight&&"iframe"!==h.type&&(g.width(c),j=g.height()),j=Math.max(u,Math.min(j,v)));if(h.fitToView)if(g.width(c).height(j),e.width(c+y),a=e.width(),p=e.height(),h.aspectRatio)for(;(a>A||p>r)&&(c>m&&j>u)&&!(19<d++);)j=Math.max(u,Math.min(v,j-10)),c=l(j*E),c<m&&(c=m,j=l(c/E)),c>n&&(c=n,j=l(c/E)),g.width(c).height(j),e.width(c+y),a=e.width(),p=e.height();else c=Math.max(m,Math.min(c,c-(a-A))),j=Math.max(u,Math.min(j,j-(p-r)));q&&("auto"===s&&j<B&&c+y+
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     q<A)&&(c+=q);g.width(c).height(j);e.width(c+y);a=e.width();p=e.height();e=(a>A||p>r)&&c>m&&j>u;c=h.aspectRatio?c<G&&j<C&&c<D&&j<B:(c<G||j<C)&&(c<D||j<B);f.extend(h,{dim:{width:x(a),height:x(p)},origWidth:D,origHeight:B,canShrink:e,canExpand:c,wPadding:y,hPadding:z,wrapSpace:p-k.outerHeight(!0),skinSpace:k.height()-j});!w&&(h.autoHeight&&j>u&&j<v&&!c)&&g.height("auto")},_getPosition:function(a){var d=b.current,e=b.getViewport(),c=d.margin,f=b.wrap.width()+c[1]+c[3],g=b.wrap.height()+c[0]+c[2],c={position:"absolute",
        top:c[0],left:c[3]};d.autoCenter&&d.fixed&&!a&&g<=e.h&&f<=e.w?c.position="fixed":d.locked||(c.top+=e.y,c.left+=e.x);c.top=x(Math.max(c.top,c.top+(e.h-g)*d.topRatio));c.left=x(Math.max(c.left,c.left+(e.w-f)*d.leftRatio));return c},_afterZoomIn:function(){var a=b.current;a&&(b.isOpen=b.isOpened=!0,b.wrap.css("overflow","visible").addClass("fancybox-opened"),b.update(),(a.closeClick||a.nextClick&&1<b.group.length)&&b.inner.css("cursor","pointer").bind("click.fb",function(d){!f(d.target).is("a")&&!f(d.target).parent().is("a")&&
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    (d.preventDefault(),b[a.closeClick?"close":"next"]())}),a.closeBtn&&f(a.tpl.closeBtn).appendTo(b.skin).bind("click.fb",function(a){a.preventDefault();b.close()}),a.arrows&&1<b.group.length&&((a.loop||0<a.index)&&f(a.tpl.prev).appendTo(b.outer).bind("click.fb",b.prev),(a.loop||a.index<b.group.length-1)&&f(a.tpl.next).appendTo(b.outer).bind("click.fb",b.next)),b.trigger("afterShow"),!a.loop&&a.index===a.group.length-1?b.play(!1):b.opts.autoPlay&&!b.player.isActive&&(b.opts.autoPlay=!1,b.play()))},_afterZoomOut:function(a){a=
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  a||b.current;f(".fancybox-wrap").trigger("onReset").remove();f.extend(b,{group:{},opts:{},router:!1,current:null,isActive:!1,isOpened:!1,isOpen:!1,isClosing:!1,wrap:null,skin:null,outer:null,inner:null});b.trigger("afterClose",a)}});b.transitions={getOrigPosition:function(){var a=b.current,d=a.element,e=a.orig,c={},f=50,g=50,h=a.hPadding,j=a.wPadding,m=b.getViewport();!e&&(a.isDom&&d.is(":visible"))&&(e=d.find("img:first"),e.length||(e=d));t(e)?(c=e.offset(),e.is("img")&&(f=e.outerWidth(),g=e.outerHeight())):
        (c.top=m.y+(m.h-g)*a.topRatio,c.left=m.x+(m.w-f)*a.leftRatio);if("fixed"===b.wrap.css("position")||a.locked)c.top-=m.y,c.left-=m.x;return c={top:x(c.top-h*a.topRatio),left:x(c.left-j*a.leftRatio),width:x(f+j),height:x(g+h)}},step:function(a,d){var e,c,f=d.prop;c=b.current;var g=c.wrapSpace,h=c.skinSpace;if("width"===f||"height"===f)e=d.end===d.start?1:(a-d.start)/(d.end-d.start),b.isClosing&&(e=1-e),c="width"===f?c.wPadding:c.hPadding,c=a-c,b.skin[f](l("width"===f?c:c-g*e)),b.inner[f](l("width"===
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    f?c:c-g*e-h*e))},zoomIn:function(){var a=b.current,d=a.pos,e=a.openEffect,c="elastic"===e,k=f.extend({opacity:1},d);delete k.position;c?(d=this.getOrigPosition(),a.openOpacity&&(d.opacity=0.1)):"fade"===e&&(d.opacity=0.1);b.wrap.css(d).animate(k,{duration:"none"===e?0:a.openSpeed,easing:a.openEasing,step:c?this.step:null,complete:b._afterZoomIn})},zoomOut:function(){var a=b.current,d=a.closeEffect,e="elastic"===d,c={opacity:0.1};e&&(c=this.getOrigPosition(),a.closeOpacity&&(c.opacity=0.1));b.wrap.animate(c,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  {duration:"none"===d?0:a.closeSpeed,easing:a.closeEasing,step:e?this.step:null,complete:b._afterZoomOut})},changeIn:function(){var a=b.current,d=a.nextEffect,e=a.pos,c={opacity:1},f=b.direction,g;e.opacity=0.1;"elastic"===d&&(g="down"===f||"up"===f?"top":"left","down"===f||"right"===f?(e[g]=x(l(e[g])-200),c[g]="+=200px"):(e[g]=x(l(e[g])+200),c[g]="-=200px"));"none"===d?b._afterZoomIn():b.wrap.css(e).animate(c,{duration:a.nextSpeed,easing:a.nextEasing,complete:b._afterZoomIn})},changeOut:function(){var a=
        b.previous,d=a.prevEffect,e={opacity:0.1},c=b.direction;"elastic"===d&&(e["down"===c||"up"===c?"top":"left"]=("up"===c||"left"===c?"-":"+")+"=200px");a.wrap.animate(e,{duration:"none"===d?0:a.prevSpeed,easing:a.prevEasing,complete:function(){f(this).trigger("onReset").remove()}})}};b.helpers.overlay={defaults:{closeClick:!0,speedOut:200,showEarly:!0,css:{},locked:!s,fixed:!0},overlay:null,fixed:!1,create:function(a){a=f.extend({},this.defaults,a);this.overlay&&this.close();this.overlay=f('<div class="fancybox-overlay"></div>').appendTo("body");
    this.fixed=!1;a.fixed&&b.defaults.fixed&&(this.overlay.addClass("fancybox-overlay-fixed"),this.fixed=!0)},open:function(a){var d=this;a=f.extend({},this.defaults,a);this.overlay?this.overlay.unbind(".overlay").width("auto").height("auto"):this.create(a);this.fixed||(q.bind("resize.overlay",f.proxy(this.update,this)),this.update());a.closeClick&&this.overlay.bind("click.overlay",function(a){f(a.target).hasClass("fancybox-overlay")&&(b.isActive?b.close():d.close())});this.overlay.css(a.css).show()},
    close:function(){f(".fancybox-overlay").remove();q.unbind("resize.overlay");this.overlay=null;!1!==this.margin&&(f("body").css("margin-right",this.margin),this.margin=!1);this.el&&this.el.removeClass("fancybox-lock")},update:function(){var a="100%",b;this.overlay.width(a).height("100%");H?(b=Math.max(z.documentElement.offsetWidth,z.body.offsetWidth),n.width()>b&&(a=n.width())):n.width()>q.width()&&(a=n.width());this.overlay.width(a).height(n.height())},onReady:function(a,b){f(".fancybox-overlay").stop(!0,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               !0);this.overlay||(this.margin=n.height()>q.height()||"scroll"===f("body").css("overflow-y")?f("body").css("margin-right"):!1,this.el=z.all&&!z.querySelector?f("html"):f("body"),this.create(a));a.locked&&this.fixed&&(b.locked=this.overlay.append(b.wrap),b.fixed=!1);!0===a.showEarly&&this.beforeShow.apply(this,arguments)},beforeShow:function(a,b){b.locked&&(this.el.addClass("fancybox-lock"),!1!==this.margin&&f("body").css("margin-right",l(this.margin)+b.scrollbarWidth));this.open(a)},onUpdate:function(){this.fixed||
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           this.update()},afterClose:function(a){this.overlay&&!b.isActive&&this.overlay.fadeOut(a.speedOut,f.proxy(this.close,this))}};b.helpers.title={defaults:{type:"float",position:"bottom"},beforeShow:function(a){var d=b.current,e=d.title,c=a.type;f.isFunction(e)&&(e=e.call(d.element,d));if(p(e)&&""!==f.trim(e)){d=f('<div class="fancybox-title fancybox-title-'+c+'-wrap">'+e+"</div>");switch(c){case "inside":c=b.skin;break;case "outside":c=b.wrap;break;case "over":c=b.inner;break;default:c=b.skin,d.appendTo("body"),
        H&&d.width(d.width()),d.wrapInner('<span class="child"></span>'),b.current.margin[2]+=Math.abs(l(d.css("margin-bottom")))}d["top"===a.position?"prependTo":"appendTo"](c)}}};f.fn.fancybox=function(a){var d,e=f(this),c=this.selector||"",k=function(g){var h=f(this).blur(),j=d,k,l;!g.ctrlKey&&(!g.altKey&&!g.shiftKey&&!g.metaKey)&&!h.is(".fancybox-wrap")&&(k=a.groupAttr||"data-fancybox-group",l=h.attr(k),l||(k="rel",l=h.get(0)[k]),l&&(""!==l&&"nofollow"!==l)&&(h=c.length?f(c):e,h=h.filter("["+k+'="'+l+
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 '"]'),j=h.index(this)),a.index=j,!1!==b.open(h,a)&&g.preventDefault())};a=a||{};d=a.index||0;!c||!1===a.live?e.unbind("click.fb-start").bind("click.fb-start",k):n.undelegate(c,"click.fb-start").delegate(c+":not('.fancybox-item, .fancybox-nav')","click.fb-start",k);this.filter("[data-fancybox-start=1]").trigger("click");return this};n.ready(function(){f.scrollbarWidth===r&&(f.scrollbarWidth=function(){var a=f('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body"),b=a.children(),
        b=b.innerWidth()-b.height(99).innerWidth();a.remove();return b});if(f.support.fixedPosition===r){var a=f.support,d=f('<div style="position:fixed;top:20px;"></div>').appendTo("body"),e=20===d[0].offsetTop||15===d[0].offsetTop;d.remove();a.fixedPosition=e}f.extend(b.defaults,{scrollbarWidth:f.scrollbarWidth(),fixed:f.support.fixedPosition,parent:f("body")})})})(window,document,jQuery);
/*!
 * Media helper for fancyBox
 * version: 1.0.5 (Tue, 23 Oct 2012)
 * @requires fancyBox v2.0 or later
 *
 * Usage:
 *     $(".fancybox").fancybox({
 *         helpers : {
 *             media: true
 *         }
 *     });
 *
 * Set custom URL parameters:
 *     $(".fancybox").fancybox({
 *         helpers : {
 *             media: {
 *                 youtube : {
 *                     params : {
 *                         autoplay : 0
 *                     }
 *                 }
 *             }
 *         }
 *     });
 *
 * Or:
 *     $(".fancybox").fancybox({,
 *	       helpers : {
 *             media: true
 *         },
 *         youtube : {
 *             autoplay: 0
 *         }
 *     });
 *
 *  Supports:
 *
 *      Youtube
 *          http://www.youtube.com/watch?v=opj24KnzrWo
 *          http://www.youtube.com/embed/opj24KnzrWo
 *          http://youtu.be/opj24KnzrWo
 *      Vimeo
 *          http://vimeo.com/40648169
 *          http://vimeo.com/channels/staffpicks/38843628
 *          http://vimeo.com/groups/surrealism/videos/36516384
 *          http://player.vimeo.com/video/45074303
 *      Metacafe
 *          http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/
 *          http://www.metacafe.com/watch/7635964/
 *      Dailymotion
 *          http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people
 *      Twitvid
 *          http://twitvid.com/QY7MD
 *      Twitpic
 *          http://twitpic.com/7p93st
 *      Instagram
 *          http://instagr.am/p/IejkuUGxQn/
 *          http://instagram.com/p/IejkuUGxQn/
 *      Google maps
 *          http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17
 *          http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16
 *          http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56
 */
(function ($) {
	"use strict";

	//Shortcut for fancyBox object
	var F = $.fancybox,
		format = function( url, rez, params ) {
			params = params || '';

			if ( $.type( params ) === "object" ) {
				params = $.param(params, true);
			}

			$.each(rez, function(key, value) {
				url = url.replace( '$' + key, value || '' );
			});

			if (params.length) {
				url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params;
			}

			return url;
		};

	//Add helper object
	F.helpers.media = {
		defaults : {
			youtube : {
				matcher : /(youtube\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i,
				params  : {
					autoplay    : 1,
					autohide    : 1,
					fs          : 1,
					rel         : 0,
					hd          : 1,
					wmode       : 'opaque',
					enablejsapi : 1
				},
				type : 'iframe',
				url  : '//www.youtube.com/embed/$3'
			},
			vimeo : {
				matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/,
				params  : {
					autoplay      : 1,
					hd            : 1,
					show_title    : 1,
					show_byline   : 1,
					show_portrait : 0,
					fullscreen    : 1
				},
				type : 'iframe',
				url  : '//player.vimeo.com/video/$1'
			},
			metacafe : {
				matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/,
				params  : {
					autoPlay : 'yes'
				},
				type : 'swf',
				url  : function( rez, params, obj ) {
					obj.swf.flashVars = 'playerVars=' + $.param( params, true );

					return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf';
				}
			},
			dailymotion : {
				matcher : /dailymotion.com\/video\/(.*)\/?(.*)/,
				params  : {
					additionalInfos : 0,
					autoStart : 1
				},
				type : 'swf',
				url  : '//www.dailymotion.com/swf/video/$1'
			},
			twitvid : {
				matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i,
				params  : {
					autoplay : 0
				},
				type : 'iframe',
				url  : '//www.twitvid.com/embed.php?guid=$1'
			},
			twitpic : {
				matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i,
				type : 'image',
				url  : '//twitpic.com/show/full/$1/'
			},
			instagram : {
				matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i,
				type : 'image',
				url  : '//$1/p/$2/media/'
			},
			google_maps : {
				matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i,
				type : 'iframe',
				url  : function( rez ) {
					return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed');
				}
			}
		},

		beforeLoad : function(opts, obj) {
			var url   = obj.href || '',
				type  = false,
				what,
				item,
				rez,
				params;

			for (what in opts) {
				item = opts[ what ];
				rez  = url.match( item.matcher );

				if (rez) {
					type   = item.type;
					params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null));

					url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params );

					break;
				}
			}

			if (type) {
				obj.href = url;
				obj.type = type;

				obj.autoHeight = false;
			}
		}
	};

}(jQuery));
// Chosen, a Select Box Enhancer for jQuery and Protoype
// by Patrick Filler for Harvest, http://getharvest.com
// 
// Version 0.9.10
// Full source at https://github.com/harvesthq/chosen
// Copyright (c) 2011 Harvest http://getharvest.com

// MIT License, https://github.com/harvesthq/chosen/blob/master/LICENSE.md
// This file is generated by `cake build`, do not edit it by hand.
(function(){var e;e=function(){function e(){this.options_index=0,this.parsed=[]}return e.prototype.add_node=function(e){return e.nodeName.toUpperCase()==="OPTGROUP"?this.add_group(e):this.add_option(e)},e.prototype.add_group=function(e){var t,n,r,i,s,o;t=this.parsed.length,this.parsed.push({array_index:t,group:!0,label:e.label,children:0,disabled:e.disabled}),s=e.childNodes,o=[];for(r=0,i=s.length;r<i;r++)n=s[r],o.push(this.add_option(n,t,e.disabled));return o},e.prototype.add_option=function(e,t,n){if(e.nodeName.toUpperCase()==="OPTION")return e.text!==""?(t!=null&&(this.parsed[t].children+=1),this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,value:e.value,text:e.text,html:e.innerHTML,selected:e.selected,disabled:n===!0?n:e.disabled,group_array_index:t,classes:e.className,style:e.style.cssText})):this.parsed.push({array_index:this.parsed.length,options_index:this.options_index,empty:!0}),this.options_index+=1},e}(),e.select_to_array=function(t){var n,r,i,s,o;r=new e,o=t.childNodes;for(i=0,s=o.length;i<s;i++)n=o[i],r.add_node(n);return r.parsed},this.SelectParser=e}).call(this),function(){var e,t;t=this,e=function(){function e(e,t){this.form_field=e,this.options=t!=null?t:{},this.is_multiple=this.form_field.multiple,this.set_default_text(),this.set_default_values(),this.setup(),this.set_up_html(),this.register_observers(),this.finish_setup()}return e.prototype.set_default_values=function(){var e=this;return this.click_test_action=function(t){return e.test_active_click(t)},this.activate_action=function(t){return e.activate_field(t)},this.active_field=!1,this.mouse_on_container=!1,this.results_showing=!1,this.result_highlighted=null,this.result_single_selected=null,this.allow_single_deselect=this.options.allow_single_deselect!=null&&this.form_field.options[0]!=null&&this.form_field.options[0].text===""?this.options.allow_single_deselect:!1,this.disable_search_threshold=this.options.disable_search_threshold||0,this.disable_search=this.options.disable_search||!1,this.search_split_words=!this.options.disable_search_split_words&&!0,this.search_contains=this.options.search_contains||!1,this.choices=0,this.single_backstroke_delete=this.options.single_backstroke_delete||!1,this.max_selected_options=this.options.max_selected_options||Infinity},e.prototype.set_default_text=function(){return this.form_field.getAttribute("data-placeholder")?this.default_text=this.form_field.getAttribute("data-placeholder"):this.is_multiple?this.default_text=this.options.placeholder_text_multiple||this.options.placeholder_text||"Select Some Options":this.default_text=this.options.placeholder_text_single||this.options.placeholder_text||"Select an Option",this.results_none_found=this.form_field.getAttribute("data-no_results_text")||this.options.no_results_text||"No results match"},e.prototype.mouse_enter=function(){return this.mouse_on_container=!0},e.prototype.mouse_leave=function(){return this.mouse_on_container=!1},e.prototype.input_focus=function(e){var t=this;if(this.is_multiple){if(!this.active_field)return setTimeout(function(){return t.container_mousedown()},50)}else if(!this.active_field)return this.activate_field()},e.prototype.input_blur=function(e){var t=this;if(!this.mouse_on_container)return this.active_field=!1,setTimeout(function(){return t.blur_test()},100)},e.prototype.result_add_option=function(e){var t,n;return e.disabled?"":(e.dom_id=this.container_id+"_o_"+e.array_index,t=e.selected&&this.is_multiple?[]:["active-result"],e.selected&&t.push("result-selected"),e.group_array_index!=null&&t.push("group-option"),e.classes!==""&&t.push(e.classes),n=e.style.cssText!==""?' style="'+e.style+'"':"",'<li id="'+e.dom_id+'" class="'+t.join(" ")+'"'+n+">"+e.html+"</li>")},e.prototype.results_update_field=function(){return this.is_multiple||this.results_reset_cleanup(),this.result_clear_highlight(),this.result_single_selected=null,this.results_build()},e.prototype.results_toggle=function(){return this.results_showing?this.results_hide():this.results_show()},e.prototype.results_search=function(e){return this.results_showing?this.winnow_results():this.results_show()},e.prototype.keyup_checker=function(e){var t,n;t=(n=e.which)!=null?n:e.keyCode,this.search_field_scale();switch(t){case 8:if(this.is_multiple&&this.backstroke_length<1&&this.choices>0)return this.keydown_backstroke();if(!this.pending_backstroke)return this.result_clear_highlight(),this.results_search();break;case 13:e.preventDefault();if(this.results_showing)return this.result_select(e);break;case 27:return this.results_showing&&this.results_hide(),!0;case 9:case 38:case 40:case 16:case 91:case 17:break;default:return this.results_search()}},e.prototype.generate_field_id=function(){var e;return e=this.generate_random_id(),this.form_field.id=e,e},e.prototype.generate_random_char=function(){var e,t,n;return e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",n=Math.floor(Math.random()*e.length),t=e.substring(n,n+1)},e}(),t.AbstractChosen=e}.call(this),function(){var e,t,n,r,i={}.hasOwnProperty,s=function(e,t){function r(){this.constructor=e}for(var n in t)i.call(t,n)&&(e[n]=t[n]);return r.prototype=t.prototype,e.prototype=new r,e.__super__=t.prototype,e};r=this,e=jQuery,e.fn.extend({chosen:function(n){return e.browser.msie&&(e.browser.version==="6.0"||e.browser.version==="7.0"&&document.documentMode===7)?this:this.each(function(r){var i;i=e(this);if(!i.hasClass("chzn-done"))return i.data("chosen",new t(this,n))})}}),t=function(t){function i(){return i.__super__.constructor.apply(this,arguments)}return s(i,t),i.prototype.setup=function(){return this.form_field_jq=e(this.form_field),this.current_value=this.form_field_jq.val(),this.is_rtl=this.form_field_jq.hasClass("chzn-rtl")},i.prototype.finish_setup=function(){return this.form_field_jq.addClass("chzn-done")},i.prototype.set_up_html=function(){var t,r,i,s,o;return this.container_id=this.form_field.id.length?this.form_field.id.replace(/[^\w]/g,"_"):this.generate_field_id(),this.container_id+="_chzn",this.f_width=this.form_field_jq.outerWidth(),r={id:this.container_id,"class":"chzn-container"+(this.is_rtl?" chzn-rtl":""),style:"width: "+this.f_width+"px;",title:this.form_field.title},t=e("<div />",r),this.is_multiple?t.html('<ul class="chzn-choices"><li class="search-field"><input type="text" value="'+this.default_text+'" class="default" autocomplete="off" style="width:25px;" /></li></ul><div class="chzn-drop" style="left:-9000px;"><ul class="chzn-results"></ul></div>'):t.html('<a href="javascript:void(0)" class="chzn-single chzn-default" tabindex="-1"><span>'+this.default_text+'</span><div><b></b></div></a><div class="chzn-drop" style="left:-9000px;"><div class="chzn-search"><input type="text" autocomplete="off" /></div><ul class="chzn-results"></ul></div>'),this.form_field_jq.hide().after(t),this.container=e("#"+this.container_id),this.container.addClass("chzn-container-"+(this.is_multiple?"multi":"single")),this.dropdown=this.container.find("div.chzn-drop").first(),i=this.container.height(),s=this.f_width-n(this.dropdown),this.dropdown.css({width:s+"px",top:i+"px"}),this.search_field=this.container.find("input").first(),this.search_results=this.container.find("ul.chzn-results").first(),this.search_field_scale(),this.search_no_results=this.container.find("li.no-results").first(),this.is_multiple?(this.search_choices=this.container.find("ul.chzn-choices").first(),this.search_container=this.container.find("li.search-field").first()):(this.search_container=this.container.find("div.chzn-search").first(),this.selected_item=this.container.find(".chzn-single").first(),o=s-n(this.search_container)-n(this.search_field),this.search_field.css({width:o+"px"})),this.results_build(),this.set_tab_index(),this.form_field_jq.trigger("liszt:ready",{chosen:this})},i.prototype.register_observers=function(){var e=this;return this.container.mousedown(function(t){return e.container_mousedown(t)}),this.container.mouseup(function(t){return e.container_mouseup(t)}),this.container.mouseenter(function(t){return e.mouse_enter(t)}),this.container.mouseleave(function(t){return e.mouse_leave(t)}),this.search_results.mouseup(function(t){return e.search_results_mouseup(t)}),this.search_results.mouseover(function(t){return e.search_results_mouseover(t)}),this.search_results.mouseout(function(t){return e.search_results_mouseout(t)}),this.form_field_jq.bind("liszt:updated",function(t){return e.results_update_field(t)}),this.form_field_jq.bind("liszt:activate",function(t){return e.activate_field(t)}),this.form_field_jq.bind("liszt:open",function(t){return e.container_mousedown(t)}),this.search_field.blur(function(t){return e.input_blur(t)}),this.search_field.keyup(function(t){return e.keyup_checker(t)}),this.search_field.keydown(function(t){return e.keydown_checker(t)}),this.search_field.focus(function(t){return e.input_focus(t)}),this.is_multiple?this.search_choices.click(function(t){return e.choices_click(t)}):this.container.click(function(e){return e.preventDefault()})},i.prototype.search_field_disabled=function(){this.is_disabled=this.form_field_jq[0].disabled;if(this.is_disabled)return this.container.addClass("chzn-disabled"),this.search_field[0].disabled=!0,this.is_multiple||this.selected_item.unbind("focus",this.activate_action),this.close_field();this.container.removeClass("chzn-disabled"),this.search_field[0].disabled=!1;if(!this.is_multiple)return this.selected_item.bind("focus",this.activate_action)},i.prototype.container_mousedown=function(t){var n;if(!this.is_disabled)return n=t!=null?e(t.target).hasClass("search-choice-close"):!1,t&&t.type==="mousedown"&&!this.results_showing&&t.preventDefault(),!this.pending_destroy_click&&!n?(this.active_field?!this.is_multiple&&t&&(e(t.target)[0]===this.selected_item[0]||e(t.target).parents("a.chzn-single").length)&&(t.preventDefault(),this.results_toggle()):(this.is_multiple&&this.search_field.val(""),e(document).click(this.click_test_action),this.results_show()),this.activate_field()):this.pending_destroy_click=!1},i.prototype.container_mouseup=function(e){if(e.target.nodeName==="ABBR"&&!this.is_disabled)return this.results_reset(e)},i.prototype.blur_test=function(e){if(!this.active_field&&this.container.hasClass("chzn-container-active"))return this.close_field()},i.prototype.close_field=function(){return e(document).unbind("click",this.click_test_action),this.active_field=!1,this.results_hide(),this.container.removeClass("chzn-container-active"),this.winnow_results_clear(),this.clear_backstroke(),this.show_search_field_default(),this.search_field_scale()},i.prototype.activate_field=function(){return this.container.addClass("chzn-container-active"),this.active_field=!0,this.search_field.val(this.search_field.val()),this.search_field.focus()},i.prototype.test_active_click=function(t){return e(t.target).parents("#"+this.container_id).length?this.active_field=!0:this.close_field()},i.prototype.results_build=function(){var e,t,n,i,s;this.parsing=!0,this.results_data=r.SelectParser.select_to_array(this.form_field),this.is_multiple&&this.choices>0?(this.search_choices.find("li.search-choice").remove(),this.choices=0):this.is_multiple||(this.selected_item.addClass("chzn-default").find("span").text(this.default_text),this.disable_search||this.form_field.options.length<=this.disable_search_threshold?this.container.addClass("chzn-container-single-nosearch"):this.container.removeClass("chzn-container-single-nosearch")),e="",s=this.results_data;for(n=0,i=s.length;n<i;n++)t=s[n],t.group?e+=this.result_add_group(t):t.empty||(e+=this.result_add_option(t),t.selected&&this.is_multiple?this.choice_build(t):t.selected&&!this.is_multiple&&(this.selected_item.removeClass("chzn-default").find("span").text(t.text),this.allow_single_deselect&&this.single_deselect_control_build()));return this.search_field_disabled(),this.show_search_field_default(),this.search_field_scale(),this.search_results.html(e),this.parsing=!1},i.prototype.result_add_group=function(t){return t.disabled?"":(t.dom_id=this.container_id+"_g_"+t.array_index,'<li id="'+t.dom_id+'" class="group-result">'+e("<div />").text(t.label).html()+"</li>")},i.prototype.result_do_highlight=function(e){var t,n,r,i,s;if(e.length){this.result_clear_highlight(),this.result_highlight=e,this.result_highlight.addClass("highlighted"),r=parseInt(this.search_results.css("maxHeight"),10),s=this.search_results.scrollTop(),i=r+s,n=this.result_highlight.position().top+this.search_results.scrollTop(),t=n+this.result_highlight.outerHeight();if(t>=i)return this.search_results.scrollTop(t-r>0?t-r:0);if(n<s)return this.search_results.scrollTop(n)}},i.prototype.result_clear_highlight=function(){return this.result_highlight&&this.result_highlight.removeClass("highlighted"),this.result_highlight=null},i.prototype.results_show=function(){var e;if(!this.is_multiple)this.selected_item.addClass("chzn-single-with-drop"),this.result_single_selected&&this.result_do_highlight(this.result_single_selected);else if(this.max_selected_options<=this.choices)return this.form_field_jq.trigger("liszt:maxselected",{chosen:this}),!1;return e=this.is_multiple?this.container.height():this.container.height()-1,this.form_field_jq.trigger("liszt:showing_dropdown",{chosen:this}),this.dropdown.css({top:e+"px",left:0}),this.results_showing=!0,this.search_field.focus(),this.search_field.val(this.search_field.val()),this.winnow_results()},i.prototype.results_hide=function(){return this.is_multiple||this.selected_item.removeClass("chzn-single-with-drop"),this.result_clear_highlight(),this.form_field_jq.trigger("liszt:hiding_dropdown",{chosen:this}),this.dropdown.css({left:"-9000px"}),this.results_showing=!1},i.prototype.set_tab_index=function(e){var t;if(this.form_field_jq.attr("tabindex"))return t=this.form_field_jq.attr("tabindex"),this.form_field_jq.attr("tabindex",-1),this.search_field.attr("tabindex",t)},i.prototype.show_search_field_default=function(){return this.is_multiple&&this.choices<1&&!this.active_field?(this.search_field.val(this.default_text),this.search_field.addClass("default")):(this.search_field.val(""),this.search_field.removeClass("default"))},i.prototype.search_results_mouseup=function(t){var n;n=e(t.target).hasClass("active-result")?e(t.target):e(t.target).parents(".active-result").first();if(n.length)return this.result_highlight=n,this.result_select(t),this.search_field.focus()},i.prototype.search_results_mouseover=function(t){var n;n=e(t.target).hasClass("active-result")?e(t.target):e(t.target).parents(".active-result").first();if(n)return this.result_do_highlight(n)},i.prototype.search_results_mouseout=function(t){if(e(t.target).hasClass("active-result"))return this.result_clear_highlight()},i.prototype.choices_click=function(t){t.preventDefault();if(this.active_field&&!e(t.target).hasClass("search-choice")&&!this.results_showing)return this.results_show()},i.prototype.choice_build=function(t){var n,r,i,s=this;return this.is_multiple&&this.max_selected_options<=this.choices?(this.form_field_jq.trigger("liszt:maxselected",{chosen:this}),!1):(n=this.container_id+"_c_"+t.array_index,this.choices+=1,t.disabled?r='<li class="search-choice search-choice-disabled" id="'+n+'"><span>'+t.html+"</span></li>":r='<li class="search-choice" id="'+n+'"><span>'+t.html+'</span><a href="javascript:void(0)" class="search-choice-close" rel="'+t.array_index+'"></a></li>',this.search_container.before(r),i=e("#"+n).find("a").first(),i.click(function(e){return s.choice_destroy_link_click(e)}))},i.prototype.choice_destroy_link_click=function(t){return t.preventDefault(),this.is_disabled?t.stopPropagation:(this.pending_destroy_click=!0,this.choice_destroy(e(t.target)))},i.prototype.choice_destroy=function(e){if(this.result_deselect(e.attr("rel")))return this.choices-=1,this.show_search_field_default(),this.is_multiple&&this.choices>0&&this.search_field.val().length<1&&this.results_hide(),e.parents("li").first().remove(),this.search_field_scale()},i.prototype.results_reset=function(){this.form_field.options[0].selected=!0,this.selected_item.find("span").text(this.default_text),this.is_multiple||this.selected_item.addClass("chzn-default"),this.show_search_field_default(),this.results_reset_cleanup(),this.form_field_jq.trigger("change");if(this.active_field)return this.results_hide()},i.prototype.results_reset_cleanup=function(){return this.current_value=this.form_field_jq.val(),this.selected_item.find("abbr").remove()},i.prototype.result_select=function(e){var t,n,r,i;if(this.result_highlight)return t=this.result_highlight,n=t.attr("id"),this.result_clear_highlight(),this.is_multiple?this.result_deactivate(t):(this.search_results.find(".result-selected").removeClass("result-selected"),this.result_single_selected=t,this.selected_item.removeClass("chzn-default")),t.addClass("result-selected"),i=n.substr(n.lastIndexOf("_")+1),r=this.results_data[i],r.selected=!0,this.form_field.options[r.options_index].selected=!0,this.is_multiple?this.choice_build(r):(this.selected_item.find("span").first().text(r.text),this.allow_single_deselect&&this.single_deselect_control_build()),(!e.metaKey&&!e.ctrlKey||!this.is_multiple)&&this.results_hide(),this.search_field.val(""),(this.is_multiple||this.form_field_jq.val()!==this.current_value)&&this.form_field_jq.trigger("change",{selected:this.form_field.options[r.options_index].value}),this.current_value=this.form_field_jq.val(),this.search_field_scale()},i.prototype.result_activate=function(e){return e.addClass("active-result")},i.prototype.result_deactivate=function(e){return e.removeClass("active-result")},i.prototype.result_deselect=function(t){var n,r;return r=this.results_data[t],this.form_field.options[r.options_index].disabled?!1:(r.selected=!1,this.form_field.options[r.options_index].selected=!1,n=e("#"+this.container_id+"_o_"+t),n.removeClass("result-selected").addClass("active-result").show(),this.result_clear_highlight(),this.winnow_results(),this.form_field_jq.trigger("change",{deselected:this.form_field.options[r.options_index].value}),this.search_field_scale(),!0)},i.prototype.single_deselect_control_build=function(){if(this.allow_single_deselect&&this.selected_item.find("abbr").length<1)return this.selected_item.find("span").first().after('<abbr class="search-choice-close"></abbr>')},i.prototype.winnow_results=function(){var t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y;this.no_results_clear(),f=0,l=this.search_field.val()===this.default_text?"":e("<div/>").text(e.trim(this.search_field.val())).html(),o=this.search_contains?"":"^",s=new RegExp(o+l.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"i"),p=new RegExp(l.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),"i"),y=this.results_data;for(d=0,m=y.length;d<m;d++){n=y[d];if(!n.disabled&&!n.empty)if(n.group)e("#"+n.dom_id).css("display","none");else if(!this.is_multiple||!n.selected){t=!1,a=n.dom_id,u=e("#"+a);if(s.test(n.html))t=!0,f+=1;else if(this.search_split_words&&(n.html.indexOf(" ")>=0||n.html.indexOf("[")===0)){i=n.html.replace(/\[|\]/g,"").split(" ");if(i.length)for(v=0,g=i.length;v<g;v++)r=i[v],s.test(r)&&(t=!0,f+=1)}t?(l.length?(c=n.html.search(p),h=n.html.substr(0,c+l.length)+"</em>"+n.html.substr(c+l.length),h=h.substr(0,c)+"<em>"+h.substr(c)):h=n.html,u.html(h),this.result_activate(u),n.group_array_index!=null&&e("#"+this.results_data[n.group_array_index].dom_id).css("display","list-item")):(this.result_highlight&&a===this.result_highlight.attr("id")&&this.result_clear_highlight(),this.result_deactivate(u))}}return f<1&&l.length?this.no_results(l):this.winnow_results_set_highlight()},i.prototype.winnow_results_clear=function(){var t,n,r,i,s;this.search_field.val(""),n=this.search_results.find("li"),s=[];for(r=0,i=n.length;r<i;r++)t=n[r],t=e(t),t.hasClass("group-result")?s.push(t.css("display","auto")):!this.is_multiple||!t.hasClass("result-selected")?s.push(this.result_activate(t)):s.push(void 0);return s},i.prototype.winnow_results_set_highlight=function(){var e,t;if(!this.result_highlight){t=this.is_multiple?[]:this.search_results.find(".result-selected.active-result"),e=t.length?t.first():this.search_results.find(".active-result").first();if(e!=null)return this.result_do_highlight(e)}},i.prototype.no_results=function(t){var n;return n=e('<li class="no-results">'+this.results_none_found+' "<span></span>"</li>'),n.find("span").first().html(t),this.search_results.append(n)},i.prototype.no_results_clear=function(){return this.search_results.find(".no-results").remove()},i.prototype.keydown_arrow=function(){var t,n;this.result_highlight?this.results_showing&&(n=this.result_highlight.nextAll("li.active-result").first(),n&&this.result_do_highlight(n)):(t=this.search_results.find("li.active-result").first(),t&&this.result_do_highlight(e(t)));if(!this.results_showing)return this.results_show()},i.prototype.keyup_arrow=function(){var e;if(!this.results_showing&&!this.is_multiple)return this.results_show();if(this.result_highlight)return e=this.result_highlight.prevAll("li.active-result"),e.length?this.result_do_highlight(e.first()):(this.choices>0&&this.results_hide(),this.result_clear_highlight())},i.prototype.keydown_backstroke=function(){var e;if(this.pending_backstroke)return this.choice_destroy(this.pending_backstroke.find("a").first()),this.clear_backstroke();e=this.search_container.siblings("li.search-choice").last();if(e.length&&!e.hasClass("search-choice-disabled"))return this.pending_backstroke=e,this.single_backstroke_delete?this.keydown_backstroke():this.pending_backstroke.addClass("search-choice-focus")},i.prototype.clear_backstroke=function(){return this.pending_backstroke&&this.pending_backstroke.removeClass("search-choice-focus"),this.pending_backstroke=null},i.prototype.keydown_checker=function(e){var t,n;t=(n=e.which)!=null?n:e.keyCode,this.search_field_scale(),t!==8&&this.pending_backstroke&&this.clear_backstroke();switch(t){case 8:this.backstroke_length=this.search_field.val().length;break;case 9:this.results_showing&&!this.is_multiple&&this.result_select(e),this.mouse_on_container=!1;break;case 13:e.preventDefault();break;case 38:e.preventDefault(),this.keyup_arrow();break;case 40:this.keydown_arrow()}},i.prototype.search_field_scale=function(){var t,n,r,i,s,o,u,a,f;if(this.is_multiple){r=0,u=0,s="position:absolute; left: -1000px; top: -1000px; display:none;",o=["font-size","font-style","font-weight","font-family","line-height","text-transform","letter-spacing"];for(a=0,f=o.length;a<f;a++)i=o[a],s+=i+":"+this.search_field.css(i)+";";return n=e("<div />",{style:s}),n.text(this.search_field.val()),e("body").append(n),u=n.width()+25,n.remove(),u>this.f_width-10&&(u=this.f_width-10),this.search_field.css({width:u+"px"}),t=this.container.height(),this.dropdown.css({top:t+"px"})}},i.prototype.generate_random_id=function(){var t;t="sel"+this.generate_random_char()+this.generate_random_char()+this.generate_random_char();while(e("#"+t).length>0)t+=this.generate_random_char();return t},i}(AbstractChosen),r.Chosen=t,n=function(e){var t;return t=e.outerWidth()-e.width()},r.get_side_border_padding=n}.call(this);
/* =========================================================
 * bootstrap-datepicker.js
 * http://www.eyecon.ro/bootstrap-datepicker
 * =========================================================
 * Copyright 2012 Stefan Petre
 * Improvements by Andrew Rowls
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================= */

!function( $ ) {

	function UTCDate(){
		return new Date(Date.UTC.apply(Date, arguments));
	}
	function UTCToday(){
		var today = new Date();
		return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
	}

	// Picker object

	var Datepicker = function(element, options) {
		var that = this;

		this.element = $(element);
		this.language = options.language||this.element.data('date-language')||"en";
		this.language = this.language in dates ? this.language : "en";
		this.isRTL = dates[this.language].rtl||false;
		this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'mm/dd/yyyy');
		this.isInline = false;
		this.isInput = this.element.is('input');
		this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
		this.hasInput = this.component && this.element.find('input').length;
		if(this.component && this.component.length === 0)
			this.component = false;

		this._attachEvents();

		this.forceParse = true;
		if ('forceParse' in options) {
			this.forceParse = options.forceParse;
		} else if ('dateForceParse' in this.element.data()) {
			this.forceParse = this.element.data('date-force-parse');
		}
		 

		this.picker = $(DPGlobal.template)
							.appendTo(this.isInline ? this.element : 'body')
							.on({
								click: $.proxy(this.click, this),
								mousedown: $.proxy(this.mousedown, this)
							});

		if(this.isInline) {
			this.picker.addClass('datepicker-inline');
		} else {
			this.picker.addClass('datepicker-dropdown dropdown-menu');
		}
		if (this.isRTL){
			this.picker.addClass('datepicker-rtl');
			this.picker.find('.prev i, .next i')
						.toggleClass('icon-arrow-left icon-arrow-right');
		}
		$(document).on('mousedown', function (e) {
			// Clicked outside the datepicker, hide it
			if ($(e.target).closest('.datepicker').length === 0) {
				that.hide();
			}
		});

		this.autoclose = false;
		if ('autoclose' in options) {
			this.autoclose = options.autoclose;
		} else if ('dateAutoclose' in this.element.data()) {
			this.autoclose = this.element.data('date-autoclose');
		}

		this.keyboardNavigation = true;
		if ('keyboardNavigation' in options) {
			this.keyboardNavigation = options.keyboardNavigation;
		} else if ('dateKeyboardNavigation' in this.element.data()) {
			this.keyboardNavigation = this.element.data('date-keyboard-navigation');
		}

		this.viewMode = this.startViewMode = 0;
		switch(options.startView || this.element.data('date-start-view')){
			case 2:
			case 'decade':
				this.viewMode = this.startViewMode = 2;
				break;
			case 1:
			case 'year':
				this.viewMode = this.startViewMode = 1;
				break;
		}

		this.todayBtn = (options.todayBtn||this.element.data('date-today-btn')||false);
		this.todayHighlight = (options.todayHighlight||this.element.data('date-today-highlight')||false);

		this.weekStart = ((options.weekStart||this.element.data('date-weekstart')||dates[this.language].weekStart||0) % 7);
		this.weekEnd = ((this.weekStart + 6) % 7);
		this.startDate = -Infinity;
		this.endDate = Infinity;
		this.daysOfWeekDisabled = [];
		this.setStartDate(options.startDate||this.element.data('date-startdate'));
		this.setEndDate(options.endDate||this.element.data('date-enddate'));
		this.setDaysOfWeekDisabled(options.daysOfWeekDisabled||this.element.data('date-days-of-week-disabled'));
		this.fillDow();
		this.fillMonths();
		this.update();
		this.showMode();

		if(this.isInline) {
			this.show();
		}
	};

	Datepicker.prototype = {
		constructor: Datepicker,

		_events: [],
		_attachEvents: function(){
			this._detachEvents();
			if (this.isInput) { // single input
				this._events = [
					[this.element, {
						focus: $.proxy(this.show, this),
						keyup: $.proxy(this.update, this),
						keydown: $.proxy(this.keydown, this)
					}]
				];
			}
			else if (this.component && this.hasInput){ // component: input + button
				this._events = [
					// For components that are not readonly, allow keyboard nav
					[this.element.find('input'), {
						focus: $.proxy(this.show, this),
						keyup: $.proxy(this.update, this),
						keydown: $.proxy(this.keydown, this)
					}],
					[this.component, {
						click: $.proxy(this.show, this)
					}]
				];
			}
						else if (this.element.is('div')) {  // inline datepicker
							this.isInline = true;
						}
			else {
				this._events = [
					[this.element, {
						click: $.proxy(this.show, this)
					}]
				];
			}
			for (var i=0, el, ev; i<this._events.length; i++){
				el = this._events[i][0];
				ev = this._events[i][1];
				el.on(ev);
			}
		},
		_detachEvents: function(){
			for (var i=0, el, ev; i<this._events.length; i++){
				el = this._events[i][0];
				ev = this._events[i][1];
				el.off(ev);
			}
			this._events = [];
		},

		show: function(e) {
			this.picker.show();
			this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
			this.update();
			this.place();
			$(window).on('resize', $.proxy(this.place, this));
			if (e ) {
				e.stopPropagation();
				e.preventDefault();
			}
			this.element.trigger({
				type: 'show',
				date: this.date
			});
		},

		hide: function(e){
			if(this.isInline) return;
			this.picker.hide();
			$(window).off('resize', this.place);
			this.viewMode = this.startViewMode;
			this.showMode();
			if (!this.isInput) {
				$(document).off('mousedown', this.hide);
			}

			if (
				this.forceParse &&
				(
					this.isInput && this.element.val() ||
					this.hasInput && this.element.find('input').val()
				)
			)
				this.setValue();
			this.element.trigger({
				type: 'hide',
				date: this.date
			});
		},

		remove: function() {
			this._detachEvents();
			this.picker.remove();
			delete this.element.data().datepicker;
		},

		getDate: function() {
			var d = this.getUTCDate();
			return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
		},

		getUTCDate: function() {
			return this.date;
		},

		setDate: function(d) {
			this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
		},

		setUTCDate: function(d) {
			this.date = d;
			this.setValue();
		},

		setValue: function() {
			var formatted = this.getFormattedDate();
			if (!this.isInput) {
				if (this.component){
					this.element.find('input').prop('value', formatted);
				}
				this.element.data('date', formatted);
			} else {
				this.element.prop('value', formatted);
			}
		},

		getFormattedDate: function(format) {
			if(format == undefined) format = this.format;
			return DPGlobal.formatDate(this.date, format, this.language);
		},

		setStartDate: function(startDate){
			this.startDate = startDate||-Infinity;
			if (this.startDate !== -Infinity) {
				this.startDate = DPGlobal.parseDate(this.startDate, this.format, this.language);
			}
			this.update();
			this.updateNavArrows();
		},

		setEndDate: function(endDate){
			this.endDate = endDate||Infinity;
			if (this.endDate !== Infinity) {
				this.endDate = DPGlobal.parseDate(this.endDate, this.format, this.language);
			}
			this.update();
			this.updateNavArrows();
		},

		setDaysOfWeekDisabled: function(daysOfWeekDisabled){
			this.daysOfWeekDisabled = daysOfWeekDisabled||[];
			if (!$.isArray(this.daysOfWeekDisabled)) {
				this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
			}
			this.daysOfWeekDisabled = $.map(this.daysOfWeekDisabled, function (d) {
				return parseInt(d, 10);
			});
			this.update();
			this.updateNavArrows();
		},

		place: function(){
						if(this.isInline) return;
			var zIndex = parseInt(this.element.parents().filter(function() {
							return $(this).css('z-index') != 'auto';
						}).first().css('z-index'))+10;
			var offset = this.component ? this.component.offset() : this.element.offset();
			this.picker.css({
				top: offset.top + this.height,
				left: offset.left,
				zIndex: zIndex
			});
		},

		update: function(){
			var date, fromArgs = false;
			if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
				date = arguments[0];
				fromArgs = true;
			} else {
				date = this.isInput ? this.element.prop('value') : this.element.data('date') || this.element.find('input').prop('value');
			}

			this.date = DPGlobal.parseDate(date, this.format, this.language);

			if(fromArgs) this.setValue();

			var oldViewDate = this.viewDate;
			if (this.date < this.startDate) {
				this.viewDate = new Date(this.startDate);
			} else if (this.date > this.endDate) {
				this.viewDate = new Date(this.endDate);
			} else {
				this.viewDate = new Date(this.date);
			}

			if (oldViewDate && oldViewDate.getTime() != this.viewDate.getTime()){
				this.element.trigger({
					type: 'changeDate',
					date: this.viewDate
				});
			}
			this.fill();
		},

		fillDow: function(){
			var dowCnt = this.weekStart,
			html = '<tr>';
			while (dowCnt < this.weekStart + 7) {
				html += '<th class="dow">'+dates[this.language].daysMin[(dowCnt++)%7]+'</th>';
			}
			html += '</tr>';
			this.picker.find('.datepicker-days thead').append(html);
		},

		fillMonths: function(){
			var html = '',
			i = 0;
			while (i < 12) {
				html += '<span class="month">'+dates[this.language].monthsShort[i++]+'</span>';
			}
			this.picker.find('.datepicker-months td').html(html);
		},

		fill: function() {
			var d = new Date(this.viewDate),
				year = d.getUTCFullYear(),
				month = d.getUTCMonth(),
				startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
				startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
				endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
				endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
				currentDate = this.date && this.date.valueOf(),
				today = new Date();
			this.picker.find('.datepicker-days thead th:eq(1)')
						.text(dates[this.language].months[month]+' '+year);
			this.picker.find('tfoot th.today')
						.text(dates[this.language].today)
						.toggle(this.todayBtn !== false);
			this.updateNavArrows();
			this.fillMonths();
			var prevMonth = UTCDate(year, month-1, 28,0,0,0,0),
				day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
			prevMonth.setUTCDate(day);
			prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7)%7);
			var nextMonth = new Date(prevMonth);
			nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
			nextMonth = nextMonth.valueOf();
			var html = [];
			var clsName;
			while(prevMonth.valueOf() < nextMonth) {
				if (prevMonth.getUTCDay() == this.weekStart) {
					html.push('<tr>');
				}
				clsName = '';
				if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) {
					clsName += ' old';
				} else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) {
					clsName += ' new';
				}
				// Compare internal UTC date with local today, not UTC today
				if (this.todayHighlight &&
					prevMonth.getUTCFullYear() == today.getFullYear() &&
					prevMonth.getUTCMonth() == today.getMonth() &&
					prevMonth.getUTCDate() == today.getDate()) {
					clsName += ' today';
				}
				if (currentDate && prevMonth.valueOf() == currentDate) {
					clsName += ' active';
				}
				if (prevMonth.valueOf() < this.startDate || prevMonth.valueOf() > this.endDate ||
					$.inArray(prevMonth.getUTCDay(), this.daysOfWeekDisabled) !== -1) {
					clsName += ' disabled';
				}
				html.push('<td class="day'+clsName+'">'+prevMonth.getUTCDate() + '</td>');
				if (prevMonth.getUTCDay() == this.weekEnd) {
					html.push('</tr>');
				}
				prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
			}
			this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
			var currentYear = this.date && this.date.getUTCFullYear();

			var months = this.picker.find('.datepicker-months')
						.find('th:eq(1)')
							.text(year)
							.end()
						.find('span').removeClass('active');
			if (currentYear && currentYear == year) {
				months.eq(this.date.getUTCMonth()).addClass('active');
			}
			if (year < startYear || year > endYear) {
				months.addClass('disabled');
			}
			if (year == startYear) {
				months.slice(0, startMonth).addClass('disabled');
			}
			if (year == endYear) {
				months.slice(endMonth+1).addClass('disabled');
			}

			html = '';
			year = parseInt(year/10, 10) * 10;
			var yearCont = this.picker.find('.datepicker-years')
								.find('th:eq(1)')
									.text(year + '-' + (year + 9))
									.end()
								.find('td');
			year -= 1;
			for (var i = -1; i < 11; i++) {
				html += '<span class="year'+(i == -1 || i == 10 ? ' old' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>';
				year += 1;
			}
			yearCont.html(html);
		},

		updateNavArrows: function() {
			var d = new Date(this.viewDate),
				year = d.getUTCFullYear(),
				month = d.getUTCMonth();
			switch (this.viewMode) {
				case 0:
					if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) {
						this.picker.find('.prev').css({visibility: 'hidden'});
					} else {
						this.picker.find('.prev').css({visibility: 'visible'});
					}
					if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) {
						this.picker.find('.next').css({visibility: 'hidden'});
					} else {
						this.picker.find('.next').css({visibility: 'visible'});
					}
					break;
				case 1:
				case 2:
					if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) {
						this.picker.find('.prev').css({visibility: 'hidden'});
					} else {
						this.picker.find('.prev').css({visibility: 'visible'});
					}
					if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) {
						this.picker.find('.next').css({visibility: 'hidden'});
					} else {
						this.picker.find('.next').css({visibility: 'visible'});
					}
					break;
			}
		},

		click: function(e) {
			e.stopPropagation();
			e.preventDefault();
			var target = $(e.target).closest('span, td, th');
			if (target.length == 1) {
				switch(target[0].nodeName.toLowerCase()) {
					case 'th':
						switch(target[0].className) {
							case 'switch':
								this.showMode(1);
								break;
							case 'prev':
							case 'next':
								var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
								switch(this.viewMode){
									case 0:
										this.viewDate = this.moveMonth(this.viewDate, dir);
										break;
									case 1:
									case 2:
										this.viewDate = this.moveYear(this.viewDate, dir);
										break;
								}
								this.fill();
								break;
							case 'today':
								var date = new Date();
								date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);

								this.showMode(-2);
								var which = this.todayBtn == 'linked' ? null : 'view';
								this._setDate(date, which);
								break;
						}
						break;
					case 'span':
						if (!target.is('.disabled')) {
							this.viewDate.setUTCDate(1);
							if (target.is('.month')) {
								var month = target.parent().find('span').index(target);
								this.viewDate.setUTCMonth(month);
								this.element.trigger({
									type: 'changeMonth',
									date: this.viewDate
								});
							} else {
								var year = parseInt(target.text(), 10)||0;
								this.viewDate.setUTCFullYear(year);
								this.element.trigger({
									type: 'changeYear',
									date: this.viewDate
								});
							}
							this.showMode(-1);
							this.fill();
						}
						break;
					case 'td':
						if (target.is('.day') && !target.is('.disabled')){
							var day = parseInt(target.text(), 10)||1;
							var year = this.viewDate.getUTCFullYear(),
								month = this.viewDate.getUTCMonth();
							if (target.is('.old')) {
								if (month === 0) {
									month = 11;
									year -= 1;
								} else {
									month -= 1;
								}
							} else if (target.is('.new')) {
								if (month == 11) {
									month = 0;
									year += 1;
								} else {
									month += 1;
								}
							}
							this._setDate(UTCDate(year, month, day,0,0,0,0));
						}
						break;
				}
			}
		},

		_setDate: function(date, which){
			if (!which || which == 'date')
				this.date = date;
			if (!which || which  == 'view')
				this.viewDate = date;
			this.fill();
			this.setValue();
			this.element.trigger({
				type: 'changeDate',
				date: this.date
			});
			var element;
			if (this.isInput) {
				element = this.element;
			} else if (this.component){
				element = this.element.find('input');
			}
			if (element) {
				element.change();
				if (this.autoclose && (!which || which == 'date')) {
					this.hide();
				}
			}
		},

		moveMonth: function(date, dir){
			if (!dir) return date;
			var new_date = new Date(date.valueOf()),
				day = new_date.getUTCDate(),
				month = new_date.getUTCMonth(),
				mag = Math.abs(dir),
				new_month, test;
			dir = dir > 0 ? 1 : -1;
			if (mag == 1){
				test = dir == -1
					// If going back one month, make sure month is not current month
					// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
					? function(){ return new_date.getUTCMonth() == month; }
					// If going forward one month, make sure month is as expected
					// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
					: function(){ return new_date.getUTCMonth() != new_month; };
				new_month = month + dir;
				new_date.setUTCMonth(new_month);
				// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
				if (new_month < 0 || new_month > 11)
					new_month = (new_month + 12) % 12;
			} else {
				// For magnitudes >1, move one month at a time...
				for (var i=0; i<mag; i++)
					// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
					new_date = this.moveMonth(new_date, dir);
				// ...then reset the day, keeping it in the new month
				new_month = new_date.getUTCMonth();
				new_date.setUTCDate(day);
				test = function(){ return new_month != new_date.getUTCMonth(); };
			}
			// Common date-resetting loop -- if date is beyond end of month, make it
			// end of month
			while (test()){
				new_date.setUTCDate(--day);
				new_date.setUTCMonth(new_month);
			}
			return new_date;
		},

		moveYear: function(date, dir){
			return this.moveMonth(date, dir*12);
		},

		dateWithinRange: function(date){
			return date >= this.startDate && date <= this.endDate;
		},

		keydown: function(e){
			if (this.picker.is(':not(:visible)')){
				if (e.keyCode == 27) // allow escape to hide and re-show picker
					this.show();
				return;
			}
			var dateChanged = false,
				dir, day, month,
				newDate, newViewDate;
			switch(e.keyCode){
				case 27: // escape
					this.hide();
					e.preventDefault();
					break;
				case 37: // left
				case 39: // right
					if (!this.keyboardNavigation) break;
					dir = e.keyCode == 37 ? -1 : 1;
					if (e.ctrlKey){
						newDate = this.moveYear(this.date, dir);
						newViewDate = this.moveYear(this.viewDate, dir);
					} else if (e.shiftKey){
						newDate = this.moveMonth(this.date, dir);
						newViewDate = this.moveMonth(this.viewDate, dir);
					} else {
						newDate = new Date(this.date);
						newDate.setUTCDate(this.date.getUTCDate() + dir);
						newViewDate = new Date(this.viewDate);
						newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
					}
					if (this.dateWithinRange(newDate)){
						this.date = newDate;
						this.viewDate = newViewDate;
						this.setValue();
						this.update();
						e.preventDefault();
						dateChanged = true;
					}
					break;
				case 38: // up
				case 40: // down
					if (!this.keyboardNavigation) break;
					dir = e.keyCode == 38 ? -1 : 1;
					if (e.ctrlKey){
						newDate = this.moveYear(this.date, dir);
						newViewDate = this.moveYear(this.viewDate, dir);
					} else if (e.shiftKey){
						newDate = this.moveMonth(this.date, dir);
						newViewDate = this.moveMonth(this.viewDate, dir);
					} else {
						newDate = new Date(this.date);
						newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
						newViewDate = new Date(this.viewDate);
						newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
					}
					if (this.dateWithinRange(newDate)){
						this.date = newDate;
						this.viewDate = newViewDate;
						this.setValue();
						this.update();
						e.preventDefault();
						dateChanged = true;
					}
					break;
				case 13: // enter
					this.hide();
					e.preventDefault();
					break;
				case 9: // tab
					this.hide();
					break;
			}
			if (dateChanged){
				this.element.trigger({
					type: 'changeDate',
					date: this.date
				});
				var element;
				if (this.isInput) {
					element = this.element;
				} else if (this.component){
					element = this.element.find('input');
				}
				if (element) {
					element.change();
				}
			}
		},

		showMode: function(dir) {
			if (dir) {
				this.viewMode = Math.max(0, Math.min(2, this.viewMode + dir));
			}
			/*
			  vitalets: fixing bug of very special conditions:
			  jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
			  Method show() does not set display css correctly and datepicker is not shown.
			  Changed to .css('display', 'block') solve the problem.
			  See https://github.com/vitalets/x-editable/issues/37

			  In jquery 1.7.2+ everything works fine.
			*/
			//this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
			this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
			this.updateNavArrows();
		}
	};

	$.fn.datepicker = function ( option ) {
		var args = Array.apply(null, arguments);
		args.shift();
		return this.each(function () {
			var $this = $(this),
				data = $this.data('datepicker'),
				options = typeof option == 'object' && option;
			if (!data) {
				$this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
			}
			if (typeof option == 'string' && typeof data[option] == 'function') {
				data[option].apply(data, args);
			}
		});
	};

	$.fn.datepicker.defaults = {
	};
	$.fn.datepicker.Constructor = Datepicker;
	var dates = $.fn.datepicker.dates = {
		en: {
			days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
			daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
			daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
			months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
			monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
			today: "Today"
		}
	};

	var DPGlobal = {
		modes: [
			{
				clsName: 'days',
				navFnc: 'Month',
				navStep: 1
			},
			{
				clsName: 'months',
				navFnc: 'FullYear',
				navStep: 1
			},
			{
				clsName: 'years',
				navFnc: 'FullYear',
				navStep: 10
		}],
		isLeapYear: function (year) {
			return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
		},
		getDaysInMonth: function (year, month) {
			return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
		},
		validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
		nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
		parseFormat: function(format){
			// IE treats \0 as a string end in inputs (truncating the value),
			// so it's a bad format delimiter, anyway
			var separators = format.replace(this.validParts, '\0').split('\0'),
				parts = format.match(this.validParts);
			if (!separators || !separators.length || !parts || parts.length == 0){
				throw new Error("Invalid date format.");
			}
			return {separators: separators, parts: parts};
		},
		parseDate: function(date, format, language) {
			if (date instanceof Date) return date;
			if (/^[-+]\d+[dmwy]([\s,]+[-+]\d+[dmwy])*$/.test(date)) {
				var part_re = /([-+]\d+)([dmwy])/,
					parts = date.match(/([-+]\d+)([dmwy])/g),
					part, dir;
				date = new Date();
				for (var i=0; i<parts.length; i++) {
					part = part_re.exec(parts[i]);
					dir = parseInt(part[1]);
					switch(part[2]){
						case 'd':
							date.setUTCDate(date.getUTCDate() + dir);
							break;
						case 'm':
							date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
							break;
						case 'w':
							date.setUTCDate(date.getUTCDate() + dir * 7);
							break;
						case 'y':
							date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
							break;
					}
				}
				return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
			}
			var parts = date && date.match(this.nonpunctuation) || [],
				date = new Date(),
				parsed = {},
				setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
				setters_map = {
					yyyy: function(d,v){ return d.setUTCFullYear(v); },
					yy: function(d,v){ return d.setUTCFullYear(2000+v); },
					m: function(d,v){
						v -= 1;
						while (v<0) v += 12;
						v %= 12;
						d.setUTCMonth(v);
						while (d.getUTCMonth() != v)
							d.setUTCDate(d.getUTCDate()-1);
						return d;
					},
					d: function(d,v){ return d.setUTCDate(v); }
				},
				val, filtered, part;
			setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
			setters_map['dd'] = setters_map['d'];
			date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
			var fparts = format.parts.slice();
			// Remove noop parts
			if (parts.length != fparts.length) {
				fparts = $(fparts).filter(function(i,p){
					return $.inArray(p, setters_order) !== -1;
				}).toArray();
			}
			// Process remainder
			if (parts.length == fparts.length) {
				for (var i=0, cnt = fparts.length; i < cnt; i++) {
					val = parseInt(parts[i], 10);
					part = fparts[i];
					if (isNaN(val)) {
						switch(part) {
							case 'MM':
								filtered = $(dates[language].months).filter(function(){
									var m = this.slice(0, parts[i].length),
										p = parts[i].slice(0, m.length);
									return m == p;
								});
								val = $.inArray(filtered[0], dates[language].months) + 1;
								break;
							case 'M':
								filtered = $(dates[language].monthsShort).filter(function(){
									var m = this.slice(0, parts[i].length),
										p = parts[i].slice(0, m.length);
									return m == p;
								});
								val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
								break;
						}
					}
					parsed[part] = val;
				}
				for (var i=0, s; i<setters_order.length; i++){
					s = setters_order[i];
					if (s in parsed && !isNaN(parsed[s]))
						setters_map[s](date, parsed[s])
				}
			}
			return date;
		},
		formatDate: function(date, format, language){
			var val = {
				d: date.getUTCDate(),
				D: dates[language].daysShort[date.getUTCDay()],
				DD: dates[language].days[date.getUTCDay()],
				m: date.getUTCMonth() + 1,
				M: dates[language].monthsShort[date.getUTCMonth()],
				MM: dates[language].months[date.getUTCMonth()],
				yy: date.getUTCFullYear().toString().substring(2),
				yyyy: date.getUTCFullYear()
			};
			val.dd = (val.d < 10 ? '0' : '') + val.d;
			val.mm = (val.m < 10 ? '0' : '') + val.m;
			var date = [],
				seps = $.extend([], format.separators);
			for (var i=0, cnt = format.parts.length; i < cnt; i++) {
				if (seps.length)
					date.push(seps.shift())
				date.push(val[format.parts[i]]);
			}
			return date.join('');
		},
		headTemplate: '<thead>'+
							'<tr>'+
								'<th class="prev">‹ <i class="icon-arrow-left"/></th>'+
								'<th colspan="5" class="switch"></th>'+
								'<th class="next"> ›<i class="icon-arrow-right"/></th>'+
							'</tr>'+
						'</thead>',
		contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
		footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr></tfoot>'
	};
	DPGlobal.template = '<div class="datepicker">'+
							'<div class="datepicker-days">'+
								'<table class=" table-condensed">'+
									DPGlobal.headTemplate+
									'<tbody></tbody>'+
									DPGlobal.footTemplate+
								'</table>'+
							'</div>'+
							'<div class="datepicker-months">'+
								'<table class="table-condensed">'+
									DPGlobal.headTemplate+
									DPGlobal.contTemplate+
									DPGlobal.footTemplate+
								'</table>'+
							'</div>'+
							'<div class="datepicker-years">'+
								'<table class="table-condensed">'+
									DPGlobal.headTemplate+
									DPGlobal.contTemplate+
									DPGlobal.footTemplate+
								'</table>'+
							'</div>'+
						'</div>';

	$.fn.datepicker.DPGlobal = DPGlobal;

}( window.jQuery );

/**
 * French translation for bootstrap-datepicker
 * Nico Mollet <nico.mollet@gmail.com>
 */
;(function($){
	$.fn.datepicker.dates['fr'] = {
		days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
		daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
		daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
		months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
		monthsShort: ["Jan", "Fev", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Dec"],
		today: "Aujourd'hui"
	};
}(jQuery));

/**
 * German translation for bootstrap-datepicker
 * Sam Zurcher <sam@orelias.ch>
 */
;(function($){
	$.fn.datepicker.dates['de'] = {
		days: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"],
		daysShort: ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam", "Son"],
		daysMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"],
		months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"],
		monthsShort: ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"],
		today: "Heute"
	};
}(jQuery));

document.createElement('section');
document.createElement('article');
document.createElement('footer');
document.createElement('header');
document.createElement('nav');
document.createElement('aside');

function randomFromInterval(from, to) {
    return Math.floor(Math.random() * (to - from + 1) + from);
}

$(function($) {

    $('.gc:first-child').addClass('first');
    $('.gc:last-child').addClass('last');

    try {
        $('.fancybox').fancybox({
            openEffect: 'none',
            closeEffect: 'none'
        });

    }catch(err){
        //Handle errors here
    }

    // Equal Height Boxes
    function equalHeight(group) {
        tallest = 0;
        group.each(function() {
            thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });
        group.height(tallest);
        group.addClass('fixed');
    }

    $('#nav-main > ul > li').mouseenter(function(event) {
        $(this).find('.sub').fadeIn('fast');
        if ($(window).width() > 600) {
            equalHeight($(this).find('.sub .col'));
        }
        ;
    });

    $('#nav-main > ul > li').mouseleave(function(event) {
        $(this).find('.sub').delay(200).fadeOut('fast');
    });

    function mobileSubNav() {
        if ($(window).width() > 780) {
            $('#nav-lang, #nav-quicklinks').prependTo('#nav-top');
            $('#nav-sub ul').show();
            $('#nav-sub .toggle-nav').remove();

        } else {

            /*$(".tree .no-list li span").each(function(e,i){
                if($(this).text().indexOf("- ")){
                    $(this).text($(this).text().replace("- ", ""));
                }
            });

            $(".social-icons").remove().insertBefore($("#nav-main"));
            $("#nav-quicklinks").remove().insertAfter($("#nav-main"));

            if ($("#nav-sub ul").is(":visible")) {
                if ($("#nav-sub .toggle-nav").length == "") {
                    $("#nav-sub").prepend($('<button class="toggle-nav">'  + mobileNavLabel + '</button>'));
                    // Mobile SubNav Toggle Event
                }
            };
            $("#nav-sub > ul").hide();*/

            $('#nav-main > ul > li').unbind('mouseenter mouseleave');

            var activeNav = $('#nav-main > ul > li.has-sub > .sub.active');

            activeNav.parent('li').addClass('open')

            if (activeNav.find('.parent').size() <= 0) {
                var $li = $('<li class="parent" />').append(activeNav.prev().clone());
                $(activeNav).find('ul.second-level').prepend($li);
            }
            console.log($(activeNav).find('.third-level.active'))
            $(activeNav).find('.third-level.active').css('display', 'block')

            $('#nav-main > ul > li.has-sub > a').on('click', function(e) {
                e.preventDefault();

                $('#nav-main > ul > li.open').removeClass('open')

                if ($(this).next().find('.parent').size() <= 0) {
                    var $li = $('<li class="parent" />').
                        append($(this).clone());
                    $(this).next().find('ul.second-level').prepend($li);
                }
            });
        }
        ;
    };

    // Trigger Mobile SubNav
    mobileSubNav();
    $(window).resize(function() {
        mobileSubNav();
    });

    $('.toggle-nav').bind('touchstart click', function(e) {
        $(this).next().slideToggle();

        return false;
    });
});

jQuery(document).ready(function($) {
    $('#searchBoxButton').bind('click', function() {
        $('#searchBox').toggleClass('show-block');
    });

  //Scroll to top button
  var $scrollTop = $('.scroll-top');

  $(window).scroll(function() {
    var topPos = $(this).scrollTop();

    if (topPos > 100) {
      $scrollTop.css({opacity: 1});
    } else {
      $scrollTop.css({opacity: 0});
    }
  });

  $scrollTop.click(function() {
    $('html, body').animate({
      scrollTop: 0
    }, 500);

    return false;
  });

    // Toggle menu
    $('.toggle-menu').bind('click', function(e) {
        e.preventDefault();

        $('body').toggleClass('open-menu');

        $('#main').one('click', function(e) {
            e.preventDefault();

            $('body').removeClass('open-menu');
        });
    });

    // Subsubmenu
    $('.show-submenu').bind('click', function(e) {
        e.preventDefault();
        $(this).parent().toggleClass('open-submenu');
    });

  // Event Widget
  var eventContentWidth, eventWidget, eventWidgetButton;
  eventWidget = $('.event-widget');

  if (eventWidget.length > 0 && eventWidget.attr('data-visible') == 1) {

    // Case desktop
    if ($(window).width() >= 768) {
      eventWidget.addClass('desktop');
      eventContentWidth = eventWidget.find('.event-widget-content').outerWidth();
      eventWidgetButton = eventWidget.find('.event-widget-button');

      // Add animate on event button click
      eventWidgetButton.click(function () {
        if (eventWidgetButton.hasClass('active')) {
          eventWidget.animate({right: -eventContentWidth}, 500);
          eventWidgetButton.removeClass('active');
        } else {
          eventWidget.animate({right: 0}, 500);
          eventWidgetButton.addClass('active');
        }
      });

      // Close widget when user scroll
      $(window).scroll(function () {
        if (eventWidgetButton.hasClass('active')) {
          eventWidget.animate({right: -eventContentWidth}, 500);
          eventWidgetButton.removeClass('active');
        }
      });

      // Init event widget
      eventWidget.css('right', -eventContentWidth);
      eventWidget.css('visibility', 'visible');
      if (eventWidget.data('type-visible') === 1) {
        eventWidget.animate({right: 0}, 1000);
      }
    }
    else // Case mobile
    {
      eventWidget.addClass('mobile');
      eventWidget.css('visibility', 'visible');
    }
  } else {
    eventWidget.css('display', 'none');
  }
  // Add color for widgets
  $.each(eventWidget, function () {
    var $widget = $(this);
    var colorWidget = $widget.data('color');
    var $widgetContent = $widget.find('.event-widget-content');
    if ($(window).width() >= 768) {
      $widget.css('border-color', colorWidget);
      $widget.find('.event-widget-button').css('background-color', colorWidget);
      $widgetContent.find('a, .event-infos').css('color', colorWidget);
    } else {
      $widget.css('background-color', colorWidget);
      $widgetContent.find('a, .event-infos').css('color', '#FFF');
    }
  });

  // Hubspot CTA to trigger iFrame
  $('#hubspotCTA').click(function(event) {
    event.preventDefault();
    const self = $('#hubspotIFrame');
    const parent = self.parent('article');
    parent.nextAll().addClass('hidden');
    parent.removeClass('hidden');
    self.removeClass('hidden');
  });

  // Hide Hubspot CTA when no iFrame
  if ($('#hubspotIFrame').length === 0) {
    $('#hubspotCTA').addClass('hidden');
  }
});

function AdrollTracker()
{
    this.adrollSegments = {
        'fr' : '6aa60bb4',
        'de' : 'bf97c202'
    };

    this.buttonSelector = '#subscribe_button';

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

    this.initEvent = function()
    {
        var self = this;

        $(this.buttonSelector).click(function() {
            self.processTracking(this);
        });
    };

    this.processTracking = function(element)
    {
        var segmentId = this.defineSegment(element)

        try{
            __adroll.record_user({"adroll_segments": segmentId});
        } catch(err) {
            console.log("Adroll Error:");
            console.log(err);
        }
    };

    this.defineSegment = function(element)
    {
        var language = $(element).data('language');
        var segmentId = this.adrollSegments[language];

        return segmentId;
    };

    this.init();
}


jQuery(document).ready(function($){
    var adrollTracker = new AdrollTracker();
});

/**
 * UniDistance mixins scripts.
 *
 * @author Mykhailo YATSYSHYN <myyat@smile.fr>
 * @copyright 2018 Smile
 */

//---------------------------------
//    HELPERS LIST
//---------------------------------

UNI_HELPER = {
  /**
   * Checks if current element is empty
   * @param $element
   * @returns {boolean}
   */
  isEmpty: function($element) {
    return (!$element || !$element.length);
  }
};

/**
 * Fancy box media scripts.
 *
 * @author Mykhailo YATSYSHYN <myyat@smile.fr>
 * @copyright 2018 Smile
 */
(function($, HELPER) {
  'use strict';

  var $items = {};

  $(document).ready(function() {
    $items = $('.fancybox-media');
    if (!HELPER.isEmpty($items)) {
      initFancyBoxMedia();
    }
  });

  //---------------------------------
  //    FUNCTIONS LIST
  //---------------------------------

  /**
   * Initialize fancybox with use media helpers
   */
  function initFancyBoxMedia() {
    $.each($items, function() {
      var $item = $(this);
      $item.fancybox({
        openEffect: 'none',
        closeEffect: 'none',
        helpers: {
          media: true
        }
      });
    });
  }
})(jQuery, UNI_HELPER);

