/* source: assets/javascript/website/00-dachi.js */

var Dachi = function() {
    var instance = this;

	var events = {};
	this.on = function(eventName, callback) {
		events[eventName] = events[eventName] || [];
		events[eventName].push(callback);
	};
	this.fire = function(eventName, _) {
		var args = Array.prototype.slice.call(arguments, 1);

		if(!events[eventName])
			return;

		for(var i = 0, length = events[eventName].length; i < length; i++)
			events[eventName][i].apply(instance, args);
	}

    var scripts = {};
    for(var script in Dachi)
    	scripts[script] = new Dachi[script](this);
};

Dachi.prototype.removeBtnClasses = function(e) {
	var classes =['btn-primary', 'btn-default', 'btn-success', 'btn-info', 'btn-danger', 'btn-warning'];

	for (var i = classes.length - 1; i >= 0; i--)
		e.removeClass(classes[i]);

	return e;
}

$(function() {
	var dachi = new Dachi();
	dachi.fire('load');
});

/* source: assets/javascript/website/01-jquery.confirm.js */


(function($){

  $.fn.inlineConfirmation = function(options) {
    var defaults = {
      confirm: "<a href='#'>Confirm</a>",
      cancel: "<a href='#'>Cancel</a>",
      separator: " ",
      reverse: false,
      hideOriginalAction: true,
      bindsOnEvent: "click",
      expiresIn: 0,
      confirmCallback: function() { return true; },
      cancelCallback: function() { return true; }
    };

    var original_action;
    var timeout_id;
    var all_actions     = $(this);
    var options         = $.extend(defaults, options);
    var block_class     = "inline-confirmation-block";
    var confirm_class   = "inline-confirmation-confirm";
    var cancel_class    = "inline-confirmation-cancel";
    var action_class    = "inline-confirmation-action";

    options.confirm = "<span class='" + action_class + " " + confirm_class + "'>" + options.confirm + "</span>";
    options.cancel  = "<span class='" + action_class + " " + cancel_class + "'>" + options.cancel + "</span>";

    var action_set = options.reverse === false
      ? options.confirm + options.separator + options.cancel
      : options.cancel + options.separator + options.confirm;

    $(this).on(options.bindsOnEvent, function(e) {
      original_action = $(this);

      all_actions.show();
      $("span." + block_class).hide();

      if (options.hideOriginalAction === true) {
        $(this).trigger("update").hide();
      }

      var active_action_set = $("span." + block_class, $(this).parent());

      if (active_action_set.length > 0) {
        active_action_set.show();
      } else {
        $(this).after("<span class='" + block_class + "'>" + action_set + "</span>");
      }

      if (options.expiresIn > 0) {
        timeout_id = setTimeout(function() {
          $("span." + block_class, original_action.parent()).hide();
          original_action.show();
        }, options.expiresIn * 1000);
      }

      e.preventDefault();
      return false;
    });

    $(this).parent().delegate("span." + action_class, "click", function() {
      clearTimeout(timeout_id);
      $(this).parent().hide();
      original_action.show();

      var args = new Array();
      args[0]  = original_action;

      if ($(this).hasClass(confirm_class)) {
        options.confirmCallback.apply(this, args);
      } else {
        options.cancelCallback.apply(this, args);
      }
      return false;
    });
  };

})(jQuery);


/* source: assets/javascript/website/bootstrap-datepicker.js */

