var delay = 5000;
var _url = window.location.origin + "/request/";
//var _url = "https://c0r.net/request/";


function alert(message) {



	iziToast.show({

		title: message,

		closeOnClick: true

	})

	

}



function log(log, delay = 5000) {



	iziToast.show({

		title: log,

		timeout: delay,

		position: 'bottomLeft'

	});

	

}



function success(message, delay = 5000) {



	iziToast.show({

		title: 'Başarılı',

		message: message,

		timeout: delay,

		position: 'center'

	});



}



function error(message, delay = 5000) {



	iziToast.show({

		title: 'Hata',

		message: message,

		timeout: delay,

		position: 'center'

	});



}



$(function() {

	$('.datepicker').datepicker({

		format: "mm/dd/yyyy"

	});

	$('[data-toggle="tooltip"]').tooltip();

	$("#service_type").change(function() {

		$("div[id^='type_']").hide();

		var id = $("#service_type").val();

		$("#type_"+id).show();

	});

	$(".messages").animate({

		scrollTop: 10000

	}, 500);

	var url = window.location;

	var element = $('ul.navbar-nav li a').filter(function() {

		return this.href == url

	}).parent().addClass('active');

	var element = $('ul.nav-tabs li a').filter(function() {

		return this.href == url

	}).addClass('active');

	var categories = [];

	var services = "";

	$("#category > option").each(function() {

		categories.push($(this).val());

	});

	var request_url = _url + "get_services";

	$.post(request_url, {categories:categories}, function(response) {

		if(response.status) {

			services = JSON.parse(response.services);

		}

	}, 'json').done(function() {

		if(services != "") {

			$("#service").html("");

			var category = $("#category").find('option:selected').val();

			for(var i = 0; i < services[category].length; i++) {

				var service = services[category][i];

				$("#service").append('<option value="'+ service.id +'" data-desc="'+ service.desc +'" data-charge="'+ service.charge +'" data-min="'+ service.min +'" data-max="'+ service.max +'" data-drip="'+ service.drip +'" data-comment="'+ service.comment +'" data-package="'+ service.package +'">'+ service.name +'</option>');

			}

			service_change();

		}

	});

	$("#category").change(function() {

		$("#service").html("");

		var category = $(this).val();

		for(var i = 0; i < services[category].length; i++) {

			var service = services[category][i];

			$("#service").append('<option value="'+ service.id +'" data-desc="'+ service.desc +'" data-charge="'+ service.charge +'" data-min="'+ service.min +'" data-max="'+ service.max +'" data-drip="'+ service.drip +'" data-comment="'+ service.comment +'" data-package="'+ service.package +'">'+ service.name +'</option>');

		}

		service_change();

	});

	$("#service").change(function() {

		service_change();

	});

	$("#drip-check").change(function() {

		if(this.checked) {

			$("#drip-group").removeClass("hide");

		} else {

			$("#runs, #total_quantity").val("");

			$("#interval").selectedIndex = 0;

			$("#drip-group").addClass("hide");

			var quantity = $("#quantity").val();

			if($.isNumeric(quantity)) {

				var selected = $("#service").find("option:selected");

				var charge = selected.data("charge");

				var package = selected.data("package");

				calculate(quantity, charge, package);

			} else {

				$("#amount").val("0");

				$("#total_quantity").val("");

			}

		}

	});

	$("#comments").keyup(function() {

		var comments = $(this).val();

		if (comments == "") {

			$("#quantity").val("");

			$("#amount").val("0");

		} else {

			comments = $.trim(comments);

			var lines = comments.split(/\r|\r\n|\n/);

			var count = lines.length;

			$("#quantity").val(count);

			var selected = $("#service").find("option:selected");

			var charge = selected.data("charge");

			var package = selected.data("package");

			calculate(count, charge, package);

		}

	});

	var timer;
	var timeout = 200;

	$("#quantity").keyup(function(){
		clearTimeout(timer);
		if ($("#quantity").val) {
			timer = setTimeout(function(){
				var quantity = $("#quantity").val();
				var runs = $("#runs").val();
				if($.isNumeric(quantity)) {

					var selected = $("#service").find("option:selected");

					var charge = selected.data("charge");

					var package = selected.data("package");

					calculate(quantity, charge, package, runs);

				} else {

					$("#quantity").val("");

					$("#amount").val("0");

					$("#total_quantity").val("");

				}
			}, timeout);
		}
	});

	$("#runs").keyup(function() {

		var runs = $(this).val();

		var quantity = $("#quantity").val();

		if($.isNumeric(runs) && $.isNumeric(quantity)) {

			var selected = $("#service").find("option:selected");

			var charge = selected.data("charge");

			var package = selected.data("package");

			calculate(quantity, charge, package, runs);

		} else {

			$("#amount").val("0");

			$("#total_quantity").val("");

		}

	});

});



