/* -------------------- Check Browser --------------------- */

function browser() {
	
	var isOpera = !!(window.opera && window.opera.version);  // Opera 8.0+
	var isFirefox = testCSS('MozBoxSizing');                 // FF 0.8+
	var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
	    // At least Safari 3+: "[object HTMLElementConstructor]"
	var isChrome = !isSafari && testCSS('WebkitTransform');  // Chrome 1+
	//var isIE = /*@cc_on!@*/false || testCSS('msTransform');  // At least IE6

	function testCSS(prop) {
	    return prop in document.documentElement.style;
	}
	
	if (isOpera) {
		
		return false;
		
	}else if (isSafari || isChrome) {
		
		return true;
		
	} else {
		
		return false;
		
	}
	
}

/* ---------- IE8 list style hack (:nth-child(odd)) ---------- */

jQuery(document).ready(function($){
	
	if($('.messagesList').width()) {
		
		if(jQuery.browser.version.substring(0, 2) == "8.") {

			$('ul.messagesList li:nth-child(2n+1)').addClass('odd');
			
		}
		
	}
	
});	

$(document).ready(function(){
		
			
	$("#username").focus(function() {
		
		$(this).parent(".input-prepend").addClass("input-prepend-focus");
	
	});
	
	$("#username").focusout(function() {
		
		$(this).parent(".input-prepend").removeClass("input-prepend-focus");
	
	});
	
	$("#password").focus(function() {
		
		$(this).parent(".input-prepend").addClass("input-prepend-focus");
	
	});
	
	$("#password").focusout(function() {
		
		$(this).parent(".input-prepend").removeClass("input-prepend-focus");
	
	});
	
				
	/* ---------- Add class .active to current link  ---------- */
	/*$('ul.main-menu li a').each(function(){
		
			if($($(this))[0].href==String(window.location)) {
				
				$(this).parent().addClass('active');
				
			}
	
	});*/
	
	/*$('ul.main-menu li ul li a').each(function(){
		
			if($($(this))[0].href==String(window.location)) {
				
				$(this).parent().addClass('active');
				$(this).parent().parent().show();
				
			}
	
	});*/
	
	/* ---------- Submenu  ---------- */
	
	$('.dropmenu1').click(function(e){

		e.preventDefault();

		$('.dropmenu1').parent().find('ul').slideToggle();
		$('.dropmenu2').parent().find('ul').slideUp();
		$('.dropmenu3').parent().find('ul').slideUp();
		$('.dropmenu4').parent().find('ul').slideUp();
		$('.dropmenu5').parent().find('ul').slideUp();
	
	});

	$('.dropmenu2').click(function(e){

		e.preventDefault();

		$('.dropmenu2').parent().find('ul').slideToggle();
		$('.dropmenu1').parent().find('ul').slideUp();
		$('.dropmenu3').parent().find('ul').slideUp();
		$('.dropmenu4').parent().find('ul').slideUp();
		$('.dropmenu5').parent().find('ul').slideUp();
	
	});

	$('.dropmenu3').click(function(e){

		e.preventDefault();

		$('.dropmenu3').parent().find('ul').slideToggle();
		$('.dropmenu1').parent().find('ul').slideUp();
		$('.dropmenu2').parent().find('ul').slideUp();
		$('.dropmenu4').parent().find('ul').slideUp();
		$('.dropmenu5').parent().find('ul').slideUp();
	
	});

	$('.dropmenu4').click(function(e){

		e.preventDefault();

		$('.dropmenu4').parent().find('ul').slideToggle();
		$('.dropmenu1').parent().find('ul').slideUp();
		$('.dropmenu2').parent().find('ul').slideUp();
		$('.dropmenu3').parent().find('ul').slideUp();
		$('.dropmenu5').parent().find('ul').slideUp();
	
	});

	$('.dropmenu5').click(function(e){

		e.preventDefault();

		$('.dropmenu5').parent().find('ul').slideToggle();
		$('.dropmenu1').parent().find('ul').slideUp();
		$('.dropmenu2').parent().find('ul').slideUp();
		$('.dropmenu3').parent().find('ul').slideUp();
		$('.dropmenu4').parent().find('ul').slideUp();
	
	});

	/* ---------- Acivate Functions ---------- */
	template_functions();
	init_masonry();
	sparkline_charts();
	charts();
	calendars();
	growlLikeNotifications();
	widthFunctions();
	
	if(jQuery.browser.version.substring(0, 2) == "8.") {
		 
		//disable jQuery Knob
		
	} else {
		
		circle_progess();
		
	}
	
	chart();
	messageLike();	
	
});

/* ---------- Like/Dislike ---------- */

function messageLike(){
	
	if($('.messagesList')) {
		
		$('.messagesList').on('click', '.star', function(){
			
			$(this).removeClass('star');
			
			$(this).addClass('dislikes');
			
			//here add your function
			
		});
		
		$('.messagesList').on('click', '.dislikes', function(){
			
			$(this).removeClass('dislikes');
			
			$(this).addClass('star');
			
			//here add your function
			
		});		
		
	}	
	
}

/* ---------- Check Retina ---------- */

function retina(){
	
	retinaMode = (window.devicePixelRatio > 1);
	
	return retinaMode;
	
}

/* ---------- Chart ---------- */

function chart(){
	
	if($('.verticalChart')) {
		
		$('.singleBar').each(function(){
			
			var theColorIs = $(this).parent().parent().parent().css("background");
			
			var percent = $(this).find('.value p').html();
			
			$(this).find('.value span').css('color','#000');
			
			$(this).find('.value').animate({height:percent}, 2000, function() {
			    
				$(this).find('span').fadeIn();
			 
			});
			
		});
		
	}
	
}

/* ---------- Masonry Gallery ---------- */

function init_masonry(){
    var $container = $('.masonry-gallery');

    var gutter = 6;
    var min_width = 250;
    $container.imagesLoaded( function(){
        $container.masonry({
            itemSelector : '.masonry-thumb',
            gutterWidth: gutter,
            isAnimated: true,
              columnWidth: function( containerWidth ) {
                var num_of_boxes = (containerWidth/min_width | 0);

                var box_width = (((containerWidth - (num_of_boxes-1)*gutter)/num_of_boxes) | 0) ;

                if (containerWidth < min_width) {
                    box_width = containerWidth;
                }

                $('.masonry-thumb').width(box_width);

                return box_width;
              }
        });
    });
}

/* ---------- Numbers Sepparator ---------- */

function numberWithCommas(x) {
    x = x.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(x))
        x = x.replace(pattern, "$1.$2");
    return x;
}

/* ---------- Template Functions ---------- */		
		
function template_functions(){
	
	/* ---------- ToDo List Action Buttons ---------- */
	
	$(".todo-remove").click(function(){
		
		$(this).parent().parent().fadeTo("slow", 0.00, function(){ //fade
			$(this).slideUp("slow", function() { //slide up
		    	$(this).remove(); //then remove from the DOM
		    });
		});
		
		
		return false;
	});
	
	$(".todo-list").find('.action').each(function(){
		
		$(this).click(function(){
			
			if($(this).hasClass('icon-check-empty')) {
				
				$(this).removeClass('icon-check-empty');
				$(this).addClass('icon-check');
				
				$(this).parent().css('text-decoration','line-through');
				
			} else {
				
				$(this).removeClass('icon-check');
				$(this).addClass('icon-check-empty');
				
				$(this).parent().css('text-decoration','none');
				
			}
			
			return false;
			
		});
		
	});
	
	

	/* ---------- Skill Bars ---------- */
	$(".meter > span").each(function() {
		
		var getColor = $(this).parent().css('borderTopColor');
				
		$(this).css('background',getColor);
		
		$(this)
		.data("origWidth", $(this).width())
		.width(0)
		.animate({
			width: $(this).data("origWidth")
		}, 3000);
	});
	
	/* ---------- Disable moving to top ---------- */
	$('a[href="#"][data-top!=true]').click(function(e){
		e.preventDefault();
	});
	
	/* ---------- Text editor ---------- */
	/*$('.cleditor').cleditor({
		width: 800
	});
    $.cleditor.buttons.image.uploadUrl = 'cleditorUploadImage.php';*/

	/* ---------- Datapicker ---------- */
	$('.datepicker').datepicker({
		dateFormat: "mm/dd/yy",
		changeMonth: true,
      	changeYear: true
	});

	$('.monthpicker').datepicker({
		changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: "mm/yy",
        onClose: function(dateText, inst) { 
            $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
        }
	});

	/* ---------- Timepicker ---------- */
	//$('.timepickerss').wickedpicker({
  	//twentyFour: true,
  	//upArrow: 'wickedpicker__controls__control-up',  //The up arrow class selector to use, for custom CSS
    //downArrow: 'wickedpicker__controls__control-down'
	//});

	$('.timepicker').timepicker({
        timeFormat: 'HH:mm',
        minTime: '00:00', // 11:45:00 AM,
        maxHour: 24,
        maxMinutes: 60,
        dropdown: true,
    	scrollbar: true
    });

	/* ---------- Notifications ---------- */
	/*$('.noty').click(function(e){
		e.preventDefault();
		var options = $.parseJSON($(this).attr('data-noty-options'));
		noty(options);
	});*/

	/* ---------- Uniform ---------- */
	$("input:checkbox, input:radio, input:file").not('[data-no-uniform="true"],#uniform-is-ajax').uniform();

	/* ---------- Choosen ---------- */
	$('[data-rel="chosen"],[rel="chosen"]').chosen();

	/* ---------- Tabs ---------- */
	$('#myTab a:first').tab('show');
	$('#myTab a').click(function (e) {
	  e.preventDefault();
	  $(this).tab('show');
	});

	/* ---------- Makes elements soratble, elements that sort need to have id attribute to save the result ---------- */
	$('.sortable').sortable({
		revert:true,
		cancel:'.btn,.box-content,.nav-header',
		update:function(event,ui){
			//line below gives the ids of elements, you can make ajax call here to save it to the database
			//console.log($(this).sortable('toArray'));
		}
	});


	/* Input Number*/
	$('input.number').keyup(function(event) {

	  // skip for arrow keys
	  if(event.which >= 37 && event.which <= 40) return;

	  // format number
	  $(this).val(function(index, value) {
	    return value
	    .replace(/\D/g, "")
	    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
	    ;
	  });
	});
	/* --------- Res Menu ---------- */
	$(document).ready(function(){
		var w_size = $(window).width();
		if(w_size <= '767'){
			$('.header-nav').removeClass('nav-no-collapse');
			$('.header-nav').addClass('nav-collapse');
			$('.sub-icon').addClass('white');
		} else if(w_size >= '768'){
			$('.header-nav').removeClass('nav-collapse');
			$('.header-nav').addClass('nav-no-collapse');
			$('.sub-icon').removeClass('white');
		} else {
			return false;
		}
	});

	/* ---------- Tooltip ---------- */
	$('[rel="tooltip"],[data-rel="tooltip"]').tooltip({"placement":"bottom",delay: { show: 400, hide: 200 }});

	/* ---------- Popover ---------- */
	$('[rel="popover"],[data-rel="popover"]').popover();

	/* ---------- File Manager ---------- */
	var elf = $('.file-manager').elfinder({
		url : 'misc/elfinder-connector/connector.php'  // connector URL (REQUIRED)
	}).elfinder('instance');

	/* ---------- Star Rating ---------- */
	$('.raty').raty({
		score : 4 //default stars
	});

	/* ---------- Uploadify ---------- */
	$('#file_upload').uploadify({
		'swf'      : 'misc/uploadify.swf',
		'uploader' : 'misc/uploadify.php'
		// Put your options here
	});

	/* ---------- Fullscreen ---------- */
	$('#toggle-fullscreen').button().click(function () {
		var button = $(this), root = document.documentElement;
		if (!button.hasClass('active')) {
			$('#thumbnails').addClass('modal-fullscreen');
			if (root.webkitRequestFullScreen) {
				root.webkitRequestFullScreen(
					window.Element.ALLOW_KEYBOARD_INPUT
				);
			} else if (root.mozRequestFullScreen) {
				root.mozRequestFullScreen();
			}
		} else {
			$('#thumbnails').removeClass('modal-fullscreen');
			(document.webkitCancelFullScreen ||
				document.mozCancelFullScreen ||
				$.noop).apply(document);
		}
	});

	/* ---------- Datable ---------- */
	$('.datatable').dataTable({
			"dom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span12'i><'span12 center'p>>",
			"pagingType": "bootstrap",
			"ordering": true,
			"responsive": true,
			"language": {
			"lengthMenu": "แสดง _MENU_ ข้อมูลต่อหน้า"
			}
		} );
	$('.btn-close').click(function(e){
		e.preventDefault();
		$(this).parent().parent().parent().fadeOut();
	});
	$('.btn-minimize').click(function(e){
		e.preventDefault();
		var $target = $(this).parent().parent().next('.box-content');
		if($target.is(':visible')) $('i',$(this)).removeClass('chevron-up').addClass('chevron-down');
		else 					   $('i',$(this)).removeClass('chevron-down').addClass('chevron-up');
		$target.slideToggle();
	});
	$('table').on('click', '.delete-confirm', function(e){
		e.preventDefault();
		var del_item = $(this).attr('data-item-del');
		var del_id = $(this).attr('id');
		$('#myModal').modal('show');
		$('.user_del').attr('id', del_id);
		$('.program_del').attr('id', del_id);
		$('.period_del').attr('id', del_id);
		$('.country_del').attr('id', del_id);
		$('.airline_del').attr('id', del_id);
		$('.airport_del').attr('id', del_id);
		$('.price_del').attr('id', del_id);
		$('.upload_del').attr('id', del_id);
		$('.package_del').attr('id', del_id);
		$('.promo_del').attr('id', del_id);
		$('.app_del').attr('id', del_id);
		$('.tag_del').attr('id', del_id);
		$('.agency_del').attr('id', del_id);
		$('.sale_agency_del').attr('id', del_id);
		$('.book_del').attr('id', del_id);
		$('.book_cancel').attr('id', del_id);
		$('.book_cant').attr('id', del_id);
		$('.tl_del').attr('id', del_id);
		$('.pass_del').attr('id', del_id);
		$('.del-item').text(del_item);
	});

	$('table').on('click', '.delete-confirm-pass', function(e){
		e.preventDefault();
		var del_id = $(this).attr('id');
		var link_img = $(this).attr('data-pass');
		var folder = $(this).attr('folder');
		var all_link = folder+'/'+link_img;
		$('#img-del-show').attr('src', all_link);
		$('.pass_del').attr('id', del_id);
		$('#Modal-C').modal('show');
	});
	
	
	/* ---------- Progress  ---------- */

		$(".simpleProgress").progressbar({
			value: 89
		});

		/*$(".progressAnimate").progressbar({
			value: 1,
			create: function() {
				$(".progressAnimate .ui-progressbar-value").animate({"width":"100%"},{
					duration: 10000,
					step: function(now){
						$(".progressAnimateValue").html(parseInt(now)+"%");
					}
					easing: "linear"
				})
			}
		});*/

		$(".progressUploadAnimate").progressbar({
			value: 1,
			create: function() {
				$(".progressUploadAnimate .ui-progressbar-value").animate({"width":"100%"},{
					duration: 20000,
					easing: 'linear',
					step: function(now){
						$(".progressUploadAnimateValue").html(parseInt(now*40.96)+" Gb");
					},
					complete: function(){
						$(".progressUploadAnimate + .field_notice").html("<span class='must'>Upload Finished</span>");
					} 
				})
			}
		});
		
		if($(".taskProgress")) {
		
			$(".taskProgress").each(function(){
				
				var endValue = parseInt($(this).html());
												
				$(this).progressbar({
					value: endValue
				});
				
				$(this).parent().find(".percent").html(endValue + "%");
				
			});
		
		}
		
		if($(".progressBarValue")) {
		
			$(".progressBarValue").each(function(){
				
				var endValueHTML = $(this).find(".progressCustomValueVal").html();
				
				var endValue = parseInt(endValueHTML);
												
				$(this).find(".progressCustomValue").progressbar({
					
					value: 1,
					create: function() {
						$(this).find(".ui-progressbar-value").animate({"width": endValue + "%"},{
							duration: 5000,
							step: function(now){
																
								$(this).parent().parent().parent().find(".progressCustomValueVal").html(parseInt(now)+"%");
							},
							easing: "linear"
						})
					}
				});
				
			});
		
		}
	
	
	/* ---------- Custom Slider ---------- */
		$(".sliderSimple").slider();

		$(".sliderMin").slider({
			range: "min",
			value: 180,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderMinLabel" ).html( "$" + ui.value );
			}
		});

		$(".sliderMin-1").slider({
			range: "min",
			value: 50,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderMin1Label" ).html( "$" + ui.value );
			}
		});

		$(".sliderMin-2").slider({
			range: "min",
			value: 100,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderMin2Label" ).html( "$" + ui.value );
			}
		});

		$(".sliderMin-3").slider({
			range: "min",
			value: 150,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderMin3Label" ).html( "$" + ui.value );
			}
		});

		$(".sliderMin-4").slider({
			range: "min",
			value: 250,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderMin4Label" ).html( "$" + ui.value );
			}
		});

		$(".sliderMin-5").slider({
			range: "min",
			value: 350,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderLabel" ).html( "$" + ui.value );
			}
		});
		
		$(".sliderMin-6").slider({
			range: "min",
			value: 450,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderLabel" ).html( "$" + ui.value );
			}
		});
		
		$(".sliderMin-7").slider({
			range: "min",
			value: 550,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderLabel" ).html( "$" + ui.value );
			}
		});
		
		$(".sliderMin-8").slider({
			range: "min",
			value: 650,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderLabel" ).html( "$" + ui.value );
			}
		});
		
		
		$(".sliderMax").slider({
			range: "max",
			value: 280,
			min: 1,
			max: 700,
			slide: function( event, ui ) {
				$( ".sliderMaxLabel" ).html( "$" + ui.value );
			}
		});

		$( ".sliderRange" ).slider({
			range: true,
			min: 0,
			max: 500,
			values: [ 192, 470 ],
			slide: function( event, ui ) {
				$( ".sliderRangeLabel" ).html( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
			}
		});

		$( "#sliderVertical-1" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 60,
		});

		$( "#sliderVertical-2" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 40,
		});

		$( "#sliderVertical-3" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 30,
		});

		$( "#sliderVertical-4" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 15,
		});

		$( "#sliderVertical-5" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 40,
		});

		$( "#sliderVertical-6" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 80,
		});
		
		$( "#sliderVertical-7" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 60,
		});

		$( "#sliderVertical-8" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 40,
		});

		$( "#sliderVertical-9" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 30,
		});

		$( "#sliderVertical-10" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 15,
		});

		$( "#sliderVertical-11" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 40,
		});

		$( "#sliderVertical-12" ).slider({
			orientation: "vertical",
			range: "min",
			min: 0,
			max: 100,
			value: 80,
		});
			
}

/* ---------- Circle Progess Bars ---------- */

function circle_progess() {
	
	var divElement = $('div'); //log all div elements
	
	if (retina()) {
		
		$(".whiteCircle").knob({
	        'min':0,
	        'max':100,
	        'readOnly': true,
	        'width': 240,
	        'height': 240,
			'bgColor': 'rgba(255,255,255,0.5)',
	        'fgColor': 'rgba(255,255,255,0.9)',
	        'dynamicDraw': true,
	        'thickness': 0.2,
	        'tickColorizeValues': true
	    });
	
		$(".circleStat").css('zoom',0.5);
		$(".whiteCircle").css('zoom',0.999);
		
		
	} else {
		
		$(".whiteCircle").knob({
	        'min':0,
	        'max':100,
	        'readOnly': true,
	        'width': 120,
	        'height': 120,
			'bgColor': 'rgba(255,255,255,0.5)',
	        'fgColor': 'rgba(255,255,255,0.9)',
	        'dynamicDraw': true,
	        'thickness': 0.2,
	        'tickColorizeValues': true
	    });
		
	}
	
	
	
	$(".circleStatsItemBox").each(function(){
		
		var value = $(this).find(".value > .number").html();
		var unit = $(this).find(".value > .unit").html();
		var percent = $(this).find("input").val()/100;
		
		countSpeed = 2300*percent;
		
		endValue = value*percent;
		
		$(this).find(".count > .unit").html(unit);
		$(this).find(".count > .number").countTo({
			
			from: 0,
		    to: endValue,
		    speed: countSpeed,
		    refreshInterval: 50
		
		});
		
		//$(this).find(".count").html(value*percent + unit);
		
	});
	
}                

      