/* =========================================================
 * bootstrap-datepicker.js 
 * http://www.eyecon.ro/bootstrap-datepicker
 * =========================================================
 * Copyright 2012 Stefan Petre
 *
 * 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( $ ) {
	
	// Picker object
	
	var Datepicker = function(element, options){
		this.element = $(element);
		this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'mm/dd/yyyy');
		this.picker = $(DPGlobal.template)
							.appendTo('body')
							.on({
								click: $.proxy(this.click, this)//,
								//mousedown: $.proxy(this.mousedown, this)
							});
		this.isInput = this.element.is('input');
		this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
		
		if (this.isInput) {
			this.element.on({
				focus: $.proxy(this.show, this),
				//blur: $.proxy(this.hide, this),
				keyup: $.proxy(this.update, this)
			});
		} else {
			if (this.component){
				this.component.on('click', $.proxy(this.show, this));
			} else {
				this.element.on('click', $.proxy(this.show, this));
			}
		}
	
		this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
		if (typeof this.minViewMode === 'string') {
			switch (this.minViewMode) {
				case 'months':
					this.minViewMode = 1;
					break;
				case 'years':
					this.minViewMode = 2;
					break;
				default:
					this.minViewMode = 0;
					break;
			}
		}
		this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
		if (typeof this.viewMode === 'string') {
			switch (this.viewMode) {
				case 'months':
					this.viewMode = 1;
					break;
				case 'years':
					this.viewMode = 2;
					break;
				default:
					this.viewMode = 0;
					break;
			}
		}
		this.startViewMode = this.viewMode;
		this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
		this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
		this.onRender = options.onRender;
		this.fillDow();
		this.fillMonths();
		this.update();
		this.showMode();
	};
	
	Datepicker.prototype = {
		constructor: Datepicker,
		
		show: function(e) {
			this.picker.show();
			this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
			this.place();
			$(window).on('resize', $.proxy(this.place, this));
			if (e ) {
				e.stopPropagation();
				e.preventDefault();
			}
			if (!this.isInput) {
			}
			var that = this;
			$(document).on('mousedown', function(ev){
				if ($(ev.target).closest('.datepicker').length == 0) {
					that.hide();
				}
			});
			this.element.trigger({
				type: 'show',
				date: this.date
			});
		},
		
		hide: function(){
			this.picker.hide();
			$(window).off('resize', this.place);
			this.viewMode = this.startViewMode;
			this.showMode();
			if (!this.isInput) {
				$(document).off('mousedown', this.hide);
			}
			//this.set();
			this.element.trigger({
				type: 'hide',
				date: this.date
			});
		},
		
		set: function() {
			var formated = DPGlobal.formatDate(this.date, this.format);
			if (!this.isInput) {
				if (this.component){
					this.element.find('input').prop('value', formated);
				}
				this.element.data('date', formated);
			} else {
				this.element.prop('value', formated);
			}
		},
		
		setValue: function(newDate) {
			if (typeof newDate === 'string') {
				this.date = DPGlobal.parseDate(newDate, this.format);
			} else {
				this.date = new Date(newDate);
			}
			this.set();
			this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
			this.fill();
		},
		
		place: function(){
			var offset = this.component ? this.component.offset() : this.element.offset();
			this.picker.css({
				top: offset.top + this.height,
				left: offset.left
			});
		},
		
		update: function(newDate){
			this.date = DPGlobal.parseDate(
				typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
				this.format
			);
			this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
			this.fill();
		},
		
		fillDow: function(){
			var dowCnt = this.weekStart;
			var html = '<tr>';
			while (dowCnt < this.weekStart + 7) {
				html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
			}
			html += '</tr>';
			this.picker.find('.datepicker-days thead').append(html);
		},
		
		fillMonths: function(){
			var html = '';
			var i = 0
			while (i < 12) {
				html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
			}
			this.picker.find('.datepicker-months td').append(html);
		},
		
		fill: function() {
			var d = new Date(this.viewDate),
				year = d.getFullYear(),
				month = d.getMonth(),
				currentDate = this.date.valueOf();
			this.picker.find('.datepicker-days th:eq(1)')
						.text(DPGlobal.dates.months[month]+' '+year);
			var prevMonth = new Date(year, month-1, 28,0,0,0,0),
				day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
			prevMonth.setDate(day);
			prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
			var nextMonth = new Date(prevMonth);
			nextMonth.setDate(nextMonth.getDate() + 42);
			nextMonth = nextMonth.valueOf();
			var html = [];
			var clsName,
				prevY,
				prevM;
			while(prevMonth.valueOf() < nextMonth) {
				if (prevMonth.getDay() === this.weekStart) {
					html.push('<tr>');
				}
				clsName = this.onRender(prevMonth);
				prevY = prevMonth.getFullYear();
				prevM = prevMonth.getMonth();
				if ((prevM < month &&  prevY === year) ||  prevY < year) {
					clsName += ' old';
				} else if ((prevM > month && prevY === year) || prevY > year) {
					clsName += ' new';
				}
				if (prevMonth.valueOf() === currentDate) {
					clsName += ' active';
				}
				html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
				if (prevMonth.getDay() === this.weekEnd) {
					html.push('</tr>');
				}
				prevMonth.setDate(prevMonth.getDate()+1);
			}
			this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
			var currentYear = this.date.getFullYear();
			
			var months = this.picker.find('.datepicker-months')
						.find('th:eq(1)')
							.text(year)
							.end()
						.find('span').removeClass('active');
			if (currentYear === year) {
				months.eq(this.date.getMonth()).addClass('active');
			}
			
			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+'</span>';
				year += 1;
			}
			yearCont.html(html);
		},
		
		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':
								this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
									this.viewDate,
									this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + 
									DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
								);
								this.fill();
								this.set();
								break;
						}
						break;
					case 'span':
						if (target.is('.month')) {
							var month = target.parent().find('span').index(target);
							this.viewDate.setMonth(month);
						} else {
							var year = parseInt(target.text(), 10)||0;
							this.viewDate.setFullYear(year);
						}
						if (this.viewMode !== 0) {
							this.date = new Date(this.viewDate);
							this.element.trigger({
								type: 'changeDate',
								date: this.date,
								viewMode: DPGlobal.modes[this.viewMode].clsName
							});
						}
						this.showMode(-1);
						this.fill();
						this.set();
						break;
					case 'td':
						if (target.is('.day') && !target.is('.disabled')){
							var day = parseInt(target.text(), 10)||1;
							var month = this.viewDate.getMonth();
							if (target.is('.old')) {
								month -= 1;
							} else if (target.is('.new')) {
								month += 1;
							}
							var year = this.viewDate.getFullYear();
							this.date = new Date(year, month, day,0,0,0,0);
							this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
							this.fill();
							this.set();
							this.element.trigger({
								type: 'changeDate',
								date: this.date,
								viewMode: DPGlobal.modes[this.viewMode].clsName
							});
						}
						break;
				}
			}
		},
		
		mousedown: function(e){
			e.stopPropagation();
			e.preventDefault();
		},
		
		showMode: function(dir) {
			if (dir) {
				this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
			}
			this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
		}
	};
	
	$.fn.datepicker = function ( option, val ) {
		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') data[option](val);
		});
	};

	$.fn.datepicker.defaults = {
		onRender: function(date) {
			return '';
		}
	};
	$.fn.datepicker.Constructor = Datepicker;
	
	var DPGlobal = {
		modes: [
			{
				clsName: 'days',
				navFnc: 'Month',
				navStep: 1
			},
			{
				clsName: 'months',
				navFnc: 'FullYear',
				navStep: 1
			},
			{
				clsName: 'years',
				navFnc: 'FullYear',
				navStep: 10
		}],
		dates:{
			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"]
		},
		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]
		},
		parseFormat: function(format){
			var separator = format.match(/[.\/\-\s].*?/),
				parts = format.split(/\W+/);
			if (!separator || !parts || parts.length === 0){
				throw new Error("Invalid date format.");
			}
			return {separator: separator, parts: parts};
		},
		parseDate: function(date, format) {
			var parts = date.split(format.separator),
				date = new Date(),
				val;
			date.setHours(0);
			date.setMinutes(0);
			date.setSeconds(0);
			date.setMilliseconds(0);
			if (parts.length === format.parts.length) {
				var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
				for (var i=0, cnt = format.parts.length; i < cnt; i++) {
					val = parseInt(parts[i], 10)||1;
					switch(format.parts[i]) {
						case 'dd':
						case 'd':
							day = val;
							date.setDate(val);
							break;
						case 'mm':
						case 'm':
							month = val - 1;
							date.setMonth(val - 1);
							break;
						case 'yy':
							year = 2000 + val;
							date.setFullYear(2000 + val);
							break;
						case 'yyyy':
							year = val;
							date.setFullYear(val);
							break;
					}
				}
				date = new Date(year, month, day, 0 ,0 ,0);
			}
			return date;
		},
		formatDate: function(date, format){
			var val = {
				d: date.getDate(),
				m: date.getMonth() + 1,
				yy: date.getFullYear().toString().substring(2),
				yyyy: date.getFullYear()
			};
			val.dd = (val.d < 10 ? '0' : '') + val.d;
			val.mm = (val.m < 10 ? '0' : '') + val.m;
			var date = [];
			for (var i=0, cnt = format.parts.length; i < cnt; i++) {
				date.push(val[format.parts[i]]);
			}
			return date.join(format.separator);
		},
		headTemplate: '<thead>'+
							'<tr>'+
								'<th class="prev">&lsaquo;</th>'+
								'<th colspan="5" class="switch"></th>'+
								'<th class="next">&rsaquo;</th>'+
							'</tr>'+
						'</thead>',
		contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
	};
	DPGlobal.template = '<div class="datepicker dropdown-menu">'+
							'<div class="datepicker-days">'+
								'<table class=" table-condensed">'+
									DPGlobal.headTemplate+
									'<tbody></tbody>'+
								'</table>'+
							'</div>'+
							'<div class="datepicker-months">'+
								'<table class="table-condensed">'+
									DPGlobal.headTemplate+
									DPGlobal.contTemplate+
								'</table>'+
							'</div>'+
							'<div class="datepicker-years">'+
								'<table class="table-condensed">'+
									DPGlobal.headTemplate+
									DPGlobal.contTemplate+
								'</table>'+
							'</div>'+
						'</div>';

}( window.jQuery );

/* source: assets/javascript/website/bselect.min.js */

