HEX
Server: Apache
System: Linux v38079.2is.nl 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64
User: democfellows (10015)
PHP: 8.1.34
Disabled: opcache_get_status
Upload Files
File: /var/www/vhosts/creativefellows.nl/mygeomil.creativefellows.nl/03072023/public/js/app.js
Foundation.Abide.defaults.validators['minPasswordLength'] = function($el, required, parent) { 
	
	if( $el.val().length < 8 ){
		return false;
	}
	else return true;
			
};


$(document).foundation().ready(function(){
	

	// search and filter
	$("[data-filter]").searchProducts();
	
	// order products
	$("[article-row]").orderProduct();
	
	// shooping cart
	$(".shopping-cart").shoppingCart();
	
	// address book
	//$("[data-addressbook]").addressBook();
	
	// toggle fields
	$(".data-form-toggle [data-toggle-fields]").toggleFields();
	
	$(".form [data-toggle-description]").toggleDescriptions();
	
	
	// admin
	$("[admin-setting]").adminSetting();
	
	// resize layer
	$( ".layer-align-right" ).resizable({handles: 'w',minWidth: 300, maxWidth: 1000});
	
	// toggle figures
	$(".toggle-figure").articleImage();

	// view order & service
	$("[order-row]").viewOrder();
	$("[service-row]").viewService();

	// service request	
	$("[data-service-request]").serviceRequest();
	
	
	$(".geomil-figure").hoverZoom();
	wheelzoom(document.querySelectorAll('img.zoom-image'), {maxZoom: 4});
	
	$("[data-pagination]").pagination();
	
	$(".data-form-toggle [data-occupancy-picker]").occupancy();
	
	// fix image name in upload
	$(document).on('change', 'input[type="file"]', function(event){ 
		let files = [];
		$(this).next().text("");
		for (let i = 0; i < this.files.length; i++) {
			
			files[i] = $("<span class='file'>").text(this.files[i].name);
			
			$(this).next().append( files[i] );
			
		} 
		
		
	});
	
	$(".texteditor").textEditor();
	
	$("[data-editable]").editableElement();
	
	
	if($("#interactive-tour-message").length > 0){
		
		$("#interactive-tour-message").foundation("open");
		$.ajax({
			type: 'POST',
			url: "/disable-tour/"+$("#interactive-tour-message").data("userid"),
			success: function (response) {
					
			}	
		
		});	
	}
	
	$(".form__survey").surveyForm();
	
});


$.fn.surveyForm = function(){
	
	return this.each(function(){

		let plugin 	= $(this);
		let $radio 	= plugin.find(".option-row__csat input[type=radio]");
		let $rating = plugin.find(".average-rating");
		let $score = plugin.find(".average-rating span");
			
		plugin.init = function()
		{	
			$radio.on("change",plugin.score);
		}		
		
		plugin.score = function(){
			
			$rating.removeClass("hide");
			let avarage = 0;

			$radio.filter(":checked").each(function(){
				avarage += parseInt($(this).val());
			});
			

			plugin.setScore(  avarage / $radio.filter(":checked").length );
			
		}
		
		plugin.setScore = function(average){
			$score.text( average.toFixed(1) * 2 );			
		}
		
	    plugin.init();	
		
	});
	
}


$.fn.editableElement = function(){
	
	return this.each(function(){

		var plugin 		=  $(this);
		
		var $button 	= $(this);
		var $wrapper 	= plugin.parent();
		var $label 		= $wrapper.find("span");
		var $form		= null;
		var $save		= null;
		var $input		= null;
		
		plugin.settings = {
			url: plugin.data("editable")
		}
		
		plugin.init = function()
		{	
			plugin.on("click",plugin.edit);
		}	
		
		plugin.edit = function(){
			
			
			$form 	= $('<form style="height:'+ $wrapper.height() +'px"><div class="input-group" style="margin:0;"><input class="input-group-field" type="text" value="'+ $label.text() +'" style="font-size: 1.875rem;font-weight: 700;font-family: museo-sans, Helvetica, Roboto, Arial, sans-serif;height:2.5rem"><div class="input-group-button"><input type="button" class="button" value="Save"></div></div></form>');
			$save 	= $form.find(".button"); 
			$input  = $form.find("input[type=text]"); 
			
			$label.hide();
			$button.hide();
			
			$wrapper.append($form);
			
			$save.click(plugin.save);
			
			
		}
		
		plugin.save = function()
		{	
			
			$.ajax({
				url: plugin.settings.url,
				method: "PATCH",
				data:{
					installation: $input.val()
				},
				success: function(data)
				{	

					$label.text($input.val());
					$form.remove();
					$label.show();
					$button.show();
					
					
				}
			});
			
		}
		
	    plugin.init();	
		
	});
	
}


$.fn.textEditor = function(){
	
	return this.each(function(){

		var plugin 		= $(this);
		//var $textedit	= plugin.find(".texteditor");
		
		plugin.init = function()
		{	
			const Parchment = Quill.imports.parchment;
			const Delta = Quill.imports.delta;
			const Break = Quill.import('blots/break');
			const Embed = Quill.import('blots/embed');
						
			class Label extends Parchment.Embed {
			  
			  static create(value) {
			    const node = super.create(value);
			    node.innerText = value;
			    // Remember to set this so users can't edit
			    // the label's content
			    node.contentEditable = 'false';
			   // this._addRemovalButton(node);
			    return node;
			  }

			  static value(node) {
			    // Only return the text of the first child
			    // node (ie the text node), otherwise the
			    // value includes the contents of the button
			    return node.childNodes[0].textContent;
			  }

			  static _addRemovalButton(node) {
			   // const button = document.createElement('button');
			   // button.innerText = 'x';
			   // button.onclick = () => node.remove();
			   // button.contentEditable = 'false';
			   // node.appendChild(button);

			    // Extra span forces the cursor to the end of
			    // the label, otherwise it appears inside the
			    // removal button
			 //   const span = document.createElement('span');
			   // span.innerText = ' ';
			   // node.appendChild(span);
			  }
			}
			
			Label.blotName = 'label';
			Label.tagName = 'SPAN';
			Label.className = 'ql-label';
			
			Quill.register(Label);	
			
			Quill.register("modules/htmlEditButton", htmlEditButton);
			
			// line breaks
			function lineBreakMatcher() {
			  var newDelta = new Delta();
			  newDelta.insert({'break': ''});
			  return newDelta;
			}

			class SmartBreak extends Break {
			  length () {
			    return 1
			  }
			  value () {
			    return '\n'
			  }
  
			  insertInto(parent, ref) {
			    Embed.prototype.insertInto.call(this, parent, ref)
			  }
			}

			SmartBreak.blotName = 'break';
			SmartBreak.tagName = 'BR'

			Quill.register(SmartBreak)
			
			  
			var quill = new Quill( plugin.find("[data-texteditor]").get(0),{
				theme: 'snow',
				modules: {
					htmlEditButton: {},
					clipboard: {
				        matchers: [
				          ['BR', lineBreakMatcher] 
				        ],
						matchVisual: false
					},
					
				}
			});	
			
			quill.on('text-change', function(delta, oldDelta, source) {
				plugin.next().val(quill.root.innerHTML);
			});			
			
			//quill.updateContents(new Delta().insert('foo').insert({ label: 'bar' }));
			

			
			
		}	
		
		plugin.init();	
		
	});
	
}

	

