function get_open_quotas(restaurant_id, target_date, people, callback){
    var apiPath = 'restaurant/get_open_quotas/';
    apiPath += restaurant_id + '/';
    apiPath += target_date + '/';
    apiPath += people + '/';
    
    EZTABLE.api({
        path: apiPath, 
        params: {}, 
        success: callback
    });
};

/**
 * Get open quotas of a restaurant: ((quota_id, time(HH:ii)), ...) for a given reservation.
 * The reservation itself does not count when consider quota full. 
 * The results are sorted by time in ascending order. 
 * For the same time, only one quota is returned.
 * 
 * @param int reservation_id
 * @param int restaurant_id
 * @param string target_date yyyy-mm-dd date string
 * @param int people number of people
 * @return array ((quota_id, hour:minute, availability), ...) in time ascending order.
 */
function get_reservation_open_quotas(reservation_id, restaurant_id, target_date, people, callback){
     var apiPath = 'restaurant/get_reservation_open_quotas/';
     apiPath += reservation_id + '/';
     apiPath += restaurant_id + '/';
     apiPath += target_date + '/';
     apiPath += people + '/';
     
     EZTABLE.api({
         path: apiPath, 
         params: {}, 
         success: callback
     });
};


/**
 * list_bookable_time
 *
 * @param restaurant_id
 * @param target_date 
 * @param people
 * @param options
 * @param callback
 * @return  void
 */
function list_bookable_time(restaurant_id, target_date, people, options, callback) {
   get_open_quotas( restaurant_id, target_date, people, function( response){
       // load settings 
       var ulClass = options.ulClass  || 'timeList' ;
       var availableClass = options.availableClass || 'available' ;
       var unavailableClass = options.availableClass || 'unavailable' ;

       if ( response.status !== 'OK'  || response.data.length === 0)
       {
           callback($('#booking_page_config_no_available_quota_message').val());
           return;
       }

       var quota_array = response.data;
       var html_list = '<ul class="' + ulClass + '">';
       var bookable_time_count = 0;
       $.each( quota_array, function( index, quota){
           var quota_id = quota.start_time + '@' + quota.QU_ID;
           if (quota.availability) {
               bookable_time_count += 1;
               var quotaText = quota.start_time;
               if(undefined !== quota.comment && quota.comment.length > 0) {
                   quotaText += ' (' + quota.comment + ')';
               }
               if($('#param_request_time').val() == quotaText){
                   html_list += ('<li id="' + quota_id + '"><a href="#" title="' + quotaText + '" class="' + availableClass + ' visited">' + quotaText + '</a></li>');
                   $('#quota_id').val( quota_id );
                   show_step3();
               }
               else{
                   html_list += ('<li id="' + quota_id + '"><a href="#" title="' + quotaText + '" class="' + availableClass + '">' + quotaText + '</a></li>');
               }
           }
       });
       if ( bookable_time_count === 0)
       {
            html_list = $('#booking_page_config_no_available_quota_message').val();
       }
       callback( html_list);
   });
};


/**
 * list_reservation_bookable_time
 *
 * @param reservation_id
 * @param restaurant_id
 * @param target_date 
 * @param people
 * @param options
 * @param callback
 * @return  void
 */
function list_reservation_bookable_time(reservation_id, restaurant_id, target_date, people, options, callback) {

   get_reservation_open_quotas(reservation_id, restaurant_id, target_date, people, function( response){
       // load settings 
       var ulClass = options.ulClass  || 'timeList' ;
       var availableClass = options.availableClass || 'available' ;
       var unavailableClass = options.availableClass || 'unavailable' ;
       var selected_time = options.selected_time;

       if ( response.status.toUpperCase() != 'OK'  || response.data.length === 0)
       {
           callback( $('#booking_page_config_no_available_quota_message').val());
           return;
       }

       var quota_array = response.data;
       var html_list = '<ul class="' + ulClass + '">';
       var bookable_time_count = 0;
       $.each( quota_array, function( index, quota){
           var quota_id = quota.start_time + '@' + quota.QU_ID;
           var selected_class = (quota.start_time == selected_time ) ? 'visited' : '';
           if (quota.availability) {
               var quotaText = quota.start_time;
               if(undefined !== quota.comment && quota.comment.length > 0) {
                   quotaText += ' (' + quota.comment + ')';
               }
               bookable_time_count += 1;
               var li = '<li id="' + quota_id + '"><a href="#" title="' + quotaText + '" class="' + 
                        availableClass + ' ' + selected_class + '">' + quotaText + '</a></li>';
               html_list += li;
           }
       });
       if ( bookable_time_count === 0)
       {
            html_list = $('#booking_page_config_no_available_quota_message').val();
       }
       callback( html_list);
   });
};