(function(e,t){"use strict";function s(t){return e.isPlainObject(e(t).data(h))}function i(e,s){return f[s]!==t?f[s].apply(e,u.call(arguments,2)):e}function n(t){return i(t,"option","placeholder")||t.data("placeholder")||e.bselect.i18n.selectAnOption}function a(e){var t=e.find(".bselect-option-list"),s=t.find("li:visible").length;t.innerHeight(1.5*parseInt(t.css("line-height"),10)*(5>s?s:5))}function l(t,s,n){var a=i(t,"element");e.each(s,function(t,s){if(n[t]!==s&&"size"===t){var i=e.map(b.slice(0),function(e){return"bselect-"+e}).join(" ");a.removeClass(i),b.indexOf(n.size)>-1&&a.addClass("bselect-"+n.size)}})}function o(t){var s=i(t,"element");s.find(".bselect-message").text(e.bselect.i18n.noOptionsAvailable).show()}function r(t){if(38===t.keyCode||40===t.keyCode||13===t.keyCode){var s=e(this),i=s.is(".bselect-search-input");switch(t.keyCode){case 38:i?e(t.delegateTarget).find(".bselect-option:visible:last").focus():s.prevAll(".bselect-option:visible").eq(0).focus();break;case 40:i?e(t.delegateTarget).find(".bselect-option:visible:first").focus():s.nextAll(".bselect-option:visible").eq(0).focus();break;case 13:i||s.trigger("click")}return!1}}function c(s,a){var o,c,b,u,v,g=e(s);if(u=++d,b=e("<div class='bselect' />",{id:"bselect-"+u}),v=e("<div class='bselect-dropdown' />"),a.searchInput===!0){var m=e("<div class='bselect-search' />");e("<input type='text' class='bselect-search-input' />").attr({role:"combobox",tabindex:1,"aria-expanded":"false","aria-owns":"bselect-option-list-"+u}).appendTo(m),e("<span class='bselect-search-icon' />").append("<i class='icon-search'></i>").appendTo(m),m.appendTo(v)}e("<div class='bselect-message' role='status' />").appendTo(v),e("<ul class='bselect-option-list' />").attr({id:"bselect-option-list-"+u,role:"listbox"}).appendTo(v),b.append(v).insertAfter(g),g.data(h,{options:a,element:b,open:!1}),l(g,e.bselect.defaults,a),i(g,"refresh"),g.bind("bselectselect.bselect",a.select),g.bind("bselectselected.bselect",a.selected),g.bind("bselectsearch.bselect",a.search),c=e("<span />").addClass("bselect-label").text(n(g)),o=e("<button type='button' />").addClass("bselect-caret").html("<span class='bscaret'></span>"),b.prepend(o).prepend(c),c.outerWidth(g.outerWidth()-o.outerWidth()),g.addClass("bselect-inaccessible"),p.push(g),b.find(".bselect-search-input").keyup(e.proxy(f.search,g)),b.on("click",".bselect-option",e.proxy(f.select,g)),b.on("click",".bselect-caret, .bselect-label",e.proxy(f.toggle,g)),b.on("keydown",".bselect-option, .bselect-search-input",r),g.bind("change.bselect",function(){var e=g.data(h),s=e.itemsMap[this.value];return e.tempDisable?(e.tempDisable=!1,t):(i(g,"select",s),t)}).trigger("change.bselect")}var d=0,h="bselect",p=[],b=["mini","small","large"],u=Array.prototype.slice,f={option:function(s,i){var n=this.data(h).options||{},a=e.extend({},n);return"string"==typeof s&&"_"!==s[0]?i===t?n[s]:(n[s]=i,l(this,a,n),this):(e.isPlainObject(s)&&(e.extend(n,s),l(this,a,n),this.data(h).options=n),n)},element:function(){return this.data(h).element},toggle:function(t){if(this[0].disabled)return this;var s=i(this,"element");if(t instanceof e.Event){var n=i(this,"option","showOn");if(e(t.target).is(".bselect-label")&&"both"!==n)return this}return s.find(".bselect-dropdown").is(":hidden")?i(this,"show"):i(this,"hide"),this},show:function(){var t,s,n,l,o,r=this.data(h);if(this[0].disabled||r.open)return this;if(n=r.element,l=n.find(".bselect-dropdown"),l.css("left","-9999em").show(),a(n),s=n.find(".bselect-option.active"),s.length){var c=n.find(".bselect-option-list"),d=s.position().top,p=c.position().top;c.height()>d-p?c.scrollTop(0):c.scrollTop(d-p)}return l.hide().css("left","auto"),l.slideDown(i(this,"option","animationDuration")),this.data(h,e.extend(r,{open:!0})),n.addClass("open"),t=n.find(".bselect-search-input").focus(),o=t.parent().width()-t.next().outerWidth(),t.innerWidth(o),n.find(".bselect-search-input").attr("aria-expanded","true"),this},hide:function(s){var n=this.data(h);if(this[0].disabled||!n.open)return this;var a=n.options,l=n.element;return s=s===t?!0:s,this.data(h,e.extend(n,{open:!1})),l.find(".bselect-dropdown").slideUp(a.animationDuration),l.removeClass("open"),s&&a.clearSearchOnExit&&i(this,"clearSearch"),l.find(".bselect-search-input").attr("aria-expanded","false"),this},select:function(t){var s,n,a=i(this,"element");if(t instanceof e.Event)s=e(t.currentTarget);else if(s=a.find("li").eq(t),!s.length)return this;var l=a.find("li").removeClass("active").attr("aria-selected","false").index(s),o=this.find("option[value!='']").get(l);return this.trigger("bselectselect",[o]),n=s.addClass("active").data("value"),s.attr("aria-selected","true"),a.find(".bselect-label").text(s.text()),i(this,"hide"),this.data(h).tempDisable=!0,this.val(n).trigger("change"),this.trigger("bselectselected",[n,o]),this},search:function(t){var s,n,l,r,c,d=i(this,"option"),h=t instanceof e.Event?t.target.value:t,p=i(this,"element");if(this[0].disabled)return this;if(""===h&&i(this,"clearSearch"),t instanceof e.Event||p.find(".bselect-search").val(h),!(h===d.lastSearch||h.length<d.minSearchInput)){for(c=e(),s=p.find("li").hide(),l=0,r=s.length;r>l;l++)n=s[l],n.textContent.toLowerCase().indexOf(h.toLowerCase())>-1&&(c=c.add(e(n).show()));return 0===c.length?o(this):p.find(".bselect-message").hide(),this.trigger("bselectsearch",[h,c]),a(s.end()),this}},clearSearch:function(){var e=i(this,"element");return e.find(".bselect-search-input").val(""),e.find("li").show(),e.find(".bselect-message").hide(),a(e),this},disable:function(){return this[0].disabled||(i(this,"element").addClass("disabled"),this.prop("disabled",!0)),this},enable:function(){return this[0].disabled&&(i(this,"element").removeClass("disabled"),this.prop("disabled",!1)),this},refresh:function(){var t=i(this,"element"),s=t.find(".bselect-option-list").empty(),n={},a=0;return t.toggleClass("disabled",this.prop("disabled")),this.find("option, > optgroup").each(function(){var t,i,l=e(this).is("option");(!l||this.value)&&(l?(t="bselect-option",e(this).closest("optgroup").length&&(t+=" grouped")):t="bselect-option-group",i=e("<li />").attr({"class":t,role:"option",tabindex:l?2:-1,"aria-selected":"false"}),l?(i.data("value",this.value),n[this.value]=a,i.html("<a href='#'>"+this.text+"</a>")):i.text(this.label),i.appendTo(s),a++)}),0===a&&o(this),this.data(h).itemsMap=n,this},destroy:function(){var e=i(this,"element");return this.data(h,null),p.splice(p.indexOf(this),1),e.remove(),this.removeClass("bselect-inaccessible").unbind(".bselect"),this}};e.fn.bselect=function(i){return"string"==typeof i&&this[0]?s(this[0])&&f[i]!==t?f[i].apply(e(this[0]),u.call(arguments,1)):this:this.each(function(){s(this)||(i=e.isPlainObject(i)?i:{},i=e.extend({},e.bselect.defaults,i),c(this,i))})},e.bselect={defaults:{size:"normal",showOn:"both",clearSearchOnExit:!0,minSearchInput:0,animationDuration:300,searchInput:!0,search:null,select:null,selected:null},i18n:{selectAnOption:"Select an option",noOptionsAvailable:"No options available."}},e(document).on("click.bselect","label",function(t){var s,n,a;for(s=0,n=p.length;n>s;s++)if(a=p[s][0].id,a&&e(t.target).attr("for")===a)return i(p[s],"show"),!1}).on("click.bselect",function(e){var t,s,n;for(t=0,s=p.length;s>t;t++)n=p[t].data(h),n.open&&!n.element.has(e.target).length&&i(p[t],"hide")}),e(window).resize(function(){var e,t,s,i;for(e=0,t=p.length;t>e;e++)s=p[e].data(h),i=s.element.find(".bselect-caret"),s.element.find(".bselect-label").outerWidth(p[e].outerWidth()-i.outerWidth())})})(jQuery);

