function prepare(){
	// const startTime = performance.now();
  var data = {};
  var temp = [];
  $('input, select, textarea').each(function(){
    attr = $(this).attr('name');
    if(typeof attr !== typeof undefined && attr !== false){
      name = $(this).attr('name');
  		if(name.includes('[]')){
        name2 = name.replace('[]', '');
      	$('[name="'+name+'"]').each(function(){
       	 temp.push($(this).val());
			 	});
      	data[name2] = temp;
      	temp = [];
    	} else {
      	if($('[name="'+name+'"]').attr('type')=='checkbox'){
        	data[name] = $('[name="'+name+'"]').is(':checked') ? 1 : 0;
      	} else if($('[name="'+name+'"]').attr('type')=='radio'){
          data[name] = $('[name="'+name+'"]:checked').val();
        } else {
        	data[name] = $(this).val();
      	}
    	}
    }
	});
	// const duration = performance.now() - startTime;
  // console.log(`prepare took ${duration}ms`);
  return(data);
}

function copy_id(id){
	var $temp = $("<input>");
	$("body").append($temp);
	$temp.val(id).select();
	document.execCommand("copy");
	$temp.remove();
	alertify.success('Το ID αντεγράφη');
	// alert("Copied the text: " + id.value);
}

function zoom(url) {
	$('#piczoom').html('<center><img class="img-responsive" src="uploads/images/' + url + '" /></center>');
	$('#piczoom').show();
}
function delphoto(pic){
	filearr = JSON.parse($('#picinp').val());
	filearr.splice(filearr.indexOf(pic) ,1);
	$('#picinp').val(JSON.stringify(filearr));
	// pic = pic.split('.');
	// $('#'+pic[0]+' .pic').hide();
	$('#pics').find("[data-name='"+pic+"']").hide();
}

function mail_notify(id){
	$.ajax({
  method: "POST",
  url: "sendMail.php",
  data: {id: id},
  success: function(r){
    // console.log(r);
  }
});
}

function control2db(type="new",id=-1,async=true){
	var form_data = prepare();
	$.ajax({
  	method: "POST",
  	url: "control_parse.php",
		async: async,
  	data: {type: type, id: id, data: form_data},
  	success: function(r){
  	 //   console.log(r);
			res = JSON.parse(r);
			if(res.status==1){
				if(type!="midsave"){
					if(form_data.apodekth==0){
						if(id!=-1){
							mail_notify(id);
						} else {
							mail_notify(res.id);
						}

					}
					alertify.success('Η Ενέργεια ολοκληρώθηκε επιτυχώς!');
					if(type=='edit'){
						copy_id(res.id);
					}
				} else {
				// 	window.location.replace('Cview.php?type=edit&cID='+res.id);
				}
			} else {
				alertify.error(res.error);
				// console.log(r);
			}
  	}
	})
}

function prod2db(type="new",id=-1,async=true){
	$.ajax({
  	method: "POST",
  	url: "controlpar_parse.php",
		async: async,
  	data: {type: type, id: id, data: prepare()},
  	success: function(r){
			res = JSON.parse(r);
			if(res.status==1){
				if(type!="midsave"){
					alertify.success('Η Ενέργεια ολοκληρώθηκε επιτυχώς!');
					// copy_id(res.id);
				} else {
					window.location.replace('controlpar_view.php?type=edit&id='+res.id);
				}
			} else {
				alertify.error('Παρουσιάστηκε Σφάλμα κατα την Αποθήκευση!');
				// console.log(res.error);
				// console.log(res.qry);
			}
  	}
	})
}

function get_rowmax(){
  x = 0;
	return $('.parrow').length;
}

function add_row(n=1){
	for(var i=1;i<=n;i++){
		var max = get_rowmax()+1;
	  var x = $('.partr').wrap('<p/>').parent().html();
		$('.partr').unwrap();
	  x = x.replace(/("parrow">)\d+/, "$1"+max);
	  x = x.replace(/value=".*"/, 'value=""')
		$('#pinpar').append(x);
	}
}

