// JavaScript Document


function getAjaxData(form, func,action='none',sender=null,senderval=null)
{
	//$('#ajax-err').html('İşleminiz Yapılıyor...&nbsp;');
	if(sender==null)makePopup('Form İşlemi', 'Lütfen Bekleyiniz');
	//console.log(form.serialize());
	var senderparam = '';
	if( senderval== 'undefined')senderval='';
	if(senderval!== null) senderparam = '?sender='+ senderval;
	console.log(site_url+"ajax/"+func+senderparam);
	var ajaxsrv = $.post( site_url+"ajax/"+func+senderparam, form.serialize(),
	function(data) {
		console.log(data);
		var result = jQuery.parseJSON(data);
		if(result.state=='err')
		{
			//makePopup('Hata',result.html);
			 alert_popup('İşlem Hatası!','warning');
			return false;
		}
		if(result.refresh)
		{
			location.reload();
			return false;
		}
		else if(result.redirect)
		{
			window.location = result.redirect;
			return false;
		}

		if (action in window) {
			window[action]( result,sender,senderval );

		} else{
			alert_popup(result.message,result.state);
		}
	})
	.fail(function(data) 
	  {
		alert_popup('Bağlantı kurulamadı. Daha sonra tekrar deneyiniz', 'danger');
		$('#loading').fadeOut(100);
	  })
	.always(function() 
	  {
		//alert( "finished" );
	  });
}

//

    // Initialize
function alert_popup(message='',  css='warning')
{
	var html = '    <div class="alert alert-'+css+' alert-styled-left alert-arrow-left alert-bordered"><span id="modal-body" class="text-semibold">'+message+'</div>';
	$('#modal-body').html(html);
}
function makePopup(title,content='...' ,lnk='', css='warning')
{

	//$('.modal-backdrop').hide();
	$('#modal-box').modal('hide');
	$('.modal-backdrop').remove();

	$('body').find('#modal-box').remove();

			var html  = '<div id="modal-box" class="modal fade" tabindex="-1" role="dialog"> ';

			html += '  <div class="modal-dialog">';

			html += '    <div class="modal-content">';

			html += '      <div class="modal-header">';

			html += '        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';

			html += '        <h4 id="modal-title" class="modal-title">' + title + '</h4>';

			html += '      </div>';

			html += '      <div id="modal-body" class="modal-body">'+content+'</div>';

			html += '    <div class="modal-footer">';

			if(lnk!='')html += '    <a href="'+lnk+'" class="btn btn-success"><i class="icon-checkmark-circle"></i> Submit</a>';

			html += '    <button class="btn btn-warning" data-dismiss="modal"><i class="icon-cancel-circle2"></i> Close</button>';

			html += '    </div>';

			html += '    </div';

			html += '  </div>';

			html += '</div>';

			$('body').append(html);

			$('#modal-box').modal({
  backdrop: 'static',
  keyboard: false
});


}
$( ".form-validate-jquery" ).each(function( index )
{
	$(this).validate({
			ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
			errorClass: 'validation-error-label',
			successClass: 'validation-valid-label',
			highlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},
			unhighlight: function(element, errorClass) {
				$(element).removeClass(errorClass);
			},

			// Different components require proper error label placement
			errorPlacement: function(error, element) {

				// Styled checkboxes, radios, bootstrap switch
				if (element.parents('div').hasClass("checker") || element.parents('div').hasClass("choice") || element.parent().hasClass('bootstrap-switch-container') ) {
					if(element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
						error.appendTo( element.parent().parent().parent().parent() );
					}
					 else {
						error.appendTo( element.parent().parent().parent().parent().parent() );
					}
				}

				// Unstyled checkboxes, radios
				else if (element.parents('div').hasClass('checkbox') || element.parents('div').hasClass('radio')) {
					error.appendTo( element.parent().parent().parent() );
				}

				// Input with icons and Select2
				else if (element.parents('div').hasClass('has-feedback') || element.hasClass('select2-hidden-accessible')) {
					error.appendTo( element.parent() );
				}

				// Inline checkboxes, radios
				else if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
					error.appendTo( element.parent().parent() );
				}

				// Input group, styled file input
				else if (element.parent().hasClass('uploader') || element.parents().hasClass('input-group')) {
					error.appendTo( element.parent().parent() );
				}

				else {
					error.insertAfter(element);
				}
			},
			validClass: "validation-valid-label",
			success: function(label) {
				label.remove();
				//label.addClass("validation-valid-label").text("Success.")
			},
			rules: {
				password: {
					minlength: 5
				},
				repeat_password: {
					equalTo: "#password"
				},
				email: {
					email: true
				},
				repeat_email: {
					equalTo: "#email"
				},
				minimum_characters: {
					minlength: 10
				},
				maximum_characters: {
					maxlength: 10
				},
				minimum_number: {
					min: 10
				},
				maximum_number: {
					max: 10
				},
				number_range: {
					range: [10, 20]
				},
				url: {
					url: true
				},
				date: {
					date: true
				},
				date_iso: {
					dateISO: true
				},
				numbers: {
					number: true
				},
				digits: {
					digits: true
				},
				creditcard: {
					creditcard: true
				},
				basic_checkbox: {
					minlength: 2
				},
				styled_checkbox: {
					minlength: 2
				},
				switchery_group: {
					minlength: 2
				},
				switch_group: {
					minlength: 2
				}
			},
			messages: {
				custom: {
					required: "This is a custom error message",
				},
				agree: "Please accept our policy"
			}
		  ,submitHandler: function(form) {
			  //console.log( $(form).serialize() );
			  var func = $(form).attr('f');
			  var action = 'callBack_'+func;
			  //alert(getAjaxData());
			  getAjaxData($(form),func,action,null);
			  //console.log(form);

				}

		});
});