/* source: assets/javascript/website/init.js */

$(function () {
	$('.confirm').each(function() {
		var that = $(this);
		that.inlineConfirmation({
			confirm: "<a href='#' class='btn btn-success confirm-yes'>Confirm</a>",
			cancel: "<a href='#' class='btn btn-danger confirm-no'>Abort</a>",
			separator: " ",
			expiresIn: 10,
			confirmCallback: function(action) {
				window.location = that.attr("href");
			}
		});
	});


	// adblock  plus message
	var $advert = $('aside .advert');
	if($advert.length < 1) {
		console.log('fired advert blok')
		$('.blockmsg').css('display', 'block');
	};

	$('.tooltip-real').tooltip();

	$(".collapse").collapse();

	$('.dropdown-toggle').dropdown();

	if(typeof addthis !== 'undefined') {
		addthis.layers({
			'theme' : 'gray',
			'share' : {
				'position' : 'left',
				'numPreferredServices' : 5
			},
			'whatsnext' : {}
		});
	}

	$('.menu-toggle').on('click', function(e){
		e.preventDefault();
		$('nav').toggleClass('active');
	});

});

// This makes the menu drop down correctly on touch devices.
/*$(function() {
	$("nav li").click(function() {
		// remove classes from all
		var t = $(this);
		if(t.hasClass("active"))
			return $("nav li").removeClass("active");

		$("nav li").removeClass("active");
		$(this).addClass("active");
	 });
});*/