function check_fishsum(kivn=-1, element="") {
	// const startTime = performance.now();
	if(kivn==-1){
		for(var i=0;i<=9;i++){
			check_fishsum(i);
		}
	} else {
		if(element!=""){
			var sum = 0;
			var res = 0;
			ar_psar = $('[name="ar_psariwn[]"]')[kivn];
			parent = $(element).closest('.panel-body');
			children = $(parent).find('[data-kivn="'+kivn+'"]');
			$(children).each(function(){
				if($(this).val().length!=0){
						sum+=parseFloat($(this).val());
				}
			})
			res = $(ar_psar).val()-sum;
			$(children).each(function(){
				if(res<0){
					$(this).addClass('red');
				} else {
					$(this).removeClass('red');
				}
			});

		} else {
			var cat = {"matia":"matia_lampera[]", "vragxia":"vragxia_rodina[]","kefalh":"","koilia":"","swma":""};
			for(var id in cat){
				var sum = 0;
				var res = 0;
				ar_psar = $('[name="ar_psariwn[]"]')[kivn];
				if($(ar_psar).val().length==0){
					continue;
				}
				var curbox = $('[name^="' + id + '"][data-kivn="' + kivn + '"]:not([name="vragxia_rodina[]"]):not([name="matia_lampera[]"])');
				$(curbox).each(function(){
					if($(this).val().length!=0){
						sum+=parseFloat($(this).val());
					}
				});
				res = $(ar_psar).val()-sum;
				$('[name="'+cat[id]+'"][data-kivn="'+kivn+'"]').val(res);
				if(res<0){
					$(curbox).each(function(){
						$(this).addClass('red');
					});
				} else {
					$(curbox).each(function(){
						$(this).removeClass('red');
					});
				}
			}
		}
		return 0;
	}

	// const duration = performance.now() - startTime;
  // console.log(`check_fishsum took ${duration}ms`);
}

function check_ice(elm){
	$('[name="pagos_kg[]"]').each(function(){
		cent = 0;
		index = $(this).data('kivn');
		curpercent = $('[name="posothta_pagou[]"]')[index];
		varos = parseFloat($('.varos_kiv[data-order="'+(index+1)+'"]').val());
		// console.log('index: '+index+', varos: '+varos);
		if($(curpercent).val()=="" && $(this).val()==""){
			return;
		}
		if($(this).val()!="" && $(elm).attr('name')!="posothta_pagou[]"){
			if ($('[name="eidos_kiv"]').val() != 'Καστράκι' && $('[name="eidos_kiv"]').val()!="") {
				cent = (($(this).val() / (varos/2) * 100)).toFixed(2);
				$(curpercent).val(cent);
			} else {
				cent = (($(this).val() / (varos/4) * 100)).toFixed(2);
				$(curpercent).val(cent);
			}
		} else {
			if ($('[name="eidos_kiv"]').val() != 'Καστράκι' && $('[name="eidos_kiv"]').val()!="") {
				$(this).val( (($(curpercent).val()*(varos / 2))/100).toFixed(2) );
			} else {
				$(this).val( ((($(curpercent).val()*(varos / 4))/100)).toFixed(2) );
			}
			cent = $(curpercent).val();
		}
		$(curpercent).removeClass('green orange red');
		if (cent >= 80 && cent <= 100) {
			$(curpercent).addClass('green');
		} else if (cent < 80 && cent >= 60) {
			$(curpercent).addClass('orange');
		} else if (cent < 60) {
			$(curpercent).addClass('red');
		} else {
			$(curpercent).addClass('green');
		}

	});
}

function eidos_kiv(){
  kastraki = "<option>3.7</option><option>3.8</option><option>3.9</option><option>4.7</option><option>4.8</option><option>4.9</option><option>5</option>";
  other = "<option>3</option><option>6</option><option>10</option>";
  if($('[name="eidos_kiv"]').val()=='Καστράκι'){
    $('[name="varos_kiv2[]"]').each(function(){
      if($(this).html()!=kastraki){
        $(this).html(kastraki);
      }
    })
  } else {
    $('[name="varos_kiv2[]"]').each(function(){
      if($(this).html()!=other){
        $(this).html(other);
      }
    })
  }
}

function check_varoskiv(order){
	$('[name="varos_kiv[]"]').each(function(){
		var varos = parseFloat($('.varos_kiv[data-order="'+($(this).data('kivn')+1)+'"]').val());
		cv = $(this).val();
			// if(cv%1==0){
			// 	len = cv.toString().length;
			// 	// console.log(cv+' / '+'(10 ^ ('+len+'))='+cv / (Math.pow(10, (len-1))));
			// 	console.log(cv);
			// 	cv = cv / (Math.pow(10, (len-1)));
			// 	console.log(cv);
			// }
			// console.log(cv);
			$(this).removeClass('green orange red');
			varr = (varos * (1.5 / 100)) + varos;
			// console.log('varos: '+varos+', varr: '+varr);
			if (cv>=varos && cv<=varr && cv!="") {
				$(this).addClass('green');
			} else if (varr < cv && cv!="") {
				$(this).addClass('orange');
			} else if (varr > cv && cv!="") {
				$(this).addClass('red');
			}
	});
}


