var NUM_OF_BOOKING_PER_DAY = 5;

$(document).ready(function(){
    hide_step3();
	set_other_request_message();
	$("#RE_ID").change(find_bookable_time).change(find_discount);
	$("#step2 :input").change(find_bookable_time).change(find_discount);
	if($("#BR_ID").val() != ""){
		find_bookable_time();
		find_discount();
		show_step3();
	}
    $('#button').click(find_bookable_time).click(find_discount);
    $('#button').attr('disabled', false);

    // if GET variable has set number of people, show bookable time
    var m_people = jQuery.url.param("people");
		
    if( (m_people != undefined) && (m_people != "") )
    {
        find_bookable_time();
	}
    $('#booking_info_form').submit( function(){
        if ( formsubmit_2() )
        {
			check_other_request_message();
            set_submit_effect();
        }
        else
        {
            return false;
        }
    } );
});

/**
 * 將可訂位時間區塊 & 下一步隱藏
 *
 * @return
 */
function hide_step3(){
    $('#loading_image_div').hide(); 
    $('#check_bookable_div').hide();
    $('#submit_div').hide();
    $('#step3').hide();
}

/**
 * 檢查表單欄位
 *
 * @return void
 */
function check_booking()
{
	
	if ( ! check_required_column( "name", NAME_IS_REQUIRED )     ) 
    {
        return false;
    }
	if ( ! check_required_column( "tel", PHONE_IS_REQUIRED )     ) 
    {
        return false;
    }
	if ( ! check_email_column( "email", EMAIL_IS_NOT_AVAILABLE)     ) 
    {
        return false;
    }
	return true;
}

/**
 *
 * @param
 *
 * @return
 */
function formsubmit_2()
{
	var fm = document.form1;
    var checked_bookable_time = $("#msg [@type=checkbox]:checked");

    // check one of the bookable time has been selected
	if(checked_bookable_time.length <= 0)
	{
		alert(SELECT_AVAILABLE_TIME);
		return false;
	}
	else
	{
		if(!check_booking())
		{
			return false;
		}
		else
		{
            var today = get_today();
            var cookie_name = "num_of_booking_" + today;
            var num_of_booking = parseInt(
                    getCookie(cookie_name), 10);
            if ( isNaN(num_of_booking) )
            {
                setCookie(cookie_name, 1, 1);
                return true;
            }
            else if ( num_of_booking >= NUM_OF_BOOKING_PER_DAY)
            {
                alert(MAX_BOOKING_PER_DAY);
                return false;
            }
            else
            {
                setCookie(cookie_name, (num_of_booking+1), 1);
                return true;
            }
		}
	} 

}

/**
 * Check if RE_ID has been set
 *
 * @return void
 */
function check_did_been_set()
{
    // check RE_ID has been chosen
    if ( isNaN( parseInt( $('#RE_ID').val() ) ) || parseInt( $('#RE_ID').val() ) < 1 )
    {
		hide_step3();
        alert(SELECT_RESTAURANT_FIRST);
        return false;
    }
    return true;
}

/**
 * 使用 ajax 從 server 取得鄰近可訂位時間
 *
 * @return void
 */
function find_bookable_time() 
{
    // check RE_ID has been set
    if ( !check_did_been_set() )
    {
        return;
    }

    // show loading image
    hide_step3();
    show_loading_image();
	hide_discount();

    $.ajax({
        type: "post",
        url: '/bookable_meal.php',
        data: {RE_ID: $('#RE_ID').val(), people: $('#people').val(), 
    		year: $('#year').val(), month: $('#month').val(), 
    		day: $('#day').val(), time: $('#time').val(), 
    		using_vip_room: ( $('#using_vip_room').attr('checked') ) ? 1 : 0, 
    		BR_ID: $("#BR_ID").val()},
        error: function(xhr) {
            alert('Ajax request error');
            $(e.target).attr('disabled', false);},
        success: function(response) {
            $('#msg').html(response);
            remove_unbookable_check_box();
            // set_unbookable_time_msg();
            show_bookable_time();
            $("input[name='quota_id[]']").each(function(){
                if($(this).attr("checked")){
                    show_step3();
                }
            })
        }
    });
}

/**
 * let 使用者從「提前」、「符合」、「延後」三個可訂位時間之間挑選一個
 *
 * @param index 使用者所想挑選的 index 
 *              (0: 「提前」; 1: 「符合」; 2: 「延後」)
 *
 * @return void
 */
function single_choice(index)
{
    // make checkbox single choice
    if (index >= 0)
    {
        $("INPUT[@name^=quota_id][type='checkbox']").attr("checked", false);
		$("#quota_id_" + index).attr("checked", true);
    }
    return;

}