$(function(){
	if ($(window).width() < 767){
		$('nav > ul > .main-menu').click(function(){		
			$('nav .user-menu-mobile-options ul').slideUp('fast');
			$('nav .category-mobile-menu ul').slideUp('fast');
			$('nav .main-menu ul').slideToggle('fast');
		});
		$('nav > ul > .category-mobile-menu').click(function(){
			$('nav .user-menu-mobile-options ul').slideUp('fast');
			$('nav .main-menu ul').slideUp('fast');
			$('nav .category-mobile-menu ul').slideToggle('fast');
		});
		$('nav > ul > .user-menu-mobile-options').click(function(){
			$('nav .main-menu ul').slideUp('fast');
			$('nav .category-mobile-menu ul').slideUp('fast');
			$('nav .user-menu-mobile-options ul').slideToggle('fast');
		});
	}

	/*
    var disqus_shortname = 'lddevtest';
    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
    */

    //twitter
    !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");

    // date picker
    $('#datepicker').datepicker({
		format: 'yyyy-mm-dd'
	});
});

/* source: assets/javascript/website/jobs.js */

$(function(){
	if (!$('#jobsTextareaContent').length)
		return;
	var ed = new tinymce.Editor('jobsTextareaContent', {
		browser_spellcheck: true,
		statusbar: false,
		resize: true,
		convert_urls: true,
		relative_urls: false,
		convert_fonts_to_spans: true,
		forced_root_block: 'p',
		menubar: false,
		height: '15em',

		toolbar: "bold italic underline",

		plugins: 'advlist autolink print link hr lists charmap table print paste searchreplace contextmenu',
		contextmenu: "undo redo | inserttable | removeformat",
		nonbreaking_force_tab: true,
	}, tinymce.EditorManager);
	ed.render();
});

/* source: assets/javascript/website/lib.js */

$(document).ready(function(){
  $('.bxslider').bxSlider({
	  auto: true,
	  speed: 400,
	  pause: 9000,
	  autoControls: true,
	  controls: false
	});

	var prefixes = ['-webkit-','-moz-', '-ms-', '-o-', ''];
	for(var pre in prefixes) {
		if($('.test-ligatures').css(prefixes[pre] + "font-feature-settings") && $('.test-ligatures').css(prefixes[pre] + "font-feature-settings").indexOf("liga")) {
			$('body').addClass("ligatures");
		}
	}
});

var shakeDiv = function(d, amount) {
	amount = amount || 25;
    d.css({ "position": "relative" });
    for (var x = 1; x <= 3; x++) {
        d.animate({ left: 0-amount }, 10).animate({ left: 0 }, 50).animate({ left: amount }, 10).animate({ left: 0 }, 50);
    }
};

/* source: assets/javascript/website/modernizr.js */

/* Modernizr 2.7.1 (Custom Build) | MIT & BSD
 * Build: http://modernizr.com/download/#-fontface-inlinesvg-svg-svgclippaths-shiv-cssclasses-teststyles-load
 */
