function isEmail(email){
	var regExp = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return regExp.test(email);
}

function getExt(src){
	return /[^.]+$/.exec(src);
}

function getFile(src){
	var ext = getExt(src);
	return src.substring(0, parseInt(src.length) - (parseInt(ext.length) + 3));
}

function setSlipType(){
	if(document.getElementById('slip_type1').checked){
		$('#slip_detail_upload').hide();
		$('#slip_detail_fax').show();
	}else{
		$('#slip_detail_upload').show();
		$('#slip_detail_fax').hide();
	}
}

$(document).ready(function(){
	if($(".datepicker").get(0)){
		$(".datepicker").datepicker({
			dateFormat: 'yy-mm-dd',
			changeYear: true,
			changeMonth: true,
			buttonImageOnly: true,
			buttonText: 'คลิกเลือกวันที่',
			showOn: 'button',
			yearRange: "-40:+5",
			buttonImage: 'Asset/Images/calendar.gif',
			duration: 'fast'
		}).mask("9999-99-99");
	}
	
	if($(".datepicker_back").get(0)){
		$(".datepicker_back").datepicker({
			dateFormat: 'yy-mm-dd',
			changeYear: true,
			changeMonth: true,
			buttonImageOnly: true,
			buttonText: 'คลิกเลือกวันที่',
			showOn: 'button',
			yearRange: "-5:+5",
			buttonImage: '../../Asset/Images/calendar.gif',
			duration: 'fast'
		}).mask("9999-99-99");
	}
	
	if($(".timepicker").get(0)){
		$(".timepicker").datetimepicker({
			dateFormat: 'yy-mm-dd',
			timeFormat: "hh:mm",
			changeYear: true,
			changeMonth: true,
			buttonImageOnly: true,
			buttonText: 'คลิกเลือกวันที่',
			showOn: 'button',
			buttonImage: 'Asset/Images/calendar.gif',
			duration: 'fast'
		}).mask("9999-99-99 99:99");
	}
	
	if($(".timepicker_back").get(0)){
		$(".timepicker_back").datetimepicker({
			dateFormat: 'yy-mm-dd',
			timeFormat: "hh:mm",
			changeYear: true,
			changeMonth: true,
			buttonImageOnly: true,
			buttonText: 'คลิกเลือกวันที่',
			showOn: 'button',
			buttonImage: '../../Asset/Images/calendar.gif',
			duration: 'fast'
		}).mask("9999-99-99 99:99");
	}
	
	$(".image-swap").mouseenter(function(){
		var imgExt = getExt($(this).attr('src'));
		var imgFile = getFile($(this).attr('src'));
		var imgAry = imgFile.split('-out');
		var imgOver = imgAry[0] + '-over.' + imgExt;
		$(this).attr('src', imgOver);
	}).mouseleave(function(){
		var imgExt = getExt($(this).attr('src'));
		var imgFile = getFile($(this).attr('src'));
		var imgAry = imgFile.split('-over');
		var imgOver = imgAry[0] + '-out.' + imgExt;
		$(this).attr('src', imgOver);
	}).css('cursor', 'pointer');

	$('#btn-subscribe').click(function(e){
		var user_email = $('#subscribe').val();
		if(!isEmail(user_email)){
			alert('อีเมล์ไม่ถูกต้องค่ะ');
		}else{
			if(confirm('ยืนยันรับข้อมูลผ่านทางอีเมล์')==true)
			{
				$.ajax({
					type: "POST",
					url: "ajax.php",
					data: ({"action" : "subscribe",
							email : user_email
					}),
					success: function(response) {
						if (response == "true"){
							alert('บันทึกข้อมูลเรียบร้อยแล้ว');
						}else if (response == ""){
							alert('เกิดข้อผิดพลาดบางประการ กรุณาลองใหม่อีกครั้ง.');
						}else
							alert(response);
					}
				});
			}else{ 
				return false;
			}				
		}			
		e.preventDefault();				 
	});

	if($('img#btn-recom-next').get(0)){
		var RecomWidth = $("div.book-listing").width();
		var RecomNumPage = Math.ceil(parseFloat(RecomWidth) / 768);
		var RecomCurPage = 1;
		
		$('img#btn-recom-next').click(function(){
			$("div.book-listing").each(function(){
				if(RecomCurPage < RecomNumPage){
					$(this).animate({"left": "-=735px"}, 300);
					RecomCurPage++;
				}
			});
		})
		
		$('img#btn-recom-prev').click(function(){
			$("div.book-listing").each(function(){
				if(RecomCurPage > 1){
					$(this).animate({"left": "+=735px"}, 300);
					RecomCurPage--;
				}
			});
		})
	}

	if($('img#btn-relate-next').get(0)){
		var RelatedWidth = $("div.book-listing").width();
		var RelatedNumPage = Math.ceil(parseFloat(RelatedWidth) / 731);
		var RelatedCurPage = 1;
		
		$('img#btn-relate-next').click(function(){
			$("div.book-listing").each(function(){
				if(RelatedCurPage < RelatedNumPage){
					$(this).animate({"left": "-=700px"}, 300);
					RelatedCurPage++;
				}
			});
		})
		
		$('img#btn-relate-prev').click(function(){
			$("div.book-listing").each(function(){
				if(RelatedCurPage > 1){
					$(this).animate({"left": "+=700px"}, 300);
					RelatedCurPage--;
				}
			});
		})
	}	

	$("#pay_type1").click(function(){
		$('#bank-detail').hide();
	});	
	$("#pay_type2").click(function(){
		$('#bank-detail').hide();
	});
	$("#pay_type3").click(function(){
		$('#bank-detail').show();
	});

	$("#slip_type1").click(function(){
		$('#slip_detail_upload').hide();
		$('#slip_detail_fax').show();

	});	
	$("#slip_type2").click(function(){
		$('#slip_detail_upload').show();
		$('#slip_detail_fax').hide();
	});	
	
		
	$("#btn-search").click(function(){
		if($('#search_find').val() == ""){
			alert('กรุณากรอกชื่อหนังสือที่ต้องการค้นหาค่ะ');
			return false;
		}
	});
	
	$("#user_login").click(function(){
		if($('#user_login').val() == "กรุณากรอก Email"){
			$('#user_login').val("");
		}
	});
	$("#user_pass").click(function(){
		if($('#user_pass').val() == "Password."){
			$('#user_pass').val("");
		}
	});
	$("#user_login").blur(function(){
		if($.trim($('#user_login').val()) == ""){
			$('#user_login').val("กรุณากรอก Email");
		}else{
			if($('#user_pass').val() == "Password."){
				$('#user_pass').val("");
			}
			$('#user_pass').focus();
		}
	});
	$("#user_pass").blur(function(){
		if($('#user_login').val() == "กรุณากรอก Email"){
			if($('#user_pass').val() == ""){
				$('#user_pass').val("Password.");
			}
		}
	});
	
	if($('form#frm-login').get(0)){
		$('form#frm-login').submit(function(e){
			//alert('submit'+$('#keep-signed-in').attr('checked'));
			if($.trim($('#user_login').val()) == "กรุณากรอก Email"){
				alert('กรุณากรอกอีเมลหรือชื่อผู้ใช้ค่ะ');
				$('#user_login').focus();
			}else if($.trim($('#user_login').val()) == ""){
				alert('กรุณากรอกอีเมลหรือชื่อผู้ใช้ค่ะ');
				$('#user_login').focus();
			}else if($.trim($('#user_pass').val()) == ""){
				alert('กรุณากรอกรหัสผ่านค่ะ');
				$('#user_pass').focus();
			}else{
				$.ajax({
					type: "POST",
					url: "ajax.php",
					data: ({"action" : "login",
							user_login : $('#user_login').val(),
							user_pwd : $('#user_pass').val(),
							remember : $('#keep-signed-in').attr('checked')
					}),
					success: function(response) {
						if (response == "true"){
							redirect("เข้าสู่ระบบเรียบร้อยแล้ว...", "index.php", 3);
						}else if (response == ""){
							alert('เกิดข้อผิดพลาดบางประการ กรุณาลองใหม่อีกครั้ง.');
						}else if (response == "false"){
							alert('Email หรือ Password ไม่ถูกต้อง กรุณาลองใหม่อีกครั้ง.');
						}else
							alert(response);
					}
				});
			}
			e.preventDefault();
		});
	}
	
	if($('#btnLogout').get(0)){
		$('#btnLogout').click(function(){
			if(confirm('ยืนยันการออกจากระบบ!')){
				$.ajax({
					type: "POST",
					url: "ajax.php",
					data: ({"action" : "logout"
					}),
					success: function(response) {
						if (response == "true"){
							redirect("ออกจากระบบเรียบร้อยแล้ว...", "index.php", 3);
						}else
							alert(response);
					}
				});
			}
		});
	}
	
	if($('form.use_valid_engine').get(0)){
		$('form.use_valid_engine').validationEngine('attach', {promptPosition : "centerRight", scroll: false});
	}
	
	if($("#user_zipcode").get(0)){
		$("#user_zipcode").mask("99999");
	}
	
	if($(".checkall").get(0)){
		$('.checkall').click(function(){
			if($(this).is(":checked")){
				$(this).closest("form").find(":checkbox").attr("checked","checked");
			}else{
				$(this).closest("form").find(":checkbox").removeAttr("checked");
			}
		});
	}
	
	if($("#clear-delivery").get(0)){
		$("#clear-delivery").click(function(){
			if($(this).is(":checked")){
				$(this).closest("form")[0].reset();
			}else{
				$(this).closest("form").find(".delivery-info").val('');
			}
		});
	}

	if($("input.book_piece").get(0)){
		$("input.book_piece").each(function(){
			$(this).blur(function(){
				if($(this).val() == '')
					$(this).val("0");
				calcCart();
			});
			$(this).keyup(function(){
				if(isNaN($(this).val())){
					alert('กรุณากรอกจำนวนหนังสือ(เล่ม)ค่ะ');
					$(this).val("0");
				}
				
				calcCart();
				
				var book_isbn_type = $(this).closest("tr").find("input[name=book_isbn_type]").val();
				var split_isbn_type = book_isbn_type.split(',');
				
				editCart(split_isbn_type[0], split_isbn_type[1], $(this).val());
			});
		});
	}
	
	if($("#btn-conf-pay").get(0)){
		$("#btn-conf-pay").click(function(){
			
		});
	}

	if($('form#frm-rate-book').get(0)){
    	$('div.rateit').rateit({starheight:22, starwidth:22, resetable: true, step : 1});
		$("#rateit").bind('rated', function (e, value) { $('#book_rate').val(value); });
		$('form#frm-rate-book').submit(function(e){
			$.ajax({
				type: "POST",
				url: "ajax.php",
				data: ({"action" : "rate_book", book_rate : $('#book_rate').val(), book_isbn : $('#book_isbn').val()}),
				success: function(response) {
					/*
					alert(response);
					*/
					var result = jQuery.parseJSON(response);
					if(result.success){
						alert(result.message);
						$('#book-rating').html(result.data);
						$('#frm-rate-it').remove();
					}else{
						alert(result.message);
					}
				}
			});
			e.preventDefault();
		});
	}
	
	if($('#btn-check-transaction').get(0)){
		$('#btn-check-transaction').click(function(){
			msgOpen('กรุณารอสักครู่');
			$.ajax({
				type: "POST",
				url: "ajax.php",
				data: ({"action" : "check_transaction", "order_no" : $('#hdn_order_no').val()}),
				success: function(response) {
					/*
					alert(response);
					*/
					var result = jQuery.parseJSON(response);
					msgbox(result.status.message,4);
				},
				error: function(x, e) {
					msgbox("เกิดข้อผิดพลาดบางประการ กรุณาลองใหม่อีกครั้ง", 4);
				}
			});
		});
	}
	setSlipType();
});