$(document).delegate('form', 'submit', function(event) {

	var form = $(this);

	var id = form.attr('id');

	var data = form.serialize();

	if(id != null && id != undefined && id != "") {

		if(!form.hasClass("loading")) {

			form.addClass("loading");

			var request_url = _url + id;

			$.post(request_url, data, function(response) {



				

				if($(".g-recaptcha").length) {

					grecaptcha.reset();

				}

				if(response.delay) {

					delay = response.delay;

				}



				if (response.error) {

					error(response.error, delay);

				} else if(response.success) {



					success(response.success, delay);

					if(id == "new_order") {

						$("#balance").html(response.balance);

						$("#drip-group").addClass("hide");

						$("#comment-group").addClass("hide");

						$("#link").val("");

						$("#quantity").val("");

						$("#amount").val("0");

					} else {

						if(form.data("reset") == "1") {

							form[0].reset();

						}

					}

				}else if(response.verify){

					$("#verify").html(response.verify);

				} else if(response.log) {

					log(response.log, delay);

				} else if(response.alert) {

					alert(response.alert);

				} else if(response.reload) {

					window.location.reload(!0);

				}

				if(response.edit) {

					if(response.type == "html") {

						$(response.item).html(response.text);

					} else if(response.type == "value") {

						$(response.item).val(response.text);

					}

				}

				if(response.redirect) {

					var delay = 0;

					if(response.delay) {

						delay = response.delay;

					}

					if(response.newtab) {

						setTimeout(function () {

							window.open(response.location, "_top");

						}, response.delay);

					} else {

						setTimeout(function () {

							window.location.href = response.location;

						}, response.delay);

					}

					

				}

			}, 'json').fail(function() {

				error(messages["UNKNOWN_ERROR"]);

			}).always(function() {

				form.removeClass("loading");

			});

		} else {

			log(messages["PROCESS_ERROR"]);

		}

	}

});



function openDesc(id) {

	$("#modalContent").html($("#desc_"+id).data("desc"));

	$("#descModal").modal();

	$('#descModal').on('shown.bs.modal', function () {

		$('#descModal').trigger('focus');

	});

}
function openService(id) {

	$("#modalContent").html($("#service_"+id).data("service"));

	$("#serviceModal").modal();

	$('#serviceModal').on('shown.bs.modal', function () {

		$('#serviceModal').trigger('focus');

	});

}
function openLink(id) {

	$("#modalContent2").html($("#link_"+id).data("link"));

	$("#linkModal").modal();

	$('#linkModal').on('shown.bs.modal', function () {

		$('#linkModal').trigger('focus');

	});

}


function stop_auto(id) {

	var form = $("table");

	var data = {id:id};

	if(id != null && id != undefined && id != "") {

		if(!form.hasClass("loading")) {

			form.addClass("loading");

			var request_url = _url + "stop_auto";

			$.post(request_url, data, function(response) {

				if(response.delay) {

					delay = response.delay;

				}

				if(response.error) {

					error(response.error, delay);

				} else if(response.success) {

					success(response.success, delay);

					$("tr#auto_"+id+">td:nth-child(6)").html(response.content_status);

					$("tr#auto_"+id+">td:nth-child(7)").html(response.content_edit);

				} else if(response.log) {

					log(response.log, delay);

				} else if(response.alert) {

					alert(response.alert);

				} else if(response.reload) {

					window.location.reload(!0);

				}

			}, 'json').fail(function() {

				error(messages["UNKNOWN_ERROR"]);

			}).always(function() {

				form.removeClass("loading");

			});

		} else {

			log(messages["PROCESS_ERROR"]);

		}

	}

}