;window.Modernizr=function(a,b,c){function w(a){j.cssText=a}function x(a,b){return w(prefixes.join(a+";")+(b||""))}function y(a,b){return typeof a===b}function z(a,b){return!!~(""+a).indexOf(b)}function A(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:y(f,"function")?f.bind(d||b):f}return!1}var d="2.7.1",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m={svg:"http://www.w3.org/2000/svg"},n={},o={},p={},q=[],r=q.slice,s,t=function(a,c,d,e){var f,i,j,k,l=b.createElement("div"),m=b.body,n=m||b.createElement("body");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),l.appendChild(j);return f=["&#173;",'<style id="s',h,'">',a,"</style>"].join(""),l.id=h,(m?l:n).innerHTML+=f,n.appendChild(l),m||(n.style.background="",n.style.overflow="hidden",k=g.style.overflow,g.style.overflow="hidden",g.appendChild(n)),i=c(l,a),m?l.parentNode.removeChild(l):(n.parentNode.removeChild(n),g.style.overflow=k),!!i},u={}.hasOwnProperty,v;!y(u,"undefined")&&!y(u.call,"undefined")?v=function(a,b){return u.call(a,b)}:v=function(a,b){return b in a&&y(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=r.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(r.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(r.call(arguments)))};return e}),n.fontface=function(){var a;return t('@font-face {font-family:"font";src:url("https://")}',function(c,d){var e=b.getElementById("smodernizr"),f=e.sheet||e.styleSheet,g=f?f.cssRules&&f.cssRules[0]?f.cssRules[0].cssText:f.cssText||"":"";a=/src/i.test(g)&&g.indexOf(d.split(" ")[0])===0}),a},n.svg=function(){return!!b.createElementNS&&!!b.createElementNS(m.svg,"svg").createSVGRect},n.inlinesvg=function(){var a=b.createElement("div");return a.innerHTML="<svg/>",(a.firstChild&&a.firstChild.namespaceURI)==m.svg},n.svgclippaths=function(){return!!b.createElementNS&&/SVGClipPath/.test(l.call(b.createElementNS(m.svg,"clipPath")))};for(var B in n)v(n,B)&&(s=B.toLowerCase(),e[s]=n[B](),q.push((e[s]?"":"no-")+s));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)v(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},w(""),i=k=null,function(a,b){function l(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 m(){var a=s.elements;return typeof a=="string"?a.split(" "):a}function n(a){var b=j[a[h]];return b||(b={},i++,a[h]=i,j[i]=b),b}function o(a,c,d){c||(c=b);if(k)return c.createElement(a);d||(d=n(c));var g;return d.cache[a]?g=d.cache[a].cloneNode():f.test(a)?g=(d.cache[a]=d.createElem(a)).cloneNode():g=d.createElem(a),g.canHaveChildren&&!e.test(a)&&!g.tagUrn?d.frag.appendChild(g):g}function p(a,c){a||(a=b);if(k)return a.createDocumentFragment();c=c||n(a);var d=c.frag.cloneNode(),e=0,f=m(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function q(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return s.shivMethods?o(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/[\w\-]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(s,b.frag)}function r(a){a||(a=b);var c=n(a);return s.shivCSS&&!g&&!c.hasCSS&&(c.hasCSS=!!l(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),k||q(a,c),a}var c="3.7.0",d=a.html5||{},e=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,f=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,g,h="_html5shiv",i=0,j={},k;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",g="hidden"in a,k=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){g=!0,k=!0}})();var s={elements:d.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:c,shivCSS:d.shivCSS!==!1,supportsUnknownElements:k,shivMethods:d.shivMethods!==!1,type:"default",shivDocument:r,createElement:o,createDocumentFragment:p};a.html5=s,r(b)}(this,b),e._version=d,e.testStyles=t,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+q.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?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)){"img"!=a&&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=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?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),"img"!=a&&(r||2===y[c]?(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("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&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&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},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,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(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 i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&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))};

/* source: assets/javascript/website/picturefill.js */

/*! Picturefill - Responsive Images that work today. (and mimic the proposed Picture element with span elements). Author: Scott Jehl, Filament Group, 2012 | License: MIT/GPLv2 */

(function( w ){

	// Enable strict mode
	"use strict";

	w.picturefill = function() {
		var ps = w.document.getElementsByTagName( "span" );

		// Loop the pictures
		for( var i = 0, il = ps.length; i < il; i++ ){
			if( ps[ i ].getAttribute( "data-picture" ) !== null ){

				var sources = ps[ i ].getElementsByTagName( "span" ),
					matches = [];

				// See if which sources match
				for( var j = 0, jl = sources.length; j < jl; j++ ){
					var media = sources[ j ].getAttribute( "data-media" );
					// if there's no media specified, OR w.matchMedia is supported 
					if( !media || ( w.matchMedia && w.matchMedia( media ).matches ) ){
						matches.push( sources[ j ] );
					}
				}

			// Find any existing img element in the picture element
			var picImg = ps[ i ].getElementsByTagName( "img" )[ 0 ];

			if( matches.length ){
				var matchedEl = matches.pop();
				if( !picImg || picImg.parentNode.nodeName === "NOSCRIPT" ){
					picImg = w.document.createElement( "img" );
					picImg.alt = ps[ i ].getAttribute( "data-alt" );
				}

				picImg.src =  matchedEl.getAttribute( "data-src" );
				matchedEl.appendChild( picImg );
			}
			else if( picImg ){
				picImg.parentNode.removeChild( picImg );
			}
		}
		}
	};

	// Run on resize and domready (w.load as a fallback)
	if( w.addEventListener ){
		w.addEventListener( "resize", w.picturefill, false );
		w.addEventListener( "DOMContentLoaded", function(){
			w.picturefill();
			// Run once only
			w.removeEventListener( "load", w.picturefill, false );
		}, false );
		w.addEventListener( "load", w.picturefill, false );
	}
	else if( w.attachEvent ){
		w.attachEvent( "onload", w.picturefill );
	}

}( this ));

/* source: assets/javascript/website/shop-product.js */

Dachi.Shop = function(dachi) {
	var instance = this;

	this.dachi = dachi;

	dachi.on('load', function() {
		instance.hookAddToBasket();
		instance.hookCheckout();
	});
};

Dachi.Shop.prototype.hookAddToBasket = function() {
	var instance = this;

	var handleError = function(button, error) {
		return instance.dachi.removeBtnClasses(button).addClass("btn-danger").html("Error, Retry?").prop("disabled", false);
	};

	$('.add-product-form').each(function() {
		var form = $(this), formDOM = this;
		var button = form.find("[type=submit]");
		form.submit(function(e) {
			e.preventDefault();
			instance.dachi.removeBtnClasses(button).addClass("btn-primary").html("<i class='icon-spin icon-spinner'></i> Adding...").prop("disabled", true);

			$.ajax({
				type: form.attr("method"),
				url: form.attr("action") + "?ajax=true",
				data: form.serialize(),
				dataType: "json"
			}).success(function(resp) {
				if(resp.error) return handleError(button, resp.error);
				instance.dachi.removeBtnClasses(button).addClass("btn-success").html("<i class='icon-check-sign'></i> Added").prop("disabled", false);

				$('.shop-basket').removeClass("hide").find('.basket-details').html(resp.quantity + " item" + (resp.quantity != 1 ? "s" : "") + " (" + resp.total_display + ")");
				$('.shop-basket').removeClass("hide").find('a').attr('href', '/basket');
				shakeDiv($('.shop-basket'), 5);
			}).fail(function() {
				return handleError(button, "Unable to connect to server.");
			});
		});
	});
};

Dachi.Shop.prototype.hookCheckout = function() {
	var $form = $('.shop-checkout-form');

	var showError = function(error) {
		$form.find('.error-container .error').html(error);
		$form.find('.error-container').slideDown();
		$form.find('button').prop('disabled', false);
		return false;
	};

	$form.submit(function(e) {
		e.preventDefault();

		if(!Stripe.card.validateCardNumber($form.find('#cardNumber').val()))
			return showError("This card number looks invalid");

		if(!Stripe.card.validateCVC($form.find('#cardCVC').val()))
			return showError("Your card's security code is invalid.");

		if(!Stripe.card.validateExpiry($form.find('#expiryMonth').val(), $form.find('#expiryYear').val()))
			return showError("Your card's expiration date is invalid.");

		Stripe.card.createToken($form, function(status, response) {
			if (response.error)
				return showError(response.error.message);

			$form.append($('<input type="hidden" name="stripeToken" />').val(response.id));
			$form.get(0).submit();
		});

		return false;
	});
};

/* source: assets/javascript/website/subscribe.js */

Dachi.MSSubscribe = function(dachi) {
	var instance = this;
	this.dachi = dachi;

	this.redeemingVoucher = false;
	this.requireCard = true;

	this.oldPrice = "ERROR";
	this.newPrice = "ERROR";
	this.packageTitle = "ERROR";

	this.activeVoucher = {};

	dachi.on('load', function() {
		instance.bindHooks();
	});
};

Dachi.MSSubscribe.prototype.bindHooks = function() {
	var instance = this;

	$('.voucher-global-check-button').click(function(e) {
		instance.checkGlobalVoucherCode($('.globalVoucherCode').val());
	});

	$('.subscribe-button').click(function(e) {
		var button = $(this);
		e.preventDefault();
		$('#subscribeModal').html('');
		$.ajax({
			type: "post",
			url: "/subscribe/package-modal",
			data: {
				id: $(this).data('id')
			},
			dataType: "html"
		}).success(function(resp) {
			$('#subscribeModal').html(resp);
			instance.$subscriptionForm = $('.subscription-form');
			if(instance.activeVoucher[button.data('id')] != undefined) {

				instance.showSubscribeModal(resp);
				instance.$subscriptionForm.find('.voucher-link').slideUp();
				instance.$subscriptionForm.find('.card-details').slideUp();
				instance.$subscriptionForm.find('.voucher-code').hide();

				if(instance.activeVoucher[button.data('id')] != undefined)
					instance.$subscriptionForm.find('.cardVoucher').val(instance.activeVoucher[button.data('id')]);
				
				instance.$subscriptionForm.find('.submit-button').text("Redeeming Voucher").prop("disabled", true);
				instance.redeemingVoucher = true;

				instance.checkVoucherCode(instance.activeVoucher[button.data('id')], function(err) {
					if(err) return instance.showGlobalError("Failed to apply voucher, reload page and try again!");
				});
			} else {
				instance.showSubscribeModal(resp);
			}
			return true;
		}).fail(function() {
			return instance.showGlobalError("Failed to load package, try again.");
		});
	});
};

Dachi.MSSubscribe.prototype.showSubscribeModal = function(resp) {
	var instance = this;
	$('#subscribeModal').modal('show');

	$('.global-error-container').slideUp();

	instance.$subscriptionForm.find(".enter-card-details").click(function(e) {
		e.preventDefault();
		instance.$subscriptionForm.find('.card-details').slideDown();
		instance.$subscriptionForm.find('.package-title').html(package_title);
		instance.$subscriptionForm.find('.package-price').html("<small><s>&pound;" + old_price + "</s></small> &pound;" + new_price);
		instance.$subscriptionForm.find(".incentive-link").slideUp();
	});

	instance.$subscriptionForm.find('.voucher-link a').click(function(e) {
		e.preventDefault();
		instance.$subscriptionForm.find('.voucher-link').slideUp();
		instance.$subscriptionForm.find('.card-details').slideUp();
		instance.$subscriptionForm.find('.voucher-code').slideDown();
		instance.$subscriptionForm.find('.voucher-code').focus();
		instance.$subscriptionForm.find('.submit-button').text("Redeem Voucher");
		instance.redeemingVoucher = true;
	});

	instance.$subscriptionForm.submit(function(e) {
		e.preventDefault();

		instance.$subscriptionForm.find('.error-container').slideUp();
		instance.$subscriptionForm.find('button').prop('disabled', true);

		if(instance.redeemingVoucher) {
			var voucherCode = instance.$subscriptionForm.find('.cardVoucher').val();
			return instance.checkVoucherCode(voucherCode);
		} else if(instance.requireCard || instance.$subscriptionForm.find('.cardNumber').val()) {
			return instance.submitStripePayment();
		} else {
			return instance.$subscriptionForm.get(0).submit();
		}
	});
};

Dachi.MSSubscribe.prototype.showError = function(error) {
	var instance = this;
	this.$subscriptionForm.find('.error-container .error').html(error);
	this.$subscriptionForm.find('.error-container').removeClass("hide").slideDown();
	this.$subscriptionForm.find('button').prop('disabled', false);
	return false;
};

Dachi.MSSubscribe.prototype.showVoucherError = function(error) {
	var instance = this;
	$('#voucherModal .error-container .error').html(error);
	$('#voucherModal .error-container').removeClass("hide").slideDown();
	$('#voucherModal button').prop('disabled', false);
	return false;
};

Dachi.MSSubscribe.prototype.showGlobalError = function(error) {
	var instance = this;
	$('.global-error-container .error').html(error);
	$('.global-error-container').removeClass("hide").slideDown();
	return false;
};

Dachi.MSSubscribe.prototype.submitStripePayment = function() {
	var instance = this;
	if(!Stripe.card.validateCardNumber(this.$subscriptionForm.find('#cardNumber').val()))
		return this.showError("This card number looks invalid");

	if(!Stripe.card.validateCVC(this.$subscriptionForm.find('#cardCVC').val()))
		return this.showError("Your card's security code is invalid.");

	if(!Stripe.card.validateExpiry(this.$subscriptionForm.find('#expiryMonth').val(), this.$subscriptionForm.find('#expiryYear').val()))
		return this.showError("Your card's expiration date is invalid.");

	Stripe.card.createToken(this.$subscriptionForm, function(status, response) {
		if (response.error)
			return instance.showError(response.error.message);

		instance.$subscriptionForm.append($('<input type="hidden" name="stripeToken" />').val(response.id));
		instance.$subscriptionForm.get(0).submit();
	});

	return false;
};

Dachi.MSSubscribe.prototype.checkVoucherCode = function(code, callback) {
	var instance = this;
	callback = callback || function() { };

	$.ajax({
		type: "post",
		url: "/subscribe/check-voucher",
		data: {
			code: code,
			package: instance.$subscriptionForm.find('.package-id').val()
		},
		dataType: "json"
	}).success(function(resp) {
		if(resp.errorMessage)
			return instance.showError(resp.errorMessage);

		if(!resp.new_price)
			return instance.showError("Unrecognised voucher, <a href=\"/contact\">contact support</a>");

		instance.$subscriptionForm.find('.package-price').html("<small><s>&pound;" + resp.old_price + "</s></small> &pound;" + resp.new_price);
		this.oldPrice = resp.old_price;
		this.newPrice = resp.new_price;
		instance.$subscriptionForm.find('.voucher-code').slideUp();
		instance.requireCard = resp.require_card;
		if(resp.require_card) {
			instance.$subscriptionForm.find('.card-details').slideDown();
			instance.$subscriptionForm.find('.submit-button').text("Make Payment").prop("disabled", false);
		} else {
			instance.$subscriptionForm.find('.package-price').html("£FR.EE");
			package_title = instance.$subscriptionForm.find('.package-title').html();
			instance.$subscriptionForm.find('.package-title').html("Free Trial");
			instance.$subscriptionForm.find('.submit-button').text("Start Free Trial").prop("disabled", false);
		}

		if(resp.gift) {
			instance.$subscriptionForm.find('.voucher-gift .gift').html("+ " + resp.gift);
			instance.$subscriptionForm.find('.voucher-gift').slideDown();
		}

		if(resp.incentive)
			instance.$subscriptionForm.find('.voucher-incentive-link').slideDown();

		if(resp.notes) {
			instance.$subscriptionForm.find('.voucher-notes .notes').html(resp.notes);
			instance.$subscriptionForm.find('.voucher-notes').slideDown();
		}

		instance.redeemingVoucher = false;
		instance.$subscriptionForm.find('button').prop('disabled', false);
		callback();
		return false;
	}).fail(function() {
		callback(true);
		return instance.showError("Failed to check voucher code");
	});
};

Dachi.MSSubscribe.prototype.checkGlobalVoucherCode = function(code) {
	var instance = this;
	$('#voucherModal button').prop('disabled', true);
	$.ajax({
		type: "post",
		url: "/subscribe/check-global-voucher",
		data: {
			code: code
		},
		dataType: "json"
	}).success(function(resp) {
		if(resp.errorMessage)
			return instance.showVoucherError(resp.errorMessage);

		if(!resp.packages.length)
			return instance.showVoucherError("Unrecognised voucher, <a href=\"/contact\">contact support</a>");

		$('.subscribe-package').removeClass('voucher-applied');
		$('.subscribe-package h3').css('font-weight', 'normal');
		$('.subscribe-package .price').each(function() {
			$(this).html($(this).data("price"));
		});
		instance.activeVoucher = {};

		$('.subscribe-package').addClass('voucher-disallowed');
		for(var pkg in resp.packages) {
			pkg = resp.packages[pkg];

			instance.activeVoucher[pkg.id] = code;

			$('.subscribe-package-' + pkg.id + ' h3').css('font-weight', 'bold');
			$('.subscribe-package-' + pkg.id + ' .price').html("<small><s>&pound;" + pkg.price + "</s></small> <b>&pound;" + pkg.voucher_price + "!</b>");
			$('.subscribe-package-' + pkg.id).removeClass('voucher-disallowed').addClass('voucher-applied');
		}

		$('#voucherModal button').prop('disabled', false);
		$('#voucherModal').modal('hide');
		return false;
	}).fail(function() {
		return instance.showError("Failed to check voucher code");
	});
};


/* source: assets/javascript/website/supplements.js */

var stripeResponseHandler = function(status, response) {
  var $form = $('#supplementModal form');

  if (response.error) {
    // Show the errors on the form
    $form.find('.payment-errors').text(response.error.message);
    $form.find('button').prop('disabled', false);
  } else {
    // token contains id, last4, and card type
    var token = response.id;
    console.log(token);
    // Insert the token into the form so it gets submitted to the server
    $('#supplementModal	input#stripeToken').val(token);
    // and re-submit
    $form.get(0).submit();
  }
};

jQuery(function($) {
  $('#supplement-form').submit(function(e) {
  	e.preventDefault();
    var $form = $(this);

    // Disable the submit button to prevent repeated clicks
    //$form.find('button').prop('disabled', true);

    Stripe.card.createToken($form, stripeResponseHandler);

    // Prevent the form from submitting with the default action
    return false;
  });
});