/* ---------- Calendars ---------- */

function calendars(){
	

	$('#external-events div.external-event').each(function() {

		// it doesn't need to have a start or end
		var eventObject = {
			title: $.trim($(this).text()) // use the element's text as the event title
		};
		
		// store the Event Object in the DOM element so we can get to it later
		$(this).data('eventObject', eventObject);
		
		// make the event draggable using jQuery UI
		$(this).draggable({
			zIndex: 999,
			revert: true,      // will cause the event to go back to its
			revertDuration: 0  //  original position after the drag
		});
		
	});
	
	var date = new Date();
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();

	$('#main_calendar').fullCalendar({
		header: {
			left: 'title',
			right: 'prev,next today,month,agendaWeek,agendaDay'
		},
		editable: true,
		events: [
			{
				title: 'All Day Event',
				start: new Date(y, m, 1)
			},
			{
				title: 'Long Event',
				start: new Date(y, m, d-5),
				end: new Date(y, m, d-2)
			},
			{
				id: 999,
				title: 'Repeating Event',
				start: new Date(y, m, d-3, 16, 0),
				allDay: false
			},
			{
				id: 999,
				title: 'Repeating Event',
				start: new Date(y, m, d+4, 16, 0),
				allDay: false
			},
			{
				title: 'Meeting',
				start: new Date(y, m, d, 10, 30),
				allDay: false
			},
			{
				title: 'Lunch',
				start: new Date(y, m, d, 12, 0),
				end: new Date(y, m, d, 14, 0),
				allDay: false
			},
			{
				title: 'Birthday Party',
				start: new Date(y, m, d+1, 19, 0),
				end: new Date(y, m, d+1, 22, 30),
				allDay: false
			},
			{
				title: 'Click for Google',
				start: new Date(y, m, 28),
				end: new Date(y, m, 29),
				url: 'http://google.com/'
			}
		]
	});
	
	$('#main_calendar_phone').fullCalendar({
		header: {
			left: 'title',
			right: 'prev,next'
		},
		defaultView: 'agendaDay',
		editable: true,
		events: [
			{
				title: 'All Day Event',
				start: new Date(y, m, 1)
			},
			{
				title: 'Long Event',
				start: new Date(y, m, d-5),
				end: new Date(y, m, d-2)
			},
			{
				id: 999,
				title: 'Repeating Event',
				start: new Date(y, m, d-3, 16, 0),
				allDay: false
			},
			{
				id: 999,
				title: 'Repeating Event',
				start: new Date(y, m, d+4, 16, 0),
				allDay: false
			},
			{
				title: 'Meeting',
				start: new Date(y, m, d, 10, 30),
				allDay: false
			},
			{
				title: 'Lunch',
				start: new Date(y, m, d, 12, 0),
				end: new Date(y, m, d, 14, 0),
				allDay: false
			},
			{
				title: 'Birthday Party',
				start: new Date(y, m, d+1, 19, 0),
				end: new Date(y, m, d+1, 22, 30),
				allDay: false
			},
			{
				title: 'Click for Google',
				start: new Date(y, m, 28),
				end: new Date(y, m, 29),
				url: 'http://google.com/'
			}
		]
	});		
	
			
	$('#calendar').fullCalendar({
		header: {
			left: 'title',
			right: 'prev,next today,month,agendaWeek,agendaDay'
		},
		editable: true,
		droppable: true, // this allows things to be dropped onto the calendar !!!
		drop: function(date, allDay) { // this function is called when something is dropped
		
			// retrieve the dropped element's stored Event Object
			var originalEventObject = $(this).data('eventObject');
			
			// we need to copy it, so that multiple events don't have a reference to the same object
			var copiedEventObject = $.extend({}, originalEventObject);
			
			// assign it the date that was reported
			copiedEventObject.start = date;
			copiedEventObject.allDay = allDay;
			
			// render the event on the calendar
			// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
			$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
			
			// is the "remove after drop" checkbox checked?
			if ($('#drop-remove').is(':checked')) {
				// if so, remove the element from the "Draggable Events" list
				$(this).remove();
			}
			
		}
	});
	
}

/* ---------- Sparkline Charts ---------- */

function sparkline_charts() {
	
	//generate random number for charts
	randNum = function(){
		//return Math.floor(Math.random()*101);
		return (Math.floor( Math.random()* (1+40-20) ) ) + 20;
	}

	var chartColours = ['#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff'];

	//sparklines (making loop with random data for all 7 sparkline)
	i=1;
	for (i=1; i<9; i++) {
	 	var data = [[1, 3+randNum()], [2, 5+randNum()], [3, 8+randNum()], [4, 11+randNum()],[5, 14+randNum()],[6, 17+randNum()],[7, 20+randNum()], [8, 15+randNum()], [9, 18+randNum()], [10, 22+randNum()]];
	 	placeholder = '.sparkLineStats' + i;
		
		if (retina()) {
			
			$(placeholder).sparkline(data, {
				width: 160,//Width of the chart - Defaults to 'auto' - May be any valid css width - 1.5em, 20px, etc (using a number without a unit specifier won't do what you want) - This option does nothing for bar and tristate chars (see barWidth)
				height: 80,//Height of the chart - Defaults to 'auto' (line height of the containing tag)
				lineColor: '#ffffff',//Used by line and discrete charts to specify the colour of the line drawn as a CSS values string
				fillColor: 'rgba(255,255,255,0.2)',//Specify the colour used to fill the area under the graph as a CSS value. Set to false to disable fill
				spotColor: '#ffffff',//The CSS colour of the final value marker. Set to false or an empty string to hide it
				maxSpotColor: '#ffffff',//The CSS colour of the marker displayed for the maximum value. Set to false or an empty string to hide it
				minSpotColor: '#ffffff',//The CSS colour of the marker displayed for the mimum value. Set to false or an empty string to hide it
				spotRadius: 2,//Radius of all spot markers, In pixels (default: 1.5) - Integer
				lineWidth: 1//In pixels (default: 1) - Integer
			});
			
			$(placeholder).css('zoom',0.5);
			
		} else {
			
			if($.browser.msie  && parseInt($.browser.version, 10) === 8) {
				
				$(placeholder).sparkline(data, {
					width: 80,//Width of the chart - Defaults to 'auto' - May be any valid css width - 1.5em, 20px, etc (using a number without a unit specifier won't do what you want) - This option does nothing for bar and tristate chars (see barWidth)
					height: 40,//Height of the chart - Defaults to 'auto' (line height of the containing tag)
					lineColor: '#ffffff',//Used by line and discrete charts to specify the colour of the line drawn as a CSS values string
					fillColor: '#ffffff',//Specify the colour used to fill the area under the graph as a CSS value. Set to false to disable fill
					spotColor: '#ffffff',//The CSS colour of the final value marker. Set to false or an empty string to hide it
					maxSpotColor: '#ffffff',//The CSS colour of the marker displayed for the maximum value. Set to false or an empty string to hide it
					minSpotColor: '#ffffff',//The CSS colour of the marker displayed for the mimum value. Set to false or an empty string to hide it
					spotRadius: 2,//Radius of all spot markers, In pixels (default: 1.5) - Integer
					lineWidth: 1//In pixels (default: 1) - Integer
				});
				
			} else {
				
				$(placeholder).sparkline(data, {
					width: 80,//Width of the chart - Defaults to 'auto' - May be any valid css width - 1.5em, 20px, etc (using a number without a unit specifier won't do what you want) - This option does nothing for bar and tristate chars (see barWidth)
					height: 40,//Height of the chart - Defaults to 'auto' (line height of the containing tag)
					lineColor: '#ffffff',//Used by line and discrete charts to specify the colour of the line drawn as a CSS values string
					fillColor: 'rgba(255,255,255,0.2)',//Specify the colour used to fill the area under the graph as a CSS value. Set to false to disable fill
					spotColor: '#ffffff',//The CSS colour of the final value marker. Set to false or an empty string to hide it
					maxSpotColor: '#ffffff',//The CSS colour of the marker displayed for the maximum value. Set to false or an empty string to hide it
					minSpotColor: '#ffffff',//The CSS colour of the marker displayed for the mimum value. Set to false or an empty string to hide it
					spotRadius: 2,//Radius of all spot markers, In pixels (default: 1.5) - Integer
					lineWidth: 1//In pixels (default: 1) - Integer
				});
				
			}
			
		}
	
	}
	
	if($(".boxchart")) {
		
		if (retina()) {
			
			$(".boxchart").sparkline('html', {
			    type: 'bar',
			    height: '120', // Double pixel number for retina display
				barWidth: '8', // Double pixel number for retina display
				barSpacing: '2', // Double pixel number for retina display
			    barColor: '#ffffff',
			    negBarColor: '#eeeeee'}
			);
			
			$(".boxchart").css('zoom',0.5);
			
		} else {
			
			$(".boxchart").sparkline('html', {
			    type: 'bar',
			    height: '60',
				barWidth: '4',
				barSpacing: '1',
			    barColor: '#ffffff',
			    negBarColor: '#eeeeee'}
			);
			
		}		
		
	}
		
}

/* ---------- Charts ---------- */