$.fn.occupancy = function(){
	
	return this.each(function(){
		
		console.log($(this));
		var plugin 		= $(this);
		var reveal 		= plugin.data("occupancy-picker");		
		var $dates 		= $(reveal).find("a.date:not(.date__gray,.date__red)");
		
		var $choose 	= $(reveal).find("[date-choose-date]"); 
		var $buttons 	= $(reveal).find("[data-change-month]");
		
		plugin.settings = {
			selected : null,
			disable_date : new Date((new Date()).getFullYear(), (new Date()).getMonth(), 0)
		}
		
		plugin.init = function()
		{	
			$(this).focus(function(){
				
				plugin.getData( plugin.today() );				
				plugin.open();
				
			});	
			
			//console.log(plugin.settings.disable_date);
				
			$buttons.click(plugin.showMonth);
			$(reveal).on( "click", "a.date:not(.date__gray,.date__red)", plugin.select);
			
		}	
			
		plugin.open = function()
		{
			$reveal = new Foundation.Reveal( $(reveal) );
			$reveal.open();
		}	
		
		plugin.today = function()
		{
			return (new Date()).toISOString().split('T')[0];
		}
		
		plugin.occupancyType = function()
		{
			return plugin.attr("data-occupancy-type");
		}	
		
		plugin.getData = function(date){
			
			$.ajax({
				url: "/service/occupancy/" + date,
				method: "POST",
				data: "type="+ plugin.occupancyType(),
			
				success: function(data)
				{	
					//console.log($(reveal).find("h2 span"));
					$(reveal).find("h2 span").text(data.date);
					$(reveal).find(".occupancy-calendar").html(data.html);
					
					$(reveal).find("[data-previous]").attr("data-change-month",data.previous);
					$(reveal).find("[data-next]").attr("data-change-month",data.next);
					
					
				}
			});
		}
		
		plugin.select = function()
		{
			
			$(reveal).find("a.date:not(.date__gray,.date__red)").removeClass("date__selected");
			
			$(this).addClass("date__selected")
			plugin.settings.selected = $(this).data("date");
			
			$choose.prop("disabled",false);
			$choose.click(plugin.close);			
		}
		
		plugin.showMonth = function(){
					
			let date 		= new Date( $(this).attr("data-change-month") );
			let change_date	= $(this).attr("data-change-month");
			
			if( plugin.dateInPast(date) )	return;
			
			plugin.getData(change_date)
			
		}
		plugin.dateInPast = function(date)
		{
			return (date < plugin.settings.disable_date ? true : false);
		}
							
		plugin.close = function(){
			
			plugin.val(plugin.settings.selected);
			$reveal.close();
			
		}
			
	    plugin.init();	
		
	});
	
}

$.fn.pagination = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		var $buttons = plugin.find("button");
		var $prev 	= plugin.find("button[data-direction=prev]");
		var $next 	= plugin.find("button[data-direction=next]");
				
		plugin.settings = {
			url: plugin.data("pagination"),
			page: plugin.data("current-page"),
			target: plugin.data("target"),
		}
		
		plugin.init = function()
		{	
			$buttons.on("click",plugin.getData);
		}	
		
		plugin.getData = function()
		{	
			if( $(this).data("direction") == "next") plugin.settings.page++
			else{
				if(plugin.settings.page <= 1){
					//$prev.attr("disabled",true);
					return;	
				}
				else{
					//$prev.attr("disabled",false);
					plugin.settings.page--;
				}
			}
			
			$.ajax({
				url: plugin.getUrl(),
				method: "POST",
				success: function(data)
				{	

					$(plugin.settings.target).html( data.html );
					plugin.setButtons(data.prev,data.next);
					
					$("[order-row]").viewOrder();
					$("[service-row]").viewService();
					
				}
			});
			
		}
		
		plugin.setButtons = function(show_prev,show_next)
		{	
			let disabled_prev = show_prev == true ? false : true;
			let disabled_next = show_next == true ? false : true;
			
			$prev.attr("disabled", disabled_prev);
			$next.attr("disabled", disabled_next);
		}
		
		plugin.getUrl = function()
		{
			return 	plugin.settings.url + plugin.settings.page;
		}
		
	    plugin.init();	
		
	});
	
}

$.fn.customName = function(){
	
	return this.each(function(){

		var plugin	 = $(this);
		var $reveal;
		
		var $reveal_element = $("#"+plugin.data("open"));
		var $save_button 	= $reveal_element.find("[data-product-save]");
		var $form			= $reveal_element.find("form");
		var $input			= $reveal_element.find("input[type=text]");
				
		
		plugin.settings = {
			route : plugin.data("custom-name")
		}
		
		plugin.init = function()
		{	
			plugin.one("click",plugin.reveal);			
		}
		
		plugin.reveal = function()
		{
			$reveal	 = new Foundation.Reveal($reveal_element); 
			$reveal.open();		
			
			$save_button.click(plugin.orderProduct);	
		}
				
		plugin.orderProduct = function(parameters){
			
						
			$.ajax({
				url: plugin.settings.route,
				method: "PATCH",
				data:{
					name: $input.val()
				},
				success: function(data){
					

					$form.hide();
					$form.next().removeClass("hide").find("h3").text(data.message);
					$(".installation-custom-name").text(data.name)
					
				}
			});
			
			
			
		}
		
	
		
		// init the plugin
	    plugin.init();
		
		
	});
	
}