/*-------------------MSGBOX---------------------*/
function msgWidth(){
	return (parseFloat($(document).width()) < parseFloat($(window).width()))? $(window).width() : $(document).width();
}

function msgHeight(){
	return (parseFloat($(document).height()) < parseFloat($(window).height()))? $(window).height() : $(document).height();
}

function msgbox(text,sec) {
	msgOpen(text);
	msgClose(sec);
}

function msgOpen(text) {
    $("#wait").unmask();
    $("#wait").css("position", "absolute");
    $("#wait").width(msgWidth());
    $("#wait").height(msgHeight());
    $("#wait").css("z-index", "10000");
    $("#wait").loadmask(text);
    $("#wait").show();
}

function msgClose(sec){
    setTimeout("forceUnmask()", (sec * 1000));
}

function forceUnmask(){
    $("#wait").unmark();
    $("#wait").height(0);
}

function redirect(text, url, sec) {
    //$("#wait").unmark();
    $("#wait").css("position", "absolute");
    $("#wait").css("width", "100%");
    //$("#wait").css("height", msgHeight());
    $("#wait").css("height", "100%");
    $("#wait").css("z-index", "10000");
    $("#wait").loadmask(text);
    $("#wait").show();
	
	if(url == "back")
		setTimeout("history.back();", (sec * 1000));
	else
		setTimeout("window.location.href='" + url + "';", (sec * 1000));
}
/*-------------------MSGBOX---------------------*/