function charts() {
	
	function randNum(){
		return ((Math.floor( Math.random()* (1+40-20) ) ) + 20)* 1200;
	}
	
	function randNum2(){
		return ((Math.floor( Math.random()* (1+40-20) ) ) + 20) * 500;
	}
	
	function randNum3(){
		return ((Math.floor( Math.random()* (1+40-20) ) ) + 20) * 300;
	}
	
	function randNum4(){
		return ((Math.floor( Math.random()* (1+40-20) ) ) + 20) * 100;
	}
	
	/* ---------- Chart with points ---------- */
	if($("#stats-chart2").length)
	{	
		var pageviews = [[1, 5+randNum()], [1.5, 10+randNum()], [2, 15+randNum()], [2.5, 20+randNum()],[3, 25+randNum()],[3.5, 30+randNum()],[4, 35+randNum()],[4.5, 40+randNum()],[5, 45+randNum()],[5.5, 50+randNum()],[6, 55+randNum()],[6.5, 60+randNum()],[7, 65+randNum()],[7.5, 70+randNum()],[8, 75+randNum()],[8.5, 80+randNum()],[9, 85+randNum()],[9.5, 90+randNum()],[10, 85+randNum()],[10.5, 80+randNum()],[11, 75+randNum()],[11.5, 80+randNum()],[12, 75+randNum()],[12.5, 70+randNum()],[13, 65+randNum()],[13.5, 75+randNum()],[14,80+randNum()],[14.5, 85+randNum()],[15, 90+randNum()], [15.5, 95+randNum()], [16, 5+randNum()], [16.5, 15+randNum()], [17, 15+randNum()], [17.5, 10+randNum()], [18, 15+randNum()], [18.5, 20+randNum()],[19, 25+randNum()],[19.5, 30+randNum()],[20, 35+randNum()],[20.5, 40+randNum()],[21, 45+randNum()],[21.5, 50+randNum()],[22, 55+randNum()],[22.5, 60+randNum()],[23, 65+randNum()],[23.5, 70+randNum()],[24, 75+randNum()],[24.5, 80+randNum()],[25, 85+randNum()],[25.5, 90+randNum()],[26, 85+randNum()],[26.5, 80+randNum()],[27, 75+randNum()],[27.5, 80+randNum()],[28, 75+randNum()],[28.5, 70+randNum()],[29, 65+randNum()],[29.5, 75+randNum()],[30,80+randNum()]];
		var visits = [[1, randNum2()-10], [2, randNum2()-10], [3, randNum2()-10], [4, randNum2()],[5, randNum2()],[6, 4+randNum2()],[7, 5+randNum2()],[8, 6+randNum2()],[9, 6+randNum2()],[10, 8+randNum2()],[11, 9+randNum2()],[12, 10+randNum2()],[13,11+randNum2()],[14, 12+randNum2()],[15, 13+randNum2()],[16, 14+randNum2()],[17, 15+randNum2()],[18, 15+randNum2()],[19, 16+randNum2()],[20, 17+randNum2()],[21, 18+randNum2()],[22, 19+randNum2()],[23, 20+randNum2()],[24, 21+randNum2()],[25, 14+randNum2()],[26, 24+randNum2()],[27,25+randNum2()],[28, 26+randNum2()],[29, 27+randNum2()], [30, 31+randNum2()]];
		var visitors = [[1, 5+randNum3()], [2, 10+randNum3()], [3, 15+randNum3()], [4, 20+randNum3()],[5, 25+randNum3()],[6, 30+randNum3()],[7, 35+randNum3()],[8, 40+randNum3()],[9, 45+randNum3()],[10, 50+randNum3()],[11, 55+randNum3()],[12, 60+randNum3()],[13, 65+randNum3()],[14, 70+randNum3()],[15, 75+randNum3()],[16, 80+randNum3()],[17, 85+randNum3()],[18, 90+randNum3()],[19, 85+randNum3()],[20, 80+randNum3()],[21, 75+randNum3()],[22, 80+randNum3()],[23, 75+randNum3()],[24, 70+randNum3()],[25, 65+randNum3()],[26, 75+randNum3()],[27,80+randNum3()],[28, 85+randNum3()],[29, 90+randNum3()], [30, 95+randNum3()]];
		var newVisitors = [[1, randNum4()-10], [2, randNum4()-10], [3, randNum4()-10], [4, randNum4()],[5, randNum4()],[6, 4+randNum4()],[7, 5+randNum4()],[8, 6+randNum4()],[9, 6+randNum4()],[10, 8+randNum4()],[11, 9+randNum4()],[12, 10+randNum4()],[13,11+randNum4()],[14, 12+randNum4()],[15, 13+randNum4()],[16, 14+randNum4()],[17, 15+randNum4()],[18, 15+randNum4()],[19, 16+randNum4()],[20, 17+randNum4()],[21, 18+randNum4()],[22, 19+randNum4()],[23, 20+randNum4()],[24, 21+randNum4()],[25, 14+randNum4()],[26, 24+randNum4()],[27,25+randNum4()],[28, 26+randNum4()],[29, 27+randNum4()], [30, 31+randNum4()]];

		var plot = $.plot($("#stats-chart2"),
			   [ { data: visitors, 
				   label: "Visits", 
				   lines: { show: true, 
							fill: false,
							lineWidth: 2 
						  },
				   shadowSize: 0	
				  }, {
					data: pageviews,
					bars: { show: true,
							fill: false, 
							barWidth: 0.1, 
							align: "center",
							lineWidth: 5,
					}
				  }
				], {
				   
				   grid: { hoverable: true, 
						   clickable: true, 
						   tickColor: "rgba(255,255,255,0.05)",
						   borderWidth: 0
						 },
				 legend: {
						    show: false
						},	
				   colors: ["rgba(255,255,255,0.8)", "rgba(255,255,255,0.6)", "rgba(255,255,255,0.4)", "rgba(255,255,255,0.2)"],
				xaxis: {ticks:15, tickDecimals: 0, color: "rgba(255,255,255,0.8)" },
					yaxis: {ticks:5, tickDecimals: 0, color: "rgba(255,255,255,0.8)" },
				});
		
		/*
		   [ { data: visitors, label: "Visits"}], {
			   series: {
				   lines: { show: true,
							lineWidth: 2
						 },
				   points: { show: true, 
							 lineWidth: 2 
						 },
				   shadowSize: 0
			   },	
			   grid: { hoverable: true, 
					   clickable: true, 
					   tickColor: "rgba(255,255,255,0.025)",
					   borderWidth: 0
					 },
			 legend: {
					    show: false
					},	
			   colors: ["rgba(255,255,255,0.8)", "rgba(255,255,255,0.6)", "rgba(255,255,255,0.4)", "rgba(255,255,255,0.2)"],
				xaxis: {ticks:15, tickDecimals: 0},
				yaxis: {ticks:5, tickDecimals: 0},
			 });
		*/		
		
				

		function showTooltip(x, y, contents) {
			$('<div id="tooltip">' + contents + '</div>').css( {
				position: 'absolute',
				display: 'none',
				top: y + 5,
				left: x + 5,
				border: '1px solid #fdd',
				padding: '2px',
				'background-color': '#dfeffc',
				opacity: 0.80
			}).appendTo("body").fadeIn(200);
		}

		var previousPoint = null;
		$("#stats-chart2").bind("plothover", function (event, pos, item) {
			$("#x").text(pos.x.toFixed(2));
			$("#y").text(pos.y.toFixed(2));

				if (item) {
					if (previousPoint != item.dataIndex) {
						previousPoint = item.dataIndex;

						$("#tooltip").remove();
						var x = item.datapoint[0].toFixed(2),
							y = item.datapoint[1].toFixed(2);

						showTooltip(item.pageX, item.pageY,
									item.series.label + " of " + x + " = " + y);
					}
				}
				else {
					$("#tooltip").remove();
					previousPoint = null;
				}
		});
	
	}
	
	function randNumFB(){
		return ((Math.floor( Math.random()* (1+40-20) ) ) + 20);
	}
	
	/* ---------- Chart with points ---------- */
	if($("#facebookChart").length)
	{	
		var likes = [[1, 5+randNumFB()], [2, 10+randNumFB()], [3, 15+randNumFB()], [4, 20+randNumFB()],[5, 25+randNumFB()],[6, 30+randNumFB()],[7, 35+randNumFB()],[8, 40+randNumFB()],[9, 45+randNumFB()],[10, 50+randNumFB()],[11, 55+randNumFB()],[12, 60+randNumFB()],[13, 65+randNumFB()],[14, 70+randNumFB()],[15, 75+randNumFB()],[16, 80+randNumFB()],[17, 85+randNumFB()],[18, 90+randNumFB()],[19, 85+randNumFB()],[20, 80+randNumFB()],[21, 75+randNumFB()],[22, 80+randNumFB()],[23, 75+randNumFB()],[24, 70+randNumFB()],[25, 65+randNumFB()],[26, 75+randNumFB()],[27,80+randNumFB()],[28, 85+randNumFB()],[29, 90+randNumFB()], [30, 95+randNumFB()]];

		var plot = $.plot($("#facebookChart"),
			   [ { data: likes, label: "Fans"} ], {
				   series: {
					   lines: { show: true,
								lineWidth: 2,
								fill: true, fillColor: { colors: [ { opacity: 0.5 }, { opacity: 0.2 } ] }
							 },
					   points: { show: true, 
								 lineWidth: 2 
							 },
					   shadowSize: 0
				   },
				   grid: { hoverable: true, 
						   clickable: true, 
						   tickColor: "#f9f9f9",
						   borderWidth: 0
						 },
				   colors: ["#3B5998"],
					xaxis: {ticks:6, tickDecimals: 0},
					yaxis: {ticks:3, tickDecimals: 0},
				 });

		function showTooltip(x, y, contents) {
			$('<div id="tooltip">' + contents + '</div>').css( {
				position: 'absolute',
				display: 'none',
				top: y + 5,
				left: x + 5,
				border: '1px solid #fdd',
				padding: '2px',
				'background-color': '#dfeffc',
				opacity: 0.80
			}).appendTo("body").fadeIn(200);
		}

		var previousPoint = null;
		$("#facebookChart").bind("plothover", function (event, pos, item) {
			$("#x").text(pos.x.toFixed(2));
			$("#y").text(pos.y.toFixed(2));

				if (item) {
					if (previousPoint != item.dataIndex) {
						previousPoint = item.dataIndex;

						$("#tooltip").remove();
						var x = item.datapoint[0].toFixed(2),
							y = item.datapoint[1].toFixed(2);

						showTooltip(item.pageX, item.pageY,
									item.series.label + " of " + x + " = " + y);
					}
				}
				else {
					$("#tooltip").remove();
					previousPoint = null;
				}
		});
	
	}
	
	function randNumTW(){
		return ((Math.floor( Math.random()* (1+40-20) ) ) + 20);
	}
	
	/* ---------- Chart with points ---------- */
	if($("#twitterChart").length)
	{	
		var followers = [[1, 5+randNumTW()], [2, 10+randNumTW()], [3, 15+randNumTW()], [4, 20+randNumTW()],[5, 25+randNumTW()],[6, 30+randNumTW()],[7, 35+randNumTW()],[8, 40+randNumTW()],[9, 45+randNumTW()],[10, 50+randNumTW()],[11, 55+randNumTW()],[12, 60+randNumTW()],[13, 65+randNumTW()],[14, 70+randNumTW()],[15, 75+randNumTW()],[16, 80+randNumTW()],[17, 85+randNumTW()],[18, 90+randNumTW()],[19, 85+randNumTW()],[20, 80+randNumTW()],[21, 75+randNumTW()],[22, 80+randNumTW()],[23, 75+randNumTW()],[24, 70+randNumTW()],[25, 65+randNumTW()],[26, 75+randNumTW()],[27,80+randNumTW()],[28, 85+randNumTW()],[29, 90+randNumTW()], [30, 95+randNumTW()]];

		var plot = $.plot($("#twitterChart"),
			   [ { data: followers, label: "Followers"} ], {
				   series: {
					   lines: { show: true,
								lineWidth: 2,
								fill: true, fillColor: { colors: [ { opacity: 0.5 }, { opacity: 0.2 } ] }
							 },
					   points: { show: true, 
								 lineWidth: 2 
							 },
					   shadowSize: 0
				   },
				   grid: { hoverable: true, 
						   clickable: true, 
						   tickColor: "#f9f9f9",
						   borderWidth: 0
						 },
				   colors: ["#1BB2E9"],
					xaxis: {ticks:6, tickDecimals: 0},
					yaxis: {ticks:3, tickDecimals: 0},
				 });

		function showTooltip(x, y, contents) {
			$('<div id="tooltip">' + contents + '</div>').css( {
				position: 'absolute',
				display: 'none',
				top: y + 5,
				left: x + 5,
				border: '1px solid #fdd',
				padding: '2px',
				'background-color': '#dfeffc',
				opacity: 0.80
			}).appendTo("body").fadeIn(200);
		}

		var previousPoint = null;
		$("#twitterChart").bind("plothover", function (event, pos, item) {
			$("#x").text(pos.x.toFixed(2));
			$("#y").text(pos.y.toFixed(2));

				if (item) {
					if (previousPoint != item.dataIndex) {
						previousPoint = item.dataIndex;

						$("#tooltip").remove();
						var x = item.datapoint[0].toFixed(2),
							y = item.datapoint[1].toFixed(2);

						showTooltip(item.pageX, item.pageY,
									item.series.label + " of " + x + " = " + y);
					}
				}
				else {
					$("#tooltip").remove();
					previousPoint = null;
				}
		});
	
	}
	

	if($("#activeUsers").length) {
	    var d1 = [];
	    
	    for (var i = 0; i <= 160; i += 1) {
	        d1.push([i, parseInt(Math.random() * 123123)]);
		}	

	    var stack = 0, bars = true, lines = false, steps = false;

	    function plotWithOptions2() {
					
	        $.plot($("#activeUsers"), [ d1 ], {
	            series: {
	                bars: { show: bars, 
							fill: true, 
							barWidth: 0.1, 
							align: "center",
							lineWidth: 5,
							fillColor: { colors: [ { opacity: 1 }, { opacity: 0.5 } ] }
						},
	            },
				grid: { hoverable: true, 
						   clickable: true, 
						   tickColor: "#f6f6f6",
						   borderWidth: 0,
						},
				colors: ["#CBE968"],
				xaxis: {ticks:0, tickDecimals: 0, tickFormatter: function(v, a) {return v }},
				yaxis: {ticks:5, tickDecimals: 0, tickFormatter: function (v) { return v }},
	
	        });
	    }
	
	    plotWithOptions2();

	}
	
	/* ---------- Chart with points ---------- */
	if($("#stats-chart").length)
	{
		var visitors = [[1, randNum()-10], [2, randNum()-10], [3, randNum()-10], [4, randNum()],[5, randNum()],[6, 4+randNum()],[7, 5+randNum()],[8, 6+randNum()],[9, 6+randNum()],[10, 8+randNum()],[11, 9+randNum()],[12, 10+randNum()],[13,11+randNum()],[14, 12+randNum()],[15, 13+randNum()],[16, 14+randNum()],[17, 15+randNum()],[18, 15+randNum()],[19, 16+randNum()],[20, 17+randNum()],[21, 18+randNum()],[22, 19+randNum()],[23, 20+randNum()],[24, 21+randNum()],[25, 14+randNum()],[26, 24+randNum()],[27,25+randNum()],[28, 26+randNum()],[29, 27+randNum()], [30, 31+randNum()]];

		var plot = $.plot($("#stats-chart"),
			   [ { data: visitors, label: "visitors" } ], {
				   series: {
					   lines: { show: true,
								lineWidth: 3,
								fill: true, fillColor: { colors: [ { opacity: 0.5 }, { opacity: 0.2 } ] }
							 },
					   points: { show: true },
					   shadowSize: 2
				   },
				   grid: { hoverable: true, 
						   clickable: true, 
						   tickColor: "#eee",
						   borderWidth: 0,
						 },
				   colors: ["#b1d3d4"],
					xaxis: {ticks:11, tickDecimals: 0},
					yaxis: {ticks:11, tickDecimals: 0},
				 });

		function showTooltip(x, y, contents) {
			$('<div id="tooltip">' + contents + '</div>').css( {
				position: 'absolute',
				display: 'none',
				top: y + 5,
				left: x + 5,
				border: '1px solid #fdd',
				padding: '2px',
				'background-color': '#dfeffc',
				opacity: 0.80
			}).appendTo("body").fadeIn(200);
		}

		var previousPoint = null;
		$("#stats-chart").bind("plothover", function (event, pos, item) {
			$("#x").text(pos.x.toFixed(2));
			$("#y").text(pos.y.toFixed(2));

				if (item) {
					if (previousPoint != item.dataIndex) {
						previousPoint = item.dataIndex;

						$("#tooltip").remove();
						var x = item.datapoint[0].toFixed(2),
							y = item.datapoint[1].toFixed(2);

						showTooltip(item.pageX, item.pageY,
									item.series.label + " of " + x + " = " + y);
					}
				}
				else {
					$("#tooltip").remove();
					previousPoint = null;
				}
		});
		


		$("#sincos").bind("plotclick", function (event, pos, item) {
			if (item) {
				$("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
				plot.highlight(item.series, item.datapoint);
			}
		});
	}
	
	
	
	/* ---------- Chart with points ---------- */
	if($("#sincos").length)
	{
		var sin = [], cos = [];

		for (var i = 0; i < 14; i += 0.5) {
			sin.push([i, Math.sin(i)/i]);
			cos.push([i, Math.cos(i)]);
		}

		var plot = $.plot($("#sincos"),
			   [ { data: sin, label: "sin(x)/x"}, { data: cos, label: "cos(x)" } ], {
				   series: {
					   lines: { show: true,
								lineWidth: 2,
							 },
					   points: { show: true },
					   shadowSize: 2
				   },
				   grid: { hoverable: true, 
						   clickable: true, 
						   tickColor: "#dddddd",
						   borderWidth: 0 
						 },
				   yaxis: { min: -1.2, max: 1.2 },
				   colors: ["#FA5833", "#2FABE9"]
				 });

		function showTooltip(x, y, contents) {
			$('<div id="tooltip">' + contents + '</div>').css( {
				position: 'absolute',
				display: 'none',
				top: y + 5,
				left: x + 5,
				border: '1px solid #fdd',
				padding: '2px',
				'background-color': '#dfeffc',
				opacity: 0.80
			}).appendTo("body").fadeIn(200);
		}

		var previousPoint = null;
		$("#sincos").bind("plothover", function (event, pos, item) {
			$("#x").text(pos.x.toFixed(2));
			$("#y").text(pos.y.toFixed(2));

				if (item) {
					if (previousPoint != item.dataIndex) {
						previousPoint = item.dataIndex;

						$("#tooltip").remove();
						var x = item.datapoint[0].toFixed(2),
							y = item.datapoint[1].toFixed(2);

						showTooltip(item.pageX, item.pageY,
									item.series.label + " of " + x + " = " + y);
					}
				}
				else {
					$("#tooltip").remove();
					previousPoint = null;
				}
		});
		


		$("#sincos").bind("plotclick", function (event, pos, item) {
			if (item) {
				$("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + ".");
				plot.highlight(item.series, item.datapoint);
			}
		});
	}
	
	/* ---------- Flot chart ---------- */
	if($("#flotchart").length)
	{
		var d1 = [];
		for (var i = 0; i < Math.PI * 2; i += 0.25)
			d1.push([i, Math.sin(i)]);
		
		var d2 = [];
		for (var i = 0; i < Math.PI * 2; i += 0.25)
			d2.push([i, Math.cos(i)]);

		var d3 = [];
		for (var i = 0; i < Math.PI * 2; i += 0.1)
			d3.push([i, Math.tan(i)]);
		
		$.plot($("#flotchart"), [
			{ label: "sin(x)",  data: d1},
			{ label: "cos(x)",  data: d2},
			{ label: "tan(x)",  data: d3}
		], {
			series: {
				lines: { show: true },
				points: { show: true }
			},
			xaxis: {
				ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"], [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]
			},
			yaxis: {
				ticks: 10,
				min: -2,
				max: 2
			},
			grid: {	tickColor: "#dddddd",
					borderWidth: 0 
			},
			colors: ["#FA5833", "#2FABE9", "#FABB3D"]
		});
	}
	
	/* ---------- Stack chart ---------- */
	if($("#stackchart").length)
	{
		var d1 = [];
		for (var i = 0; i <= 10; i += 1)
		d1.push([i, parseInt(Math.random() * 30)]);

		var d2 = [];
		for (var i = 0; i <= 10; i += 1)
			d2.push([i, parseInt(Math.random() * 30)]);

		var d3 = [];
		for (var i = 0; i <= 10; i += 1)
			d3.push([i, parseInt(Math.random() * 30)]);

		var stack = 0, bars = true, lines = false, steps = false;

		function plotWithOptions() {
			$.plot($("#stackchart"), [ d1, d2, d3 ], {
				series: {
					stack: stack,
					lines: { show: lines, fill: true, steps: steps },
					bars: { show: bars, barWidth: 0.6 },
				},
				colors: ["#FA5833", "#2FABE9", "#FABB3D"]
			});
		}

		plotWithOptions();

		$(".stackControls input").click(function (e) {
			e.preventDefault();
			stack = $(this).val() == "With stacking" ? true : null;
			plotWithOptions();
		});
		$(".graphControls input").click(function (e) {
			e.preventDefault();
			bars = $(this).val().indexOf("Bars") != -1;
			lines = $(this).val().indexOf("Lines") != -1;
			steps = $(this).val().indexOf("steps") != -1;
			plotWithOptions();
		});
	}
	
	/* ---------- Device chart ---------- 
	
	var data = [
	{ label: "Desktop",  data: 73},
	{ label: "Mobile",  data: 27}
	]; */
	
	/* ---------- Donut chart ---------- 
	if($("#deviceChart").length)
	{
		$.plot($("#deviceChart"), data,
		{
				series: {
						pie: {
								innerRadius: 0.6,
								show: true
						}
				},
				legend: {
					show: true
				},
				colors: ["#FA5833", "#2FABE9", "#FABB3D", "#78CD51"]
		});
	}
	
	var data = [
	{ label: "iOS",  data: 20},
	{ label: "Android",  data: 7},
	{ label: "Linux",  data: 11},
	{ label: "Mac OSX",  data: 14},
	{ label: "Windows",  data: 48}
	]; */
	
	/* ---------- Donut chart ---------- 
	if($("#osChart").length)
	{
		$.plot($("#osChart"), data,
		{
				series: {
						pie: {
								innerRadius: 0.6,
								show: true
						}
				},
				legend: {
					show: true
				},
				colors: ["#FA5833", "#2FABE9", "#FABB3D", "#78CD51"]
		});
	} */

	/* ---------- Pie chart ---------- 
	var n1 = $('#name1').attr('data-nname1');
	var n2 = $('#name2').attr('data-nname2');
	var n3 = $('#name3').attr('data-nname3');
	var n4 = $('#name4').attr('data-nname4');
	var n5 = $('#name5').attr('data-nname5');
	var n6 = $('#name6').attr('data-nname6');
	var n7 = $('#name7').attr('data-nname7');
	var n8 = $('#name8').attr('data-nname8');
	var n9 = $('#name9').attr('data-nname9');
	var n10 = $('#name10').attr('data-nname10');
	var n11 = $('#name11').attr('data-nname11');
	
	var d1 = $('#name1').attr('data-dname1');
	var d2 = $('#name2').attr('data-dname2');
	var d3 = $('#name3').attr('data-dname3');
	var d4 = $('#name4').attr('data-dname4');
	var d5 = $('#name5').attr('data-dname5');
	var d6 = $('#name6').attr('data-dname6');
	var d7 = $('#name7').attr('data-dname7');
	var d8 = $('#name8').attr('data-dname8');
	var d9 = $('#name9').attr('data-dname9');
	var d10 = $('#name10').attr('data-dname10');
	var d11 = $('#name11').attr('data-dname11');
	//var data = [{ label: n1, data: d1},{ label: n2, data: d2},{ label: n3, data: d3},{ label: n4, data: d4},{ label: n5, data: d5},{ label: n6, data: d6},{ label: n7, data: d7},{ label: n8, data: d8},{ label: n9, data: d9},{ label: n10, data: d10},{ label: n11, data: d11}];
	var data = [
	{ label: "iOS",  data: 20},
	{ label: "Android",  data: 7},
	{ label: "Linux",  data: 11},
	{ label: "Mac OSX",  data: 14},
	{ label: "Windows",  data: 48}
	];*/
	
	
	/* ---------- Donut chart ---------- */
	if($("#donutchart").length)
	{
		$.plot($("#donutchart"), data,
		{
				series: {
						pie: {
								innerRadius: 0.5,
								show: true
						}
				},
				legend: {
					show: false
				},
				colors: ["#FA5833", "#2FABE9", "#FABB3D", "#78CD51"]
		});
	}

	/* ---------- Realtime chart ---------- */
	if($("#serverLoad").length)
	{	
		var options = {
			series: { shadowSize: 1 },
			lines: { show: true, lineWidth: 3, fill: true, fillColor: { colors: [ { opacity: 0.9 }, { opacity: 0.9 } ] }},
			yaxis: { min: 0, max: 100, tickFormatter: function (v) { return v + "%"; }},
			xaxis: { show: false },
			colors: ["#FA5833"],
			grid: {	tickColor: "#f9f9f9",
					borderWidth: 0, 
			},
		};
		var plot = $.plot($("#serverLoad"), [ getRandomData() ], options);
		function update() {
			plot.setData([ getRandomData() ]);
			// since the axes don't change, we don't need to call plot.setupGrid()
			plot.draw();
			
			setTimeout(update, updateInterval);
		}

		update();
	}
	
	if($("#serverLoad2").length)
	{	
		var options = {
			series: { shadowSize: 1 },
			lines: { show: true, lineWidth: 2, fill: true, fillColor: { colors: [ { opacity: 0.9 }, { opacity: 0.9 } ] }},
			yaxis: { min: 0, max: 100, tickFormatter: function (v) { return v + "%"; }, color: "rgba(255,255,255,0.8)"},
			xaxis: { show: false, color: "rgba(255,255,255,0.8)" },
			colors: ["rgba(255,255,255,0.95)"],
			grid: {	tickColor: "rgba(255,255,255,0.15)",
					borderWidth: 0, 
			},
		};
		var plot = $.plot($("#serverLoad2"), [ getRandomData() ], options);
		function update() {
			plot.setData([ getRandomData() ]);
			// since the axes don't change, we don't need to call plot.setupGrid()
			plot.draw();
			
			setTimeout(update, updateInterval);
		}

		update();
	}
	
	if($("#realtimechart").length)
	{
		var options = {
			series: { shadowSize: 1 },
			lines: { fill: true, fillColor: { colors: [ { opacity: 1 }, { opacity: 0.1 } ] }},
			yaxis: { min: 0, max: 100 },
			xaxis: { show: false },
			colors: ["#F4A506"],
			grid: {	tickColor: "#dddddd",
					borderWidth: 0 
			},
		};
		var plot = $.plot($("#realtimechart"), [ getRandomData() ], options);
		function update() {
			plot.setData([ getRandomData() ]);
			// since the axes don't change, we don't need to call plot.setupGrid()
			plot.draw();
			
			setTimeout(update, updateInterval);
		}

		update();
	}
}

function growlLikeNotifications() {
	
	$('#add-sticky').click(function(){

		var unique_id = $.gritter.add({
			// (string | mandatory) the heading of the notification
			title: 'This is a sticky notice!',
			// (string | mandatory) the text inside the notification
			text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.',
			// (string | optional) the image to display on the left
			image: 'img/avatar.jpg',
			// (bool | optional) if you want it to fade out on its own or just sit there
			sticky: true,
			// (int | optional) the time you want it to be alive for before fading out
			time: '',
			// (string | optional) the class name you want to apply to that specific message
			class_name: 'my-sticky-class'
		});

		// You can have it return a unique id, this can be used to manually remove it later using
		/* ----------
		setTimeout(function(){

			$.gritter.remove(unique_id, {
				fade: true,
				speed: 'slow'
			});

		}, 6000)
		*/

		return false;

	});

	$('#add-regular').click(function(){

		$.gritter.add({
			// (string | mandatory) the heading of the notification
			title: 'This is a regular notice!',
			// (string | mandatory) the text inside the notification
			text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.',
			// (string | optional) the image to display on the left
			image: 'img/avatar.jpg',
			// (bool | optional) if you want it to fade out on its own or just sit there
			sticky: false,
			// (int | optional) the time you want it to be alive for before fading out
			time: ''
		});

		return false;

	});

    $('#add-max').click(function(){

        $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: 'This is a notice with a max of 3 on screen at one time!',
            // (string | mandatory) the text inside the notification
            text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.',
            // (string | optional) the image to display on the left
            image: 'img/avatar.jpg',
            // (bool | optional) if you want it to fade out on its own or just sit there
            sticky: false,
            // (function) before the gritter notice is opened
            before_open: function(){
                if($('.gritter-item-wrapper').length == 3)
                {
                    // Returning false prevents a new gritter from opening
                    return false;
                }
            }
        });

        return false;

    });

	$('#add-without-image').click(function(){

		$.gritter.add({
			// (string | mandatory) the heading of the notification
			title: 'This is a notice without an image!',
			// (string | mandatory) the text inside the notification
			text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.'
		});

		return false;
	});

    $('#add-gritter-light').click(function(){

        $.gritter.add({
            // (string | mandatory) the heading of the notification
            title: 'This is a light notification',
            // (string | mandatory) the text inside the notification
            text: 'Just add a "gritter-light" class_name to your $.gritter.add or globally to $.gritter.options.class_name',
            class_name: 'gritter-light'
        });

        return false;
    });

	$('#add-with-callbacks').click(function(){

		$.gritter.add({
			// (string | mandatory) the heading of the notification
			title: 'This is a notice with callbacks!',
			// (string | mandatory) the text inside the notification
			text: 'The callback is...',
			// (function | optional) function called before it opens
			before_open: function(){
				alert('I am called before it opens');
			},
			// (function | optional) function called after it opens
			after_open: function(e){
				alert("I am called after it opens: \nI am passed the jQuery object for the created Gritter element...\n" + e);
			},
			// (function | optional) function called before it closes
			before_close: function(e, manual_close){
                var manually = (manual_close) ? 'The "X" was clicked to close me!' : '';
				alert("I am called before it closes: I am passed the jQuery object for the Gritter element... \n" + manually);
			},
			// (function | optional) function called after it closes
			after_close: function(e, manual_close){
                var manually = (manual_close) ? 'The "X" was clicked to close me!' : '';
				alert('I am called after it closes. ' + manually);
			}
		});

		return false;
	});

	$('#add-sticky-with-callbacks').click(function(){

		$.gritter.add({
			// (string | mandatory) the heading of the notification
			title: 'This is a sticky notice with callbacks!',
			// (string | mandatory) the text inside the notification
			text: 'Sticky sticky notice.. sticky sticky notice...',
			// Stickeh!
			sticky: true,
			// (function | optional) function called before it opens
			before_open: function(){
				alert('I am a sticky called before it opens');
			},
			// (function | optional) function called after it opens
			after_open: function(e){
				alert("I am a sticky called after it opens: \nI am passed the jQuery object for the created Gritter element...\n" + e);
			},
			// (function | optional) function called before it closes
			before_close: function(e){
				alert("I am a sticky called before it closes: I am passed the jQuery object for the Gritter element... \n" + e);
			},
			// (function | optional) function called after it closes
			after_close: function(){
				alert('I am a sticky called after it closes');
			}
		});

		return false;

	});

	$("#remove-all").click(function(){

		$.gritter.removeAll();
		return false;

	});

	$("#remove-all-with-callbacks").click(function(){

		$.gritter.removeAll({
			before_close: function(e){
				alert("I am called before all notifications are closed.  I am passed the jQuery object containing all  of Gritter notifications.\n" + e);
			},
			after_close: function(){
				alert('I am called after everything has been closed.');
			}
		});
		return false;

	});


}