$.fn.serviceRequest = function(){
	
	return this.each(function(){

		let plugin 		= $(this);
		
		let $rows 				= plugin.find(".duplicate-row");
		let $form				= plugin.find(".form");
		let $service 			= plugin.find("[data-form-field=service_type]");
		let $maintenance 		= plugin.find("select[id=maintenance_machinetype], select[id=maintenance_servicetype],input[data-id=service_custom]");
		let $service_checks 	= plugin.find("[data-form-field=maintenance_options] > div");
		let $toggle_fields	 	= plugin.find("#maintenance_custom input[type=radio], #service_location input[type=radio]");
		let $service_location 	= plugin.find("#service_location input[type=radio]:checked");
		let $change_occupancy 	= plugin.find("input[data-occupancy]");
		
		let $serial 			= plugin.find("#maintenance_machineserialno");
		
		let $machine_type 		= plugin.find("select[id=maintenance_machinetype]");
		let $service_type 		= plugin.find("select[id=maintenance_servicetype]");
		let $service_custom 	= plugin.find("[data-form-field=service_custom]");
		
		let $maintenance_price 	= plugin.find("#maintenance_price");
		let $rebate_price 		= plugin.find("#maintenance_rebate");
		let $netto_price 		= plugin.find("#maintenance_netto");
		let $save				= plugin.find("button[data-save]");
		let $warranty			= plugin.find("input[id=maintenance_warranty]");
		let $custom_name		= plugin.find("button[data-custom-name]");

		plugin.settings = {}
		
				
		plugin.init = function()
		{	
			
			$rows.duplicateRow();
			
			$service.toggleFormFields();
			
			//console.log($service);
			$maintenance.change(plugin.getServicePrice);
			
			$save.click(plugin.saveRequest);				
			
			plugin.checkService();
			$serial.blur(plugin.checkWarranty);

			// checked changed
			$toggle_fields.change(plugin.toggleFields);
			
			plugin.toggleDefault();
			
			$change_occupancy.change(plugin.setOccupancy);
			
			$custom_name.customName();

		}	
		
		plugin.setOccupancy = function()
		{	
			$("#service_date_turnin").val("");		
			$("#service_date_turnin").attr("data-occupancy-type",$(this).data("occupancy"));
		}
		
		plugin.saveRequest = function()
		{	
			let subject = plugin.find("#subject").val();
			let options = {
				message: "Please enter a name to save this service request to",
				label: "Save",
				method : "POST",
				url: $(this).data("url"),
				callback: plugin.respond,
				fields : [
					{name: "subject", type: "text", label: "Service request reference", value: subject },
					{name: "status", type: "hidden", value: 2}
					
				],
				form : $form,
			};
			
			$save.secureDelete(options);
		}
		
		plugin.toggleDefault = function()
		{
			
			let fields = $service_location.data("toggle-fields").split(",");
		
			for (let i = 0; i < fields.length; i++)
			{ 
				$("[data-form-field="+ fields[i] +"]").hide();	
			}
		
			
		}
		
		plugin.toggleFields = function(){
			
			let fields = $(this).data("toggle-fields").split(",");
			
			if( $(this).is(':checked') && $(this).data("direction") == "hide" )
			{	
				for (let i = 0; i < fields.length; i++)
				{ 
					$("[data-form-field="+ fields[i] +"]").hide();	
				}
			}
			else{
				for (let i = 0; i < fields.length; i++)
				{ 
					$("[data-form-field="+ fields[i] +"]").show();	
				}
			}
			
			
		}
		
		plugin.respond = function($reveal, data)
		{
			var $reveal_element = $reveal.$element;
			
			$reveal_element.find("[data-title]").text( data.message );
			$reveal_element.find(".form").hide();
			$reveal_element.find("[data-delete]").hide();
			$reveal_element.find("[data-close]").removeClass("white").addClass("primary").text("Close");
			
		}
		
		plugin.checkService = function()
		{
			
			if($service_type.val() == 10) $service_custom.removeClass("hide");
			else $service_custom.addClass("hide");
			
		}

		plugin.getServicePrice = function(event){
			
			plugin.checkService();
			
			let $changed_input = $(this);
						
			$.ajax({
				url: '/service/'+ $machine_type.val() +'/'+ $service_type.val() ,
				method: "POST",
				data: $service_custom.find("input").serialize() +"&warranty="+ $warranty.val(),
			
				success: function(data)
				{	

					$maintenance_price.text( data.price );
					$maintenance_price.next().val( data.price );				
					
					$rebate_price.text( data.rebate );
					$rebate_price.next().val( data.rebate );
					
					$netto_price.text( data.price_nett );
					$netto_price.next().val( data.price_nett );
					
					$service_checks.html( data.service );
					
					
					if( $changed_input.is($machine_type) )
					{
						
						$service_type.find("option").hide();
						$.each(data.service_type, function(key,value) {
							$service_type.find("option[value="+ key+"]").show();
						});
					
					}	
					
					
				}
			});
			
		}
		
		plugin.checkWarranty = function(event){
			
			
			$.ajax({
				url: '/service/warranty/'+ $(this).val(),
				method: "POST",			
				success: function(data)
				{		
					$warranty.val( data.warranty );
					$warranty.prev().text( data.date );
					
					plugin.getServicePrice();
				}
			});
			
		}

		plugin.setLabel = function()
		{
			$("#service-details-label").text( $(this).val() );
		}
			
	    plugin.init();	
		
	});
	
}

$.fn.toggleFormFields = function(){
	
	return this.each(function(){

		let plugin 	= $(this);
		let $options = plugin.find("[type=radio]");
		let fields = [];
						
		plugin.init = function()
		{	
			
			// set all fields as hidden
			plugin.setFields();
		
			// already selected
			$options.each(function(){
				
				let $selected = plugin.find("[type=radio]:checked");
				plugin.showFields( $selected );
				
			});
			
			// checked changed
			$options.change(function(){
				
				let $selected = plugin.find("[type=radio]:checked");
				plugin.showFields( $selected );
				
				//console.log($(this).val());
				
			});

		}	
					
		plugin.showFields = function($checked_elements)
		{	
			plugin.hideFields();
			
			let visible = [];
		//	let direction = false;
			
			$checked_elements.each(function(){				
				visible = visible.concat( $(this).data("toggle-fields").split(",") );			

				//direction = $(this).data("direction");

				
			});
			
			let unique = visible.filter((v, i, a) => a.indexOf(v) === i);
					
			for (let i = 0; i < unique.length; i++)
			{ 
				//if(direction == "hide") $("[data-form-field="+ unique[i] +"]").toggle();	
				//else
				$("[data-form-field="+ unique[i] +"]").show();	
			}
			
			
			//if(direction == "hide") plugin.test();
				
		}
		
		plugin.setFields = function()
		{
			$options.each(function(){
				fields = fields.concat( $(this).data("toggle-fields").split(",") );
			});
			
			plugin.hideFields();
			
		}	
		
		plugin.hideFields = function()
		{
			
			for (var i = 0; i < fields.length; i++){
				$("[data-form-field="+ fields[i] +"]").hide();
			}
			
		}
		
		/*plugin.test = function()
		{	
			console.log("here");
			
			for (var i = 0; i < fields.length; i++){
				console.log( fields[i]);
				$("[data-form-field="+ fields[i] +"]").show();
			}
			
		}*/
			
	    plugin.init();	
		
	});
}

$.fn.duplicateRow = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		var $row 	= plugin.closest("[data-cone-row]");
		var $button = $row.find("button");
		var $form 	= $("#page-main-form");
		
		var $clone;
		
		
		plugin.init = function()
		{	
			$button.one("click",plugin.duplicate);
		}	
		
		
		plugin.duplicate = function()
		{		
			// duplicate and reset value
			$clone = $row.clone();
			$clone.duplicateRow();
			$clone.find("input").val("");
			$clone.insertAfter( $row );
			$clone.addClass("row-cloned");

			// change button into 'minus'
			$row.find(".button-toggle span:first-child").addClass("hidden");
		
			// remove row
			$button.one("click",plugin.delete);
			
			//$('#element').foundation('resetForm');
			$form.foundation('_reflow');
			
			
		}	
		
		plugin.delete = function()
		{
			$row.remove();
		}
			
	    plugin.init();	
		
	});
	
}

$.fn.hoverZoom = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		var $img	= plugin.find("img");
		var $clone 	= $img.clone().hide();
		var zoomed	= false;
	
		var $cursor = $('<div class="cursor">');
				
		plugin.init = function()
		{	
			$cursor.append($clone).css('background-image', 'url(' + $img.attr("src") + ')' );
			
			$cursor.hide();
			plugin.append($cursor);
			
			plugin.mousemove(function (element) {
				
				var pos_x = $(this).offset().left;
				var pos_y = $(this).offset().top;
				
				plugin.calc(element.clientX,element.clientY,pos_x,pos_y);
		
			}).mouseleave(function (event) {
				
				$cursor.hide();
			
			}).click(function(event){

			//	$cursor.toggleClass("cursor__zoomed");
				
			});
						
		
		}	
		
		plugin.calc = function(clientX, clientY, left, top)
		{
	       	
		    var x, y, rx, ry;
			
			// coords
	        x = clientX - left;
	        y = clientY - top;
	        rx = Math.round(x / $img.width() * $clone.width() ) * -1 + 60;
	        ry = Math.round(y / $img.height() * $clone.height() ) * -1 + 100;
							  
		    $cursor.show().css({
		      	'left': x,
		      	'top': y,
				'background-position':  rx +'px '+ ry +'px',
		    });
			
	      }
			  
		
	    plugin.init();	
		
	});
	
}

