// EZTABLE
var $EZTABLE = {};

$EZTABLE.MSG_TYPE = {
        TYPE_TEXT: 'text',
        TYPE_RESERVATION_ADD: 'reservation_add',
        TYPE_RESERVATION_MODIFICATION: 'reservation_modification',
        TYPE_RESERVATION_CANCELED: 'reservation_canceled',
        TYPE_RESERVATION_INVITATION: 'reservation_invitation',
        TYPE_QUESTIONNAIRE_LINK: 'questionnaire_link'
};

$EZTABLE.CHANNEL_TYPE = {
        RESERVATION: 'RESERVATION',
        RESTAURANT: 'RESTAURANT'
};

$EZTABLE.RESERVATION_STATUS = {
        OK: 'ok',
        NO_SHOW: 'no-show',
        CANCELED: 'canceled',
        NNEW: 'new',
        CHANGED: 'changed'
};

$EZTABLE.API_STATUS = {
        OK: 'OK',
        EZ_PERMISSION_EXCEPTION: 'EZPermissionException'
};

$EZTABLE.debugMsg = function(msg) {
    if(location.hostname == "eztable.com" || 
            location.hostname == "eztable.com.tw" || 
            location.hostname == "www.eztable.com" || 
            location.hostname == "www.eztable.com.tw") {
        return;
    }
    alert(msg);
};

$EZTABLE.getAPIHost = function() {
    if( location.hostname == "eztable.com" || 
        location.hostname == "eztable.com.tw" || 
        location.hostname == "www.eztable.com" || 
        location.hostname == "www.eztable.com.tw" || 
        location.hostname == "partner.eztable.com.tw" || 
        location.hostname == "partner.eztable.com" || 
        location.hostname == "partner-staging.eztable.com" || 
        location.hostname == "staging.eztable.com.tw") {
        return "http://api.eztable.com/v2/";
    }
    if(location.hostname == "zac.eztable.com.tw" || location.hostname == 'partner-dev.eztable.com.tw') {
        return "http://api-dev.eztable.com/v2/";
    }
    return "http://" + location.host + "/v2/";
};

$EZTABLE.addCommonParams = function(params) {
    // add access token
    var access_token = $('#param_access_token');
    if(access_token.length > 0) {
        params.access_token = access_token.val();
    }
    // add lang
    var lang = $('#param_lang');
    if(lang.length > 0) {
        params.lang = lang.val();
    }
    return params;
};

$EZTABLE.api = function(settingsOrPath, params, success, error) {
    // $EZTABLE.api({
    //     "path"   : '...',
    //     "params" : {...},
    //     "success": function() {...},
    //     "error"  : function() {...}
    // });
    var path;
    if (arguments.length===1 && typeof settingsOrPath==='object') {
        path    = settingsOrPath.path;
        params  = settingsOrPath.params;
        success = settingsOrPath.success;
        error   = settingsOrPath.error;
    } else {
        path = settingsOrPath;
        if (typeof window.console!=='undefined' && typeof window.console.log!=='undefined') {
            console.log('Now you can request EZTABLE-API like $.ajax; i.e. $EZTABLE.api(settings)');
        }
    }
    
    // jsonp
    $.ajax({
        url: $EZTABLE.getAPIHost() + path + '?jsoncallback=?',
        dataType: 'json',
        data: $EZTABLE.addCommonParams(params),
        success: success,
        error: function(xhr, status, thrown) {
            if (typeof error === 'function') {
                error(xhr, status, thrown);
            } else {
                $EZTABLE.debugMsg('error in: ' + thrown.url + ' \n'+'error:\n' + xhr.responseText);
            }
        }
    });
};


$EZTABLE.restaurant = {};
$EZTABLE.restaurant.get_open_quota = function( restaurant_id, target_date, people, callback) {
     // call api
     var apiPath = 'restaurant/get_open_quotas/';
     apiPath += restaurant_id + '/';
     apiPath += target_date + '/';
     apiPath += people + '/';
     
     var params = {};
     
     $EZTABLE.api(apiPath, params, 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.
 * 
 * <h4>Permission:</h4> public.
 * 
 * @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.
 */
$EZTABLE.restaurant.get_reservation_open_quotas = function( 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 + '/';
     
     var params = {};
     
     $EZTABLE.api(apiPath, params, callback);
};


/**
 * list_bookable_time
 *
 * @param restaurant_id
 * @param target_date 
 * @param people
 * @param options
 * @param callback
 * @return  void
 */
$EZTABLE.restaurant.list_bookable_time = function( restaurant_id, target_date, people, options, callback) {
    var MSG_NO_AVAILABLE_QUOTA = 
        'No tables are available at the restaurant you selected. ' + 
        ' Please re-select your time or choose another restaurant instead.'; 

   $EZTABLE.restaurant.get_open_quota( 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( MSG_NO_AVAILABLE_QUOTA);
           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;
               html_list += ('<li id="' + quota_id + '"><a href="#" class="' + availableClass + '">' + quota.start_time + '</a></li>');
           }
       });
       if ( bookable_time_count === 0)
       {
            html_list = '當日已無法接受訂位';
       }
       callback( html_list);
   });
};


/**
 * list_reservation_bookable_time
 *
 * @param reservation_id
 * @param restaurant_id
 * @param target_date 
 * @param people
 * @param options
 * @param callback
 * @return  void
 */
$EZTABLE.restaurant.list_reservation_bookable_time = function( 
        reservation_id, restaurant_id, target_date, people, options, callback) {

    var MSG_NO_AVAILABLE_QUOTA = 
        'No tables are available at the restaurant you selected. ' + 
        ' Please re-select your time or choose another restaurant instead.'; 

   $EZTABLE.restaurant.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( MSG_NO_AVAILABLE_QUOTA);
           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) {
                bookable_time_count += 1;
               html_list += ('<li id="' + quota_id + '"><a href="#" class="' + 
                   availableClass + ' ' + selected_class + '">' + quota.start_time + '</a></li>');
           }
       });
       if ( bookable_time_count === 0)
       {
            html_list = '當日已無法接受訂位';
       }
       callback( html_list);
   });
};