/**
 *  Enable the submit button in booking.php when one of the following
 * situation has been meet.
 *
 * 1. Checkbox "checkbox_exact" has been checked and 
 *    div "book" (與使用者想訂位的時間相符的可訂位時間)
 *    does not equal to INVALID_BOOKING_TIME
 *
 * 2. Checkbox "checkbox_pre" has been checked and 
 *    div "prebook" (提前可訂位時間)
 *    does not equal to INVALID_BOOKING_TIME
 *
 * 3. Checkbox "checkbox_post" has been checked and 
 *    div "postbook" (延後可訂位時間)
 *    does not equal to INVALID_BOOKING_TIME
 *
 * @return void
 */
function check( index )
{
    var obj = $("INPUT[@name^=quota_id][type='checkbox']");

    // var obj = document.getElementsByName("quota_id[]");
	
	// exit when no checkbox is available, which happens when
	// people has not be set
	if (obj == undefined || obj.length == 0)
	{
	    return;
	}
   
	index=parseInt(index);
    single_choice(index);
	
	for(var i = 0; i < obj.length; i++){
		var values = obj[i].value.split("@");
		if(obj[i].checked == true && parseInt(values[1]) > 0){
			show_step3();
			show_discount();
		}
	}
}	

/**
 * Show loading 圖示
 *
 * @return void
 */
function show_loading_image()
{
    $('#check_bookable_div').hide();
    $('#loading_image_div').show(); 
}

/**
 * 將可訂位時間區塊 & 下一步顯示
 *
 * @return
 */
function show_step3()
{
    $('#loading_image_div').hide(); 
    $('#check_bookable_div').show();
    $('#step3').show();
    $('#submit_div').show();

}

/**
 * 呈現可訂位時間區塊
 *
 * @return void
 */
function show_bookable_time()
{
    $('#loading_image_div').hide(); 
    $('#check_bookable_div').show();
}

/**
 * show loading image in 可訂位時間區塊
 *
 * @return void
 */
function hide_bookable_time()
{
    $('#check_bookable_div').hide();
    $('#loading_image_div').hide(); 
}

/**
 * 在使用者送出所有訂位資訊時，呈現運算中的 image
 *
 * @return void
 */
function set_submit_effect()
{
    $('#submit_btn').attr('disabled', '');
    add_drop_sheet();
	show_sending_image();
	
	return false;
}

/**
 * Create 遮罩 to 罩住整個頁面，主要用於當使用者按下「確認訂位」
 *
 * @param 
 *
 * @return 
 *
 */
function add_drop_sheet()
{
  var body = document.getElementsByTagName("body")[0];
  var pageDimensions = getPageDimensions();
  var viewportSize = getViewportSize();

  if (viewportSize[1] > pageDimensions[1])
  {
    pageDimensions[1] = viewportSize[1];
  }

  // create drop-sheet
  var dropSheet = document.createElement("div");

  // set properties of drop-sheet
  dropSheet.setAttribute("id", "dropSheet");
  dropSheet.style.position = "absolute";
  dropSheet.style.left = "0";
  dropSheet.style.top = "0";
  dropSheet.style.width = pageDimensions[0] + "px";
  dropSheet.style.height = pageDimensions[1] + "px";
  body.appendChild(dropSheet);
    
}

/**
 * 呈現運算中的 image for 整個頁面
 * 
 * @return void
 */
function show_sending_image()
{
    $('#sending_image_div').show();
    $('#sending_image_div').css('z-index', 999);

}

/**
 * 隱藏不可訂位時間的 checkbox
 *
 * @return void
 */
function remove_unbookable_check_box()
{
    $("input[type=checkbox][value^=" + INVALID_BOOKING_TIME  + "]").hide();
}

/**
 * Get date('Y-m-d') 
 *
 * @return yyyy-mm-dd
 */
function get_today()
{
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    return(year + "-" + month + "-" + day)
}

function find_discount() 
{
    if ( check_did_been_set() )
    {
		$.ajax({
			type: "post",
			url: '/find_discount.php',
			data: {id: $('#RE_ID').val(), select_year: $('#year').val(), select_month: $('#month').val(), select_day: $('#day').val(), discount_id: $("#selected_discount").val()},
			error: function(xhr) {
				alert('Ajax request error');
				$(e.target).attr('disabled', false);
			},
			success: function(response) {
				$('#discount_inner').html(response);
			}
		});
	}
}

function hide_discount()
{
    $("#discount_inner").hide(); 
}

function show_discount()
{
    $("#discount_inner").show(); 
}

function set_other_request_message(){
	if($("#other_request").val() == ""){
		$("#other_request").text("請勿在此修改訂位人數");
		$("#other_request").addClass("gray");
	}
	$("#other_request").click(function(){
		$("#other_request").text("");
		$("#other_request").removeClass("gray");
	});
}

function check_other_request_message(){
	if($("#other_request").val() == "請勿在此修改訂位人數"){
		$("#other_request").text("");	
	}
}