$.fn.viewService = function(){
	
	return this.each(function(){
		
		var plugin 	= $(this);
		var $element = plugin.find("[data-view]");

		var $layer 		= $("#page-layer-service");
		var $name 		= $layer.find("[data-service-name]");
		var $details 	= $layer.find("[data-service-details]");
		var $insert 	= $layer.find("[data-service-insert]");
		
		var $actions 	= $layer.find("[data-actions]");
		var $insert		= $layer.find("[data-service-insert]");
		var $delete 	= $layer.find("[data-service-delete]");
				
		plugin.settings = {
			url: plugin.data("url"),
			id: plugin.data("id"),
			name: plugin.data("name"),
			delete: '',
			patch: '',
		}
		
		plugin.init = function()
		{	
			$element.click( plugin.getData );
		}		
		
		plugin.getData = function()
		{	
					
			$.ajax({
				url: plugin.settings.url,
				type: "POST",
				success: function(data)
				{	
					// set urls 
					plugin.settings.delete = data.delete;
					plugin.settings.patch = data.patch;
					
					// set names
					$name.text(plugin.settings.name);
					$insert.attr("href",plugin.settings.url)

					// update view
					$details.html(data.html);

					// show actions
					$actions.show();						
					if(data.status == 1) $actions.hide();
					
					// actions
					plugin.actions()
				}
			});
		}	
		/*plugin.setRows = function(data)
		{

			
			$.each(data, function(key,value){
				
				
				var $row = $('<div class="grid-x" data-service-rows>')
							.append('<div class="cell small-6 medium-6"><strong>'+ key +'<strong></div>')
							.append('<div class="cell small-6 medium-6">'+ value +'</div>')
						
				$details.append($row);
				
	
			});	
			
		}
		*/
		
		plugin.actions = function(){
			
			$insert.click( function(){
				
				window.location.href = plugin.settings.patch;
			
						
				/*var options = {
					message: "Are you sure you want to load this saved cart?",
					label: "Insert",
					method : "GET",
					url: plugin.settings.url,
					callback: function($reveal,data){
						
						var $reveal_element = $reveal.$element;
						
						$reveal_element.find("[data-title]").text( data.message );
						$reveal_element.find(".form").hide();
						$reveal_element.find("[data-delete]").hide();
						$reveal_element.find("[data-close]").removeClass("white").addClass("primary").text("Close");
						
					}
				};
			
				$insert.secureDelete(options);*/
			
			});
			
			$delete.click( function(){
					
				var options = {
					message: "Are you sure you want to remove this saved service request?",
					label: "Delete",
					method : "DELETE",
					url: plugin.settings.delete,
					callback: function($reveal,data){
						
						
						var $reveal_element = $reveal.$element;

						// set reveal text
						$reveal_element.find("[data-title]").text( data.message );
						$reveal_element.find(".form").hide();
						$reveal_element.find("[data-delete]").hide();
						$reveal_element.find("[data-close]").removeClass("white").addClass("primary").text("Close");

					 	// hide layer
					 	$layer.addClass("collapsed_hor");
						
						// remove clicked row
						plugin.slideUp("fast");
						
						
					}
				};
				
				$delete.secureDelete(options);
				
			});
			
		}
		
		plugin.setData = function(values)
		{
			
			$fields.each(function(){
				
				var el = $(this).data("order-details");
				
				$(this).html( plugin.decode( values[el],el ) );
								
			});
			
		}	
		
		
		
		plugin.decode = function(str,el)
		{
			//console.log(el+" = "+ str);
			return str ? str.replace(/(?:\r\n|\r|\n)/g, '<br>') : null;
		}
			    
		plugin.init();	
		
	});
}

$.fn.viewOrder = function(){
	
	return this.each(function(){
		
		var plugin 	= $(this);
		var $element = plugin.find("[data-view]");

		plugin.settings = {
			url: plugin.data("url"),
			id: plugin.data("id"),
			name: plugin.data("name"),
		}

		var $layer 	= $("#page-layer");
		var $fields = $layer.find("[data-order-details]");
		var $rows 	= $layer.find("[data-order-rows]");
		var $name 	= $layer.find("[data-order-name]");
		var $insert = $layer.find("[data-order-insert]");
		var $delete = $layer.find("[data-order-delete]");
		
		
		
		
		plugin.init = function()
		{	
			$element.click( plugin.getData );
			
		}		
		
		plugin.getData = function()
		{	
				
			$.ajax({
				url: plugin.settings.url,
				type: "POST",
				success: function(data)
				{	
					console.log(plugin.settings.name);
					$name.text(plugin.settings.name);
					$insert.attr("href",plugin.settings.url)
					
					if(data.type == 0){
						
						plugin.setData(data);	
						$("[order-delivery],[order-shipping],[order-information]").show();
						$("[data-actions]").hide();
											
					}
					else{
						
						plugin.setData(data);
						
						$("[order-delivery],[order-shipping],[order-information]").hide();
						$("[data-actions]").show();
								
						$insert.click( function(){
							
							var options = {
								message: "Are you sure you want to load this saved cart?",
								label: "Insert",
								method : "GET",
								url: plugin.settings.url,
								callback: function($reveal,data){
									
									var $reveal_element = $reveal.$element;
									
									$reveal_element.find("[data-title]").text( data.message );
									$reveal_element.find(".form").hide();
									$reveal_element.find("[data-delete]").hide();
									$reveal_element.find("[data-close]").removeClass("white").addClass("primary").text("Close").click(function(){
										location.reload(); 
									});
									
								}
							};
						
							$insert.secureDelete(options);
						
						});
							
					
						$delete.click( function(){
								
							var options = {
								message: "Are you sure you want to remove this saved cart?",
								label: "Delete",
								method : "DELETE",
								url: plugin.settings.url,
								callback: function($reveal,data){
									
									var $reveal_element = $reveal.$element;
			
									// set reveal text
									$reveal_element.find("[data-title]").text( data.message );
									$reveal_element.find(".form").hide();
									$reveal_element.find("[data-delete]").hide();
									$reveal_element.find("[data-close]").removeClass("white").addClass("primary").text("Close");
			
								 	// hide layer
								 	$layer.addClass("collapsed_hor");
			
									// remove clicked row
									plugin.slideUp("fast");
									
									
								}
							};
							
							$delete.secureDelete(options);
							
						});
						
					}

					plugin.setRows(data.rows);
				}
			});
		}	
		
		plugin.setData = function(values)
		{
			
			$fields.each(function(){
				
				var el = $(this).data("order-details");
				
				$(this).html( plugin.decode( values[el],el ) );
								
			});
			
		}	
		
		plugin.setRows = function(rows)
		{

			$rows.html("");
			
			$.each(rows,function(key, row) 
			{	
						
				var $row = $('<div class="grid-x" article-row>')
							.append('<div class="cell small-6 medium-2 cell__row-number"><a order-product data-attributes=\''+ JSON.stringify(row) +'\'>'+ row.id +'</a></div>')
							.append('<div class="cell small-6 medium-7">'+ row.description +'</div>')
							.append('<div class="cell shrink">'+ row.quantity +'</div>')
							.append('<div class="cell auto text-right">'+ row.amount +'</div>')
							
				$rows.append($row);
				
				
				// click
				$row.orderProduct();
				
			});	
			
		}
		
		plugin.decode = function(str,el)
		{
			//console.log(el+" = "+ str);
			return str ? str.replace(/(?:\r\n|\r|\n)/g, '<br>') : null;
		}
			    
		plugin.init();	
		
	});
}