$(document).ready(function(){
    hide_step3();
    
    // select default restaurant
    $('#RE_ID').find('option[value="' + $('#param_default_restaurant_id').val() + '"]').attr('selected', 1);
 
    if($('#RE_ID').find('option[value="' + $('#param_default_restaurant_id').val() + '"]').val() == null && $('#RE_ID').find('option').size() > 1){
        $('#RE_ID').prepend('<option value="-1" selected="selected">請選擇</option>');
    }
    // update bookable time list when user input booking info
	$("#RE_ID").change(find_bookable_time).change(restaurantIdChangeHandler);
 	$("#step2 :input").change(find_bookable_time).change(find_discount);

	find_bookable_time();
	restaurantIdChangeHandler();

    // set bookable time click handler
    $('ul.timeLine li a.available').live( 'click', function(event){
        $('ul.timeLine li a' ).removeClass('visited');
        $('#quota_id').val( $(event.target).parent().attr('id') );
        $(event.target).addClass('visited');
        show_step3();
        event.preventDefault();
    });

    // set form submit handler
    $('#booking_info_form').submit( function(){
        // check form input
        if($('#param_lang').val() == 'zh_TW.utf8') {
            if(!checkEmail()){
                $("#email_msg").html("信箱格式錯誤");
                return false;
            }else{
                $("#email_msg").html("");
            }
            if(!checkName()){
                $("#name_msg").html("請填寫正確姓名");
                return false;
            }else{
                $("#name_msg").html("");
            }
            if(!checkTel()){
                $("#tel_msg").html("電話號碼錯誤 (無需加上括號或連字號)");
                return false;
            }else{
                $("#tel_msg").html("");
            }
        }
        
        if ( ! validate_booking() )
        {
            return false;
        }

        set_submit_effect();
        return true;
    });

    setDatePicker();

    // facebook login
    if($("#fb-login").length > 0) {
        // init FB
        EZTABLE.login.initFB({
            locale: 'zh_TW'
        });
        
        $("#fb-login").click(function(){
            EZTABLE.login.loginFacebook({
                success: function(response) {
                    if(response.status == "OK") {
                        var data = response.data;
                        $("#email").val(data.member.email);
                        $("#tel").val(data.member.tel);
                        $("#name").val(data.member.real_name);
                        $('input[name="gender"][value="' + data.member.gender + '"]').attr('checked', 1);
                        $("#login_container").hide();
                    }
                },
                fail: function(){},
                params: EZTABLE.addCommonParams({})
            });
            return false;
        });
    }
});

function restaurantIdChangeHandler() {
    find_discount();
    // update by booking page configuration
    var apiPath = 'restaurant/get_booking_page_config/';
    apiPath += $("#RE_ID").val() + '/';
    
    var apiParams = {};
    
    EZTABLE.api({
        path: apiPath, 
        params: apiParams, 
        success: function(returnValue) {
            // check exception
            if(returnValue.status != EZTABLE.API_STATUS.OK) {
                // TODO: handle error
                return;
            }
            var data = returnValue.data;
            if(data === false) {
                // default values
                $('#html_below_restaurant_div').html('');
                $('#html_below_people_div').html('');
                $('#booking_page_config_no_available_quota_message').val(MSG_NO_AVAILABLE_QUOTA);
                return;
            }
            // update page
            $('#html_below_restaurant_div').html(data.html_below_restaurant);
            $('#html_below_people_div').html(data.html_below_people);
            if(data.has_special_request === 0) {
                $('#special_request_div').hide();
            }
            if(data.no_available_quota_message !== undefined && data.no_available_quota_message.length > 0) {
                $('#booking_page_config_no_available_quota_message').val(data.no_available_quota_message);
            } else {
                $('#booking_page_config_no_available_quota_message').val(MSG_NO_AVAILABLE_QUOTA);
            }
            // TODO: rebuild people menu
        }
    });
}