$(window).load(function() {
	if($("#ul-slide").get(0)){
		$('#ul-slide').bxSlider({auto: true,pager: true, controls:false, speed:800, pause:4000});
	}
});

function calcCart(){
	var $_sum_total = 0;
	var $_sum_piece = 0;
	$("input[name=book_isbn_type]").each(function(){
		$_sum_piece += isNaN(parseFloat($(this).closest("tr").find("input.book_piece").val()))?0:parseFloat($(this).closest("tr").find("input.book_piece").val());
		$_sum_item = isNaN(parseFloat($(this).closest("tr").find("input.book_piece").val()))?0:parseFloat($(this).closest("tr").find("input.book_piece").val()) * parseFloat($(this).closest("tr").find("td.unit_price").text());
		$(this).closest("tr").find("td.total_price").text($_sum_item);
		$_sum_total += parseFloat($_sum_item);
	});
	$("td#sum_piece").text($_sum_piece);
	$("td#sum_total").text($_sum_total);
	if($_sum_total > 400) $("td#deliver_fee").text('0');
	else $("td#deliver_fee").text('30');
	$("td#grand_total").text(parseFloat($("td#deliver_fee").text()) + parseFloat($("td#sum_total").text()));		
}

function addToCart(book_isbn, book_type)
{
	$.ajax({
		type: "POST",
		url: "ajax.php",
		data: ({"action" : "addcart", "book_isbn" : book_isbn, "book_type" : book_type}),
		success: function(response){
			var result = jQuery.parseJSON(response);
			$('#ul-short-cart').html(result.data);
			msgbox(result.message,1);
		}
	});
}