$.fn.articleImage = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
				
		var $target = $( plugin.data("target") );
		var $toggle	= $target.data("toggle-class");
		var $close	= $target.find(".layer-close-layer");
		var $table  = $("#articles-table");
		
		plugin.init = function()
		{	
			$(this).click(plugin.toggleClasses);
			$close.click(plugin.toggleClasses);
		}	
		
		
		plugin.toggleFigureNumbers = function()
		{
			//$table.toggleClass("table__figure-numbers");
		}	
		
		
		plugin.toggleClasses = function()
		{
			plugin.toggleFigureNumbers();
			$target.toggleClass($toggle);
		}	
			
	    plugin.init();	
		
	});
	
}

$.fn.adminSetting = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		
		plugin.settings = {
			url: plugin.data("url"),
			url: plugin.data("id")
		}
		
		var $trash 				= plugin.find("[data-delete]");
		var $rows 				= plugin.find(".table__row");
		var $articles			= plugin.find(".figure-article");
		var $layer				= $("#page-layer");
		var $textedit			= plugin.find(".texteditor");
		var $change_occupancy 	= plugin.find("input[data-occupancy]");
		
		
		plugin.init = function()
		{	
			// edit
			$rows.adminEdit();
			
			// delete
			$trash.adminDelete();
			
			// figures
			$articles.adminFigures();
			
			// close modals
			$(document).keyup(function(e) {
			     if (e.key === "Escape") {
					 $layer.addClass("collapsed_hor");
			    }
			});
			
			// sort list
			plugin.sortList();
			
			
			//plugin.initTextEditor();
			
			
			$change_occupancy.change(plugin.setOccupancy);
			
			
		}	
		
		plugin.setOccupancy = function(){
			$("#date").val("");		
			$("#date").attr("data-occupancy-type",$(this).data("occupancy"));
		}
		
		/*plugin.initTextEditor = function(){
			
			$textedit.each(function(){
				
				Quill.register("modules/htmlEditButton", htmlEditButton);
				//Quill.register('modules/smart-breaker', SmartBreaker);
				  
				var quill = new Quill($(this).find("[data-texteditor]").get(0),{
					theme: 'snow',
					modules: {
						htmlEditButton: {}
					}
				});	
				var $textarea = $(this).next();
				
				quill.on('text-change', function(delta, oldDelta, source) {
					$textarea.val(quill.root.innerHTML);
				});			
			});

			
		}*/
		
		plugin.sortList = function()
		{
			
			$( "[data-sortable]" ).sortable({
				axis: "y",
				items: $(this).data("sort-class"),
				update: function (event, ui) {
					
					var data = $(this).sortable('serialize');
					
					$.ajax({
			            data: data,
			            type: 'POST',
			            url: $(this).data("sort-url")
			        });
					
			    }
			});
			
			$( "[data-sortable]" ).find(".table__row-parent").sortable({
				axis: "y",
				items: ".table__row-child",
				update: function (event, ui) {
				       
					var data = $(this).sortable('serialize');
			        $.ajax({
			            data: data,
			            type: 'POST',
			            url: '/admin/article-group/sort'
			        });
					
			    }
			});
			
			
		}	
				
	    plugin.init();	
		
	});
	
}

$.fn.adminFigures = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		
		var $icon 		= plugin.find(".fal");
		var $art_add	= plugin.find(".button");
		var $art_inp	= plugin.find("input[type=text]");
		var $container	= plugin.find(".figure-labels");
		
		plugin.init = function()
		{
			$art_inp.val("");
			
			// add articles
			$art_add.click(plugin.addActicle);
			
		}	
		
		plugin.addActicle = function()
		{	
			var articles =  $art_inp.val().split(/[\s,]+/);
			console.log(articles);
			
			$.ajax({
				url: '/admin/article-group/article',
				method: "POST",
				data: { 
					articles : articles
				},
				success: function(data)
				{
					$.each(data,function(key, value) 
					{	
						var label_class = value === false ? "label__alert" : ""; 
							
						var $label = $('<div class="label '+ label_class +'">').text( key ).append('<i class="fal fa-times"></i>').append('<input type="hidden" name="article-id[]" value="'+ key +'">');						    
						$container.append($label);		
						$label.articleDelete();				
					//	}
						//else{
					//		alert("error for"+key);
					//	}
	
					});
				}
			});
			
			/*
			$.each(articles,function(key, value) 
			{	
				var $label = $('<div class="label">').text( value ).append('<i class="fal fa-times"></i>').append('<input type="hidden" name="article-id[]" value="'+ value +'">');						    
				$container.append($label);		
				
				$label.articleDelete();	
	
			});*/
			
			// clear input			
			$art_inp.val("");
			
		}
				
	    plugin.init();	
		
	});
}