// select

$(document).ready(function(){
	$( ".ajaxform .select" ).each(function(index, element)
	{
		getSelectOption(element);
	});
	function getSelectOption(sender)
	{
		var source = 'get_' + $(sender).attr('source');
		
		if( source !='get_'  )
		{
			var ajaxform = $(sender).parents('form');
			var action = 'callBack_SelectOption';
			senderval=$(sender).attr('data-val');
			getAjaxData(ajaxform, source, action, $(sender),senderval);					
		}
				

	}
	$('select.filler').change(function(e){
		e.preventDefault();
		getFillerTargetOption($(this));
	})
	function getFillerTargetOption(sender)
	{
		console.log(sender);
		var ajaxform = $(sender).parents('form');
		var func = 'get_' + $(sender).attr('target');
		var action = 'callBack_FillerTargetOption';
		senderval=$(sender).val();
		console.log(senderval);
		getAjaxData(ajaxform, func, action, $(sender),senderval);		
	}
	$('body').on('click','a.confirm',function(event){
		event.preventDefault();
		var lnk = $(this).attr('href');
		var content = $(this).attr('message');
		 makePopup('Onaylıyor musunuz?',content,lnk,'warning');
	})

})
	function callBack_SelectOption(data,sender,senderval)
	{
		//console.log(data);
		$(sender).html(data.html);
	  //$(sender).select2()('val',senderval);	

	}
	function callBack_FillerTargetOption(data,sender,senderval)
	{
		//console.log($(sender).attr('target'));
	  $('#'+$(sender).attr('target')).html(data.html);
	  val = $('#'+$(sender).attr('target')).attr('data-val');
	  $('#'+$(sender).attr('target')).select2().select2('val',val);	
	
	}