/* ---------- Additional functions for data table ---------- */
$.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings )
{
	return {
		"iStart":         oSettings._iDisplayStart,
		"iEnd":           oSettings.fnDisplayEnd(),
		"iLength":        oSettings._iDisplayLength,
		"iTotal":         oSettings.fnRecordsTotal(),
		"iFilteredTotal": oSettings.fnRecordsDisplay(),
		"iPage":          Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ),
		"iTotalPages":    Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength )
	};
}
$.extend( $.fn.dataTableExt.oPagination, {
	"bootstrap": {
		"fnInit": function( oSettings, nPaging, fnDraw ) {
			var oLang = oSettings.oLanguage.oPaginate;
			var fnClickHandler = function ( e ) {
				e.preventDefault();
				if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) {
					fnDraw( oSettings );
				}
			};

			$(nPaging).addClass('pagination').append(
				'<ul>'+
					'<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+
					'<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+
				'</ul>'
			);
			var els = $('a', nPaging);
			$(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler );
			$(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler );
		},

		"fnUpdate": function ( oSettings, fnDraw ) {
			var iListLength = 5;
			var oPaging = oSettings.oInstance.fnPagingInfo();
			var an = oSettings.aanFeatures.p;
			var i, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2);

			if ( oPaging.iTotalPages < iListLength) {
				iStart = 1;
				iEnd = oPaging.iTotalPages;
			}
			else if ( oPaging.iPage <= iHalf ) {
				iStart = 1;
				iEnd = iListLength;
			} else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) {
				iStart = oPaging.iTotalPages - iListLength + 1;
				iEnd = oPaging.iTotalPages;
			} else {
				iStart = oPaging.iPage - iHalf + 1;
				iEnd = iStart + iListLength - 1;
			}

			for ( i=0, iLen=an.length ; i<iLen ; i++ ) {
				// remove the middle elements
				$('li:gt(0)', an[i]).filter(':not(:last)').remove();

				// add the new list items and their event handlers
				for ( j=iStart ; j<=iEnd ; j++ ) {
					sClass = (j==oPaging.iPage+1) ? 'class="active"' : '';
					$('<li '+sClass+'><a href="#">'+j+'</a></li>')
						.insertBefore( $('li:last', an[i])[0] )
						.bind('click', function (e) {
							e.preventDefault();
							oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength;
							fnDraw( oSettings );
						} );
				}

				// add / remove disabled classes from the static elements
				if ( oPaging.iPage === 0 ) {
					$('li:first', an[i]).addClass('disabled');
				} else {
					$('li:first', an[i]).removeClass('disabled');
				}

				if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) {
					$('li:last', an[i]).addClass('disabled');
				} else {
					$('li:last', an[i]).removeClass('disabled');
				}
			}
		}
	}
});

/* ---------- Page width functions ---------- */

$(window).bind("resize", widthFunctions);

function widthFunctions(e) {
	
    var winHeight = $(window).height();
    var winWidth = $(window).width();

	var contentHeight = $("#content").height();

	if (winHeight) {
		
		$("#content").css("min-height",winHeight);
		
	}
	
	if (contentHeight) {
		
		$("#sidebar-left2").css("height",contentHeight);
		
	}
    
	if (winWidth < 980 && winWidth > 767) {
		
		if($("#sidebar-left").hasClass("span2")) {
			
			$("#sidebar-left").removeClass("span2");
			$("#sidebar-left").addClass("span1");
			
		}
		
		if($("#content").hasClass("span10")) {
			
			$("#content").removeClass("span10");
			$("#content").addClass("span11");
			
		}
		
		
		$("a").each(function(){
			
			if($(this).hasClass("quick-button-small span1")) {

				$(this).removeClass("quick-button-small span1");
				$(this).addClass("quick-button span2 changed");
			
			}
			
		});
		
		$(".circleStatsItem, .circleStatsItemBox").each(function() {
			
			var getOnTablet = $(this).parent().attr('onTablet');
			var getOnDesktop = $(this).parent().attr('onDesktop');
			
			if (getOnTablet) {
			
				$(this).parent().removeClass(getOnDesktop);
				$(this).parent().addClass(getOnTablet);
			
			}
			  			
		});
		
		$(".box").each(function(){
			
			var getOnTablet = $(this).attr('onTablet');
			var getOnDesktop = $(this).attr('onDesktop');
			
			if (getOnTablet) {
			
				$(this).removeClass(getOnDesktop);
				$(this).addClass(getOnTablet);
			
			}
			  			
		});
		
		$(".widget").each(function(){
			
			var getOnTablet = $(this).attr('onTablet');
			var getOnDesktop = $(this).attr('onDesktop');
			
			if (getOnTablet) {
			
				$(this).removeClass(getOnDesktop);
				$(this).addClass(getOnTablet);
			
			}
			  			
		});
		
		$(".statbox").each(function(){
			
			var getOnTablet = $(this).attr('onTablet');
			var getOnDesktop = $(this).attr('onDesktop');
			
			if (getOnTablet) {
			
				$(this).removeClass(getOnDesktop);
				$(this).addClass(getOnTablet);
			
			}
			  			
		});
							
	} else {
		
		if($("#sidebar-left").hasClass("span1")) {
			
			$("#sidebar-left").removeClass("span1");
			$("#sidebar-left").addClass("span2");
			
		}
		
		if($("#content").hasClass("span11")) {
			
			$("#content").removeClass("span11");
			$("#content").addClass("span11");
			
		}
		
		$("a").each(function(){
			
			if($(this).hasClass("quick-button span2 changed")) {

				$(this).removeClass("quick-button span2 changed");
				$(this).addClass("quick-button-small span1");
			
			}
			
		});
		
		$(".circleStatsItem, .circleStatsItemBox").each(function() {
			
			var getOnTablet = $(this).parent().attr('onTablet');
			var getOnDesktop = $(this).parent().attr('onDesktop');
			
			if (getOnTablet) {
			
				$(this).parent().removeClass(getOnTablet);
				$(this).parent().addClass(getOnDesktop);
			
			}
			  			
		});
		
		$(".box").each(function(){
			
			var getOnTablet = $(this).attr('onTablet');
			var getOnDesktop = $(this).attr('onDesktop');
			
			if (getOnTablet) {
			
				$(this).removeClass(getOnTablet);
				$(this).addClass(getOnDesktop);
			
			}
			  			
		});
		
		$(".widget").each(function(){
			
			var getOnTablet = $(this).attr('onTablet');
			var getOnDesktop = $(this).attr('onDesktop');
			
			if (getOnTablet) {
			
				$(this).removeClass(getOnTablet);
				$(this).addClass(getOnDesktop);
			
			}
			  			
		});
		
		$(".statbox").each(function(){
			
			var getOnTablet = $(this).attr('onTablet');
			var getOnDesktop = $(this).attr('onDesktop');
			
			if (getOnTablet) {
			
				$(this).removeClass(getOnTablet);
				$(this).addClass(getOnDesktop);
			
			}
			  			
		});
		
	}
	
	if($('.timeline')) {
		
		$('.timeslot').each(function(){
			
			var timeslotHeight = $(this).find('.task').outerHeight();
			
			$(this).css('height',timeslotHeight);
			
		});
		
	}

}