function check_ratings(){
	rate = 0;
	checked = 0;
	$('.rating').each(function() {
		if ($(this).is(':checked')) {
			checked++;
			rate += parseFloat($(this).val());
		}
	})
	if (checked == 3) {
		$('.ratings').each(function() {
			$(this).removeClass('blue green orange red');
		})
		if (rate > 9 && rate < 13) {
			ratelem = $('.ratings')[0];
			$(ratelem).addClass('blue');
			$('#freskothta').val('EXTRA');
			// $('#form-submit').prop('disabled', false);
		} else if (rate > 6 && rate < 10) {
			ratelem = $('.ratings')[1];
			$(ratelem).addClass('green');
			$('#freskothta').val('A');
			// $('#form-submit').prop('disabled', false);
		} else if (rate > 3 && rate < 7) {
			ratelem = $('.ratings')[2];
			$(ratelem).addClass('orange');
			$('#freskothta').val('B');
			// $('#form-submit').prop('disabled', false);
		} else if (rate < 4) {
			ratelem = $('.ratings')[3];
			$(ratelem).addClass('red');
			$('#freskothta').val('REJECTED');
			// $('#form-submit').prop('disabled', true);
		}
	}
}

function check_thermpsar(){
	$('input[name="therm_psariwn[]"]').removeClass('red green');
	$('input[name="therm_psariwn[]"]').each(function() {
		if ($(this).val() < 0 || $(this).val() > 2 && $(this).val() != '') {
			$(this).addClass('red');
		} else if ($(this).val() >= 0 && $(this).val() <= 2 && $(this).val() != '') {
			$(this).addClass('green');
		}
	});
}

function fish_check(order){
	var fish = 0;
	var upo = 0;
	var uper = 0;
	if(typeof(order)!='undefined'){
		$('[name^="par_kiv"][data-order="'+order+'"]').each(function(){
			if($(this).val()!=""){
				fish++;
				if($(this).hasClass('red')){
					upo++;
				} else if($(this).hasClass('blue')){
					uper++;
				}
			}
		});
		if(fish!=0){
			$('[name="ar_psariwn[]"][data-kivn="'+(order-1)+'"]').val(fish).trigger('change');
			$('[name="upomege8h[]"][data-kivn="'+(order-1)+'"]').val(upo);
			$('[name="upermege8h[]"][data-kivn="'+(order-1)+'"]').val(uper);
		} else {
			$('[name="ar_psariwn[]"][data-kivn="'+(order-1)+'"]').val('').trigger('change');
			$('[name="upomege8h[]"][data-kivn="'+(order-1)+'"]').val('');
			$('[name="upermege8h[]"][data-kivn="'+(order-1)+'"]').val('');
		}
	} else {
		for(var i=1;i<=10;i++){
			fish_check(i);
		}
	}
}

function check_totals(order=-1,show_total=true){
			// const startTime = performance.now();
			if(order==-1){
				for(var i=1;i<=10;i++){
					check_totals(i, show_total);
				}
			} else {
				var box = 0;
	      var total = [];
	      var filter = /(\d+)[/]?(\d+)?[+]?/;
	      var qty = $('[name="megethos[]"][data-order="'+order+'"]').val();
	      qty = filter.exec(qty);
	      $('[name^="par_kiv"][data-order="'+order+'"]').each(function(){
	        box = $(this).data('order');
	        num = parseFloat($(this).val());
	        $(this).removeClass('red green blue');
	        if(!isNaN(num)){
	          if($(this).val()!=""){
	           //   console.log(qty[1]);
	           //   console.log(qty[2]);
	            if($(this).val()<parseFloat(qty[1])*(qty[1]<100 ? 100 : 1)){
	              $(this).addClass('red');
	            } else if ($(this).val()>parseFloat(qty[2])*(qty[2]<100 ? 100 : 1)) {
	              $(this).addClass('blue');
	            } else {
	              $(this).addClass('green');
	            }
	          }
	          if(typeof total[box] == 'undefined') {
	            total[box]=num;
	          } else {
	            total[box]+=num;
	          }
	        }
	        if(show_total==true){
	          $('#athr'+box+' input').val(total[box]);
	        }
	      });

				// $('[name="ar_psariwn[]"][data-kivn="'+(order-1)+'"]').val(total[box]).trigger('change');
			}
			// const duration = performance.now() - startTime;
		  // console.log(`check_totals took ${duration}ms`);
  }



