// drag and drop
$(document).ready(function(){
	
	// set default variable
	var url = 'requires/' ;
	var allowSubmit = true ;
	
	// responsive table
	if ( $("#basic-datatable").length > 0 ){
		$("#basic-datatable").fixedThead({
			vspace: 65,
			top: 10,
			row: 0,
			col: 0
		});
	}

	$( "#tabs" ).tabs() ;
	
	// responsive table
	if ( $(".basic-datatable2").length > 0 ){
		$(".basic-datatable2").fixedThead({
			vspace: 65,
			top: 10,
			row: 0,
			col: 0
		});
	}

	if ( $("#basic-datatable-column-2").length > 0 ){
		$("#basic-datatable-column-2").fixedThead({
			vspace: 65,
			top: 10,
			row: 1,
			col: 2
		});
	}

	if ( $("#basic-datatable-column").length > 0 ){
		$("#basic-datatable-column").fixedThead({
			vspace: 65,
			top: 10,
			row: 1,
			col: ( $( window ).width() > 768 ? 3 : 2 )
		});
	}
	
	// add fancybox
	if ( $('.fancybox').length > 0 ){
		$('.fancybox').fancybox() ;
	}

	// lazy load
	if ( $(".lazy_load_img").length > 0 ){
		$(".lazy_load_img").unveil(300) ;
	}
	
	// select function with mobile friendly
	if ( $(".select2-basic-single").length > 0 ){
		$(".select2-basic-single").select2() ;
	}
	
	// datepicker
	$('.datepicker').datepicker({
		format: 'yyyy-mm-dd'
	}).on('changeDate', function(ev){
		$('.datepicker').datepicker('hide');
	}) ;
	
	// tootltip
	$('[data-toggle="tooltip"]').tooltip() ;

	// jquery validate form
	$("#quotationForm").validate();
	
	// user logout all device
	$('.user_logout_device').click(function(){
		var thisKey = $(this),
			thisParent = thisKey.parent('td'),
			thisId = thisKey.attr('id') ;
		// check confirmation box first
		if (confirm('Confirm disconnect all device?')){
			$.ajax({
				type: 'POST',
				url: url + 'ajax_login.php?type=logout',
				data: { 'id': thisId },
				dataType: 'json',
				success: function (data) {
					if (data['result'] == 'success'){
						$('#result_quantity_warning').show(0).delay(1500).hide(0) ;
						thisParent.text('-') ;
					}else{
						location.reload() ;	
					}
				}
			});
		}
		return false; // ajax used, block the normal submit
	}) ;
	
	// jquery product validate form
	$('.form_validate_form').validate() ;
	$("#productForm").validate({
		submitHandler: function (form) {
			$('#ajax_loading').show();
			// form validates so do the ajax
			var parent = $('#productForm'),
				id = $('#product_id').val(),
				title = $('#autocomplete_product').val() ;
			$.ajax({
				type: 'POST',
				url: url + 'ajax_product_title.php',
				data: { 'id': id, 'title': title },
				success: function (data) {
					if (data == 'success'){
						form.submit() ;
					}else if (data == 'error-exists'){
						$('.result_error').hide() ;
						$('.result_success').hide() ;
						$('.result_product_error').show() ;
					}else{
						location.reload() ;
					}
				}
			});
			return false; // ajax used, block the normal submit
		}
	});
	
	// get detail from company
	$('#call_company').change(function() {
		var selected_page = $('#selected_page').text(),
			company_name = ($(this).val()),
			page_input_type = $('#page_input_type').text() ;
		// show loading
		$('.loading_customer').show() ;
		$.ajax({
			type: 'POST',
			url: url + 'ajax_company_name.php' ,
			data:  { 'company_name': company_name, 'page_input_type': page_input_type },
			dataType: 'json',
			success: function (result) {
				if (result != ''){
					
					$('#call_company').val(result['id']) ;
					$('#call_company_id').text(result['id']);	
					$('#return_company').val(result['company']);
					$('#call_customer').html(result['customer']);

					// for order part
					$('.order_ajax_customer').val('') ;

					// hide loading
					$('#hide_other_customer, #hide_other_company, .loading_customer').hide() ;
				}
			}
		}) ;	
	}) ;
	
	// company search
	$('#return_company').autocomplete(url + 'autocomplete.php?type=company',{
		scroll: false,
		width: 350,
	}).result(function(){
		var company_name = $('#return_company').val() ;
		// show loading
		$('.loading_customer').show() ;
		$.ajax({
			type: 'POST',
			url: url + 'ajax_company_name.php',
			data:  { 'company_name': company_name, 'page_input_type': 'click' },
			dataType: 'json',
			success: function (result) {
				if (result != ''){
					
					$('#call_company').val(result['id']) ;
					$('#call_company_id').text(result['id']) ;	
					$('#hide_company_input_type').val('wording') ;
					$('#call_customer').html(result['customer']) ;
					$('#return_company').val(result['company']) ;
					
					// for order part
					$('.order_ajax_customer').val('') ;
					
					// hide some class
					$('#hide_other_customer, #hide_other_company, .loading_customer').hide() ;
				}
			}
		});
	});
	
	// prevent dropdown box click
	$('.dropdown-menu').on('click', function(event){
		event.stopPropagation() ;
	}) ;

	if ( $('.custom_dropdown').length !== 0 ){
		$(".custom_dropdown_toggle").click( function(){
			var thisKey      = $(this),
				thisParent   = thisKey.parents('.custom_dropdown'),
				thisParentID = thisParent.attr('id') ;

			if ( thisParent.hasClass('open') ){
				$(".dataTables_scrollBody").find("."+thisParentID).removeClass('custom_dropdown_open') ;
			}else{
				$(".dataTables_scrollBody").find("."+thisParentID).addClass('custom_dropdown_open') ;
			}
		}) ;

		$('body').on('click', function(e) {
	        if( $(e.target).closest('.custom_dropdown').length == 0 ) {
	           $(".dataTables_scrollBody").find('.custom_dropdown').removeClass('custom_dropdown_open') ;
	        }
	    });
	}
	
	// image rotate
	$('.rotate_image_button').click(function(){
		var thisKey = $(this) ;
			thisUrl = thisKey.attr('href') ;
			
		$('.rotate_loading').show() ;
		
		// ajax call
		$.ajax({
			type: 'POST',
			url: thisUrl ,
			data:  {  },
			dataType: 'json', // choosing a JSON datatype
			success: function (data) {
				if (data['result'] == 'success'){
					$('.rotate_image_link').attr('href', data['big']) ;
					$('.rotate_image').attr('src', data['small']) ;
				}else{
					alert("Image rotate failed, please try again later!") ;	
				}
				$('.rotate_loading').hide() ;
			}
		}) ;
		return false ;
	}) ;
	
	// filter
	$('.custom_dropdown_filter').keyup(function(e){
		var thisKey = $(this),
			thisParent = thisKey.parents('.dropdown-menu'),
			thisVal = thisKey.val().toLowerCase(),
			thisSubKey = thisSubParent = thisSubText = '' ;

		$('.custom_dropdown_text').css('display', 'block') ;
		if (thisVal != ''){
			thisParent.find('.custom_dropdown_text').each(function(){
				thisSubKey = $(this),
				thisSubText = thisSubKey.text() ;

				thisSubKey.hide() ;
				if (thisSubText.toLowerCase().indexOf(thisVal) != -1){
					thisSubKey.show() ;
				}
				
			}) ;
		}
		e.stopPropagation();
		
	}) ;
	
	$('.dropdown-menu').on('click', function(event){
		//The event won't be propagated to the document NODE and 
		// therefore events delegated to document won't be fired
		event.stopPropagation();
	});
	
	var thisValue = $("input[name='show_price']:checked").val() ;
		
	$(".show_price_div").hide() ;
	
	if( thisValue == 'no' ){
		$(".show_price_div").show() ;
	}
	
	$('.show_price').change(function() {
		var thisValue = $(this).val() ;
		
		$(".show_price_div").hide() ;
		
		if( thisValue == 'no' ){
			$(".show_price_div").show() ;
		}
	});

	$('.dataTable_form_edit').submit(function(){
		var thisKey       = $(this),
			list_id       = thisKey.find('.list_id').val(),
			list_work_day = thisKey.find('.list_work_day').val(),
			list_ot_day   = thisKey.find('.list_ot_day').val(),
			list_min   = thisKey.find('.list_min').val(),
			list_amt   = thisKey.find('.list_amt').val(),
			list_fd   = thisKey.find('.list_fd').val(),
			list_wt   = thisKey.find('.list_wt').val() ;

		var	list_remark   = thisKey.find('.list_remark').val() ;

		$.ajax({
			type: 'POST',
			url: url + 'ajax_hr_list_update.php' ,
			data:  { 'list_id': list_id, 'list_work_day': list_work_day, 'list_ot_day': list_ot_day, 'list_min': list_min, 'list_amt': list_amt, 'list_fd': list_fd, 'list_wt': list_wt ,"list_remark" : list_remark },
			dataType: 'json',
			success: function (data) {
				if ( data['result'] == 'success' ){
					thisKey.addClass('dataTable_form_edit_success') ;
				}else{
					thisKey.addClass('dataTable_form_edit_failed') ;
				}
				setTimeout(function(){ 
					thisKey.removeClass('dataTable_form_edit_success') 
					thisKey.removeClass('dataTable_form_edit_failed') 
				}, 3000) ;
			}
		}) ;	

		return false ;
	}) ;

	$('.dataTable_form_edit_health').submit(function(){
		var thisKey       = $(this),
			list_staff_id = thisKey.find('.list_staff_id').val(),
			list_date 	  = thisKey.find('.list_date').val(),
			list_health   = thisKey.find('.list_health').val() ;

		$.ajax({
			type: 'POST',
			url: url + 'ajax_hr_list_health.php' ,
			data:  { 'list_staff_id': list_staff_id, 'list_date': list_date, 'list_health': list_health },
			dataType: 'json',
			success: function (data) {
				if ( data['result'] == 'success' ){
					thisKey.addClass('dataTable_form_edit_success') ;
				}else{
					thisKey.addClass('dataTable_form_edit_failed') ;
				}
				setTimeout(function(){ 
					thisKey.removeClass('dataTable_form_edit_success') 
					thisKey.removeClass('dataTable_form_edit_failed') 
				}, 3000) ;
			}
		}) ;	

		return false ;
	}) ;
	
});	