$(function(){  
		      
		    $("#form_login").submit(function(){
		        $.post("check_login.php",$("#form_login").serialize(),function(data){  
		            if(data==0){
		                $.noty({
								text:"เข้าระบบสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=dashboard";
						}, 2000);
		            } else if(data==1) {  
		                $.noty({
								text:"Username หรือ Password ไม่ถูกต้อง !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"รหัสภาพไม่ถูกต้อง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }  
		        });  
		        return false;  
		    });  
		      
		});

$(function(){  
		      
		    $("#form_admin").submit(function(){ 
		        $.post("admin_insert.php",$("#form_admin").serialize(),function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดต User สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=user_list";
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม User สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=user_list";
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });  
		      
		});
		    $(function () {
        		// Define the url to send the image data to
        		var url = 'files.php';
        
        		// Call the fileupload widget and set some parameters
        		$('#imgfield').fileupload({
            		url: url,
            		dataType: 'json',
            		done: function (e, data) {
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#progress').hide();
                			$('#img-list').show();
							$('#imgfield-img').removeClass("img-error").addClass( "img-success" );
                			$('#imgfield-msg').show();
                		    $('#imgfield-img').attr('src','upload/' + file.name);
                		    $('.img-link').attr('data-img', file.name);
							$('#imgfiles').attr('value', file.name);
							$('#chkimgfield').removeClass("error").addClass( "success" );
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-imgfield').hide();
                		$('#progress').show();
                		$('#progress .bar').css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});

		    $(function () {
        		// Define the url to send the image data to
        		var url = 'files_logo.php';
        
        		// Call the fileupload widget and set some parameters
        		$('#imgfieldlogo').fileupload({
            		url: url,
            		dataType: 'json',
            		done: function (e, data) {
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#progress-logo').hide();
                			$('#img-list-logo').show();
							$('#imgfield-logo-img').removeClass("img-error").addClass( "img-success" );
                			$('#imgfield-logo-msg').show();
                		    $('#imgfield-logo-img').attr('src','logo/' + file.name);
                		    $('.img-link-logo').attr('data-img', file.name);
							$('#imgfiles-logo').attr('value', file.name);
							$('#chkimgfieldlogo').removeClass("error").addClass( "success" );
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-imgfieldlogo').hide();
                		$('#progress-logo').show();
                		$('#progress-logo .bar').css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});

    		$(function () {
        		// Define the url to send the image data to
        		var url = 'files.php';
        
        		// Call the fileupload widget and set some parameters
        		$('#imgfieldlogo2').fileupload({
            		url: url,
            		dataType: 'json',
            		done: function (e, data) {
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#progress-logo').hide();
                			$('#img-list-logo').show();
							$('#imgfield-logo-img').removeClass("img-error").addClass( "img-success" );
                			$('#imgfield-logo-msg').show();
                		    $('#imgfield-logo-img').attr('src','upload/thumbnail/' + file.name);
                		    $('.img-link-logo').attr('data-img', file.name);
							$('#imgfiles-logo').attr('value', file.name);
							$('#chkimgfieldlogo').removeClass("error").addClass( "success" );
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-imgfieldlogo2').hide();
                		$('#progress-logo').show();
                		$('#progress-logo .bar').css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});

    		$(function () {
        		// Define the url to send the image data to
        		var url = 'files_logo.php';
        
        		// Call the fileupload widget and set some parameters
        		$('#imgfieldstar').fileupload({
            		url: url,
            		dataType: 'json',
            		done: function (e, data) {
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#progress-star').hide();
                			$('#img-list-star').show();
							$('#imgfield-star-img').removeClass("img-error").addClass( "img-success" );
                			$('#imgfield-star-msg').show();
                		    $('#imgfield-star-img').attr('src','logo/thumbnail/' + file.name);
                		    $('.img-link-star').attr('data-img', file.name);
							$('#imgfiles-star').attr('value', file.name);
							$('#chkimgfieldstar').removeClass("error").addClass( "success" );
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-imgfieldstar').hide();
                		$('#progress-star').show();
                		$('#progress-star .bar').css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});

    		$(function () {
        		// Define the url to send the image data to
        		var url = 'files.php';
        
        		// Call the fileupload widget and set some parameters
        		$('#imgfieldstar2').fileupload({
            		url: url,
            		dataType: 'json',
            		done: function (e, data) {
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#progress-star2').hide();
                			$('#img-list-star2').show();
							$('#imgfield-star2-img').removeClass("img-error").addClass( "img-success" );
                			$('#imgfield-star2-msg').show();
                		    $('#imgfield-star2-img').attr('src','upload/thumbnail/' + file.name);
                		    $('.img-link-star2').attr('data-img', file.name);
							$('#imgfiles-star2').attr('value', file.name);
							$('#chkimgfieldstar2').removeClass("error").addClass( "success" );
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-imgfieldstar2').hide();
                		$('#progress-star2').show();
                		$('#progress-star2 .bar').css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});

    		$(function () {
        		// Define the url to send the image data to
        		var url = 'files.php';
        
        		// Call the fileupload widget and set some parameters
        		$('#imgfield3').fileupload({
            		url: url,
            		dataType: 'json',
            		done: function (e, data) {
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#progress3').hide();
                			$('#img3-list').show();
							$('#imgfield3-img').removeClass("img-error").addClass( "img-success" );
                			$('#imgfield3-msg').show();
                		    $('#imgfield3-img').attr('src','upload/thumbnail/' + file.name);
                		    $('.img3-link').attr('data-img', file.name);
							$('#imgfiles3').attr('value', file.name);
							$('#chkimgfield3').removeClass("error").addClass( "success" );
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-imgfield3').hide();
                		$('#progress3').show();
                		$('#progress3 .bar').css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});


    		function clicked() {
    			var image_new = $('#img-show').attr('src');
    			var code_new = $('#iv_namepro').attr('value'); 
    			var period_new = $('#period').attr('value'); 
    			var agency_new = $('#eng').attr('value'); 
    			var invoice_new = $('#invoice_h').attr('value'); 
			    var myWindow = window.open('','','width=500,height=500');
			    myWindow.document.write("<html><head></head><body onload='print()'>");
			    myWindow.document.write("<center><h3>PAY-IN</h3><p>Agency : "+agency_new+"</p>");
			    myWindow.document.write("<p>Tour Code : "+code_new+"</p>");
			    myWindow.document.write("<p>Period : "+period_new+"</p>");
			    myWindow.document.write("<p>Invoice No. : BT"+invoice_new+"</p>");
			    myWindow.document.write("<img src='"+image_new+"' style='max-width: 700px; max-height: 700px; width:auto; height:auto;'/></center>");
			    myWindow.document.write("</body></html>");
			    var document_focus = false; // var we use to monitor document focused status.
		        // Now our event handlers.
		        $(document).ready(function() { myWindow.window.print(); document_focus = true; });
		        setInterval(function() { if (document_focus === true) { myWindow.window.close(); }  }, 600);
			}
			function clicked2() {
				var pid = $('#print-btn').attr('data-id');
    			var image_new = $('#print-btn').attr('href');
    			var code_new = $('#code').attr('value'); 
    			var period_new = $('#periodpass').attr('value'); 
    			var agency_new = $('#eng').attr('value'); 
    			var invoice_new = $('#bid').attr('value'); 
    			var pass_new = $('#passno'+pid).attr('value').toUpperCase(); 
			    var myWindow = window.open('','','width=500,height=500');
			    myWindow.document.write("<html><head></head><body onload='print()'>");
			    myWindow.document.write("<center><h3>CUSTOMER PASSBOOK</h3><p>Agency : "+agency_new+"</p>");
			    myWindow.document.write("<p>Tour Code : "+code_new+"</p>");
			    myWindow.document.write("<p>Period : "+period_new+"</p>");
			    myWindow.document.write("<p>Pass No : "+pass_new+"</p>");
			    myWindow.document.write("<p>BT"+invoice_new+"</p>");
			    myWindow.document.write('<img src="'+image_new+'" style="max-width: 700px; max-height: 700px; width:auto; height:auto;"></center>');
			    myWindow.document.write("</body></html>");
			    var document_focus = false; // var we use to monitor document focused status.
		        // Now our event handlers.
		        $(document).ready(function() { myWindow.window.print();document_focus = true; });
		        setInterval(function() { if (document_focus === true) { myWindow.window.close(); }  }, 300);
			}

			$(document).ready(function() {  
				    resizes();
				});
				var rtime;
				var timeout = false;
				var delta = 100;
				$(window).resize(function() {
				    rtime = new Date();
				    if (timeout === false) {
				        timeout = true;
				        setTimeout(resizeend, delta);
				    }
				});

				function resizeend() {
				    if (new Date() - rtime < delta) {
				        setTimeout(resizeend, delta);
				    } else {
				        timeout = false;      
				        resizes();
				        // console.log('Done resizing');
				    }               
				}

				function resizes() {  
					$(".resize").each(function(i, obj) {
						$(this).css("font-size", "8em");

						while ($(this).width() > $(this).parent().width()) {
							$(this).css("font-size", (parseInt($(this).css("font-size")) - 1) + "px");
						}
					});
				}
			function clicked3() {
    			var image_new = $('#img-show').attr('src');
    			var agency_new = $('#eng').attr('value');
			    var myWindow = window.open('','','width=500,height=500');
			    var ag_l = agency_new.length;
			    if(ag_l > '26'){
			    	var size = '4.5vw';
			    } else if(ag_l > '17'){
			    	var size = '5.5vw';
			    } else {
			    	var size = '9vw';
			    }
			    myWindow.document.write("<html><head><style>@page { margin: 0cm 0cm 0cm 0cm;size: landscape; }</style></head>");
			    myWindow.document.write("<body bgcolor='#ffffff' onload='print()'>");
			    myWindow.document.write("<center><table width='100%' height='100%' border='0' padding='10px'><tr><td height='50%' align='center'>");
			    myWindow.document.write("<table width='810px' height='710px' border='0' cellpadding='0'><tr><td valign='middle' align='center' bgcolor='#fff' style='padding:5px;'><img src='"+image_new+"' style='max-height:700px; width:100%; height:auto; object-fit: contain;'/></td></tr></table>");
			    // myWindow.document.write("<h1 class='resize' style='font:bold "+size+" Helvetica Neue, Helvetica, Impact, Arial, sans-serif; background: -webkit-linear-gradient(#940094, #f414b5);-webkit-background-clip: text;-webkit-text-fill-color: transparent;'>"+agency_new+"</h1></td></tr>");
			    // myWindow.document.write("<tr><td height='50%' align='center' style='border-top:0.5px solid #000;'>");
			    // myWindow.document.write("<table width='410px' height='310px' border='0' cellpadding='0' style='margin-top:15px;'><tr><td valign='middle' align='center' bgcolor='#fff' style='padding:5px;'><img src='"+image_new+"' style='max-height:300px; width:100%; height:auto; object-fit: contain;'/></td></tr></table><br>");
			      myWindow.document.write("</td></tr></table></center>");
			     myWindow.document.write("</body></html>");
			    var document_focus = false; // var we use to monitor document focused status.
		        // Now our event handlers.
		        $(document).ready(function() { myWindow.window.print();document_focus = true; });
		        setInterval(function() { if (document_focus === true) { myWindow.window.close(); }  }, 90);
			}
		    $(function(){
				$("#form_series").submit(function(){
					        $.post("series_insert.php",$("#form_series").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดต Series สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = "http://www.bestindochina.com/backend/?url=series_program_tour";
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม Series สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=series_program_tour";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});

    		$(function () {
        		// Define the url to send the image data to
        		var url = 'files_se.php';
        
        		// Call the fileupload widget and set some parameters
        		$('#seriesfield').fileupload({
            		url: url,
            		dataType: 'json',
            		done: function (e, data) {
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#progress').hide();
                			$('.attachments').show();
                		    $('.file_name').text(file.name);
                		    $('.f_download').attr('href','files/' + file.name);
							$('#seriesdata').attr('value', file.name);
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-seriesfield').hide();
                		$('#progress').show();
                		$('#progress .bar').css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});

    		$(function () {
        		// Define the url to send the image data to
        		var url = 'files_se.php';
        
        		// Call the fileupload widget and set some parameters
        		$('#seriesfield2').fileupload({
            		url: url,
            		dataType: 'json',
            		done: function (e, data) {
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#progress2').hide();
                			$('.wordfile').show();
                		    $('.file_name2').text(file.name);
                		    $('.f_download2').attr('href','files/' + file.name);
							$('#seriesdata2').attr('value', file.name);
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-seriesfield2').hide();
                		$('#progress2').show();
                		$('#progress2 .bar').css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});  

$(function(){
		    $(".img-list").hover(function(){
		    	var imgheight = $(this).height();
                $('span.text-content').css('height',imgheight);
		    });

		    $("#form_period").submit(function(){
		    	var code = $("#form_period").attr('code');
		        var allcode = 'http://www.bestindochina.com/backend/?url=period&id=' + code;
		        $.post("trip_insert.php",$("#form_period").serialize(), function(data){
		            if(data==0){
		                $.noty({
								text:"อัพเดต Period สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม Period สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
				$("#form_files").submit(function(){
					        $.post("download_insert.php",$("#form_files").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดต File สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = "http://www.bestindochina.com/backend/?url=series_program_tour";
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม File สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=series_program_tour";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});

$(function(){
				$("#form_app").submit(function(){
					        $.post("appointment_insert.php",$("#form_app").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดต Appointment สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = "http://www.bestindochina.com/backend/?url=appointment";
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม Appointment สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=appointment";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});

$(function(){
				$("#form_tag").submit(function(){
					        $.post("tag_insert.php",$("#form_tag").serialize(), function(data){
					            if(data==0){
					            		$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					    //             $.noty({
									// 		text:"อัพเดต tag สำเร็จ ! กรุณารอสักครู่...",
									// 		layout:"bottomLeft",
									// 		type:"success"
									// 		});
					    //             setTimeout(function(){
					    //             	window.location.href = "http://www.bestindochina.com/backend/?url=tag";
									// }, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม tag สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=tag";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});


$(function(){
				$("#form_ivbup").submit(function(){
					        $.post("iv_bup_insert.php",$("#form_ivbup").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดต tag สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = "http://www.bestindochina.com/backend/?url=iv_bup";
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม tag สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=iv_bup";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});



$(function(){
				$("#form_group").submit(function(){
					        $.post("group_insert.php",$("#form_group").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดต ใบรับ - จ่าย สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = "http://www.bestindochina.com/backend/?url=group_sum";
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม ใบรับ - จ่าย สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=group_sum";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});

$(function(){
				$("#form_sale").submit(function(){
					        $.post("sale_insert.php",$("#form_sale").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดตข้อมูล Sale สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = "http://www.bestindochina.com/backend/?url=sale_agency_list";
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม Sale สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=sale_agency_list";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});

$(function(){
				$("#form_pass").submit(function(){
					var code = $("#form_pass").attr('code');
		        	var allcode = 'http://www.bestindochina.com/backend/?url=passenger_booking&id=' + code;
					        $.post("pass_insert.php",$("#form_pass").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดตข้อมูล Passenger สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = allcode;
									}, 1500);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม Passenger สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = allcode;
									}, 1500);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});

$(function(){
				$("#form_tl").submit(function(){
		        	var allcode = 'http://www.bestindochina.com/backend/?url=tour_leader';
					        $.post("tl_insert.php",$("#form_tl").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดตข้อมูลหัวหน้าทัวร์ สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = allcode;
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่มหัวหน้าทัวร์ สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = allcode;
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});

$(function(){
				$("#form_agency").submit(function(){
					        $.post("agency_insert.php",$("#form_agency").serialize(), function(data){
					            if(data==0){
					            	$(document).ready(u_agency());
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม Agency สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=agency_list";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    });
			});
						function u_agency(){
					        $.post("agency_updater.php",$("#form_agency").serialize(), function(data){
					            if(data==0){
					                $.noty({
											text:"อัพเดตข้อมูล Agency สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = "http://www.bestindochina.com/backend/?url=agency_list";
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม Agency สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function () {
					                	window.location.href = "http://www.bestindochina.com/backend/?url=agency_list";
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    };

$(function(){
	$("#form_price").submit(function(){
		    	var code = $("#form_price").attr('code');
		        var allcode = 'http://www.bestindochina.com/backend/?url=price&id=' + code;
		        $.post("price_insert.php",$("#form_price").serialize(), function(data){
		            if(data==0){
		                $.noty({
								text:"อัพเดต Price สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม Price สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
		    $("#form_package").submit(function(){
		        $.post("package_insert.php",$("#form_package").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดต Program สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = "http://www.bestindochina.com/backend/?url=program";
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม Program สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=program";
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
		    $("#form_promo").submit(function(){
		        $.post("promo_insert.php",$("#form_promo").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดต Promotion สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = "http://www.bestindochina.com/backend/?url=promo";
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม Promotion สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=promo";
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
		    $("#form_app_a").submit(function(){
		        $.post("app_insert_a.php",$("#form_app_a").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดท ใบนัดหมาย สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = "http://www.bestindochina.com/backend/?url=app";
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"เพิ่ม ใบนัดหมาย สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม Program สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=app";
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
		    $("#form_app_e").submit(function(){
		    	var code = $("#form_app_e").attr('code');
		        var allcode = 'http://www.bestindochina.com/backend/?url=app_period&id=' + code;
		        $.post("app_update_a.php",$("#form_app_e").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"เพิ่ม รายละเอียดใบนัดหมาย สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม รายละเอียดใบนัดหมาย สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});


$(function(){
		    $("#form_payin").submit(function(){
		    	var code = $("#form_payin").attr('code');
		        var allcode = 'http://www.bestindochina.com/backend/?url=finance_list&id=' + code;
		        $.post("finance_insert.php",$("#form_payin").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดต Pay-in สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม Pay-in สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});


$(function(){
		    $("#form_receipt_custom").submit(function(){
		    	var code = $("#form_receipt_custom").attr('code');
		        var allcode = 'http://www.bestindochina.com/backend/?url=finance_list&id=' + code;
		        $.post("receipt_custom_insert.php",$("#form_receipt_custom").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดต receipt สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม receipt สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});


$(function(){
		    $("#form_tour").submit(function(){
		         $.post("pack_insert.php",$("#form_tour").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดต Package Tour สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = "http://www.bestindochina.com/backend/?url=package_tour";
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม Package Tour สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=package_tour";
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });

		    $('#inlineOption1').on('change', function(){
			   this.value = this.checked ? 1 : 0;
			}).change();
			$('#inlineOption2').on('change', function(){
			   this.value = this.checked ? 1 : 0;
			}).change();
			$('#inlineOption3').on('change', function(){
			   this.value = this.checked ? 1 : 0;
			}).change();
			$('#inlineOption4').on('change', function(){
			   this.value = this.checked ? 1 : 0;
			}).change();
			$('#inlineOption5').on('change', function(){
			   this.value = this.checked ? 1 : 0;
			}).change();
});


$(function(){
		    $("#form_airline").submit(function(){
		        $.post("airline_insert.php",$("#form_airline").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดตสารการบินสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = "http://www.bestindochina.com/backend/?url=airline";
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่มสายการบินสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=airline";
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
		    $("#form_ticket").submit(function(){
		    	var ap = $("#ap").val();
		    	var al = $("#al").val();
		    	var link = "http://www.bestindochina.com/backend/?url=ticket&al="+al+"&id="+ap+"";
		        $.post("ticket_insert.php",$("#form_ticket").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดตตั๋วสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = link;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่มตั๋วสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = link;
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
		    $("#form_country").submit(function(){
		        $.post("country_insert.php",$("#form_country").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดตประเทศสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = "http://www.bestindochina.com/backend/?url=country";
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่มประเทศสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=country";
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
		    $("#form_airport").submit(function(){
		        $.post("airport_insert.php",$("#form_airport").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดตสนามบินสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = "http://www.bestindochina.com/backend/?url=airport";
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่มสนามบินสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=airport";
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});


$(function(){
		    $("#form_refund").submit(function(){
		    	var code = $("#form_refund").attr('code');
		    	var allcode = 'http://www.bestindochina.com/backend/?url=finance_edit&id=' + code;
		        $.post("refund_insert.php",$("#form_refund").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดต REFUND สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม REFUND สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
		    $("#form_credit_note").submit(function(){
		    	var code = $("#form_credit_note").attr('code');
		    	var allcode = 'http://www.bestindochina.com/backend/?url=finance_edit&id=' + code;
		        $.post("creditnote_insert.php",$("#form_credit_note").serialize(), function(data){  
		            if(data==0){
		                $.noty({
								text:"อัพเดต creditnote สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$.noty({
								text:"เพิ่ม REFUND สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==3) {
		            	$.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});

$(function(){
	$("#form_book").submit(function(){
		    	var code = $("#form_book").attr('code');
		        var allcode = 'http://www.bestindochina.com/backend/?url=booking_list&adid=' + code;
		        $.post("book_insert.php",$("#form_book").serialize(), function(data){
		            if(data==0){
		                $.noty({
								text:"อัพเดต Booking สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function(){
		                	window.location.href = allcode;
						}, 2000);
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	$(document).ready(booking());
		            } else if(data==3) {
		            	$.noty({
								text:"ไม่สามารถอัพเดตจำนวนที่จองได้ กรุณาลองใหม่อีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==4) {
		            	$.noty({
								text:"จำนวนที่นั่งไม่พอสำหรับการจอง กรุณาลองใหม่อีกครั้ง",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});			
			function booking(){
					        $.post("book_sent.php",$("#form_book").serialize(), function(data){
					        	var code = $("#form_book").attr('code');
		        				var allcode = 'http://www.bestindochina.com/backend/?url=booking_list&adid=' + code;
					            if(data==0){
					                $.noty({
											text:"เพิ่ม Booking สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = allcode;
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม Booking สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = allcode;
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    };


$(function(){
	$("#form_book2").submit(function(){
		    	var code = $("#form_book2").attr('code');
		        var allcode = 'http://www.bestindochina.com/backend/?url=booking_list&adid=' + code;
		        $.post("book_updater.php",$("#form_book2").serialize(), function(data){
		            if(data==0){
						$(document).ready(booking2());
		            } else if(data==1) {
		                $.noty({
								text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==2) {
		            	
		            } else if(data==3) {
		            	$.noty({
								text:"ไม่สามารถอัพเดตจำนวนที่จองได้ กรุณาลองใหม่อีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else if(data==4) {
		            	$.noty({
								text:"จำนวนที่นั่งไม่พอสำหรับการจอง กรุณาลองใหม่อีกครั้ง",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		            	$.noty({
								text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        });  
		        return false;  
		    });
});	
	

			function booking2(){
					        $.post("book_sent.php",$("#form_book2").serialize(), function(data){
					        	var code = $("#form_book2").attr('code');
		        				var allcode = 'http://www.bestindochina.com/backend/?url=booking_list&adid=' + code;
					            if(data==0){
					                $.noty({
											text:"อัพเดต Booking สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = allcode;
									}, 2000);
					            } else if(data==1) {
					                $.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else if(data==2) {
					            	$.noty({
											text:"เพิ่ม Booking สำเร็จ ! กรุณารอสักครู่...",
											layout:"bottomLeft",
											type:"success"
											});
					                setTimeout(function(){
					                	window.location.href = allcode;
									}, 2000);
					            } else if(data==3) {
					            	$.noty({
											text:"กรุณากรอกข้อมูลให้ครบถ้วน !",
											layout:"bottomLeft",
											type:"error"
											});
					            } else {
					            	$.noty({
											text:"ระบบขัดข้องกรุณาแจ้งผู้ดูแลเว็บไซต์ !",
											layout:"bottomLeft",
											type:"error"
											});
					            }
					        });  
					        return false;  
					    };

$(function(){  

			$('#receipt_btn').click(function(e) {
			   var data = $(this).attr('data-id');
			   var href = $(this).attr('href');
			   e.preventDefault();
			   $.redirect(href, {'re_id': data}, "POST", "_blank");
			   /*$.post('https://receipt.best-consortium.com', {'re_id': $this.attr('data-id')}, function() {
			       window.location = $this.attr('href');
			   });*/
			});

			$('#receipt_copy_btn').click(function(e) {
			   var data = $(this).attr('data-id');
			   var href = $(this).attr('href');
			   e.preventDefault();
			   $.redirect(href, {'re_id': data}, "POST", "_blank");
			   /*$.post('https://receipt.best-consortium.com', {'re_id': $this.attr('data-id')}, function() {
			       window.location = $this.attr('href');
			   });*/
			});
		      
		    $(".user_del").click(function(){ 
		    	var admin_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + admin_id;
		    	var allid = 'id=' + admin_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"admin_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ User สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=user_list";
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });  

			$(".program_del").click(function(){ 
		    	var program_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + program_id;
		    	var allid = 'id=' + program_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"package_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ Program Tour สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	window.location.href = "http://www.bestindochina.com/backend/?url=program";
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".period_del").click(function(){ 
		    	var period_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + period_id;
		    	var allid = 'id=' + period_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"trip_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ Period สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".price_del").click(function(){ 
		    	var price_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + price_id;
		    	var allid = 'id=' + price_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"price_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ Price สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		     $(".tl_del").click(function(){ 
		    	var tl_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + tl_id;
		    	var allid = 'id=' + tl_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"tl_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบหัวหน้าทัวร์ สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".pass_del").click(function(){ 
		    	var pass_id = $(this).attr('id');
		    	var allid = 'id=' + pass_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"pass_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบพาสปอร์ต สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 1500);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".app_del").click(function(){ 
		    	var app_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + app_id;
		    	var allid = 'id=' + app_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"appointment_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบใบนัดหมาย สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".agency_del").click(function(){ 
		    	var agency_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + agency_id;
		    	var allid = 'id=' + agency_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"agency_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ Agency สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".sale_agency_del").click(function(){ 
		    	var s_agency_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + s_agency_id;
		    	var allid = 'id=' + s_agency_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"sale_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ Sale สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".book_del").click(function(){ 
		    	var b_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + b_id;
		    	var allid = 'id=' + b_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"book_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบใบจองสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".book_cancel").click(function(){ 
		    	var b_id = $(this).attr('id');
		    	var allid = 'id=' + b_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"book_cancel.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ยกเลิกใบจองสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                location.reload();
		            } else if(data==1){
		                $.noty({
								text:"เพิ่มข้อมูลไม่ได้ !",
								layout:"bottomLeft",
								type:"error"
								});
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".book_cant").click(function(){ 
		    	var b_id = $(this).attr('id');
		    	var allid = 'id=' + b_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"book_cant.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"เปลี่ยนสถานะใบจองสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $("#passno").keyup(function(){	
			var admin_user = $('#passno').val();
			var english = /^[A-Za-z0-9]*$/;
			if(!english.test(admin_user)){
				$("#chkpassno").removeClass("success").addClass("error");
				$("#passno-msg").text("กรุณากรอกเป็นตัวอักษร a-z หรือเลข 0-9 เท่านั้น !");
				setTimeout(function () {
					                	$('#admin_user').val('');
									}, 1500);

			} else {

			jQuery.ajax({
			   type: "POST",
			   url: "checkpass.php",
			   data: 'passnum='+ admin_user,
			   cache: false,
			   success: function(data){ 
				$('#checkpass').html(data);
				$("#chkpassno").removeClass("error").addClass("success");
				$("#passno-msg").empty();
				$("#sex").chosen();
				$("#tname").chosen();
				$("#tnameth").chosen();
				$(".datepicker").datepicker();
				$('#doi').change(function(){
					var valdate = $('#doi').val();
					var expdate = newDayAdd(valdate,5);
					$("#doe").val(expdate);
				});
			}
			});}});

		    $(".country_del").click(function(){ 
		    	var country_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + country_id;
		    	var allid = 'id=' + country_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"country_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบประเทศสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".airline_del").click(function(){ 
		    	var airline_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + airline_id;
		    	var allid = 'id=' + airline_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"airline_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบสายการบินสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });


		    $(".tag_del").click(function(){ 
		    	var tag_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + tag_id;
		    	var allid = 'id=' + tag_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"tag_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ tag สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });


		    $(".airport_del").click(function(){ 
		    	var airport_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + airport_id;
		    	var allid = 'id=' + airport_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"airport_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบสนามบินสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".upload_del").click(function(){ 
		    	var upload_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + upload_id;
		    	var allid = 'id=' + upload_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"download_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบไฟล์สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".package_del").click(function(){ 
		    	var package_id = $(this).attr('id');
		    	var href = $(this).attr('href');
		    	var allis = href + package_id;
		    	var allid = 'id=' + package_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"pack_delete.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบแพ็กเกจทัวร์สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 2000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    if (window.innerWidth > 767) {
		     $("body").on('click','.noti_btn',function(){ 
		    	var notifi_id = $(this).attr('data-id');
		    	var code = $(this).attr('code');
		    	var allcode = 'http://www.bestindochina.com/backend/?url=' + code;
		    	var allid = 'id=' + notifi_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"noti_update.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           	if(data==0){
		           		$.ajax({
								url: "https://www.bestindochina.com/backend/notification_all.php" ,
								type: "GET",
								data: ''
							}).success(function(obj) {
								var table = '';
								if(obj != ''){
									$.each(obj, function(key, val) {
										table += '<li>';
										table += '<a href="#" code="'+val['ses']+'" class="'+val['btclass']+'" data-id="'+val['dataid']+'">';
										table += '<span class="from">';
										table += '<table cellpadding="0" border="0" cellspacing="0" style="float:left; margin-right:10px;">';
										table += '<tr>';
										table += '<td style="background-color:#fff; text-align:center; width:40px; height:40px;">';
										table += '<img src="'+val['agentpic']+'" style="max-height:40px !important; max-width:40px !important; height:auto !important; width:auto !important; margin:0 !important; float:none !important;">';
										table += '</td>';
										table += '</tr>';
										table += '</table>';
										table += ''+val['new']+' '+val['asname']+'';
										table += '</span>';
										table += '<span class="title"> '+val['status_m']+''+val['status_c']+'</span>';
										table += '<span class="date">';
										table += ''+val['time']+', <b>'+val['hour']+':'+val['min']+'</b>';
										table += '</span></a></li>';
									});
								}
								$("ul.messagesList").html(table);
							});
						var redirectWindow = window.open(allcode, '_blank');
						redirectWindow.location;
		            }
		        }
		        });
		        return false;  
		    });
		 } else {
		 	$("body").on('click','.noti_btn',function(){ 
		    	var notifi_id = $(this).attr('data-id');
		    	var code = $(this).attr('code');
		    	var allcode = 'http://www.bestindochina.com/backend/?url=' + code;
		    	var allid = 'id=' + notifi_id;
		        jQuery.ajax({
		        	method:"POST",
		        	url:"noti_update.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           	if(data==0){
						window.location.href = allcode
		            }
		        }
		        });
		        return false;  
		    });
		 }

		    $('table').on('click','.sentmail',function(){ 
		    	var send_mail_id = $(this).attr('id');
		        jQuery.ajax({
		        	method:"POST",
		        	url:"mail.php",
		        	dataType:"text",
					data:{id: send_mail_id},
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ส่ง Email สำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								});
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $("table").on('click', '.changestatus', function(){ 
		    	var change_stat = $(this).attr('status');
		    	var change_id = $(this).attr('id');
		        jQuery.ajax({
		        	method:"POST",
		        	url:"trip_status.php",
		        	dataType:"text",
					data: {status: change_stat, id: change_id},
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"เปลี่ยนสถานะสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 1000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $("table").on('click', '.addTHX', function(){
		    	var agent_id = $(this).attr('id');
		        jQuery.ajax({
		        	method:"POST",
		        	url:"addthx.php",
		        	dataType:"text",
					data: {id: agent_id},
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"เพิ่มสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $("table").on('click', '.changeof', function(){ 
		    	var change_wstat = $(this).attr('wstatus');
		    	var change_wid = $(this).attr('wid');
		        jQuery.ajax({
		        	method:"POST",
		        	url:"trip_ex.php",
		        	dataType:"text",
					data: {status: change_wstat, id: change_wid},
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"เปลี่ยนสถานะสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 1000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $("div").on('click', '.changestatus_u', function(){
		    	var change_stat = $(this).attr('status');
		    	var change_id = $(this).attr('id');
		        jQuery.ajax({
		        	method:"POST",
		        	url:"agency_status.php",
		        	dataType:"text",
					data: {status: change_stat, id: change_id},
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"เปลี่ยนสถานะสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 1000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });
            

 		    $("div").on('click', '.changestatus_app', function(){
		    	var change_stat = $(this).attr('status');
		    	var change_id = $(this).attr('id');
		        jQuery.ajax({
		        	method:"POST",
		        	url:"app_status.php",
		        	dataType:"text",
					data: {status: change_stat, id: change_id},
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"เปลี่ยนสถานะสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 1000);
		            } else {
		                $.noty({
								text:"กรุณาเพิ่มรายละเอียดใบนัดหมายก่อน !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

 		    $("div").on('click', '.changestatusticket', function(){
		    	var change_stat = $(this).attr('status');
		    	var change_id = $(this).attr('id');
		        jQuery.ajax({
		        	method:"POST",
		        	url:"changestatusticket.php",
		        	dataType:"text",
					data: {status: change_stat, id: change_id},
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"เปลี่ยนสถานะสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 1000);
		            } else {
		                $.noty({
								text:"กรุณาเพิ่มรายละเอียดใบนัดหมายก่อน !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });
                $("div").on('click', '.cstatus_profit', function(){
		    	var change_stat = $(this).attr('status');
		    	var change_id = $(this).attr('id');
		        jQuery.ajax({
		        	method:"POST",
		        	url:"sum_sale_status.php",
		        	dataType:"text",
					data: {status: change_stat, id: change_id},
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"เปลี่ยนสถานะสำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
								});
		                setTimeout(function () {
		                	location.reload();
						}, 1000);
		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  
		        return false;  
		    });

		    $(".img-del").click(function(){ 
		    	var img_id = $('#imgfiles').attr('value');
		    	var allid = 'id=' + img_id;
		    	var con = confirm('ต้องการจะลบรูปนี้ ?');
		    	if(con){
		        jQuery.ajax({
		        	method:"POST",
		        	url:"pic_del.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบรูปสำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								})
		                $('#uniform-imgfield').show();
		                $('#imgfield').show();
		                $('#img-list').hide();
		                $('#progress').hide();
						$('#imgfield-img').removeClass("img-success");
                		$('#imgfield-msg').hide();
                		$('#imgfield-img').attr('src', '');
						$('#imgfiles').attr('value', '1');
						$('#chkimgfield').removeClass("success");
						$(".filename").text('No file selected');

		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });
		    }
		        return false;  
		    });

		    $(".img3-del").click(function(){ 
		    	var img_id = $('#imgfiles3').attr('value');
		    	var allid = 'id=' + img_id;
		    	var con = confirm('ต้องการจะลบรูปนี้ ?');
		    	if(con){
		        jQuery.ajax({
		        	method:"POST",
		        	url:"pic_del.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบรูปสำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								})
		                $('#uniform-imgfield3').show();
		                $('#imgfield3').show();
		                $('#img3-list').hide();
		                $('#progress3').hide();
						$('#imgfield3-img').removeClass("img-success");
                		$('#imgfield3-msg').hide();
                		$('#imgfield3-img').attr('src', '');
						$('#imgfiles3').attr('value', '1');
						$('#chkimgfield3').removeClass("success");
						$(".filename").text('No file selected');

		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });
		    }
		        return false;  
		    });

		    $(".img-logo-del").click(function(){ 
		    	var img_id = $('#imgfiles-logo').attr('value');
		    	var allid = 'id=' + img_id;
		    	var con = confirm('ต้องการจะลบรูปนี้ ?');
		    	if(con){
		        jQuery.ajax({
		        	method:"POST",
		        	url:"logo_del.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบโลโก้สำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								})
		                $('#uniform-imgfieldlogo').show();
		                $('#uniform-imgfieldlogo2').show();
		                $('#imgfieldlogo').show();
		                $('#imgfieldlogo2').show();
		                $('#img-list-logo').hide();
		                $('#progress-logo').hide();
						$('#imgfield-logo-img').removeClass("img-success");
                		$('#imgfield-logo-msg').hide();
                		$('#imgfield-logo-img').attr('src', '');
						$('#imgfiles-logo').attr('value', '');
						$('#chkimgfieldlogo').removeClass("success");
						$(".filename").text('No file selected');

		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        }); 
		    } 
		        return false;  
		    }); 

		    $(".img-logo-del2").click(function(){ 
		    	var img_id = $('#imgfiles-logo').attr('value');
		    	var allid = 'id=' + img_id;
		    	var con = confirm('ต้องการจะลบรูปนี้ ?');
		    	if(con){
		        jQuery.ajax({
		        	method:"POST",
		        	url:"pic_del.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบโลโก้สำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								})
		                $('#uniform-imgfieldlogo2').show();
		                $('#imgfieldlogo2').show();
		                $('#img-list-logo').hide();
		                $('#progress-logo').hide();
						$('#imgfield-logo-img').removeClass("img-success");
                		$('#imgfield-logo-msg').hide();
                		$('#imgfield-logo-img').attr('src', '');
						$('#imgfiles-logo').attr('value', '1');
						$('#chkimgfieldlogo').removeClass("success");
						$(".filename").text('No file selected');

		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  }
		        return false;  
		    });

		    $(".img-star-del").click(function(){ 
		    	var img_id = $('#imgfiles-star').attr('value');
		    	var allid = 'id=' + img_id;
		    	var con = confirm('ต้องการจะลบรูปนี้ ?');
		    	if(con){
		        jQuery.ajax({
		        	method:"POST",
		        	url:"logo_del.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบโลโก้ 5 ดาว สำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								})
		                $('#uniform-imgfieldstar').show();
		                $('#imgfieldstar').show();
		                $('#img-list-star').hide();
		                $('#progress-star').hide();
						$('#imgfield-star-img').removeClass("img-success");
                		$('#imgfield-star-msg').hide();
                		$('#imgfield-star-img').attr('src', '');
						$('#imgfiles-star').attr('value', '');
						$('#chkimgfieldstar').removeClass("success");
						$(".filename").text('No file selected');

		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  }
		        return false;  
		    }); 

			$(".img-star2-del").click(function(){ 
		    	var img_id = $('#imgfiles-star2').attr('value');
		    	var allid = 'id=' + img_id;
		    	var con = confirm('ต้องการจะลบรูปนี้ ?');
		    	if(con){
		        jQuery.ajax({
		        	method:"POST",
		        	url:"pic_del.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบแบนเนอร์ 5ดาว สำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								})
		                $('#uniform-imgfieldstar2').show();
		                $('#imgfieldstar2').show();
		                $('#img-list-star2').hide();
		                $('#progress-star2').hide();
						$('#imgfield-star2-img').removeClass("img-success");
                		$('#imgfield-star2-msg').hide();
                		$('#imgfield-star2-img').attr('src', '');
						$('#imgfiles-star2').attr('value', '');
						$('#chkimgfieldstar2').removeClass("success");
						$(".filename").text('No file selected');

		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  }
		        return false;  
		    }); 

		    $(".remove_file").click(function(){ 
		    	var file_id = $('#seriesdata').attr('value');
		    	var allid = 'id=' + file_id;
		    	var con = confirm('ต้องการจะลบรูปนี้ ?');
		    	if(con){
		        jQuery.ajax({
		        	method:"POST",
		        	url:"file_del.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ PDF FILE สำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								});
		                $('#uniform-seriesfield').show();
		                $('#seriesfield').show();
		                $('.attachments').hide();
		                $('#progress').hide();
                		$('.f_download').attr('href', '');
						$('#seriesdata').attr('value', '');
						$(".filename").text('No file selected');

		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  }
		        return false;  
		    });

		    $(".remove_file2").click(function(){ 
		    	var file_id = $('#seriesdata2').attr('value');
		    	var allid = 'id=' + file_id;
		    	var con = confirm('ต้องการจะลบรูปนี้ ?');
		    	if(con){
		        jQuery.ajax({
		        	method:"POST",
		        	url:"file_del.php",
		        	dataType:"text",
					data:allid,
					cache:false,
		        	success:function(data){
		           if(data==0){
		                $.noty({
								text:"ลบ WORD FILE สำเร็จ !",
								layout:"bottomLeft",
								type:"success"
								});
		                $('#uniform-seriesfield2').show();
		                $('#seriesfield2').show();
		                $('.wordfile').hide();
		                $('#progress2').hide();
                		$('.f_download2').attr('href', '');
						$('#seriesdata2').attr('value', '');
						$(".filename").text('No file selected');

		            } else {
		                $.noty({
								text:"ข้อมูลผิดพลาดกรุณาลองอีกครั้ง !",
								layout:"bottomLeft",
								type:"error"
								});
		            }
		        }
		        });  }
		        return false;  
		    });   

		    $(".i-del").hover(
		    	function() {
		    		$(this).removeClass('icon-times-circle-o');
					$(this).addClass('icon-times-circle');
				}, function() {
				    $(this).removeClass('icon-times-circle');
				    $(this).addClass('icon-times-circle-o');
				});

		    $(".i-ext").hover(
		    	function() {
		    		$(this).removeClass('icon-arrow-circle-o-right');
					$(this).addClass('icon-arrow-circle-right');
				}, function() {
				    $(this).removeClass('icon-arrow-circle-right');
				    $(this).addClass('icon-arrow-circle-o-right');
				});
		    $(".i-pass").hover(
		    	function() {
		    		$(this).removeClass('icon-arrow-circle-o-right');
					$(this).addClass('icon-arrow-circle-right');
				}, function() {
				    $(this).removeClass('icon-arrow-circle-right');
				    $(this).addClass('icon-arrow-circle-o-right');
				});
		    $(".i-img").hover(
		    	function() {
		    		$(this).removeClass('icon-arrow-circle-o-right');
					$(this).addClass('icon-arrow-circle-right');
				}, function() {
				    $(this).removeClass('icon-arrow-circle-right');
				    $(this).addClass('icon-arrow-circle-o-right');
				});
		    $(".i-ext-logo").hover(
		    	function() {
		    		$(this).removeClass('icon-arrow-circle-o-right');
					$(this).addClass('icon-arrow-circle-right');
				}, function() {
				    $(this).removeClass('icon-arrow-circle-right');
				    $(this).addClass('icon-arrow-circle-o-right');
				});
		    $(".i-ext-logo2").hover(
		    	function() {
		    		$(this).removeClass('icon-arrow-circle-o-right');
					$(this).addClass('icon-arrow-circle-right');
				}, function() {
				    $(this).removeClass('icon-arrow-circle-right');
				    $(this).addClass('icon-arrow-circle-o-right');
				});
		    $(".i-ext-star2").hover(
		    	function() {
		    		$(this).removeClass('icon-arrow-circle-o-right');
					$(this).addClass('icon-arrow-circle-right');
				}, function() {
				    $(this).removeClass('icon-arrow-circle-right');
				    $(this).addClass('icon-arrow-circle-o-right');
				});
		    $(".i-ext-logo").click(function(){
		    	var link_img = $(".img-link-logo").attr('data-img');
		    	var all_link = 'logo/' + link_img;
		    	$('#myModal').modal('show');
		    	$('#img-show').attr('src', all_link);
		    	$('#print-btn').attr('href', all_link);
		    });
		    $(".i-ext-logo2").click(function(){
		    	var link_img = $(".img-link-logo").attr('data-img');
		    	var all_link = 'upload/' + link_img;
		    	$('#myModal').modal('show');
		    	$('#img-show').attr('src', all_link);
		    	$('#print-btn').attr('href', all_link);
		    });
		    $(".i-ext-star2").click(function(){
		    	var link_img = $(".img-link-star2").attr('data-img');
		    	var all_link = 'upload/' + link_img;
		    	$('#myModal').modal('show');
		    	$('#img-show').attr('src', all_link);
		    	$('#print-btn').attr('href', all_link);
		    });
		    $(".i-ext").click(function(){
		    	var link_img = $(".img-link").attr('data-img');
		    	var all_link = 'upload/' + link_img;
		    	$('#myModal').modal('show');
		    	$('#img-show').attr('src', all_link);
		    	$('#print-btn').attr('href', all_link);
		    });
		    $(".i-promo").click(function(){
		    	var link_img = $(".promo-img-link").attr('data-img');
		    	var all_link = 'https://static.best-consortium.com/content/images/promotion/' + link_img;
		    	$('#myModal').modal('show');
		    	$('#img-show').attr('src', all_link);
		    	$('#print-btn').attr('href', all_link);
		    });
		    $(".i-ext3").click(function(){
		    	var link_img = $(".img3-link").attr('data-img');
		    	var all_link = 'upload/' + link_img;
		    	$('#myModal').modal('show');
		    	$('#img-show').attr('src', all_link);
		    	$('#print-btn').attr('href', all_link);
		    });
		    $(".i-pass").click(function(){
		    	var link_img = $(this).attr('data-img');
		    	var pid = $(this).attr('data-id');
		    	var folder = $(this).attr('folder');
		    	var all_link = folder+'/'+link_img;
		    	$('#myModal').modal('show');
		    	$('#img-show').attr('src', all_link);
		    	$('#print-btn').attr('href', all_link);
		    	$('#print-btn').attr('data-id', pid);
		    });
		    $("table").on('click','.link',function(){
		    	var all_link = $(this).attr('data-href');
		    	$('#myModal').modal('show');
		    	$('.tl_btn').attr('data-href', all_link);
		    });
		    $('#tourlead').change(function(){
		    	var sval = $('#tourlead').chosen().val();
		    	var href = $('.tl_btn').attr('data-href');
		    	if(sval != '0'){
		    	var link = href+'&tl='+sval
		    	$('.tl_btn').attr('href', link);
		    	} else {
		    	$('.tl_btn').attr('href', '#');
		    	}
		    });
		    $('#tourlead2').change(function(){
		    	var sval = $('#tourlead2').chosen().val();
		    	var href = $('.tl_btn').attr('href');
		    	if(sval != '0'){
		    	var link = href+'&tl2='+sval
		    	$('.tl_btn').attr('href', link);
		    	} else {
		    	$('.tl_btn').attr('href', '#');
		    	}
		    });
		    $('#agen').change(function(){
		    	var sval = $('#agen').chosen().val();
		    	var href = $('.tl_btn').attr('href');
		    	if(sval != '0'){
		    	var link = href+'&agen='+sval
		    	$('.tl_btn').attr('href', link);
		    	} else {
		    	$('.tl_btn').attr('href', '#');
		    	}
		    });
		    $('#agency_appm').change(function(){
		    	var sval = $('#agency_appm').chosen().val();
		    	var href = $('.tl_btn').attr('data-href');
		    	if(sval != '0'){
		    	var link = href+'&agenapp='+sval
		    	$('.tl_btn').attr('href', link);
		    	} else {
		    	$('.tl_btn').attr('href', '#');
		    	}
		    });
		    $(".tl_btn").click(function(){
		    	var all_link = $(this).attr('href');
		    	if(all_link != '#'){
		    		window.open(all_link,'_blank');
		    		location.reload();
		    	}
		    });
		});

$(document).ready(function(){
	$('.del-error').click(function(){ 
		noty({
			text:"User นี้มีการใช้งานอยู่ ไม่สามารถลบได้ !",
			layout:"bottomLeft",
			type:"error"
			}); 
	});

		$('.controls').on('change','#adult',function(){ 
		    	var a_id = +$('#adult').chosen().val();
		    	var c_id = +$('#child').chosen().val(); 
		    	var cb_id = +$('#child_bed').chosen().val(); 
		    	var i_id = +$('#infant').chosen().val();
		    	var j_id = +$('#join').chosen().val();
		    	var count = +$('#count_val').val();
		    	var sum = a_id+c_id+cb_id+i_id;
		    	if(sum > count){
		    		$("#chkadult").removeClass("success").addClass( "error" );
		    		$("#chkchild").removeClass("success").addClass( "error" );
		    		$("#chkchild_bed").removeClass("success").addClass( "error" );
		    		$("#chkinfant").removeClass("success").addClass( "error" );
		    		$("#chkjoin").removeClass("success").addClass( "error" );
		    		$("#adult-msg").text("เลือกเกินจำนวนที่ว่างอยู่ กรุณาเลือกใหม่ !");
		    	} else {
		    		$("#chkadult").removeClass("error").addClass( "success" );
					$("#adult-msg").empty();
					$("#chkchild").removeClass("error").addClass( "success" );
					$("#child-msg").empty();
					$("#chkchild_bed").removeClass("error").addClass( "success" );
					$("#child_bed-msg").empty();
					$("#chkinfant").removeClass("error").addClass( "success" );
					$("#infant-msg").empty();
					$("#chkjoin").removeClass("error").addClass( "success" );
					$("#join-msg").empty();
					$('#p_adult_a').attr('value', a_id);
					sum_a();
					sum_all();
		    	}
	});

		$('.controls').on('change','#child',function(){ 
		    	var a_id = +$('#adult').chosen().val();
		    	var c_id = +$('#child').chosen().val(); 
		    	var cb_id = +$('#child_bed').chosen().val(); 
		    	var i_id = +$('#infant').chosen().val();
		    	var j_id = +$('#join').chosen().val();
		    	var count = +$('#count_val').val();
		    	var sum = a_id+c_id+cb_id+i_id;
		    	if(sum > count){
		    		$("#chkadult").removeClass("success").addClass( "error" );
		    		$("#chkchild").removeClass("success").addClass( "error" );
		    		$("#chkchild_bed").removeClass("success").addClass( "error" );
		    		$("#chkinfant").removeClass("success").addClass( "error" );
		    		$("#chkjoin").removeClass("success").addClass( "error" );
		    		$("#child-msg").text("เลือกเกินจำนวนที่ว่างอยู่ กรุณาเลือกใหม่ !");
		    	} else {
		    		$("#chkadult").removeClass("error").addClass( "success" );
					$("#adult-msg").empty();
					$("#chkchild").removeClass("error").addClass( "success" );
					$("#child-msg").empty();
					$("#chkchild_bed").removeClass("error").addClass( "success" );
					$("#child_bed-msg").empty();
					$("#chkinfant").removeClass("error").addClass( "success" );
					$("#infant-msg").empty();
					$("#chkjoin").removeClass("error").addClass( "success" );
					$("#join-msg").empty();
					$('#p_child_a').attr('value', c_id);
					sum_c();
					sum_all();
		    	}
	});

		$('.controls').on('change','#child_bed',function(){ 
		    	var a_id = +$('#adult').chosen().val();
		    	var c_id = +$('#child').chosen().val(); 
		    	var cb_id = +$('#child_bed').chosen().val(); 
		    	var i_id = +$('#infant').chosen().val();
		    	var j_id = +$('#join').chosen().val();
		    	var count = +$('#count_val').val();
		    	var sum = a_id+c_id+cb_id+i_id;
		    	if(sum > count){
		    		$("#chkadult").removeClass("success").addClass( "error" );
		    		$("#chkchild").removeClass("success").addClass( "error" );
		    		$("#chkchild_bed").removeClass("success").addClass( "error" );
		    		$("#chkinfant").removeClass("success").addClass( "error" );
		    		$("#chkjoin").removeClass("success").addClass( "error" );
		    		$("#child_bed-msg").text("เลือกเกินจำนวนที่ว่างอยู่ กรุณาเลือกใหม่ !");
		    	} else {
		    		$("#chkadult").removeClass("error").addClass( "success" );
					$("#adult-msg").empty();
					$("#chkchild").removeClass("error").addClass( "success" );
					$("#child-msg").empty();
					$("#chkchild_bed").removeClass("error").addClass( "success" );
					$("#child_bed-msg").empty();
					$("#chkinfant").removeClass("error").addClass( "success" );
					$("#infant-msg").empty();
					$("#chkjoin").removeClass("error").addClass( "success" );
					$("#join-msg").empty();
					$('#p_child_bed_a').attr('value', cb_id);
					sum_cb();
					sum_all();
		    	}
	});

		$('.controls').on('change','#infant',function(){ 
		    	var a_id = +$('#adult').chosen().val();
		    	var c_id = +$('#child').chosen().val(); 
		    	var cb_id = +$('#child_bed').chosen().val(); 
		    	var i_id = +$('#infant').chosen().val();
		    	var j_id = +$('#join').chosen().val();
		    	var count = +$('#count_val').val();
		    	var sum = a_id+c_id+cb_id+i_id;
		    	if(sum > count){
		    		$("#chkadult").removeClass("success").addClass( "error" );
		    		$("#chkchild").removeClass("success").addClass( "error" );
		    		$("#chkchild_bed").removeClass("success").addClass( "error" );
		    		$("#chkinfant").removeClass("success").addClass( "error" );
		    		$("#chkjoin").removeClass("success").addClass( "error" );
		    		$("#infant-msg").text("เลือกเกินจำนวนที่ว่างอยู่ กรุณาเลือกใหม่ !");
		    	} else {
		    		$("#chkadult").removeClass("error").addClass( "success" );
					$("#adult-msg").empty();
					$("#chkchild").removeClass("error").addClass( "success" );
					$("#child-msg").empty();
					$("#chkchild_bed").removeClass("error").addClass( "success" );
					$("#child_bed-msg").empty();
					$("#chkinfant").removeClass("error").addClass( "success" );
					$("#infant-msg").empty();
					$("#chkjoin").removeClass("error").addClass( "success" );
					$("#join-msg").empty();
					$('#p_infant_a').attr('value', i_id);
					sum_i();
					sum_all();
		    	}
	});

		$('.controls').on('change','#join',function(){ 
		    	var a_id = +$('#adult').chosen().val();
		    	var c_id = +$('#child').chosen().val(); 
		    	var cb_id = +$('#child_bed').chosen().val(); 
		    	var i_id = +$('#infant').chosen().val();
		    	var j_id = +$('#join').chosen().val();
		    	var count = +$('#count_val').val();
		    	var sum = a_id+c_id+cb_id+i_id;
		    	if(sum > count){
		    		$("#chkadult").removeClass("error").addClass( "success" );
					$("#adult-msg").empty();
					$("#chkchild").removeClass("error").addClass( "success" );
					$("#child-msg").empty();
					$("#chkchild_bed").removeClass("error").addClass( "success" );
					$("#child_bed-msg").empty();
					$("#chkinfant").removeClass("error").addClass( "success" );
					$("#infant-msg").empty();
					$("#chkjoin").removeClass("error").addClass( "success" );
					$("#join-msg").empty();
					$('#p_join_a').attr('value', j_id);
					sum_j();
					sum_all();
		    	} else {
		    		$("#chkadult").removeClass("error").addClass( "success" );
					$("#adult-msg").empty();
					$("#chkchild").removeClass("error").addClass( "success" );
					$("#child-msg").empty();
					$("#chkchild_bed").removeClass("error").addClass( "success" );
					$("#child_bed-msg").empty();
					$("#chkinfant").removeClass("error").addClass( "success" );
					$("#infant-msg").empty();
					$("#chkjoin").removeClass("error").addClass( "success" );
					$("#join-msg").empty();
					$('#p_join_a').attr('value', j_id);
					sum_j();
					sum_all();
		    	}
	});

		$('.controls').on('change','#sgl',function(){ 
					var s_id = +$('#sgl').chosen().val();
					$('#p_single_a').attr('value', s_id);
					sum_s();
					sum_all();
	});

		$('.controls').on('change','#visa',function(){ 
					var v_id = +$('#visa').chosen().val();
					$('#p_visa_a').attr('value', v_id);
					sum_v();
					sum_all();
	});

		$('.controls').on('change','#disney',function(){ 
					var d_id = +$('#disney').chosen().val();
					$('#p_disney_a').attr('value', d_id);
					sum_d();
					sum_all();
	});

		$('.controls').on('change','#ticket',function(){ 
					var t_id = +$('#ticket').chosen().val();
					$('#p_ticket_a').attr('value', t_id);
					sum_t();
					sum_all();
	});

		$('.controls').on('change','#foreign',function(){ 
		    	var a_id = +$('#adult').chosen().val();
		    	var c_id = +$('#child').chosen().val(); 
		    	var cb_id = +$('#child_bed').chosen().val(); 
		    	var i_id = +$('#infant').chosen().val();
		    	var j_id = +$('#join').chosen().val();
		    	var f_id = +$('#foreign').chosen().val();
		    	var sum = a_id+c_id+cb_id+i_id;
		    	if(f_id > sum){
		    		$("#chkforeign").removeClass("success").addClass( "error" );
		    		$("#foreign-msg").text("เลือกเกินจำนวนที่เลือกไว้ด้านบน กรุณาเลือกใหม่ !");
		    	} else {
		    		$("#chkforeign").removeClass("error").addClass( "success" );
					$("#foreign-msg").empty();
		    	}
	});

		$('#doi').change(function(){
			var valdate = $('#doi').val();
			var expdate = newDayAdd(valdate,5);
			$("#doe").val(expdate);
		});
});

function newDayAdd(inputDate,addYear){
    var d = new Date(inputDate);
    d.setFullYear(d.getFullYear()+addYear);
    d.setDate(d.getDate()-1);
	mkMonth=d.getMonth()+1;
	mkMonth=new String(mkMonth);
	if(mkMonth.length==1){
		mkMonth="0"+mkMonth;
	}
	mkDay=d.getDate();
	mkDay=new String(mkDay);
	if(mkDay.length==1){
		mkDay="0"+mkDay;
	}	
	mkYear=d.getFullYear();
	mkYear=new String(mkYear);
//	return mkYear+"-"+newMonth+"-"+newDay; // แสดงผลลัพธ์ในรูปแบบ ปี-เดือน-วัน
	return mkMonth+"/"+mkDay+"/"+mkYear; // แสดงผลลัพธ์ในรูปแบบ เดือน/วัน/ปี	
}

//-------- SUM ----------\\
$('.controls').on('change','#trip',function(){ 
		           	$('#p_adult').attr('value','0');
		           	$('#p_adult_a').attr('value','0');
		           	$('#p_adult_s').attr('value','0');
		           	$('#p_child').attr('value','0');
		           	$('#p_child_a').attr('value','0');
		           	$('#p_child_s').attr('value','0');
		           	$('#p_child_bed').attr('value','0');
		           	$('#p_child_bed_a').attr('value','0');
		           	$('#p_child_bed_s').attr('value','0');
		           	$('#p_infant').attr('value','0');
		           	$('#p_infant_a').attr('value','0');
		           	$('#p_infant_s').attr('value','0');
		           	$('#p_join').attr('value','0');
		           	$('#p_join_a').attr('value','0');
		           	$('#p_join_s').attr('value','0');
		           	$('#p_single').attr('value','0');
		           	$('#p_single_a').attr('value','0');
		           	$('#p_single_s').attr('value','0');
		           	$('#p_visa').attr('value','0');
		           	$('#p_visa_a').attr('value','0');
		           	$('#p_visa_s').attr('value','0');
		           	$('#p_disney').attr('value','0');
		           	$('#p_disney_a').attr('value','0');
		           	$('#p_disney_s').attr('value','0');
		           	$('#p_ticket').attr('value','0');
		           	$('#p_ticket_a').attr('value','0');
		           	$('#p_ticket_s').attr('value','0');
		           	$('#p_sum').attr('value','0');
});

$('.controls').on('change','#period',function(){ 
	var pselct_id = $('#period').chosen().val();
	var allid = 'pid=' + pselct_id;
				jQuery.ajax({
		        	method:'POST',
		        	url:'price_a.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_adult_select').html(data);
		           	$('#p_adult_a').attr('value','0');
		           	$('#p_adult_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_c.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_child_select').html(data);
		           	$('#p_child_a').attr('value','0');
		           	$('#p_child_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_cb.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_child_bed_select').html(data);
		           	$('#p_child_bed_a').attr('value','0');
		           	$('#p_child_bed_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_i.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_infant_select').html(data);
		           	$('#p_infant_a').attr('value','0');
		           	$('#p_infant_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_j.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_join_select').html(data);
		           	$('#p_join_a').attr('value','0');
		           	$('#p_join_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_s.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_single_select').html(data);
		           	$('#p_single_a').attr('value','0');
		           	$('#p_single_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_t.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_ticket_select').html(data);
		           	$('#p_ticket_a').attr('value','0');
		           	$('#p_ticket_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_d.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_disney_select').html(data);
		           	$('#p_disney_a').attr('value','0');
		           	$('#p_disney_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_v.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_visa_select').html(data);
		           	$('#p_visa_a').attr('value','0');
		           	$('#p_visa_s').attr('value','0');
		            }
		        }).responseText;
		        return false;  
});

$('.controls').on('change','#star',function(){ 
	var pselct_id = $('#period').chosen().val();
	var s_id = $('#star').chosen().val();
	var allid = 'pid=' + pselct_id + '&s=' + s_id;
				jQuery.ajax({
		        	method:'POST',
		        	url:'price_a.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_adult_select').html(data);
		           	$('#p_adult_a').attr('value','0');
		           	$('#p_adult_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_c.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_child_select').html(data);
		           	$('#p_child_a').attr('value','0');
		           	$('#p_child_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_cb.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_child_bed_select').html(data);
		           	$('#p_child_bed_a').attr('value','0');
		           	$('#p_child_bed_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_i.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_infant_select').html(data);
		           	$('#p_infant_a').attr('value','0');
		           	$('#p_infant_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_j.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_join_select').html(data);
		           	$('#p_join_a').attr('value','0');
		           	$('#p_join_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_s.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_single_select').html(data);
		           	$('#p_single_a').attr('value','0');
		           	$('#p_single_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_t.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_ticket_select').html(data);
		           	$('#p_ticket_a').attr('value','0');
		           	$('#p_ticket_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_d.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_disney_select').html(data);
		           	$('#p_disney_a').attr('value','0');
		           	$('#p_disney_s').attr('value','0');
		            }
		        }).responseText;
		        jQuery.ajax({
		        	method:'POST',
		        	url:'price_v.php',
		        	dataType:'text',
					data:allid,
					cache:false,
		        	success:function(data){
		           	$('#p_visa_select').html(data);
		           	$('#p_visa_a').attr('value','0');
		           	$('#p_visa_s').attr('value','0');
		            }
		        }).responseText;
		        return false;  
});


$('#p_dep').keyup(depcalculate)

function depcalculate(){
	var d_p = +$('#p_dep').val();
	var d_a = +$('#p_dep_a').val();
	var d_s = d_p*d_a;
	var num = addCommas(d_s);
	$('#p_dep_s').attr('value', num);
	$('#p_dep_se').attr('value', d_s);
};

$('#p_join').keyup(joincalculate)

function joincalculate(){
	var d_p = +$('#p_join').val();
	var d_a = +$('#p_join_a').val();
	var d_s = d_p*d_a;
	var num = addCommas(d_s);
	$('#p_join_s').attr('value', num);
	$('#p_join_se').attr('value', d_s);
};

$('#p_visa').keyup(visacalculate)

function visacalculate(){
	var d_p = +$('#p_visa').val();
	var d_a = +$('#p_visa_a').val();
	var d_s = d_p*d_a;
	var num = addCommas(d_s);
	$('#p_visa_s').attr('value', num);
	$('#p_visa_se').attr('value', d_s);
};

$('#p_ticket').keyup(ticketcalculate)

function ticketcalculate(){
	var d_p = +$('#p_ticket').val();
	var d_a = +$('#p_ticket_a').val();
	var d_s = d_p*d_a;
	var num = addCommas(d_s);
	$('#p_ticket_s').attr('value', num);
	$('#p_ticket_se').attr('value', d_s);
};

function sum_a(){
	var a_p = +$('#p_adult').val();
	var a_a = +$('#p_adult_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_adult_s').attr('value', num);
	$('#p_adult_se').attr('value', a_s);
};

function sum_c(){
	var a_p = +$('#p_child').val();
	var a_a = +$('#p_child_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_child_s').attr('value', num);
	$('#p_child_se').attr('value', a_s);
};

function sum_cb(){
	var a_p = +$('#p_child_bed').val();
	var a_a = +$('#p_child_bed_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_child_bed_s').attr('value', num);
	$('#p_child_bed_se').attr('value', a_s);
};

function sum_i(){
	var a_p = +$('#p_infant').val();
	var a_a = +$('#p_infant_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_infant_s').attr('value', num);
	$('#p_infant_se').attr('value', a_s);
};

function sum_j(){
	var a_p = +$('#p_join').val();
	var a_a = +$('#p_join_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_join_s').attr('value', num);
	$('#p_join_se').attr('value', a_s);
};

function sum_s(){
	var a_p = +$('#p_single').val();
	var a_a = +$('#p_single_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_single_s').attr('value', num);
	$('#p_single_se').attr('value', a_s);
};

function sum_v(){
	var a_p = +$('#p_visa').val();
	var a_a = +$('#p_visa_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_visa_s').attr('value', num);
	$('#p_visa_se').attr('value', a_s);
};

function sum_d(){
	var a_p = +$('#p_disney').val();
	var a_a = +$('#p_disney_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_disney_s').attr('value', num);
	$('#p_disney_se').attr('value', a_s);
};

function sum_t(){
	var a_p = +$('#p_ticket').val();
	var a_a = +$('#p_ticket_a').val();
	var a_s = a_p*a_a;
	var num = addCommas(a_s);
	$('#p_ticket_s').attr('value', num);
	$('#p_ticket_se').attr('value', a_s);
};

function sum_all(){
	var a = +$('#p_adult_se').val();
	var c = +$('#p_child_se').val();
	var cb = +$('#p_child_bed_se').val();
	var i = +$('#p_infant_se').val();
	var j = +$('#p_join_se').val();
	var s = +$('#p_single_se').val();
	var v = +$('#p_visa_se').val();
	var d = +$('#p_disney_se').val();
	var t = +$('#p_ticket_se').val();
	var all = a+c+cb+i+j+s+v+d+t;
	var num = addCommas(all);

	var aa = +$('#p_adult_a').val();
	var ca = +$('#p_child_a').val();
	var cba = +$('#p_child_bed_a').val();
	var ia = +$('#p_infant_a').val();
	var ja = +$('#p_join_a').val();
	var sa = +$('#p_single_a').val();
	var alla = aa+ca+cba;

	$('#p_sum').attr('value', num);
	$('#p_sum_se').attr('value', all);
	$('#p_sum_a').attr('value', alla);
	$('#p_dep_a').attr('value', alla);
};

function addCommas(str) {
    var parts = (str + "").split("."),
        main = parts[0],
        len = main.length,
        output = "",
        first = main.charAt(0),
        i;

    if (first === '-') {
        main = main.slice(1);
        len = main.length;    
    } else {
        first = "";
    }
    i = len - 1;
    while(i >= 0) {
        output = main.charAt(i) + output;
        if ((len - i) % 3 === 0 && i > 0) {
            output = "," + output;
        }
        --i;
    }
    // put sign back
    output = first + output;
    // put decimal part back
    if (parts.length > 1) {
        output += "." + parts[1];
    }
    return output;
}


/*$(function(){  
	setInterval(function(){
		var data=$.ajax({
			url:'notification.php',  
			data:'rev=1',
			async:false,  
			success:function(data){
				$('.noti .messages').html(data.notification);
			   if(data.unseen_notification > 0){
			    $('.count').html(data.unseen_notification);
			    $('.count').show();
			   }
			}  
		}).responseText;
	},5000);
});*/
$(document).ready(function(){
	function load_unseen_notification(view = ''){
		$.ajax({
		  url:"notification.php",
		  method:"POST",
		  data:{view:view},
		  dataType:"json",
		  success:function(ndata){
		   $('.noti .messages').html(ndata.notification);
		   if(ndata.unseen_notification > 0){
		    $('.count').html(ndata.unseen_notification);
		    $('.count').show();
		   }
		  }
		});
	}
	load_unseen_notification();
	setInterval(function(){
	 load_unseen_notification();
	}, 5000);
});

//-------- chk valid -------\\
$(document).ready(function(){
$('#admin_user').blur(username_check);
$('#pass').keyup(pass_check).keyup(repass_check);
$('#repass').keyup(pass_check).keyup(repass_check);
$('#firstname').keyup(firstname_check);
$('#lastname').keyup(lastname_check);
$('#nickname').keyup(nickname_check);
$('#tel').keyup(tel_check);
$('#mail').keyup(mail_check);
$('#mails').keyup(mail_check2);
$('#mailu').keyup(mailu_check);
$('#name').blur(name_check);
$('#price').keyup(price_check);
$('#code').change(code_check);
$('#time').change(time_check);
$('#month').change(month_check);
$('#month02').change(month_check);
$('#country').change(country_check);
$('#airline').change(airline_check);
});
	
function username_check(){	
var admin_user = $('#admin_user').val();
var english = /^[A-Za-z0-9]*$/;
if(!english.test(admin_user)){
	$("#chkuser").removeClass("success").addClass( "error" );
	$("#check_msg_suc").hide();
	$("#check_msg_err").hide();
	$("#user-msg").text("กรุณากรอกเป็นตัวอักษร a-z หรือเลข 0-9 เท่านั้น !");
	setTimeout(function () {
		                	$('#admin_user').val('');
						}, 1500);

} else if(admin_user == "" || admin_user.length <= 2) {
	$("#chkuser").removeClass("success").addClass( "error" );
	$("#check_msg_suc").hide();
	$("#check_msg_err").hide();
	$("#user-msg").text("กรุณากรอกข้อมูลตั้งแต่ 3 ตัวอักษรขึ้นไป !"); 
} else {

jQuery.ajax({
   type: "POST",
   url: "check.php",
   data: 'admin_user='+ admin_user,
   cache: false,
   success: function(response){
if(response == 1){
	$("#user-msg").empty();
	$("#chkuser").removeClass("success");
	$('#chkuser').addClass("error");
	$("#check_msg_suc").hide();
	$("#check_msg_err").show();
	}else{
	$("#user-msg").empty();
	$("#chkuser").removeClass("error");
	$('#chkuser').addClass( "success" );
	$("#check_msg_err").hide();
	$("#check_msg_suc").show();
	     }

}
});}};

function pass_check(){	
var pass = $('#pass').val();
var english = /^[A-Za-z0-9]*$/;
if(!english.test(pass)){
	$("#chkpass").removeClass("success").addClass( "error" );
	$("#pass-msg").text("กรุณากรอกเป็นตัวอักษร a-z หรือเลข 0-9 เท่านั้น !");
	setTimeout(function () {
		                	$('#pass').val('');
						}, 1500);
} else if(pass == "" || pass.length <= 3){
	$("#chkpass").removeClass("success").addClass( "error" );
	$("#pass-msg").text("กรุณากรอกรหัสผ่านตั้งแต่ 4 ตัวอักษรขึ้นไป !");
} else {
	$("#chkpass").removeClass("error").addClass( "success" );
	$("#pass-msg").empty();
}};

function repass_check(){
var pass = $('#pass').val();
var repass = $('#repass').val();
if(pass !== repass || repass == ""){
	$("#chkrepass").removeClass("success").addClass( "error" );
	$("#repass-msg").text("กรุณากรอกรหัสผ่านให้ตรงกัน !");
} else {
	$("#chkrepass").removeClass("error").addClass( "success" );
	$("#repass-msg").empty();
}};

function firstname_check(){
var firstname = $('#firstname').val(); 
if(firstname == ""){
	$("#chkfirstname").removeClass("success").addClass( "error" );
	$("#firstname-msg").text("กรุณากรอกชื่อ !");
} else {
	$("#chkfirstname").removeClass("error").addClass( "success" );
	$("#firstname-msg").empty();
}};

function lastname_check(){
var lastname = $('#lastname').val(); 
if(lastname == ""){
	$("#chklastname").removeClass("success").addClass( "error" );
	$("#lastname-msg").text("กรุณากรอกนามสกุล !");
} else {
	$("#chklastname").removeClass("error").addClass( "success" );
	$("#lastname-msg").empty();
}};

function nickname_check(){
var nickname = $('#nickname').val(); 
if(nickname == ""){
	$("#chknickname").removeClass("success").addClass( "error" );
	$("#nickname-msg").text("กรุณากรอกชื่อเล่น !");
} else {
	$("#chknickname").removeClass("error").addClass( "success" );
	$("#nickname-msg").empty();
}};

function tel_check(){	
var tel = $('#tel').val();
var number = /^[0-9]*$/;
if(!number.test(tel)){
	$("#chktel").removeClass("success").addClass( "error" );
	$("#tel-msg").text("กรุณากรอกเป็นตัวเลข 0-9 เท่านั้น !");
	setTimeout(function () {
		                	$('#tel').val('');
						}, 800);
} else if(tel == "" || tel.length <= 8 || tel.length >=11 ){
	$("#chktel").removeClass("success").addClass( "error" );
	$("#tel-msg").text("กรุณากรอกเบอร์โทรศัพท์มือถือให้ครบ !");
} else {
	$("#chktel").removeClass("error").addClass( "success" );
	$("#tel-msg").empty();
}};

function mail_check(){	
var mail = $('#mail').val();
var mailtext = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!mailtext.test(mail)){
	$("#chkmail").removeClass("success").addClass( "error" );
	$("#check_mail_suc").hide();
	$("#check_mail_err").hide();
	$("#mail-msg").text("กรุณากรอกเป็นตัวอักษร a-z เลข 0-9 หรือเครื่องหมาย + - _ . @ เท่านั้น !");
} else if(mail == "" || mail.length <= 2) {
	$("#chkmail").removeClass("success").addClass( "error" );
	$("#check_mail_suc").hide();
	$("#check_mail_err").hide();
	$("#mail-msg").text("กรุณากรอกข้อมูลตั้งแต่ 3 ตัวอักษรขึ้นไป !"); 
} else {

jQuery.ajax({
   type: "POST",
   url: "checkmail.php",
   data: 'mail='+ mail,
   cache: false,
   success: function(response){
if(response == 1){
	$("#mail-msg").empty();
	$("#chkmail").removeClass("success").addClass("error");
	$("#check_mail_suc").hide();
	$("#check_mail_err").show();
	setTimeout(function () {
		                	$('#mail').val('');
						}, 2000);
	}else{
	$("#mail-msg").empty();
	$("#chkmail").removeClass("error").addClass( "success" );
	$("#check_mail_err").hide();
	$("#check_mail_suc").show();
	     }

}
});}};

function mail_check2(){	
var mails = $('#mails').val();
var mailtexts = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!mailtexts.test(mails)){
	$("#chkmails").removeClass("success").addClass( "error" );
	$("#mails-msg").text("กรุณากรอกเป็นตัวอักษร a-z เลข 0-9 หรือเครื่องหมาย + - _ . @ เท่านั้น !");
} else if(mails == "" || mails.length <= 2) {
	$("#chkmails").removeClass("success").addClass( "error" );
	$("#mails-msg").text("กรุณากรอกข้อมูลตั้งแต่ 3 ตัวอักษรขึ้นไป !"); 
} else {
	$("#chkmails").removeClass("error").addClass( "success" );
	$("#mails-msg").empty(); 
}};

function mailu_check(){	
var mailu = $('#mailu').val();
var mailtextu = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(!mailtextu.test(mailu)){
	$("#chkmailu").removeClass("success").addClass( "error" );
	$("#mailu-msg").text("กรุณากรอกเป็นตัวอักษร a-z เลข 0-9 หรือเครื่องหมาย + - _ . @ เท่านั้น !");
} else if(mailu == "" || mailu.length <= 2) {
	$("#chkmailu").removeClass("success").addClass( "error" );
	$("#mailu-msg").text("กรุณากรอกข้อมูลตั้งแต่ 3 ตัวอักษรขึ้นไป !"); 
} else {
	$("#chkmailu").removeClass("error").addClass( "success" );
	$("#mailu-msg").empty(); 
}};

function name_check(){
var name = $('#name').val(); 
if(name == ""){
	$("#chkname").removeClass("success").addClass( "error" );
	$("#name-msg").text("กรุณากรอกชื่อโปรแกรมทัวร์ !");
} else {
	$("#chkname").removeClass("error").addClass( "success" );
	$("#name-msg").empty();
}};

function code_check(){
var code = $('#code').chosen().val(); 
if(code == "0"){
	$("#chkcode").removeClass("success").addClass( "error" );
	$("#code-msg").text("กรุณาเลือกรหัสทัวร์ !");
} else {
	$("#chkcode").removeClass("error").addClass( "success" );
	$("#code-msg").empty();
}};

function time_check(){
var time = $('#time').chosen().val(); 
if(time == "0"){
	$("#chktime").removeClass("success").addClass( "error" );
	$("#time-msg").text("กรุณาเลือกจำนวนวันเดินทาง !");
} else {
	$("#chktime").removeClass("error").addClass( "success" );
	$("#time-msg").empty();
}};

function month_check(){
var month = $('#month').chosen().val(); 
var month02 = $('#month02').chosen().val(); 
if(month == "0" | month02 == "0"){
	$("#chkmonth").removeClass("success").addClass( "error" );
	$("#month-msg").text("กรุณาเลือกช่วงเดือน !");
} else {
	$("#chkmonth").removeClass("error").addClass( "success" );
	$("#month-msg").empty();
}};

function country_check(){
var country = $('#country').chosen().val(); 
if(country == "0"){
	$("#chkcountry").removeClass("success").addClass( "error" );
	$("#country-msg").text("กรุณาเลือกประเทศ !");
} else {
	$("#chkcountry").removeClass("error").addClass( "success" );
	$("#country-msg").empty();
}};

function airline_check(){
var airline = $('#airline').chosen().val(); 
if(airline == "0"){
	$("#chkairline").removeClass("success").addClass( "error" );
	$("#airline-msg").text("กรุณาเลือกสายการบิน !");
} else {
	$("#chkairline").removeClass("error").addClass( "success" );
	$("#airline-msg").empty();
}};

function price_check(){	
var price = $('#price').val();
var number = /^[0-9]*$/;
if(!number.test(price)){
	$("#chkprice").removeClass("success").addClass( "error" );
	$("#price-msg").text("กรุณากรอกเป็นตัวเลข 0-9 เท่านั้น !");
	setTimeout(function () {
		                	$('#tel').val('');
						}, 800);
} else if(price == "" || price.length <= 3 ){
	$("#chkprice").removeClass("success").addClass( "error" );
	$("#price-msg").text("กรุณากรอกราคาให้ครบ !");
} else {
	$("#chkprice").removeClass("error").addClass( "success" );
	$("#price-msg").empty();
}};


$("#payin").on('keyup', function(e){
	var bt = $('#payin').val();
	var allcode = 'https://www.bestindochina.com/backend/?url=finance_edit&id=' + bt;
    if (e.keyCode == 13) {
		window.location.href = allcode;
    }
});

$("#pass_search").on('keyup', function(e){
	var bt = $('#pass_search').val();
	var allcode = 'https://www.bestindochina.com/backend/?url=passenger_list&book=' + bt;
    if (e.keyCode == 13) {
		window.location.href = allcode;
    }
});

$('#urec').chosen();
$('.select').click(function(){
    $('#urec option').prop('selected', true);
    $('#urec').trigger('liszt:updated');
});
$('.deselect').click(function(){
    $('#urec option').prop('selected', false);
    $('#urec').trigger('liszt:updated');
});

function printWindow()
{
   var printReadyEle = document.getElementById("content");
   var shtml = '<HTML>\n<HEAD>\n';
   if (document.getElementsByTagName != null)
   {
      var sheadTags = document.getElementsByTagName("head");
      if (sheadTags.length > 0)
         shtml += sheadTags[0].innerHTML;
    }
    shtml += '</HEAD>\n<BODY>\n';
    if (printReadyEle != null)
    {
       shtml += '<form name = frmform1>';
       shtml += printReadyEle.innerHTML;
    }
    shtml += '\n</form>\n</BODY>\n</HTML>';
    var printWin1 = window.open();
    printWin1.document.open();
    printWin1.document.write(shtml);
    printWin1.document.close();
    printWin1.print();
}
			$(document).on("change", ".doi", function(){
				var pid = $(this).attr('doi');
				var valdate = $('#DOI'+pid).val();
				var expdate = newDayAdd(valdate,5);
				var dateback = $('#date-back').val();
				var dsplit = expdate.split('/');
				var newexpdate = ''+dsplit[2]+'/'+dsplit[0]+'/'+dsplit[1]+'';
				var ed = new Date(newexpdate);
				var db = new Date(dateback);
				$("#DOE"+pid).val(expdate);
				if(ed > db){
					$("#EX"+pid).html('<span class="label label-success">พาสปกติ</span>');
				} else {
					$("#EX"+pid).html('<span class="label label-important">พาสหมดอายุ</span>');
				}

			});

			$(document).on("change", ".doe", function(){
				var pid = $(this).attr('doe');
				var expdate = $('#DOE'+pid).val();
				var dateback = $('#date-back').val();
				var dsplit = expdate.split('/');
				var newexpdate = ''+dsplit[2]+'/'+dsplit[0]+'/'+dsplit[1]+'';
				var ed = new Date(newexpdate);
				var db = new Date(dateback);
				if(ed > db){
					$("#EX"+pid).html('<span class="label label-success">พาสปกติ</span>');
				} else {
					$("#EX"+pid).html('<span class="label label-important">พาสหมดอายุ</span>');
				}

			});


 			$(function() {
        		// Define the url to send the image data to
        		var url = 'passUpload.php';
        		
        		// Call the fileupload widget and set some parameters
        		$('.passup').fileupload({
            		url: url,
            		dataType: 'json',
            		acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            		done: function (e, data) {
            			var uid = $(this).attr('data-id');
                		// Add each uploaded file name to the #files list
                		$.each(data.result.files, function (index, file) {
                			$('#P'+uid).hide();
                			$('#img-list'+uid).show();
                			$('#imgfield-msg'+uid).show();
                		    $('#imgfield-img'+uid).attr('src','../pass/thumbnail/' + file.name);
                		    $('#BUTTON'+uid).attr('data-img',file.name);
                		    $('#BUTTON'+uid).attr('folder','../pass');
							$('#N'+uid).attr('value', file.name);
                		});
            		},
            		progressall: function (e, data) {
                		// Update the progress bar while files are being uploaded
                		var uid = $(this).attr('data-id');
                		var progress = parseInt(data.loaded / data.total * 100, 10);
                		$('#uniform-fileupload'+uid).hide();
                		$('#P'+uid).show();
                		$('#PB'+uid).css(
		                    'width',
		                    progress + '%'
		                );
            		}
        		});
    		});

    		$("body").on("click", ".pass-add", function(){
		       var book = $(this).attr('book');
		        var aid = 'book='+book;
		          var getData=$.ajax({
		            url:'passadd.php',
		            dataType: 'html', 
		            data: aid,
		            async:false,
		            success:function(getData){
						if(getData==0){
							$.noty({
								text:"เพิ่ม Passenger สำเร็จ ! กรุณารอสักครู่...",
								layout:"bottomLeft",
								type:"success"
							});
						    setTimeout(function(){
						    	location.reload();
							}, 1500);
						} else {
						    $.noty({
								text:"พังค่ะติดต่อกะทิ !",
								layout:"bottomLeft",
								type:"error"
								});
						}
		            }  
		          }).responseText;
		    });


//-------- chk slip -------\\
$(document).ready(function(){
$('#depbank').change(dep_check);
$('#depnum').keyup(dep_check);
$('#depdate').keyup(dep_check);
$('#deptime').blur(dep_check);
$('#deptime').keyup(dep_check);

$('#depbank2').change(dep_check2);
$('#depnum2').keyup(dep_check2);
$('#depdate2').keyup(dep_check2);
$('#deptime2').blur(dep_check2);
$('#deptime2').keyup(dep_check2);

$('#fullbank').change(full_check);
$('#fullnum').keyup(full_check);
$('#fulldate').keyup(full_check);
$('#fulltime').blur(full_check);
$('#fulltime').keyup(full_check);

$('#fullbank2').change(full_check2);
$('#fullnum2').keyup(full_check2);
$('#fulldate2').keyup(full_check2);
$('#fulltime2').blur(full_check2);
$('#fulltime2').keyup(full_check2);

$('.paybank').change(pay_check);
$('.paynum').keyup(pay_check);
$('.paydate').keyup(pay_check);
$('.paytime').blur(pay_check);
$('.paytime').keyup(pay_check);
});
	
function dep_check(){
var depbank = $('#depbank').val();
var depnum = $('#depnum').val(); 
var depdate = $('#depdate').val(); 
var deptime = $('#deptime').val();
var bid = $('#invoice_h').val(); 

jQuery.ajax({
   type: "POST",
   url: "finance_slip_check.php",
   data: {'bookid': bid, 'depbank': depbank, 'depnum': depnum, 'depdate': depdate, 'deptime': deptime},
   cache: false,
   success: function(response){
if(response == 1){
		$(".depstate").html('<span class="label label-important statuslabel">Already</span>');
	} else {
		$(".depstate").html('<span class="label label-success statuslabel">Allowed</span>');
	}

}
});
};

function dep_check2(){
var depbank2 = $('#depbank2').val();
var depnum2 = $('#depnum2').val(); 
var depdate2 = $('#depdate2').val(); 
var deptime2 = $('#deptime2').val(); 
var bid = $('#invoice_h').val(); 

jQuery.ajax({
   type: "POST",
   url: "finance_slip_check.php",
   data: {'bookid': bid, 'depbank2': depbank2, 'depnum2': depnum2, 'depdate2': depdate2, 'deptime2': deptime2},
   cache: false,
   success: function(response){
if(response == 1){
		$(".depstate2").html('<span class="label label-important statuslabel">Already</span>');
	} else {
		$(".depstate2").html('<span class="label label-success statuslabel">Allowed</span>');
	}

}
});
};

function full_check(){
var fullbank = $('#fullbank').val();
var fullnum = $('#fullnum').val(); 
var fulldate = $('#fulldate').val(); 
var fulltime = $('#fulltime').val(); 
var bid = $('#invoice_h').val(); 

jQuery.ajax({
   type: "POST",
   url: "finance_slip_check.php",
   data: {'bookid': bid, 'fullbank': fullbank, 'fullnum': fullnum, 'fulldate': fulldate, 'fulltime': fulltime},
   cache: false,
   success: function(response){
if(response == 1){
		$(".fullstate").html('<span class="label label-important statuslabel">Already</span>');
	} else {
		$(".fullstate").html('<span class="label label-success statuslabel">Allowed</span>');
	}

}
});
};

function full_check2(){
var fullbank2 = $('#fullbank2').val();
var fullnum2 = $('#fullnum2').val(); 
var fulldate2 = $('#fulldate2').val(); 
var fulltime2 = $('#fulltime2').val(); 
var bid = $('#invoice_h').val(); 

jQuery.ajax({
   type: "POST",
   url: "finance_slip_check.php",
   data: {'bookid': bid, 'fullbank2': fullbank2, 'fullnum2': fullnum2, 'fulldate2': fulldate2, 'fulltime2': fulltime2},
   cache: false,
   success: function(response){
if(response == 1){
		$(".fullstate2").html('<span class="label label-important statuslabel">Already</span>');
	} else {
		$(".fullstate2").html('<span class="label label-success statuslabel">Allowed</span>');
	}

}
});
};

function pay_check(){
var uid = $(this).attr('data-id');
var paybank = $('#paybank'+uid).val();
var paynum = $('#paynum'+uid).val(); 
var paydate = $('#paydate'+uid).val(); 
var paytime = $('#paytime'+uid).val(); 
var bid = $('#invoice_h').val(); 

jQuery.ajax({
   type: "POST",
   url: "finance_slip_check.php",
   data: {'bookid': bid, 'paybank': paybank, 'paynum': paynum, 'paydate': paydate, 'paytime': paytime},
   cache: false,
   success: function(response){
if(response == 1){
		$(".paystate"+uid).html('<span class="label label-important statuslabel">Already</span>');
	} else {
		$(".paystate"+uid).html('<span class="label label-success statuslabel">Allowed</span>');
	}

}
});
};

$(function () {
      function xhr_send(file, status, progress) {
        if (file) {
          xhr.addEventListener('readystatechange', function(event) {
            if(xhr.readyState == 4){
            var img = xhr.responseText;
            var src = 'https://static.best-consortium.com/content/images/promotion/'+xhr.responseText;
            console.log(src);
              if(xhr.responseText != 0){
              	$('#progress').hide();
                $('#promo-img-list').show();
				$('#promo-imgfield-img').removeClass("img-error").addClass( "img-success" );
                $('#promo-imgfield-msg').show();
                $('#promo-imgfield-img').attr('src', src);
                $('.promo-img-link').attr('data-img', xhr.responseText);
				$('#promo-imgfiles').attr('value', xhr.responseText);
				$('#chkpromo-imgfield').removeClass("error").addClass( "success" );
              }
            }
          }, false);

	      xhr.upload.addEventListener("progress", function (event) {
            if (event.lengthComputable) {
              self.progress = event.loaded / event.total;
            } else if (this.explicitTotal) {
              self.progress = Math.min(1, event.loaded / self.explicitTotal);
            } else {
              self.progress = 0;
            }
            //document.getElementById(progress).innerHTML = ' ' + Math.floor(self.progress*1000)/10 + '%';
            //document.getElementById(progress).style.width=  self.progress*100 + '%';
            $('#uniform-promo-imgfield').hide();
            $('#progress').show();
            $('#progress .bar').css('width',self.progress*100 + '%');
          }, false);

          xhr.open("POST", "promo_upload.php?action=xhr");
          xhr.setRequestHeader("Cache-Control", "no-cache");
          xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
          xhr.setRequestHeader("X-File-Name", file.name);
          xhr.send(file);
        }
      }

      var xhr = new XMLHttpRequest();

      if (xhr && window.File && window.FileList) {
        // xhr example
        var xhr_file = null;
        $("#promo-imgfield").change(function (){
        	xhr_file = this.files[0];
          	xhr_send(xhr_file, "xhr_result", "xhr_progress");
        });

      }
    });