function setDatePicker () {
    $("#readable_date").datepicker({
        dateFormat: 'yy-mm-dd (D)',
        showOn: 'both',
        buttonImage: '/images/restaurant_img/date.png',
        buttonImageOnly: true,
        buttonText: '請選擇日期',
        altField:'#date',
        altFormat:'yy-mm-dd'                                               
    });
}

/**
 * 將可訂位時間區塊 & 下一步隱藏
 *
 * @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 validate_booking()
{
	var fm = document.form1;
    // check one of the bookable time has been selected
	if( $('ul.timeLine li a.visited').length === 0 )
	{
		alert(SELECT_AVAILABLE_TIME);
		return false;
	}

    if(!check_booking())
    {
        return false;
    }

    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(), 10 ) ) || parseInt( $('#RE_ID').val(), 10) < 1 )
    {
		hide_step3();
        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
    show_loading_image();

    var target_date; 
    var options;
    target_date = $('#date').val();
    if ( $('#BR_ID').val() === "")
    {
        options = { 
            ulClass: 'timeLine'
        };

        list_bookable_time( 
            $('#RE_ID').val(), 
            target_date, 
            $('#people').val(), 
            options, 
            show_bookable_time);
    }
    else
    {
        options = { 
            selected_time: $('#selected_time').val(),
            ulClass: 'timeLine'
        };

        list_reservation_bookable_time( 
            $('#BR_ID').val(),
            $('#RE_ID').val(), 
            target_date, 
            $('#people').val(), 
            options, 
            show_bookable_time);

        // set clicked time automatically
        var selected_time_and_quota = $('ul.timeLine li a.visited' ).parent().attr('id');
        $('#quota_id').val( selected_time_and_quota);
    }
}

/**
 * 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( response)
{
    $('#msg').html(response);
    $('#loading_image_div').hide(); 
    $('#check_bookable_div').show();
}

/**
 * 在使用者送出所有訂位資訊時，呈現運算中的 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);

}

function getToday() {
    var currentTime = new Date();
    var month = currentTime.getMonth();
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();
    return year + '-' + month + '-' + day;
}

function find_discount() {
    if (!check_did_been_set()) {
        return;
    }
    var today = getToday();
    
    var apiPath = 'restaurant/get_events/';
    apiPath += $("#RE_ID").val() + '/';
    
    var params = {};
    
    EZTABLE.api({
        path: apiPath, 
        params: params, 
        success: function(returnValue) {
            var html = '<ul style="margin-bottom:0px;margin-top:-30px;">';
            $.each(returnValue.data, function(index, event) {
                html = html + '<li><label>';
                if(event.start_date_ymd > today) {
                    html = html + event.start_date_ymd + ' 起，';
                }
                if(event.end_date_ymd < '2011-12-31') {
                    
                    html = html + '至 ' + event.end_date_ymd + ' 止，';
                }
                html = html + event.extra_booking_info;
                html = html + '</label></li>';
            });
            html = html + '</ul>';
            $('#ad_area').html(html);
        }
    });
}

function check_required_column(objID, sMessage){
    var objField = document.getElementById( objID );
    if ( objField === undefined || objField.value.replace( /\s/g, "" ).length === 0 ) {
        alert(sMessage);
        objField.focus();
        return false;
    }
    return true;    
}

function check_email_column(objID, sMessage)
{
    var objField = document.getElementById( objID );
    var filter= /^([\w-]+(?:\.\w+)*)@((?:\w+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    if ( ! filter.test( objField.value )) {
        alert(sMessage);
        objField.select();
        objField.focus();
        return false;
    }
    return true;
}

function checkEmail(){
    var mail = $("#email").val();
    var pattern =/^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    return pattern.test(mail);
}

function checkTel(){
    var tel = $("#tel").val();

    var pattern;
    if ( tel.indexOf("09") === 0 )
    {
        pattern =/^[0-9]{10,10}$/;
        return pattern.test(tel);
    }
    else
    {
        pattern =/^[0-9]{6,}$/;
        return pattern.test(tel);
    }
}

function checkName(){
    var name = $("#name").val();
    var pattern =/^[^0-9]*$/;
    return pattern.test(name) && (name.length > 0);
}