$('.file-image').click(function(){
	$(this).next('div').fadeToggle();
})
// .select
    // Single picker
    $('.daterange-single').daterangepicker({ 
        singleDatePicker: true
    });
    // Accessibility labels

    // Single file image
    // Modal template
    var modalTemplate = '<div class="modal-dialog modal-lg" role="document">\n' +
        '  <div class="modal-content">\n' +
        '    <div class="modal-header">\n' +
        '      <div class="kv-zoom-actions btn-group">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
        '      <h6 class="modal-title">{heading} <small><span class="kv-zoom-title"></span></small></h6>\n' +
        '    </div>\n' +
        '    <div class="modal-body">\n' +
        '      <div class="floating-buttons btn-group"></div>\n' +
        '      <div class="kv-zoom-body file-zoom-content"></div>\n' + '{prev} {next}\n' +
        '    </div>\n' +
        '  </div>\n' +
        '</div>\n';

    // Buttons inside zoom modal
    var previewZoomButtonClasses = {
        toggleheader: 'btn btn-default btn-icon btn-xs btn-header-toggle',
        fullscreen: 'btn btn-default btn-icon btn-xs',
        borderless: 'btn btn-default btn-icon btn-xs',
        close: 'btn btn-default btn-icon btn-xs'
    };

    // Icons inside zoom modal classes
    var previewZoomButtonIcons = {
        prev: '<i class="icon-arrow-left32"></i>',
        next: '<i class="icon-arrow-right32"></i>',
        toggleheader: '<i class="icon-menu-open"></i>',
        fullscreen: '<i class="icon-screen-full"></i>',
        borderless: '<i class="icon-alignment-unalign"></i>',
        close: '<i class="icon-cross3"></i>'
    };

    // File actions
    var fileActionSettings = {
        zoomClass: 'btn btn-link btn-xs btn-icon',
        zoomIcon: '<i class="icon-zoomin3"></i>',
        dragClass: 'btn btn-link btn-xs btn-icon',
        dragIcon: '<i class="icon-three-bars"></i>',
        removeClass: 'btn btn-link btn-icon btn-xs',
        removeIcon: '<i class="icon-trash"></i>',
        /*indicatorNew: '<i class="icon-file-plus text-slate"></i>',*/
        indicatorSuccess: '<i class="icon-checkmark3 file-icon-large text-success"></i>',
        indicatorError: '<i class="icon-cross2 text-danger"></i>',
        indicatorLoading: '<i class="icon-spinner2 spinner text-muted"></i>'
    };


    //
    // Basic example
    //

    $(".file-input-ajax").fileinput({
        uploadUrl: site_url+"fileupload/uploadfile", // server upload action
        uploadAsync: false,
        maxFileCount: 1,
        initialPreview: [],
        fileActionSettings: {
            removeIcon: '<i class="icon-bin"></i>',
            removeClass: 'btn btn-link btn-xs btn-icon',
            uploadIcon: '<i class="icon-upload"></i>',
            uploadClass: 'btn btn-link btn-xs btn-icon',
            zoomIcon: '<i class="icon-zoomin3"></i>',
            zoomClass: 'btn btn-link btn-xs btn-icon',
            indicatorNew: '<i class="icon-file-plus text-slate"></i>',
            indicatorSuccess: '<i class="icon-checkmark3 file-icon-large text-success"></i>',
            indicatorError: '<i class="icon-cross2 text-danger"></i>',
            indicatorLoading: '<i class="icon-spinner2 spinner text-muted"></i>',
        },
        layoutTemplates: {
            icon: '<i class="icon-file-check"></i>',
            modal: modalTemplate
        },
        initialCaption: "No file selected",
        previewZoomButtonClasses: previewZoomButtonClasses,
        previewZoomButtonIcons: previewZoomButtonIcons
    });
	$('.file-input-ajax').on('fileuploaded', function(event, data, previewId, index) {
		var form = data.form; 
		var files = data.files; 
		var extra = data.extra;
		response = data.response, reader = data.reader;
		console.log('File uploaded triggered');
		var url = response.data;
		var file = response.id;
		var id = $(event.target).attr('name');
		$('#img_'+id).attr('src',url);
		$('#'+id).val(file);
	});
//editor
    // Default initialization
    $('.wysihtml5-default').wysihtml5({
        parserRules:  wysihtml5ParserRules,
        /*stylesheets: ["assets/css/components.css"]*/
    });
    // Editor events
    $('.wysihtml5-init').on('click', function() {
        $(this).off('click').addClass('disabled');
        $('.wysihtml5-events').wysihtml5({
            parserRules:  wysihtml5ParserRules,
            /*stylesheets: ["assets/css/components.css"],*/
            events: {
                load: function() { 
                    $.jGrowl('Editor has been loaded.', { theme: 'bg-slate-700', header: 'WYSIHTML5 loaded' });
                },
                change_view: function() {
                    $.jGrowl('Editor view mode has been changed.', { theme: 'bg-slate-700', header: 'View mode' });
                }
            }
        });
    });
// min-max input
function minmax(value, min, max) 
{
    if(parseInt(value) < min || isNaN(parseInt(value))) 
        return ''; 
    else if(parseInt(value) > max) 
        return max; 
    else return value;
}