// custom counting method
function addNum (num1, num2) {
	var sq1, sq2, m ;
	try {
		sq1 = num1.toString().split(".")[1].length ;
	}catch (e) {
		sq1 = 0 ;
	}
	try {
		sq2 = num2.toString().split(".")[1].length ;
	}catch (e) {
		sq2 = 0 ;
	}
	m = Math.pow(10,Math.max(sq1, sq2)) ;
	return (num1 * m + num2 * m) / m ;
}

// get iframe content height
function getDocHeight(doc) {
    doc = doc || document;
    // stackoverflow.com/questions/1145850/
    var body = doc.body, html = doc.documentElement;
    var height = Math.max( body.scrollHeight, body.offsetHeight, 
        html.clientHeight, html.scrollHeight, html.offsetHeight );
    return height;
}

// set iframe height follow by content
function setIframeHeight(id) {
    var ifrm = document.getElementById(id);
    var doc = ifrm.contentDocument? ifrm.contentDocument: 
        ifrm.contentWindow.document;
    ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height ...
    // IE opt. for bing/msn needs a bit added or scrollbar appears
    ifrm.style.height = getDocHeight( doc ) + 4 + "px";
    ifrm.style.visibility = 'visible';
}

function setIframeHeight2(id) {
    var ifrm = document.getElementById(id);
    var doc = ifrm.contentDocument? ifrm.contentDocument: 
        ifrm.contentWindow.document;
    ifrm.style.visibility = 'hidden';
    ifrm.style.height = "10px"; // reset to minimal height ...
    // IE opt. for bing/msn needs a bit added or scrollbar appears
    ifrm.style.height = getDocHeight( doc ) + 4 + "px";
    ifrm.parentElement.style.height = ifrm.style.height;
    ifrm.style.visibility = 'visible';
}

function zeroPad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}