function service_change() {

	var service = $("#service").find('option:selected');

	$("#description").html(service.data("desc"));

	$("#min").html(service.data("min"));

	$("#max").html(service.data("max"));

	$("#drip-check").prop("checked", false);

	$("#drip-group").addClass("hide");

	$("#link, #comments, #quantity, #runs, #total_quantity").val("");

	$("#interval").selectedIndex = 0;

	$("#amount").val("0");

	if(service.data("comment") == 1) {

		$("#quantity").attr("readonly", "readonly");

		$("#comment-group").removeClass("hide");

	} else {

		$("#quantity").removeAttr("readonly");

		$("#comment-group").addClass("hide");

	}

	if(service.data("drip") == 1) {

		$("#drip-order").removeClass("hide");

	} else {

		$("#drip-order").addClass("hide");

	}

	if(service.data("package") == 1) {

		$("#quantity").val("1");

		$("#amount").val(service.data("charge"));

		$("#quantity_div").addClass("hide");

	} else {

		$("#quantity_div").removeClass("hide");

	}

}



function calculate(quantity, charge, package, runs = "") {

	var request_url = _url + "calculate";

	if($.isNumeric(quantity)) {

		if(runs == "" || $.isNumeric(runs)) {

			$.post(request_url, {

				quantity: quantity,

				charge: charge,

				package: package,

				runs: runs

			}, function(response) {

				if(response.status) {

					$("#amount").val(response.amount)

					if(response.total_quantity) {

						$("#total_quantity").val(response.total_quantity);

					}

				}

			}, "json");

		}

	} else {

		$("#amount").val("0");

		$("#total_quantity").val("");

	}

}



function post(action, data) {



	var request_url = _url + action;

	$.post(request_url, data, function(response) {

		if(response.delay) {

			delay = response.delay;

		}

		if (response.error) {

			error(response.error, delay);

		} else if(response.success) {

			success(response.success, delay);

		} else if(response.log) {

			log(response.log, delay);

		} else if(response.alert) {

			alert(response.alert);

		} else if(response.reload) {

			window.location.reload(!0);

		}

		if(response.edit) {

			if(response.type == "html") {

				$(response.item).html(response.text);

			} else if(response.type == "value") {

				$(response.item).val(response.text);

			}

		}

		if(response.redirect) {

			var delay = 0;

			if(response.delay) {

				delay = response.delay;

			}

			if(response.newtab) {

				setTimeout(function () {

					window.open(response.location, "_top");

				}, response.delay);

			} else {

				setTimeout(function () {

					window.location.href = response.location;

				}, response.delay);

			}

			

		}

		if(response.html){

			$("#online-pay").html(response.html);

		}



	}, 'json').fail(function() {

		error(messages["UNKNOWN_ERROR"]);

	});

}



function change_lang(id) {

	post("change_lang", {id:id});

}



function customer_cancel_order(id) {

	iziToast.show({

		theme: 'dark',

		title: '[Sipariş İptali]',

		message: 'Siparişiniz yönetici onayından sonra iptal edilecektir, emin misiniz?',

		position: 'center',

		displayMode: 1,

		timeout: false,

		buttons: [



		['<button>Evet</button>', function (instance, toast) {



			var data = {id:id};

			post("customer_cancel_order", data);

			instance.hide({

				transitionOut: 'fadeOutUp',

				onClosing: function(instance, toast, closedBy){

		                console.info('closedBy: ' + closedBy); // The return will be: 'closedBy: buttonName'

		            }

		        }, toast, 'buttonName');



	        }, true], // true to focus

	        ['<button>Hayır</button>', function (instance, toast) {

	        	instance.hide({

	        		transitionOut: 'fadeOutUp',

	        		onClosing: function(instance, toast, closedBy){

	                    console.info('closedBy: ' + closedBy); // The return will be: 'closedBy: buttonName'

	                }

	            }, toast, 'buttonName');

	        }]

	        ]

	    });

}



function refill_order(id) {

	iziToast.show({

		theme: 'dark',

		title: '[Sipariş Telafisi]',

		message: 'Siparişiniz yönetici onayından sonra telafi edilecektir, emin misiniz?',

		position: 'center',

		displayMode: 1,

		timeout: false,

		buttons: [



		['<button>Evet</button>', function (instance, toast) {



			var data = {id:id};

			post("refill_order", data);

			instance.hide({

				transitionOut: 'fadeOutUp',

				onClosing: function(instance, toast, closedBy){

		                console.info('closedBy: ' + closedBy); // The return will be: 'closedBy: buttonName'

		            }

		        }, toast, 'buttonName');



	        }, true], // true to focus

	        ['<button>Hayır</button>', function (instance, toast) {

	        	instance.hide({

	        		transitionOut: 'fadeOutUp',

	        		onClosing: function(instance, toast, closedBy){

	                    console.info('closedBy: ' + closedBy); // The return will be: 'closedBy: buttonName'

	                }

	            }, toast, 'buttonName');

	        }]

	        ]

	    });

}