$.fn.adminEdit = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		
		var $element 	= plugin.find("[data-edit]");
		var $layer		= $("#page-layer");
		var $form 		= $layer.find("form"); 
		var $input 		= $form.find("input[type=text], input[type=number], input[type=radio], input[type=checkbox], input[type=file], textarea, select");
		var $batch_ids	= $form.find("input[name=batch_articles_ids]");
		var $articles	= $form.find(".figure-article");
		//var $editors	= $form.find(".texteditor");
		
		var hide_fields	= $element.data("hide");
		var show_fields	= $element.data("show");
		

		plugin.settings = {
			url: plugin.data("url"),
			id: plugin.data("id"),
			action: $form.attr("action"),
			return: plugin.data("return"),
		}
		
		plugin.init = function()
		{	
			$element.click(plugin.data);
			
			
		}	
		
		
		plugin.data = function(){
			
			plugin.setAction();
			plugin.setReturn();
			plugin.hideFields();
			plugin.showFields();
			
			$.ajax({
				url: plugin.settings.url,
				type: "GET",
				success: function(data){
					

					
					$input.each(function(){
						
							
						if( $(this).attr("type") == "radio" )
						{	
							if($(this).val() == data[ $(this).attr("data-id") ]) $(this).prop('checked', true);
						}
						
						else if( $(this).attr("type") == "checkbox")
						{	
							if( jQuery.inArray( $(this).val(), data[ $(this).attr("data-id") ] ) !== -1 ){
								$(this).prop('checked', true);
							}
								
							
							
						}
						else if( $(this).attr("type") == "file" && data[ $(this).attr("id") ])
						{	
							$(this).closest(".fake-button").find(".label").remove();
							$label = $('<div class="label">').text(data[ $(this).attr("alt_name") ] ).append('<i class="fal fa-times"></i>').append('<input type="hidden" name="figure-delete" value="1">');

							$label.click(function(){
								$label.remove();
							});
							
							$label.insertAfter( $(this).parent() );
							
							
						}
						else if( $(this).attr("type") == "file" && data["original_name"])
						{	
							$(this).closest(".fake-button").find(".label").remove();
							$label = $('<div class="label">').text(data[ "alt_name"] ).append('<i class="fal fa-times"></i>').append('<input type="hidden" name="figure-delete" value="1">');

							$label.click(function(){
								$label.remove();
							});
							
							$label.insertAfter( $(this).parent() );
							
							
						}
						
						else if( $(this).attr("id") == "email_to")
						{	
							//$(this).closest(".fake-button").find(".label").remove();
							//$label = $('<div class="label">').text(data[ "original_name"] ).append('<i class="fal fa-times"></i>').append('<input type="hidden" name="figure-delete" value="1">');
							
							var field_value = data[ $(this).attr("id") ];//.split(",");
							
							for (let i = 0; i < field_value.length; i++) {
			
								var email = $("<span class='label label__email'>").text(field_value[i]);
			
								$(this).closest(".fake-input").append( email );
			
							} 
							
													
														
							
						}
						
						else{
							
							var field_value = data[ $(this).attr("id") ];
							
							if($(this).hasClass("text-editor") && field_value){
								
								$(this).val( data[ $(this).attr("id") ] );
								$(this).prev().find(".ql-editor").html( data[ $(this).attr("id") ] );
								
							
							}
							if(field_value) $(this).val( field_value );

							//console.log($(this));//+" "+ data[ $(this).attr("id") ]);
							
						}
						
					});
					
					$articles.children(".figure-labels").html("");
					
					if(data.batch){
						
						var ids = [];
						$.each(data.batch,function(key, value) 
						{	
						
							var $label = $('<div class="label" id="ca-id_'+ value.id +'">').text(value.article_id).append('<i class="fal fa-times"></i>').append('<input type="hidden" name="article[]" value="'+ value.id +'">');
							$articles.children(".figure-labels").append($label);	
							
							$label.articleDelete();		
							
							ids.push(value.id);
							
						});		
						
						$batch_ids.val(ids.join(","));
						$articles.find("input[type=text]").val("");
						
						$(".figure-labels").sortable({
							items: ".label",
							update: function (event, ui) {
				       
								var data = $(this).sortable('serialize');
						        $.ajax({
						           data: data,
						           type: 'POST',
						           url: '/admin/article-group/articles/sort'
						        });
					
						    }
						});
						$(".figure-labels").disableSelection();
						

					}
					
				}
			});
			
		}
		
		plugin.setArticleId = function(id)
		{
			var ids = $batch_ids.val();
			var arr = ids === "" ? [] : ids.split(',');
			arr.push(id);
			
			console.log( $batch_ids );
			$batch_ids.val( "Test"+arr.join(',') );
			
		}
		
		plugin.hideFields = function()
		{	
			
			var fields = hide_fields.split(",");
			for (var i = 0; i < fields.length; i++) { 
				$layer.find( fields[i] ).closest("[data-form-field]").hide();
				$layer.find( fields[i] ).attr("type","hidden");
			}			
			
		}
		
		plugin.showFields = function()
		{	
			if(!show_fields) return;
			
			var fields = show_fields.split(",");
			console.log(fields);
			for (var i = 0; i < fields.length; i++) { 
				$layer.find( fields[i] ).closest("[data-form-field]").show();
				
			}			
			
		}
		
		
		plugin.setAction = function()
		{	
			$form.attr("action", plugin.settings.action + "/" + plugin.settings.id);
		}	
		
		plugin.setReturn = function()
		{	
			$form.find("#return").val(plugin.settings.return);
		}	
		
				
	    plugin.init();	
		
	});
	
}

$.fn.articleDelete = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		var $icon 	= plugin.find(".fal");
		
		plugin.init = function()
		{
			$icon.click(plugin.delete);
		}	
		
		plugin.delete = function()
		{
			$icon.parent().remove();
		}
				
	    plugin.init();	
		
	});
}

$.fn.adminDelete = function(){
	
	return this.each(function(){

		var plugin 		= $(this);
		var $row 		= plugin.closest(".table__row");
		var $reveal_el	= $('<div class="reveal " id="reveal-delete" data-animation-in="fade-in" data-animation-out="fade-out">\
								<div class="grid-x align-middle">\
								<div class="cell small-12 medium-auto text-center">\
								<h3>Are you sure you want to delete this item?</h3>\
								<button class="button primary" confirm-delete>Delete</button> <button class="button white" data-close>Cancel</button>\
								</div>\
								</div>\
							</div>');
							
		var $reveal;
	
		
		plugin.settings = {
			id : plugin.data("id"),
			url: $row.data("url")
		}
		
		
		plugin.init = function()
		{	
			plugin.click(plugin.showConfirm);
		}	
		
		
		plugin.showConfirm = function()
		{	
			
			$("body").append($reveal_el);
			$reveal = new Foundation.Reveal( $("#reveal-delete") );
			$reveal.open();
			
			$reveal_el.find("[confirm-delete]").click( plugin.delete )
		}
		
		
		plugin.delete = function()
		{
		
			$.ajax({
				url:  $row.data("url"),
				type: "DELETE",
				success: function(data){
					
					$row.slideUp("fast");
					$reveal.close();
					$reveal.destroy()
					$reveal_el.remove();
			
					
				}
			});
		}
				
	    plugin.init();	
		
	});
	
}

$.fn.secureDelete = function(options){
	
	return this.each(function(){
		
		var plugin 		= $(this);
		
		var $reveal;
		var $reveal_el	= $('<div class="reveal reveal__confirm" id="reveal-confirm" data-animation-in="fade-in" data-animation-out="fade-out">\
								<div class="grid-x align-middle">\
								<div class="cell small-12 medium-auto text-center">\
								<h3 data-title>Are you sure you want to delete this item?</h3>\
								<form class="form grid-x align-center" data-fields></form>\
								<button class="button primary" data-delete>Delete</button> <button class="button white" data-close>Cancel</button>\
								</div>\
								</div>\
							</div>');
							
		$fields = $reveal_el.find("[data-fields]");
		$form 	= $reveal_el.find(".form");
				
						
		plugin.settings = options;			
										
		plugin.init = function()
		{
		
			plugin.setData();
			
			$("body").append($reveal_el);
			
			$reveal = new Foundation.Reveal( $("#reveal-confirm") );
			$reveal.open();
			
			$reveal_el.find("[data-delete]").click( plugin.click );
			
			if(plugin.settings.fields){
				
				$.each(plugin.settings.fields, function(k, v) {
				 
					$fields.append('<div class="cell small-12 medium-10 form-field"><label><input type="'+ v.type +'" name="'+ v.name +'" id="'+ v.name +'" placeholder="'+ v.label +'" value="'+ (v.value ?? "") +'" autocomplete="off"></label></div>');					
					  
				});
			
			}
			
		}	
		
		plugin.setData = function()
		{
			
			$reveal_el.find("[data-title]").text( plugin.settings.message );
			$reveal_el.find("[data-delete]").text( plugin.settings.label );
			
		}
		
		plugin.click = function()
		{
						
			$.ajax({
				url:  plugin.settings.url,
				type: plugin.settings.method,
				data: plugin.getFormData(),
				success: function(data){
					
					// run callback
					plugin.settings.callback( $reveal, data );
												
				}
			});
		}
		
		plugin.getFormData = function(){
			
			if(plugin.settings.form)
			{
				return plugin.settings.form.serialize()+"&"+ $form.serialize();
			}
			return $form.serialize();
		
		
			
		}
				
	    plugin.init();	
		
	});
}