function editCart(book_isbn, book_type, book_piece)
{
	$.ajax({
		type: "POST",
		url: "ajax.php",
		data: ({"action" : "editcart", "book_isbn" : book_isbn, "book_type" : book_type, "book_piece" : book_piece}),
		success: function(response){
			//alert(response);
			var result = jQuery.parseJSON(response);
			$('#ul-short-cart').html(result.data);
			//msgbox(result.message,1);
		}
	});
}

function delCart()
{
	$checkbox = $("#frm_cart").find(':checked');
	if($checkbox.length <= 0){
		alert('กรุณาเลือกรายการที่ต้องการลบค่ะ');
	}else{
		var book_isbn = "[";
		var book_type = "[";
		var ii = 0;
		$checkbox.each(function(){
			var isbn_type = $(this).val().split(',');
			book_isbn += (ii>0)? ',"' + isbn_type[0] + '"' : '"' + isbn_type[0] + '"';
			book_type += (ii>0)? ',"' + isbn_type[1] + '"' : '"' + isbn_type[1] + '"';
			ii++;
			$(this).closest("tr").remove();
		});
		book_isbn += "]";
		book_type += "]";
		
		var numb = 0;
		$('td.item-num').each(function(){
			numb++;
			$(this).html(numb);
		});
		
		calcCart();
		
		$.ajax({
			type: "POST",
			url: "ajax.php",
			data: ({"action" : "delcart", "book_isbn[]" : eval(book_isbn), "book_type[]" : eval(book_type)}),
			success: function(response){
				//alert(response);
				var result = jQuery.parseJSON(response);
				if(result.count <= 0){
					$('#cart-info').html(result.data);
				}else{
				}
				$('#ul-short-cart').html(result.data);
				//msgbox(result.message,1);
			}
		});
	}
}

var Bootloader = new Object();