$(document).ready(function(){
	$('[name="ar_psariwn[]"],[name^="matia"],[name^="vragxia"],[name^="kefalh"],[name^="koilia"],[name^="swma"]').on('keyup change', function(){
		 kivn = parseFloat($(this).data('kivn'));
		 check_fishsum(kivn);
	});

	$('#piczoom').on('click', function() {
	        $('#piczoom').hide();
	      });

	$('[name="upermege8h[]"],[name="upomege8h[]"]').on('keyup', function(){
		if($(this).attr('name')=='upermege8h[]'){
			$('[name="upomege8h[]"][data-kivn="'+$(this).data('kivn')+'"]').val($('[name="ar_psariwn[]"][data-kivn="'+$(this).data('kivn')+'"]').val()-$(this).val());
		} else {
			$('[name="upermege8h[]"][data-kivn="'+$(this).data('kivn')+'"]').val($('[name="ar_psariwn[]"][data-kivn="'+$(this).data('kivn')+'"]').val()-$(this).val());
		}
	});

	$('#toggle_partbl').on('click',function(){
		 $('#partbl_body').toggle();
		 if($('#toggle_partbl2').hasClass('glyphicon-plus')){
				$('#toggle_partbl2').switchClass('glyphicon-plus', 'glyphicon-minus');
		 } else {
				$('#toggle_partbl2').switchClass('glyphicon-minus', 'glyphicon-plus');
		 }
	});

	$('#partbl_body').on('keyup change', '.megethos, [name^="par_kiv"]', function(){
		var order = $(this).data('order');
		check_totals(order);
		fish_check(order);
	});

	$('[name="varos_kiv[]"], .varos_kiv').on('keyup change', function() {
		check_varoskiv();
	});

	$('[name="pagos_kg[]"], [name="posothta_pagou[]"], .varos_kiv, [name="eidos_kiv"]').on('change', function() {
      eidos_kiv();
			check_ice($(this));
	});

	$('input[name="therm_psariwn[]"]').on('keyup change', function() {
		check_thermpsar();
	});

	$('.dismorfies input, .Αlliosis input, .parasita input').on('keyup change', function() {
		kivn = parseFloat($(this).data('kivn'));
		// console.log('id: '+id+' kivn: '+kivn);
		check_fishsum(kivn, $(this));
	})

	$('.rating').on('change', function() {
		check_ratings();
	});


	var uploader = new plupload.Uploader({
		runtimes: 'html5,flash,silverlight,html4',

		browse_button: 'pickfiles', // you can pass in id...
		container: document.getElementById('upcontainer'), // ... or DOM Element itself

		url: "js/upload.php",
		chunk_size: '1mb',

		filters: {
			max_file_size: '10mb',
			mime_types: [{
				title: "Image files",
				extensions: "jpg,gif,png"
			}, {
				title: "Zip files",
				extensions: "zip"
			}]
		},

		// Flash settings
		flash_swf_url: 'js/Moxie.swf',

		// Silverlight settings
		silverlight_xap_url: 'js/Moxie.xap',


		init: {
			PostInit: function() {
				document.getElementById('filelist').innerHTML = '';

				document.getElementById('uploadfiles').onclick = function() {
					uploader.start();
					return false;
				};
			},


			FilesAdded: function(up, files) {
				var filesarr = new Array();
				if($('#picinp').val()!=''){
					filesarr = JSON.parse($('#picinp').val());
				}
				plupload.each(files, function(file) {
					document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
						if(filesarr.indexOf(file.name)==-1){
							filesarr.push(file.name);
					}
					uploader.bind('UploadComplete', function() {
						if (uploader.files.length == (uploader.total.uploaded + uploader.total.failed)) {
								$("#"+file.id).css({"color":"green", "font-weight" : "800"});
								$("#"+file.id).addClass('okbox');
						}
					});
				});
				$('#picinp').val(JSON.stringify(filesarr));
			},

			UploadProgress: function(up, file) {
				document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
			},

			Error: function(up, err) {
				document.getElementById('console').innerHTML += "\nError #" + err.code + ": " + err.message;
			}
		}
	});
	uploader.init();

});