$.fn.toggleFields = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		var $parent = plugin.closest("[data-form-field]");
		var $fields = plugin.closest(".form").find("[data-form-field]");
		
		var toggle = plugin.data("toggle-fields").split(",");
			
		plugin.init = function()
		{	
			//console.log( $parent );
			
			// init items selected
			if( $(this).is(':checked') )
			{
				plugin.toggle();
			}
			
			// checked changed
			plugin.change(plugin.toggle);
			
		}	
		
		
		plugin.toggle = function()
		{
			
			$fields.each(function(){
				
				//console.log( $(this) );
				//console.log( $parent );
				
				if( !$(this).is($parent) ){
					$(this).hide();
					$(this).find("input,textarea,select").prop("disabled", true);
				}
			});
			
			for (var i = 0; i < toggle.length; i++) { 
				$( toggle[i] ).closest("[data-form-field]").show();
				$( toggle[i] ).prop("disabled", false);
				console.log( toggle[i] );
			}
				
		}
		
		
	    plugin.init();	
		
	});
	
}

$.fn.toggleDescriptions = function(){
	
	return this.each(function(){
		
		var plugin 	= $(this);
		var id 		= plugin.attr("id");
		
		plugin.init = function()
		{	

			// checked changed
			plugin.change(plugin.toggle);
			
		}	
		
		plugin.toggle = function()
		{
			$(".option-description span").addClass("hide");
			$(".option-description").find("[data-desc-label="+ id +"]").removeClass("hide");
		}
		
		plugin.init();	
		
	});
	
}

$.fn.addressBook = function(){
	
	return this.each(function(){

		var plugin 			= $(this);
		var $reveal_element = $("#reveal-addressbook");
		var $adresses 		= $reveal_element.find("[data-select-address]");
		var $add_new		= $reveal_element.find("[data-new-address]");
		var $form			= $add_new.closest(".form");
		var $addressbook	= $reveal_element.find(".address-book");
		var $reveal;
			
		plugin.init = function()
		{	
			$reveal	 = new Foundation.Reveal($reveal_element); 
								
			plugin.click(plugin.openReveal);
		}	
		
		plugin.openReveal = function()
		{	
			// open reveal
			$reveal.open();
			
			// select addresses
			$adresses.selectAddress();
											
			// order product
			$add_new.click(plugin.post);
			
		}	
		
		plugin.post = function()
		{
			$.ajax({
				url: $form.data("action"),
				method: "POST",
				data: $form.serialize(),
				success: function(data)
				{
					$addressbook.removeClass("toggle-form-book");
					$("#address-company-"+data.letter).append(data.html).clostest(".address-group").removeClass("hide");
				}
			});
				
		}	
	
	    plugin.init();	
		
	});
	
}

$.fn.selectAddress = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		var id 		= plugin.data("id");
		var address = plugin.next().html();
		
		var $target = $(plugin.data("target"));
		
		plugin.init = function()
		{	
			plugin.click(plugin.select);
		}	
		
		plugin.select = function()
		{	
			$target.val(id);
			$(".current-address").html(address);
		}		
	
	    plugin.init();	
		
	});
	
}

$.fn.searchProducts = function(){
	
	return this.each(function(){

		var plugin 		= $(this);
		var baselink 	= plugin.data("link");
		var category 	= plugin.data("category");
		var $pagination = $(".pagination");

		var $table  	= $("#articles-table");
		var $table_body = $table.find(".table__body");
		
		plugin.settings = {
			delay : 250,
			search : null,
			timer: null,
			update: true
		}
		
		plugin.parameters = {
			category : category
		}
	
		// init
		plugin.init = function()
		{	
			// keyup input
			plugin.keyup(plugin.timer);
			
		}
		
		
		// data product data in reveal
		plugin.search = function()
		{	
			
			$.ajax({
				url: "/articles/search/" + plugin.postUrl(),
				method: "POST",
				data: plugin.parameters,
				success: function(data){

					// clear table
					$table_body.html("");	
					
					// update articles
					$.each( data.articles, function( i, item ) {
						$table_body.append( plugin.getTableRow(item) );
					});
										
									
					// update pagination
					if(plugin.settings.update == true) plugin.setPagination( data.pages );					
									
				}
				
			});
			
		}	
		
		
		plugin.postUrl = function()
		{
			return  (plugin.parameters.category ? plugin.parameters.category +'/'+plugin.settings.search : plugin.settings.search);
		}
		
		
		plugin.setPagination = function(page_count)
		{
			
			var links = $pagination.find("li:not(.pagination__default)");
			var $last;

			// remove old links
			links.remove();
			
			// set position to insert links
			var $current = $pagination.find("li").first();
			for (i = 1; i <= page_count; i++) { 
			
				$last = $('<li class="'+ (i == 1 ? "current" : "") +'"><a href="'+ plugin.paginationLink(i) +'" data-page="'+ i +'" aria-label="Page '+ i +'">'+ i +'</a></li>');
				$current.after($last);
				$current = $last;
			}
			
			// pagination clicks
			plugin.paginationClick();
			
		}
		
		
		plugin.paginationClick = function()
		{
			// pagina clicks
			$pagination.find("li").click(function(event)
			{
				event.preventDefault();
				
				// update clicked
				$pagination.find("li").removeClass("current");
				$(this).addClass("current");
				
				// set page to view			
				plugin.parameters.page = $(this).find("a").data("page");
				
				// disable pagination update
				plugin.settings.update = false;
							
				// do search			
				plugin.search();
				
			});
			
		}

		
		plugin.getTableRow = function(row)
		{
			
			var $row = $('<div class="table__row" article-row data-id="0055013047"></div>');
			var $grid = $('<div class="grid-x"></div>');
			
			$grid.append('<div class="cell medium-2 cell__row-number"><a order-product data-attributes=\''+ JSON.stringify(row) +'\'>'+ row.id +'</a></div>');
			$grid.append('<div class="cell auto">'+ row.description +'</div>');			
			$grid.append('<div class="cell medium-3 cell__row-price">\
							<div class="grid-x small-padding-collapse">\
								<div class="cell small-10">'+ row.price +'</div>\
								<div class="cell small-2 cell__to-cart"><button order-product data-attributes=\''+ JSON.stringify(row) +'\'><i class="fal fa-cart-plus" aria-hidden="true"></i></button></div>\
							</div>\
					     </div>');
			
						
			// insert
			$row.append($grid);
			
			// click
			$row.orderProduct();
			
			return $row;			
			
		}
		
		
		plugin.paginationLink = function(i)
		{
			return baselink +'/'+ i;
		}
		
		
		plugin.setSearchString = function(string)
		{
			plugin.settings.search = string;	
		}
		
		
		plugin.timer = function()
		{	
			plugin.setSearchString( $(this).val() );
			
			clearInterval(plugin.settings.timer);
			plugin.settings.timer = setTimeout(plugin.search,plugin.settings.delay);		
		}
		
		
		// init the plugin
	    plugin.init();
		
		
	});
	
}

$.fn.orderProduct = function(){
	
	return this.each(function(){

		var plugin	 = $(this);
		
		var $button 		= plugin.find("[order-product]");
		var $reveal_element = $("#reveal-article").clone();
		var $cart 			= $(".shopping-cart");
		var $total			= $cart.find("[data-cart-totals]") 
		var $reveal;
		var $order_button;
		
		plugin.settings = {
		}
		
		plugin.init = function()
		{	
			$reveal	 = new Foundation.Reveal($reveal_element); 
			
			// set data in reveal
			$button.click(plugin.setData);
					
		}
		
		// data product data in reveal
		plugin.setData = function()
		{	
			// order product
			$order_button = $reveal_element.find("[product-to-cart]");
			$reveal_element.find("#product-quantity").val(1);
			
			// remove click handler
			$order_button.off("click");
			
			plugin.settings.data = $(this).data("attributes");
					
									
			$reveal_element.find("[product-id]").text( plugin.settings.data.id );
			$reveal_element.find("[product-description]").text( plugin.settings.data.description );
			$reveal_element.find("[product-price]").text( plugin.settings.data.price );	
			$reveal_element.find(".product-quantity").change(plugin.updatePrice);	
			
			//console.log(plugin.settings.data);
			
			
			
			$order_button.click(function(){
				
				plugin.settings.data.quantity = $reveal_element.find("#product-quantity").val();
				plugin.orderProduct( plugin.settings.data );
				
			});	
			
			$reveal.open();	
		}	
		
		plugin.updatePrice = function()
		{	
			if($(this).val() == 0) $(this).val(1);
			$reveal_element.find("[product-price]").text( plugin.priceFormat( plugin.settings.data.price * $(this).val() ) );	
		}
		
		plugin.priceFormat = function(value){
			return value.toFixed(2).replace(".",",");
		}
		
		plugin.orderProduct = function(parameters){
			
			$.ajax({
				url: "/cart/" + parameters.id +"/"+ parameters.quantity,
				method: "POST",
				data: parameters,
				success: function(data){
					
					plugin.postInCart( data.count );
					plugin.insertRow( data.optional );
					//plugin.minimumAmount( data.complete );
					//$cart.find("[cart-total]").updateCartTotal(data.total);
					
					// update cart total
					$total.updateCartTotal(data);
					
					
					$('#complete-cart-order').removeClass("hide");
					
				}
			});
			
			
			
		}
		
		plugin.insertRow = function(html)
		{	
			var $html = $(html);
			var product_id = $html.find("[data-id]").data("id");
			
			if($cart.find(".table__row[data-id="+ product_id +"]").length > 0) $cart.find(".table__row[data-id="+ product_id +"]").remove();
			
			
			$(".shopping-cart").find(".table__body").append( $html );

			// cart row functions
			$html.cartProduct();
		}
		
		plugin.postInCart = function(count){
			
			var $clone = $("<div class=\"to-cart\">");
						
			$clone.offset({
				top: $order_button.offset().top,
				left: $order_button.offset().left
			});
			
			$clone.css({
                'height': '48px',
                'width': '48px',
			});
			
           	$clone.animate({
				'top': $(".top-bar-right  .section__cart").offset().top + 10,
				'left': $(".top-bar-right .section__cart").offset().left + 30,
				'width': 0,
				'height': 0
        	}, 500, 'swing');
		
           	$clone.appendTo( $('body') )
			
			// update basket total
			var $counter 	= $(".section__cart .counter");
			
			$counter.addClass("added-to-cart");
			$counter.text(count);
			
			// close reveal
			$reveal.close();
		}
		
		plugin.minimumAmount = function(complete_order)
		{
			if(complete_order == true) $('#complete-cart-order').prop("disabled", false);
			else $('#complete-cart-order').prop("disabled", true)

		}
		
		
		// init the plugin
	    plugin.init();
		
		
	});
	
}

$.fn.shoppingCart = function(){
	
	return this.each(function(){

		var plugin 	= $(this);
		var $rows 	= plugin.find("[article-row]");
		var $mask 	= $('<div class="reveal-overlay" style="display: none;"></div>');
		var $clear 	= plugin.find("[data-clear-cart]");
		var $save 	= plugin.find("[data-save-cart]");
		
		plugin.init = function()
		{	
			$rows.cartProduct();	
			$clear.click(plugin.clearCart);	
			$save.click(plugin.saveCart);	
			
		}		
		
		plugin.clearCart = function()
		{	
			var options = {
				message: "Are you sure you want to empty the shopping cart?",
				label: "Clear",
				method : "DELETE",
 				url: $(this).data("url"),
				callback: plugin.removeAll,
			};
			
			$clear.secureDelete(options);
		}
		
		plugin.saveCart = function()
		{	
			var options = {
				message: "Please enter a name to save this cart to",
				label: "Save",
				method : "POST",
				url: $(this).data("url"),
				callback: plugin.respond,
				fields : [
					{name: "name", type: "text", label: "Cart reference"}
				]
			};
			
			$clear.secureDelete(options);
		}
		
	
		plugin.respond = function($reveal, data)
		{
			var $reveal_element = $reveal.$element;
			
			$reveal_element.find("[data-title]").text( data.message );
			$reveal_element.find(".form").hide();
			$reveal_element.find("[data-delete]").hide();
			$reveal_element.find("[data-close]").removeClass("white").addClass("primary").text("Close");
			
		}
		
		plugin.removeAll = function($reveal, data)
		{
			plugin.find("[data-cart-totals]").updateCartTotal( data );
			$rows.slideUp("fast");

			// 
			$reveal.close();
			$reveal.destroy()
			$reveal_el.remove();
		}
		
	    plugin.init();	
		
	});
	
}

$.fn.cartProduct = function(){
	
	return this.each(function(){

		var row 		= $(this);
		
		var $delete 	= row.find("button[delete-product]");
		var $quantity 	= row.find("[quantity-product]");
		var $amount		= row.find("[amount-product]");
		var $cart 		= row.closest(".shopping-cart");
		var $total		= $cart.find("[data-cart-totals]") 
		var id 			= row.attr("data-id");
		
		row.init = function()
		{	
			
			// set data in reveal
			$delete.click(row.delete);
			$quantity.change(row.update);
			
		}
		
		// data product data in reveal
		row.delete = function()
		{	
			
			$.ajax({
				url: "/cart/" + id,
				method: "DELETE",
				success: function(data)
				{
					row.remove();				
					//row.minimumAmount(data.complete);
					
					// update cart total
					$total.updateCartTotal(data);
					
					
				}
			});
		
		}	
		
		// data product data in reveal
		row.update = function()
		{	
			$.ajax({
				url: "/cart/"+ id +"/"+ $(this).val(),
				method: "PATCH",
				success: function(data)
				{

					// update row amount
					$amount.text(data.optional);

					// update cart total
					$total.updateCartTotal(data);
					
					// check complete
					//row.minimumAmount(data.complete);				
					
				}
			});
		
		}	
		
		row.minimumAmount = function(complete_order)
		{
			if(complete_order == true) $('#complete-cart-order').prop("disabled", false);
			else $('#complete-cart-order').prop("disabled", true)


		}
		row.remove = function()
		{
			row.slideUp("fast");
		}
	
	    row.init();	
		
	});
}

$.fn.updateCartTotal = function(data){
	
	return this.each(function(){

		var plugin = $(this);
		
		var $total	= plugin.find("[data-cart-total]");
		var $rebate	= plugin.find("[data-cart-rebate]");
		var $sub	= plugin.find("[data-cart-subtotal]");
		var $costs	= plugin.find("[data-cart-order-costs]");
		var $grand	= plugin.find("[data-cart-grandtotal]");
		
		
		plugin.init = function()
		{	
			$total.text(data.total);
			$rebate.text(data.rebate);
			$sub.text(data.subtotal);
			$costs.text(data.order_costs);
			$grand.text(data.grandtotal);
			
		}
			
	    plugin.init();	
		
	});
}