/* update on 24/05/2018  with GTM */
'use strict';
window.App ={} ;
window.ErMsg ='';
App.weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
App.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
App.orderPlace = false ;
App.getUrlVars = function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
    
};
App.checkPrivateMode=function(){
    var storage = window.sessionStorage;
    try {
        storage.setItem("someKeyHere", "test");
        storage.removeItem("someKeyHere");
        return false;
    } catch (e) {
        if (e.code === DOMException.QUOTA_EXCEEDED_ERR && storage.length === 0) {
            return true;
        }
    }
};
App.menupanel = function(){
     $('.item_menupanel').masonry({
          percentPosition: true,
          itemSelector: '.item_menu',
          resize: true
      });
};
if($.jStorage.get("version")){
    if(window.version != $.jStorage.get("version")){
        $.jStorage.flush();
        $.jStorage.set("version",window.version);
        window.location.reload(true);
    }    
}else{
    $.jStorage.flush();
    $.jStorage.set("version",window.version);
}
$('#templates').load('templates.html?v='+version);

window.addEventListener("orientationchange", function() {
             setTimeout(function(){        
                    switch(window.location.hash){
                    case "#!reserve_a_table":
                        App.reserveATable();
                        break;
                    default :
                        if(window.location.hash !== ''){
                            var id = (window.location.hash).replace('!', '').split('?');
                            if($(id).length){
                                $('html, body').stop().animate({scrollTop: $(id[0]).offset().top}, "slow");
                            }
                        }

                }
            }, 300);
    
        });
$(document).on('ready', function() { 
    $('.t_change_address').on('click',$.proxy(App.geoSearchAddress,App));
    $('input[name=munchservices]').on('change',$.proxy(App.changeOrderType,App));
    
    $('.y-go-to-checkout').on('click',$.proxy(App.cartNcheckout,App));
    $('.y-checkoutBtn').on('click',$.proxy(App.goForCheckout,App));
    
    $('.y-go-to-menu').on('click',$.proxy(App.goToMenu,App));    
    $('.y-reserveTable').on('click',$.proxy(App.reserveATable,App));
    $('.y-third_party_reservation').on('click',$.proxy(App.thirdpartyreservation,App));
    $('.y_location').on('click',$.proxy(App.locationPopup,App));
    $('.y_goto_dmpage').on('click',$.proxy(App.trackClick,App));    
    $('input#promocode').on('keydown',$.proxy(App.hitApplyPromo,App));
    $('input#promocode').on('keyup',$.proxy(App.clearError,App));
   
    
/* for hamburger in desktop view */
  $('body').mouseup(function (e){
        var container = $(".outerDIVclose");
        if (container.has(e.target).length === 0 && !$(e.target).is('#timepicker1') ){
          container.hide();
            $('body').removeClass('modal-open');
            if($('#timepicker1').hasClass('active')) {
                $('#timepicker1').removeClass('active');
            }
        }
    });
    
    App.mobileView();     
});

App.goForCheckout= function(){
    $('.checkout_loader').removeClass('hide');
    App.validateOrderTime('checkout');
};

App.clearError=function(e){    
    if($.trim($('input#promocode').val())===''){
        $(".promo_code .error-message").addClass("hide").html('');
    }
 } ;
App.hitApplyPromo=function(e){    
    if (e.keyCode === 13) {
        App.applyPromocode();
    }
 } ;   
App.trackClick = function(){
    dataLayer.push({
        'event':'Join Now',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_dm_join_now_Button_',
        'RestaurantID':restId
    });
};
$('body').mouseup(function (e){
    if(!App.mobileDevice()){
        var container = $(".outerDIVclose_mobile");
        if (container.has(e.target).length === 0){
          container.addClass('hide').removeClass('outerDIVclose_mobile');
          $('body').removeClass('modalblackbg');
        }
        }
    });
App.mobileView=function(){
    if(App.mobileDevice()){        
        $('.ordersummarystep1').addClass('hide');
        $('.ordersummarystep2').addClass('hide');
    }else{       
        $('.ordersummarystep1').removeClass('hide');
        $('.ordersummarystep2').removeClass('hide');
    }
};
App.cartNcheckout = function() {    
    dataLayer.push({
        'event':'Cart Click',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_cart_Button',
        'RestaurantID':restId
    });
    if(App.mobileDevice()){
        $('.link_mobilemenu').removeClass('active');
        $('.dropdown_mobile').removeClass('active');
        $('body').removeClass('a_modal_open');
        if($.jStorage.get('order_items_'+restId).length === 0){
            $('body').removeClass('modalblackbg a_modal_open');
            $('.y-additems').removeClass('hide');
            $('.menutab').removeClass('hide');
            $('.sticky_deal').removeClass('hide');
            $('.checkoutDiv').addClass('hide outerDIVclose_mobile');
            $('.ordersummarystep1').addClass('hide');            
            $('#menu > ._960px > .sectiontitle').html("Menu");
            $('html, body').stop().animate({scrollTop: $('.menutab').stop().offset().top - 55}, "slow");
        }else{
            $('.y-additems').addClass('hide');
            $('.ordersummarystep1').removeClass('hide').addClass('outerDIVclose_mobile');
            $('.checkoutDiv').addClass('hide');
            $('body').addClass('modalblackbg a_modal_open');
            $.jStorage.set('mobile_card_open',1);
            $('.sticky_deal').addClass('hide');
            $('.y-backtomenu').off('click');
            $('.y-backtomenu').on('click',$.proxy(App.backtoMenu,App));
            $('.checkoutsection').removeClass('hide');            
            $('html, body').stop().animate({scrollTop: $('.ordersummarystep1').stop().offset().top - 55}, "slow");
            $('.y-go-to-menu').addClass('active');
            
        }
       App.menupanel();
       App.checkDateTime('menu');
    }else{
        if($.jStorage.get('order_items_'+restId).length === 0){ 
        $('.navbarcontainer').removeClass('active');
$('html, body').stop().animate({scrollTop: $('#menu').offset().top}, "slow");           
            if(App.orderPlace){
                $('.menutab').removeClass('hide');
                $('.checkoutDiv').addClass('hide');
                $('.t-edit_order_link').removeClass('hide');
                $('#menu > ._960px > .sectiontitle').html("Menu");
                App.renderCart();       
            }else{
                setTimeout(function(){
                    App.MinAmount('t-no-order');
                },1000);
                App.checkDateTime('menu');
            }
         App.menupanel();    
        }else{
            $('.checkout_loader').removeClass('hide');
            App.validateOrderTime('checkout');
        }       
    }
    App.clearTimeError(); 
};
App.handleCartPopup=function() {    
    if(App.mobileDevice()){
        if($.jStorage.get('mobile_card_open')){
          App.cartNcheckout(); 
        }
    }
};
App.backtoMenu = function() {  
    if(App.mobileDevice()){
       $.jStorage.set('mobile_card_open',0);
       $('#menu > ._960px > .sectiontitle').html("Menu"); 
       $('html, body').stop().animate({scrollTop: $('._menu').offset().top}, "slow");
       $('.ordersummarystep1').addClass('hide');
       $('.checkoutDiv').addClass('hide');
       $('.menutab').removeClass('hide');       
       $('.hasDeal').removeClass('hide');   
       $('body').removeClass('modalblackbg a_modal_open');
       $('html, body').stop().animate({
           scrollTop:$('._menu').offset().top
        }, "slow");
        dataLayer.push({
            'event':'back to Menu',
            'restname': App.currentRestaurant.name,
            'ev_label': 'Click_on_backtoMenu_Button',
            'RestaurantID':restId
        });
        App.renderDateTime();
    }
    App.menupanel(); 
};
App.mobileDevice = function() {
    if (/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        if($(window).width()<= 767){
            return true;
        }else {
           return false;
        }    
    } else {
        return false;
   }
};

App.goToMenu=function (){ 
 $('#menu > ._960px > .sectiontitle').html("Menu");

 $('.ordersummarystep1').css({'bottom': '','position': '','right': ''});
 $('.menutab').removeClass('hide');
 $('.checkoutDiv').addClass('hide');
 App.renderCart(); 
 App.menupanel();
 App.clearTimeError(); 
 
};
App.renderCalender=function (data){
    var tmpl = _.template($("#tmpl-restaurant-calender").html());  
    $('.y-resCalender').html(tmpl({calendar:data}));
};

App.showTooltip=function (item){
    $('.y_tooltip').removeClass('hide');
    $('.added_item').html(item);

    /* arrange ids i order item start*/
    var order_items = $.jStorage.get('order_items_'+restId);
    if(order_items.length >1){
       var items=[];
       var i=1;
       _.each(order_items,function(item){
           item.uid=item.item_id+"_"+i;
           item.id=i;
           items.push(item);
           i++;
       });
       $.jStorage.set('order_items_'+restId,items);
    }   
    /* arrange ids i order item end*/ 
    setTimeout(function(){
        $('.y_tooltip').addClass('hide');
        $('.added_item').html('');
    },5000);
};
App.renderMap=function (){
    if($('#viewmap').length){
        App.myLatLong = new google.maps.LatLng(App.currentRestaurant.latitude, App.currentRestaurant.longitude);
    //    App.myLatLong = new google.maps.LatLng(41.857813,-87.676152);
            App.mapOptions = {
                zoom:17,
                draggable: true,
                scrollwheel: false,
                disableDefaultUI:true,
                zoomControl: false,           
                disableDoubleClickZoom: true,
                center: App.myLatLong,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };    
        App.map = new google.maps.Map(document.getElementById('viewmap'),App.mapOptions);
        App.marker = new google.maps.Marker({
            position: App.myLatLong,
            title: App.currentRestaurant.name   
        });   
        App.marker.setMap(App.map);
        App.infowindow = new google.maps.InfoWindow({
              content: '<div class="map-width"><strong>' + App.currentRestaurant.name + '</strong><br>' + App.currentRestaurant.address + ', ' + App.currentRestaurant.city + ', '+stateCode+' '+ App.currentRestaurant.zipcode + '</div>'
            });
        App.marker.addListener('click', function() {
            App.infowindow.open(App.map, App.marker);
        });
        setTimeout(function(){       
            google.maps.event.trigger(App.map, 'resize');        
            App.map.setCenter(App.myLatLong);
            setTimeout(function(){ 
                App.infowindow.open(App.map, App.marker);    
            },1500);
        },5000);
    }
};
App.goToCheckout=function (){
    dataLayer.push({
        'event':'Checkout',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_Checkout_Button',
        'RestaurantID':restId
    });
    if(($.jStorage.get('order_type_'+restId)==='delivery' && $.jStorage.get('can_deliver_'+restId)===false) || ($.jStorage.get('order_type_'+restId)==='delivery' && $.jStorage.get('can_deliver_'+restId)===null)){
        $('.t_change_address').trigger('click',$.proxy(App.geoSearchAddress,App));
    }else{

    if(App.checkoutValidate()===false){
        App.tooltipselecttimeshow();
        $('body').addClass('a_modal_open');
        return false;
    }   
    if($.jStorage.get('order_items_'+restId).length === 0){
        App.MinAmount('t-no-order');
       // App.renderCart();
        return false;
    }else{
        App.renderDeliveryAddress();           
        App.renderItems();
    }
    if(($.jStorage.get('order_type_'+restId)==='delivery') && (parseFloat($.jStorage.get('order_subtotal_'+restId)) < parseFloat(App.currentRestaurant.minimum_delivery))){
        App.MinAmount('t-min-order');
        return false;
    }
    /* clear summery*/
    $('.y-paymentDetails').addClass('hide');
    $('.y-cardNo').html("");
    $('.y-cardType').html("");
    $('.y-expOn').html("");    
    if ($.jStorage.get('order_type_'+restId) === "delivery") {
        $('.y-deliveryTo').removeClass('hide');
        $('.y-deliveryAddress').html($.jStorage.get("address_value_"+restId));
    }else{
        $('.y-deliveryTo').addClass('hide');
        $('.y-deliveryAddress').html("");
    }
    $('.menutab').addClass('hide');
    $('.checkoutDiv').removeClass('hide');
    if(App.mobileDevice()){
       $('.checkoutDiv').addClass('outerDIVclose_mobile');
       $('.menutab').removeClass('hide');
       $('body').addClass('modalblackbg a_modal_open');
       $('.ordersummarystep1, .ordersummarystep2').addClass('hide').removeClass('outerDIVclose_mobile');
       $('html, body').stop().animate({scrollTop: $('.checkoutDiv').offset().top - 55}, "slow");    
    }else{
        $('.tooltip').addClass('hide');
        $('.t-edit_order_link').removeClass('hide');
        $(".t-edit_order_link").off('click');
        $(".t-edit_order_link").on('click', $.proxy(App.editOrders,App));    
        $('body').removeClass('modalblackbg a_modal_open');
        $('html, body').stop().animate({scrollTop: $('#menu').offset().top}, "slow");   
        $('#menu > ._960px > .sectiontitle').html("Checkout");
    }
    $('.y-order-type,.y-orderType').html($.jStorage.get('order_type_'+restId));
    $('.y-restarant-phone').html('<a class="contact_resphoneno" href="tel:' + App.currentRestaurant.phone_no + '">' + App.formattedPhoneNo(App.currentRestaurant.phone_no) + ' </a>');
    $('.y-order-type-msg').html($.jStorage.get('order_type_'+restId)); 
    var msg = 'Your delivery order comes to <strong class="y-order-total">$'+$.jStorage.get('order_total_'+restId)+'</strong> and gives the delivery person a chance to get in some cardio';
    if($.jStorage.get('order_type_'+restId)==='takeout'){
        $('.y-order-type-msg').html('pick up');
        msg = 'Your takeout order comes to <strong class="y-order-total">$'+$.jStorage.get('order_total_'+restId)+'</strong> and brings you one step (and a short walk) closer to food nirvana.' ; 
    }
    $('.y_checkout_heading').html(msg);
    $('.y-order-total').html("$"+$.jStorage.get('order_total_'+restId));                 
    App.getRestaurant();
    var tmpl = _.template($("#tmpl-checkout").html());
    App.checkDateTime('checkout');
    if(!App.chkoutProcess){
        $('.checkoutsection').html(tmpl());
        App.chkoutProcess=1;        
        $('input[type=checkbox]').change(function(){
        if($(this).is(":checked")){
                 $(this).parent().addClass('ticked');
            }else{
                 $(this).parent().removeClass('ticked');
            }
        });
        App.inputFormatter();
        App.bindEvents();
        
       $(".special_instruction").click(function(){App.textCounterChout();});
       $(".special_instruction").keyup(function(){ App.textCounterChout(); });
       $(".special_instruction").blur(function(){  App.textCounterHideChout(); });
       $(".placemyorder").off('click');
       $(".placemyorder").on('click', $.proxy(App.goForOrder, App));   
    }else{
        if($.jStorage.get('order_type_'+restId)==='delivery'){
           $('.y_checkout_delivery_address').removeClass('hide'); 
        }else{
           $('.y_checkout_delivery_address').addClass('hide');
        }
    }
    var tmpl_address = _.template($("#tmpl-checkout-address").html());
    if($.jStorage.get('order_type_'+restId)==='delivery'){
           $('.y_checkout_delivery_address').removeClass('hide').html(tmpl_address); 
    }else{
       $('.y_checkout_delivery_address').addClass('hide');
    } 
    var tmpl_instruction= _.template($("#tmpl-chk-instruction").html());
    $('.y_checkout_chk_instructions').html(tmpl_instruction);  
    
    if($('html').hasClass('mobile')){
       $('.creditcard-cvv').prop('type','tel');
    }else{
        $('.creditcard-cvv').prop('type','password');
    }
    
  }
   App.clearTimeError(); 
};

App.clearTimeError=function(){
    if($(".time_slot_error").length >0){
        $(".time_slot_error").html("").addClass("hide");
    }
    if($(".stripe-error").length >0){
        $(".stripe-error").html("");
        $(".stripe-error").closest('.row').addClass("hide"); 
    }
};

App.textCounterHideChout=function(){
    var text_length = $('.special_instruction').val().length;
    var text_remaining = App.text_max - text_length;                    
    $('.txt_word_count').html(text_remaining + ' character(s) remaining');
    $('.txt_word_count').css('visibility', 'hidden');
};
App.textCounterChout=function(){
    var text_length = $('.special_instruction').val().length;
    var text_remaining = App.text_max - text_length;                    
    $('.txt_word_count').html(text_remaining + ' character(s) remaining');
    $('.txt_word_count').css('visibility', '');
};
App.getRestaurant=function (){
    $.ajax({
        url:apiUrl+'/restaurant/details/'+restId+'?token='+$.jStorage.get('oauth.token'),
        cache: false,
        type: 'get',
        success: function(data) { 
            App.currentRestaurant = data;
            App.setDeliveryTakeoutTime(); 
        },
        error: function() {
            App.setDeliveryTakeoutTime();
        }
    });
};
App.renderCart=function (){
    if(App.currentRestaurant!==undefined){ 
        if((App.currentRestaurant.has_delivery=="1") && (App.currentRestaurant.has_takeout=="1")){
            $('#t_takeout').removeAttr('disabled');
            if(!$.jStorage.get('order_type_'+restId)){
                $.jStorage.set('order_type_'+restId,'delivery');
            }
            $('.but_order_type, .delivery_notavailable').addClass('hide');
        }else if(App.currentRestaurant.has_delivery=="0"){            
             $('#t_delivery').prop('disabled','disabled');

             $('.box_ordersummary .btn_service').addClass('hide');
             $('.txt_order_onlytakeout').removeClass('hide');
            
            if(!$.jStorage.get('order_type_'+restId)){
                $.jStorage.set('order_type_'+restId,'takeout');
            }
            if($.jStorage.get('order_type_'+restId)==='delivery'){
                $.jStorage.set('order_type_'+restId,'takeout');
            } 
        }else if(App.currentRestaurant.has_takeout=="0"){ 

            $('.box_ordersummary .btn_service').addClass('hide')
            $('.txt_order_onlydelivery').removeClass('hide');

            $('#t_takeout').prop('disabled','disabled');
            if(!$.jStorage.get('order_type_'+restId)){
                $.jStorage.set('order_type_'+restId,'delivery');
            }
            if($.jStorage.get('order_type_'+restId)==='takeout'){
                $.jStorage.set('order_type_'+restId,'delivery');
            }
        }    
    }else{
        $('#t_delivery').removeAttr('disabled');
        if(!$.jStorage.get('order_type_'+restId)){
            $.jStorage.set('order_type_'+restId,'takeout');
        }
    }    
    if(!$.jStorage.get('delivery_order_date_'+restId)){
        $.jStorage.set('delivery_order_date_'+restId,'');
        $.jStorage.set('delivery_order_time_'+restId,'');
    }
    if(!$.jStorage.get('takeout_order_date_'+restId)){
        $.jStorage.set('takeout_order_date_'+restId,'');
        $.jStorage.set('takeout_order_time_'+restId,'');        
    } 

    if(!$.jStorage.get('tip_'+restId)){
        App.setJStorage("tip_"+restId,15);
    }    
    $('.y-checkoutBtn').html('checkout for '+ $.jStorage.get('order_type_'+restId));
    App.orderPlace = false ; 
    App.renderDateTime();
    App.renderDeliveryAddress();           
    App.renderItems();
};
App.get12HourTime=function(time){
    var date = App.parseDate('1970-01-01 ' + time);
    var hours = date.getHours();
    var isAM = hours >= 12 ? false : true;
    hours = hours > 12 ? hours - 12 : hours;
    hours = parseInt(hours, 10) === 0 ? 12 : hours;
    return App.paddLeft(hours, 0, 2) + ":" + App.paddLeft(date.getMinutes(), 0, 2) + " " + (isAM ? "AM" : "PM");
};
App.getFormattedDateText=function(date) {
    var tempDate = App.parseDate(date);
    var tempDate2 = App.parseDate(App.currentRestaurant.current_dateTime);            
    if (tempDate.getDate() === tempDate2.getDate()) {
        return 'Today';
    }else{
        return App.weekdays[tempDate.getDay()] + ", " + App.months[tempDate.getMonth()] + " " + tempDate.getDate();
    }
};
App.setJStorage=function(key,value){
  $.jStorage.set(key, value);     
};

App.getTimeSlots = function(orderType,orderDate){
    if(!orderType){
       App.renderCart(); 
       var orderType= $.jStorage.get('order_type_'+restId);
    }
    $(".t-saveDateTime").off('click'); 
    $.ajax({
            url:apiUrl+'/restaurant/timeslot/'+restId+'?date='+orderDate+'&type='+orderType+'&token='+$.jStorage.get('oauth.token'),
            cache: false,            
            type: 'get',
            success: function(data) {
                
                if((data.timeslots != null) && (data.timeslots.length !==0)) {
                    App.renderTimeSlots(data.timeslots,orderType);
                }else{
                    App.reloadTimes('menu');
                }
                
               
            },
            error: function() {
        }
    });
};
App.renderTimeSlots=function(data,orderType){
    var options = '';
    var timeKey='delivery_order_time_'+restId;   
    if(orderType==='takeout'){ 
        timeKey='takeout_order_time_'+restId;       
    }
    var selected = $.jStorage.get(timeKey)?$.jStorage.get(timeKey):''; 
    var selectedTime = sessionStorage.getItem("timeSelected");
    if(!selectedTime){
        selected = data[0];
        $.jStorage.set(timeKey,selected);
    }  
    var i=1;
    _.each(data,function(item){
        var select='';
        if(selectedTime){
            if(item==selected){
              select =' selected'; 
              $.jStorage.set(timeKey,item);
            }else{
                if(i===1){
                    select =' selected'; 
                    $.jStorage.set(timeKey,item);
                }
            }
        }
        options +='<option value="'+item+'"'+select+'>'+App.get12HourTime(item)+'</option>'; 
        i++;
    });
    App.checkDateTime('menu');
    $('.t-order-time').html(options); 
    $(".t-saveDateTime").off('click');
    $(".t-saveDateTime").on('click', $.proxy(App.saveDateTime,App));
};
App.validateOrderTime =  function(action){
    
    var orderType = $.jStorage.get('order_type_'+restId);
    var datekey= orderType ==='delivery'?'delivery_order_date_'+restId:'takeout_order_date_'+restId;
    var timekey= orderType ==='delivery'?'delivery_order_time_'+restId:'takeout_order_time_'+restId;
    
    var date = $.jStorage.get(datekey);
    var time = $.jStorage.get(timekey);
    if(date=="" || time==""){
        $('.placemyorder').removeClass('disabled');          
        $('.checkout_loader').addClass('hide');
        $('.y-go-to-menu,.y-reserveTable,.pagejump').removeClass('disabled');  
        $('.y-go-to-checkout').removeClass('disabled'); 
        $('.t-edit_order_link').removeClass('hide');
        $('#menu').removeClass('form_disable');  
        return false ; 
    }
    var selectedTime = App.parseDate(date + " " + App.get24HourTime(time));

    $.ajax({
        url:apiUrl+'/currenttime/'+restId+'?token='+$.jStorage.get('oauth.token'),
        cache: false,            
        type: 'get',
        success: function(data) {
                var currentDateTime = App.parseDate(data.city_date_time);
                var diff_date =  parseInt(selectedTime.getTime()-currentDateTime.getTime());
                console.log(selectedTime);
                console.log(currentDateTime);
                console.log(diff_date);
                
                if((!selectedTime) || (!currentDateTime) || (diff_date < 1800000)){
                    if(action==='checkout'){
                        $('.checkout_loader').addClass('hide');
                        $(".time_slot_error").removeClass("hide").html("Psst...it's already past your order time!");
                        //$("html,body").stop().animate({scrollTop: $('.time_slot_error').offset().top - 50}); 
                    }
                    if(action==='placeOrder'){
                        
                        $(".stripe-error").html("Psst...it's already past your order time!");
                        $(".stripe-error").closest('.row').removeClass("hide");
                        
                        $('.placemyorder').removeClass('disabled');          
                        $('.confirm_loader').addClass('hide');
                        $('.y-go-to-menu,.y-reserveTable,.pagejump').removeClass('disabled');  
                        $('.y-go-to-checkout').removeClass('disabled'); 
                        $('.t-edit_order_link').removeClass('hide');
                        $('#menu').removeClass('form_disable');     
                        $('.y-timeOfOrder').html(currentDateTime.dateFormat('D, M d')+ " at " + App.get12HourTime(currentDateTime.getHours() +":"+ currentDateTime.getMinutes())); 
                    }
                    
                }else{
                    App.clearTimeError(); 
                    if(action==='checkout'){
                        $('.checkout_loader').addClass('hide');
                        App.goToCheckout(); 
                    }
                    if(action==='placeOrder'){
                        if(App.updateTimer){
                            clearTimeout(App.updateTimer);
                        }
                        $('.y-timeOfOrder').html(currentDateTime.dateFormat('D, M d')+ " at " + App.get12HourTime(currentDateTime.getHours() +":"+ currentDateTime.getMinutes()));
                        App.placeOrder(); 
                    }
                }
                
            }
    });
};

App.renderDateTime = function(){
   var orderType = $.jStorage.get('order_type_'+restId); 
    var timeslots = App.getDateSlot(orderType);  
    App.clearTimeError(); 
    if(timeslots.length>0){
        var datekey = 'delivery_order_date_'+restId, timekey =  'delivery_order_time_'+restId ;
        var hours = App.currentRestaurant.delivery_hours;
        if(orderType==='takeout'){
            datekey = 'takeout_order_date_'+restId, timekey =  'takeout_order_time_'+restId ;
            $('#t_delivery').removeAttr("checked");
            $('#t_takeout').prop('checked','checked');
            hours = App.currentRestaurant.takeout_hours;
        }else{
            $('#t_takeout').removeAttr("checked");
            $('#t_delivery').prop('checked','checked');     
        }
        var date = $.jStorage.get(datekey), time = $.jStorage.get(timekey); 
        
        
        /* reset date time if expired start*/
        
            var minDateTime = new Date();
            if(App.currentRestaurant.current_dateTime){
                minDateTime = App.parseDate(App.currentRestaurant.current_dateTime);
            }
            App.currentDateTimeSlot=minDateTime.getTime() + 1800000;
            
            var selected_date= App.parseDate(date+" "+ time);
            
            if(isNaN(selected_date.getTime())){
                App.setJStorage(datekey,"");
                App.setJStorage(timekey,"");
                time =0;
                date =0 ;
            }
            if(selected_date.getTime() <= App.currentDateTimeSlot){
                App.setJStorage(datekey,"");
                App.setJStorage(timekey,"");
                time =0;
                date =0 ;
                console.log('reset date time');
            } 
           
         /* reset date time if expired end */   
        
        
       
        var tmptdatetime = _.template($("#tmpl-dateTime").html());
        if(!orderType){
            var orderType= $.jStorage.get('order_type_'+restId);
        }
        if(!date){ 
            var firstSlot = _.first(timeslots),date = firstSlot.value;
              
        } 
        App.setJStorage(datekey,date);
        $.ajax({
            url:apiUrl+'/restaurant/timeslot/'+restId+'?date='+date+'&type='+orderType+'&token='+$.jStorage.get('oauth.token'),
            cache: false,            
            type: 'get',
            success: function(data) { 
                
                if((data.timeslots != null) && (data.timeslots.length !==0)) {
                    var times = data.timeslots;
                    if(!time){
                        time = _.first(times);
                        App.setJStorage(timekey,time);
                    }else{
                        var selected = 0;
                        _.each(times,function(item){
                            if(item==time){
                                selected = 1;
                                App.setJStorage(timekey,time);
                            }
                        });
                        if(!selected){
                           time = _.first(times);
                           App.setJStorage(timekey,time); 
                        }
                    }
                    var data1 = { order_type:orderType, date:date,time:time,selectedDate:date,selectedTime:time,dates:timeslots,hours:hours};
                    $('.t-orderDateTimePanel').html(tmptdatetime(data1));        
                    $(".t-changeTime").off('click');
                    $(".t-changeTime").on('click', $.proxy(App.editDateTime,App));
                    App.getOperationsSlots(date);
                    App.checkDateTime('menu');
                }else{
                   App.reloadTimes('menu');
                }        
            },
            error: function() {}
        }); 
    }else{
        /*window.location.reload(true);*/
    }
     
};
App.getOperationsSlots = function(orderDate){ 
    $('.t-operation-hours').html('');
    $.ajax({
            url:apiUrl+'/restaurant/operations/'+restId+'?date='+orderDate+'&token='+$.jStorage.get('oauth.token'),
            type: 'get',
            success: function(data) {
               var orderType = $.jStorage.get('order_type_'+restId);
                var slots= data.reservation ; 
                if(orderType==='delivery'){
                   slots= data.delivery ;
                }              
                if(slots===''){
                    slots= data.reservation ;
                }
               $('.t-operation-hours').html(slots.toString(", "));
            }
    });
};
App.saveDateTime =function(){
    var orderType = $.jStorage.get('order_type_'+restId);
    var datekey= orderType ==='delivery'?'delivery_order_date_'+restId:'takeout_order_date_'+restId;
    var timekey= orderType ==='delivery'?'delivery_order_time_'+restId:'takeout_order_time_'+restId;    
    var date = $('.t-order-date').val();
    var time = $('.t-order-time').val();
    App.setJStorage(datekey,date);
    App.setJStorage(timekey,time);
    App.renderDateTime();
    sessionStorage.setItem("timeSelected","1");
    App.checkDateTime('menu');
};
App.checkDateTime =function(action){
    var orderType = $.jStorage.get('order_type_'+restId);
    var datekey= orderType ==='delivery'?'delivery_order_date_'+restId:'takeout_order_date_'+restId;
    var timekey= orderType ==='delivery'?'delivery_order_time_'+restId:'takeout_order_time_'+restId; 
   
    $.ajax({
            url:apiUrl+'/currenttime/'+restId+'?token='+$.jStorage.get('oauth.token'),
            cache: false,            
            type: 'get',
            success: function(data) {
                var date = $.jStorage.get(datekey);
                if(date && date!==''){
                    var time = $.jStorage.get(timekey);
                    var selectedTime = App.parseDate(date + " " + App.get24HourTime(time));
                    var currentDateTime = App.parseDate(data.city_date_time);

                    var diff_date =  parseInt(selectedTime.getTime()-currentDateTime.getTime());
                    var timeLeft = diff_date-1800000 ;
                    console.log(action);
                    if(timeLeft >0){
                        if(App.updateTimer){
                            clearTimeout(App.updateTimer);
                        }
                        App.updateTimer = window.setTimeout(function(){
                            console.log('time update');
                           App.getCurrentDateTime(action,date,datekey,timekey); 
                        },timeLeft);
                    }
                }
            }
    });
   
};
App.getCurrentDateTime=function(action,date,datekey,timekey){
    $.ajax({
            url:apiUrl+'/currenttime/'+restId+'?token='+$.jStorage.get('oauth.token'),
            cache: false,            
            type: 'get',
            success: function(data) {
                console.log(action);
               App.updateExpectedtime(action,data.city_date_time,date,datekey,timekey);
            }
    });
};
App.updateExpectedtime=function(action,currentDateTime,date,datekey,timekey){
    if(App.orderPlace){
        //App.orderPlace = false ; 
        return false ; 
    }
    var orderType= $.jStorage.get('order_type_'+restId);
    if(orderType===''){
       App.renderCart(); 
       orderType= $.jStorage.get('order_type_'+restId);
    }
    var newDt = App.parseDate(currentDateTime);
     $.ajax({
            url:apiUrl+'/restaurant/timeslot/'+restId+'?date='+date+'&type='+orderType+'&token='+$.jStorage.get('oauth.token'),
            cache: false,            
            type: 'get',
            success: function(data) { 
                console.log(action);
                $.jStorage.set('delivery_order_date_'+restId,'');
                $.jStorage.set('delivery_order_time_'+restId,'');
                $.jStorage.set('takeout_order_date_'+restId,'');
                $.jStorage.set('takeout_order_time_'+restId,'');
               
                if((data.timeslots != null) && (data.timeslots.length !==0)) {
                    var timeslots = data.timeslots;
                    if(action==='checkout'){
                        var fTime = _.first(timeslots);
                        console.log(fTime);
                        if(fTime){
                            App.setJStorage(datekey,date);
                            App.setJStorage(timekey,fTime);
                            var dt = App.parseDate(date);
                            var expectedTime = dt.dateFormat('D, M d') + " at " + App.get12HourTime(fTime);
                            $('.y-expectedTime').html(expectedTime);                        
                            $('.y-timeOfOrder').html(newDt.dateFormat('D, M d')+ " at " + App.get12HourTime(newDt.getHours() +":"+ newDt.getMinutes()));
                            //App.renderDateTime();
                            console.log('checkout update');
                            App.checkDateTime(action);
                        }else{
                            App.reloadTimes(action);
                        }
                    }else{
                        $.ajax({
                            url:apiUrl+'/restaurant/details/'+restId+'?token='+$.jStorage.get('oauth.token'),
                            cache: false,
                            type: 'get',
                            success: function(data) { 
                                App.currentRestaurant = data;
                                App.renderDateTime();
                                console.log('menu update');
                            },
                            error: function() {
                                window.location.reload(true);
                            }
                        });    
                    }
                }else{
                   App.reloadTimes(action);
                }
                
            },
            error: function() {
               
            }
    });    
};
App.reloadTimes=function(action){
        console.log(action);
        console.log('empty slot');
        var orderType = $.jStorage.get('order_type_'+restId);
        var datekey= orderType ==='delivery'?'delivery_order_date_'+restId:'takeout_order_date_'+restId;
        var timekey= orderType ==='delivery'?'delivery_order_time_'+restId:'takeout_order_time_'+restId;   
        $.ajax({
            url:apiUrl+'/restaurant/details/'+restId+'?token='+$.jStorage.get('oauth.token'),
            cache: false,
            type: 'get',
            success: function(datar) {
                App.currentRestaurant = datar;
                var newDt = App.parseDate(datar.current_dateTime);
                 var timeslots = App.getDateSlot(orderType);    
                 var firstSlot = _.first(timeslots),ndate = firstSlot.value; 
                
                if(action==='checkout'){
                    $.ajax({
                        url:apiUrl+'/restaurant/timeslot/'+restId+'?date='+ndate+'&type='+orderType+'&token='+$.jStorage.get('oauth.token'),
                        cache: false,            
                        type: 'get',
                        success: function(data) { 
                          console.log(data);  
                        if(data.timeslots != null) {
                            var timeslots = data.timeslots;
                                var fTime = _.first(timeslots);
                                if(fTime){
                                    App.setJStorage(datekey,"");
                                    App.setJStorage(timekey,"");
                                    var dt = App.parseDate(ndate);
                                    var expectedTime = dt.dateFormat('D, M d') + " at " + App.get12HourTime(fTime);
                                    $('.y-expectedTime').html(expectedTime);                        
                                    $('.y-timeOfOrder').html(newDt.dateFormat('D, M d')+ " at " + App.get12HourTime(newDt.getHours() +":"+ newDt.getMinutes()));
                                    //App.renderDateTime();
                                    App.setJStorage(datekey,ndate);
                                    App.setJStorage(timekey,fTime);
                                }
                            }
                        }
                    })  ;                  
                }else{
                    App.setJStorage(datekey,"");
                    App.setJStorage(timekey,"");
                    App.renderDateTime();  
                }
                                 
            },
            error: function() {
                window.location.reload(true);
            }
        });                
       
};
App.showResCloseMsg=function(){
    //App.popupshow();   
    $('.close_msgpopup').on('click',function(){        
        $.ajax({
            url:apiUrl+'/restaurant/details/'+restId+'?token='+$.jStorage.get('oauth.token'),
            cache: false,
            type: 'get',
            success: function(data) {
                App.currentRestaurant = data;
                $('.u_menusection').removeClass('form_checkout');
                //App.popuphide();
                $.jStorage.set('delivery_order_date_'+restId,'');
                $.jStorage.set('delivery_order_time_'+restId,'');
                $.jStorage.set('takeout_order_date_'+restId,'');
                $.jStorage.set('takeout_order_time_'+restId,'');
                App.renderCart();
                App.editDateTime();                        
            },
            error: function() {}
        });                
    });      
};
App.showSlotChange=function(){
    var tmpl = _.template($("#tmpl-slotChange").html());
    App.popupshow()
    $('.t-popupdata').html(tmpl());
    $('.close_slotChangePopup').on('click',function(){        
        App.popuphide();
        $('#booktable').trigger('click');            
    });      
};
App.changeOrderType =function(){
    var selectedType = $("input[name=munchservices]:checked").val(); 
    if((selectedType==='delivery' && $.jStorage.get('can_deliver_'+restId)!==true)){
        $("#t_delivery").prop( "checked", false );
        $('#t_takeout').prop( "checked", true );
        App.setJStorage("select_delivery_"+restId,selectedType);
        $('.t_change_address').trigger('click',$.proxy(App.geoSearchAddress,App));
       
    }else{
        $("#t_delivery").prop( "checked",true);
        $('#t_takeout').prop( "checked",false);
        App.setJStorage("order_type_"+restId,selectedType);       
    }
    App.getTipOptions();
    App.renderDateTime();
    App.cartCalution();
    //App.closeStripSettings();
    dataLayer.push({
        'event':selectedType,
        'restname': App.currentRestaurant.name,
        'ev_label': "Click_on_"+selectedType+"_Button",
        'RestaurantID':restId
    });
};
App.closeStripSettings=function(){
    var orderType = $.jStorage.get('order_type_'+restId);   
    if((!App.currentRestaurant.is_currently_deliver) && (orderType==='delivery')){
        $('.close_restaurant').removeClass('hide');
        $('.y_ordertype_closed').html(orderType);
        $('.y_opentime_closed').html(App.currentRestaurant.next_deliver);        
    }else  if((!App.currentRestaurant.is_currently_takeout) &&(orderType==='takeout')){
        $('.close_restaurant').removeClass('hide');
        $('.y_ordertype_closed').html(orderType);
        $('.y_opentime_closed').html(App.currentRestaurant.next_takeout);
    }else{
        $('.close_restaurant').addClass('hide');
    }
};
App.changeDate =function(){
    var orderType = $.jStorage.get('order_type_'+restId);      
    var date = $('.t-order-date').val();
    var datekey= orderType ==='delivery'?'delivery_order_date_'+restId:'takeout_order_date_'+restId; 
    App.setJStorage(datekey,date);
    App.getTimeSlots(orderType,date);
    App.getOperationsSlots(date);
};
App.editDateTime = function(){  
    $(".time_slot_error").addClass("hide").html(""); 
    var orderType = $.jStorage.get('order_type_'+restId); 
    var timeslots = App.getDateSlot(orderType);
    var orderDate = $.jStorage.get('delivery_order_date_'+restId)?$.jStorage.get('delivery_order_date_'+restId):'';
    var orderTime = $.jStorage.get('delivery_order_time_'+restId)?$.jStorage.get('delivery_order_time_'+restId):'';
    var hours = App.currentRestaurant.delivery_hours;
    if(orderType==='takeout'){
        orderDate = $.jStorage.get('takeout_order_date_'+restId)?$.jStorage.get('takeout_order_date_'+restId):'';
        orderTime = $.jStorage.get('takeout_order_time_'+restId)?$.jStorage.get('takeout_order_time_'+restId):'';
        hours = App.currentRestaurant.takeout_hours;
    } 
    var data = { order_type:orderType,
                date:'',time:'',
                selectedDate:orderDate,selectedTime:orderTime,
                dates:timeslots,hours:hours};
    var tmptdatetime = _.template($("#tmpl-dateTime").html());
    $('.t-orderDateTimePanel').html(tmptdatetime(data));
    if(orderDate===''){
      var firstSlot = _.first(timeslots);
      orderDate = firstSlot.value; 
    }        
    App.getTimeSlots(orderType,orderDate);
    App.getOperationsSlots(orderDate);
    $(".t-order-date").off('change');
    $(".t-order-date").on('change', $.proxy(App.changeDate,App));
    $(".t-order-time").off('change');
    $(".t-order-time").on('change', $.proxy(App.saveDateTime,App));
    
};
App.getDateSlot= function(type) {  
    var workingDates = [];
    if(App.currentRestaurant){
        if(App.currentRestaurant.all_delivery_working_days || App.currentRestaurant.all_takeout_working_days){
            var dates= App.currentRestaurant.all_delivery_working_days;    
            if(type !== 'delivery') {
                dates = App.currentRestaurant.all_takeout_working_days;
            }
            $.each(dates, function( key, value ) {
                var dateObj = {
                        text: value,
                        value: key
                    };
                workingDates.push(dateObj);
            });
        }
    }    
    return workingDates;
};
App.renderItems = function(){
        var orderType = $.jStorage.get('order_type_'+restId);
        $('.yourorder_box').html('');
        if(($.jStorage.get('order_items_'+restId)) && ($.jStorage.get('order_items_'+restId)).length>0){            
            var order_items = $.jStorage.get('order_items_'+restId);
            var tmplOrderItem = _.template($("#tmpl-orderItem").html());
            var cartCount = 0 ; 
            _.each(order_items,function(item){
                cartCount= (cartCount + parseInt(item.quantity));
                $('.yourorder_box').append(tmplOrderItem(item));
            }); 
            $('.cartCount').html(cartCount);            
            App.bindcartEvent();
            $('.y-no-item').removeClass('disabledcard'); 
            /* bind events*/            
        }else{
            $('.t-no-order').removeClass('hide');
            $('.cartCount').html('0');
            $('.y-no-item').addClass('disabledcard'); 
        }
        App.cartCalution();        
        if(orderType==='delivery'){
            $('.y-tip').removeClass('hide');
        }else{
            $('.y-tip').addClass('hide');
        }
        App.getTipOptions();        
};
App.MinAmount = function(divClass) {    
   
    var errorElement = self.$("."+divClass);
    errorElement.removeClass('hide');
    var highlight = function() {
        errorElement.addClass('activeminsmount');
        if (errorElement.animationTimeout) {
            clearTimeout(self.animationTimeout);
        }
        errorElement.animationTimeout = setTimeout(function() {
            errorElement.removeClass('activeminsmount');
        }, 1000);
    };
    var defaultBuffer = 75;
    var defaultBuffer = $('#menu .navbarcontainer > div').outerHeight() + $('.pageheader').height()+20;
    App.renderCart();
    console.log(defaultBuffer);
    var errorTop = errorElement.offset().top;
    var isVisible = errorTop > $(window).scrollTop() + defaultBuffer && errorTop + defaultBuffer < $(window).scrollTop() + $(window).height();

    if (!isVisible) {
        $("html,body").stop().animate({scrollTop: errorTop - defaultBuffer }, 200, function() {
            highlight();
        });
    } else {
        highlight();
    }
};
App.renderAddOns=function(menuPriceId,addons,model){
    $('.addons').html('');
    if(model.length){                
        var data =_.filter(model, function(el) { return el.menu_price_id == menuPriceId; });
        var tmpl = _.template($('#tmpl-adonsItem').html());
        var items = data[0];
        if(items){
            items['selected_options'] = addons; 
            App.addons =  addons;
            App.updateAddonsText();
            $('.addons').html(tmpl(items));        
            $(".t-addonsItems").off('click');
            $(".t-addonsItems").on('click', $.proxy(App.updateOrderValue,App));
            App.addAddonValidation();
       }
    }
    $('body').addClass('a_scrollactive');
    var vh = 170;
    if(App.mobileDevice()){
        vh = 100;
    }
    $('.a_scroll').css('max-height', $(window).height() - $('.a_scroll_head').height() - $('.addonpopup_footer').height()-vh);
};
App.changeItemPrice=function(){
    var newVal =  ($(".y_price_select").val()).split('-');   
    $("#price_id").val(newVal[0]);
    $("#item_price").val(newVal[1]);
    $("#price_desc").val(newVal[2]);     
    if(window.addOnsModel){  
        var id = $("#uid").val(),addons=[];
        var order_items = $.jStorage.get('order_items_'+restId);
        if(order_items){
            var model =_.find(order_items, function(el) { return el.uid === id; });
            if(model){
               addons = model.addons;
            }
        }
        App.renderAddOns(newVal[0],addons,window.addOnsModel);
    } 
    App.updateOrderValue('ch_price');
};
App.updateAddonsText=function(){
    var addonsSeperation = {};
    _.each(App.addons,function(addon){
        if(addon['label'].toLowerCase() != 'none'){
            if(typeof addonsSeperation[addon['addonId']] == 'undefined'){
                addonsSeperation[addon['addonId']] = [];
            }
            addonsSeperation[addon['addonId']].push(addon);
        }
    });
    var html = "";
    _.each(addonsSeperation,function(addons){
        var title = "<b>" + _.first(addons)['addonName'] + "</b>";
        var labels = " &nbsp;<em>" + _.pluck(addons,'label').join("</em>,&nbsp;<em>") + "</em>";
        html += title + labels;
    });
    $('.y_short_addons').html(html);
};
App.updateOrderValue=function(e){
    App.addons=[];
    if(e!=='ch_price'){
        var priority= 1;
        var target = $(e.currentTarget);
        target.data('priority', priority++);
        var parent = target.closest(".addon-collection");
        if(parent) {
            $(".addon-error-message",parent).addClass('hide');
        }
    }
    var val =0;  
    var nowValue = parseFloat($('#item_price').val());
    _.each($(".addon-collection"),function(addons){
        var addon = $(addons);
        var data = addon.data();
        var selectionType = data['selectionType'];
        var inputType = "checkbox";
        if(parseInt(selectionType,10) === 0){
            inputType = "radio";           
        }
        var options = $("input[type="+inputType+"]:checked",addon);
        if(options.length){ 
            var cnt = 0 ,i=0;
            var addonId = 0;
            _.each(options,function(option){                
                var freeAddons =parseInt($(option).data().freeAddons) ;
                var addons = $(option).data() ;
                if(freeAddons >0){                    
                    if((addonId === 0) || (addonId == $(option).data().addonId)){                       
                        if(cnt < freeAddons){                          
                            addons.isFree=true ;                           
                            addons.priority=cnt+1 ;
                            cnt++ ;
                        }else{
                            addons.isFree=false ;
                            addons.priority=i+1 ;
                        }                        
                    }else{                      
                        addons.isFree=false ;
                        addons.priority=i+1 ;
                    }                   
                }else{                   
                    addons.isFree=false ;
                    addons.priority=i+1 ;
                }
                addonId = addons.addonId ; 
                App.addons.push(addons);
                if(addons.isFree===false){
                    val = parseFloat(val) + parseFloat(addons.optionPrice);
                }
                i++ ; 
            },this); 
            nowValue = parseFloat($('#item_price').val()) + parseFloat(val); 
        }
    });    
    var subtotal= (Math.round(nowValue * 100) / 100).toFixed(2);
    $('.sub-total').html(subtotal);
    var quantity = parseInt($('#quantity').val()) ; 
    var total = nowValue * quantity ;
    total= (Math.round(total * 100) / 100).toFixed(2) ;
    $('.total').html(total); 
    App.addAddonValidation();
    App.updateAddonsText();
};
App.addAddonValidation = function(){
    _.each($(".addon-collection"),function(addons){
        var addon = $(addons);
        var data = addon.data();
        var selectionType = data['selectionType'];
        var itemLimit = data['itemLimit'];
        if(parseInt(selectionType,10) == 1){
            var totalSelected = $("input[type=checkbox]:checked",addon).length;
            if(itemLimit && totalSelected >= itemLimit){
                var checkboxes = $("input[type=checkbox]:not(:checked)",addon);
                checkboxes.attr("disabled","disabled");
                checkboxes.parent().find("a:first").addClass("disabled");

            } else {
                var checkboxes = $("input[type=checkbox]:not(:checked)",addon);
                checkboxes.removeAttr("disabled");
                checkboxes.parent().find("a:first").removeClass("disabled");
            }
        }
    });
};
App.getAllTips = function(){
    return {
        "10": App.getTipAmount(10),
        "15": App.getTipAmount(15),
        "20": App.getTipAmount(20),
        "25": App.getTipAmount(25),
        "30": App.getTipAmount(30)
    };
};
App.getTipAmount=function(tip){
    if($.jStorage.get('order_subtotal_'+restId) >0){
        return App.getNumber((($.jStorage.get('order_subtotal_'+restId)*tip)/100),2);
    }else{
         return "0.00";
    }
};
App.getTipOptions=function(){    
    var text = '<option value="0">No Tip</option>';
    var tips = App.getAllTips ();
    var tip = $.jStorage.get('tip_'+restId);
    $.each(tips,function(per,value){
     text += '<option value="'+per+'" '+(tip == per?"selected":"")+'>'+per+'% ($'+value+')</option>';
    });
    $("select.t-tip-percent").html(text);
    var defaultTipText = "No Tip";
    if(tip!=0){
       defaultTipText = tip +'% ($'+App.getNumber((($.jStorage.get('order_subtotal_'+restId)*tip)/100),2)+')';
    }        
    $(".default-tip").html(defaultTipText);
    $("select.t-tip-percent").off('change');
    $("select.t-tip-percent").on('change', $.proxy(App.updateTipPercent,App));
};
App.updateTipPercent=function(){
    App.setJStorage('tip_'+restId,$("select.t-tip-percent").val());
    App.cartCalution();
};
App.cartCalution=function(){
    var order_items = $.jStorage.get('order_items_'+restId); 
    var orderType = $.jStorage.get('order_type_'+restId);
    var tax=0,subtotal=0,total=0;
    if(!order_items){
       order_items = []; 
       $.jStorage.set('order_items_'+restId,order_items);
    }
    _.each(order_items,function(item){
        subtotal =  parseFloat(subtotal) +  parseFloat(item.total_item_price);       
    });            
    subtotal= (Math.round(subtotal * 100) / 100).toFixed(2) ;
    App.getApplicableDeal(orderType,subtotal); 
    var discount  = 0;
    var promoDiscount  = 0;
    if(App.selectedDeal){
        if(App.selectedDeal.discount_type === 'flat'){
            discount = App.getNumber(App.selectedDeal.discount,2);
        }else{
            discount = App.getNumber((subtotal * parseInt(App.selectedDeal.discount))/100,2);
        }
    }  
    if($.jStorage.get("promocode_data")){
        var promocode_data=$.jStorage.get("promocode_data");
        if (promocode_data.status) {       
            if (subtotal >= parseFloat(promocode_data.minimum_order_amount)) {
                if (promocode_data.discount_type === 'flat') {
                    promoDiscount = App.getNumber(promocode_data.discount, 2);
                } else {
                    promoDiscount = App.getNumber((Math.round(subtotal * parseInt(promocode_data.discount))) / 100, 2);
                }            
                App.setJStorage("promocode_status","valid");
            }else{
               App.setJStorage("promocode_status","invalid");
               $('.promo_code .error-message').addClass('hide');
              //  $('.promo_code .error-message').removeClass('hide').html('Minimum order must exceed $' + promocode_data.minimum_order_amount + ' to redeem this Promo Code');
            }
        }
    }
    if(discount>0){
        $('.y-discount').removeClass('hide');
        $('.discount_amount').html(discount);
        $('.y-dealtext').removeClass('hide').html(App.selectedDeal.title);
    }else{
        $('.y-discount').addClass('hide');
        $('.discount_amount').html('');
        $('.y-dealtext').addClass('hide').html('');
    } 
    if(promoDiscount>0){
        $('.y-promocode-apply, .t_promocode,.y-promocode-control').removeClass('hide');
        $('.y-promocode, .promo_code .error-message').addClass('hide');

        $('.y-promocode-amount').html(promoDiscount);
        $('.y-promocode-coupan').html($.jStorage.get("promocode"));

        $('.y-dealtext').removeClass('hide').html(promocode_data.title);
    }else{
       $('.y-promocode-apply, .t_promocode,.y-promocode-control').addClass('hide');
       $('.y-promocode').removeClass('hide');
       $('#promocode').val('');
       $('.promo_code .error-message').addClass('hide');
       $('.y-promocode-amount').html('');
       $('.y-promocode-coupan').html('');
       $('.y-dealtext').addClass('hide').html('');
    }
    
    if(App.currentRestaurant){
       taxRate = App.currentRestaurant.sales_tax;
    }
    $.jStorage.set('order_subtotal_'+restId,subtotal);
    tax = App.getNumber(((parseFloat(subtotal) * parseFloat(taxRate))/100),2);   
    total = parseFloat(subtotal) + parseFloat(tax) ;
    var tipAmount = "0.00" ;
    if(orderType==='delivery'){
        /* $('.y-tip,.y-tip-desc').removeClass('hide');  */
        $('.y-tip').removeClass('hide');
        var tip = $.jStorage.get('tip_'+restId);
        if(tip !==''){
           tipAmount =  App.getNumber((subtotal * parseInt(tip))/100,2);
           total += parseFloat(tipAmount);
        }
        $(".default_tip").html('$'+tipAmount);
        $.jStorage.set('order_tip_'+restId,tipAmount);
        $('.t-deliverycharge').removeClass('hide');
        var delCharge= parseFloat(App.currentRestaurant.delivery_charge);
        if(delCharge){       
           total += parseFloat(delCharge);
        } 
    }else{
       /* $('.y-tip,.y-tip-desc').addClass('hide');  */
        $('.y-tip').addClass('hide');
        $('.t-deliverycharge').addClass('hide');     
    } 
    total = (total - discount) ; 
    total = (total - promoDiscount) ; 
    total= (Math.round(total * 100) / 100).toFixed(2) ;    
    $('.order_subtotal').html(subtotal);
    
    $('.order_tax').html(tax);
    var delivery_charge = 0;
    if(App.currentRestaurant){
        delivery_charge = parseFloat(App.currentRestaurant.delivery_charge) ; 
    }
    if(delCharge<0){
        $('.t-deliverycharge').addClass('hide');
    }else{        
        $('.deliverycharge_amount').html((Math.round(delivery_charge * 100) / 100).toFixed(2));
    }
    $('.order_total').html(total);    
    $.jStorage.set('order_tax_'+restId,tax);
    $.jStorage.set('order_total_'+restId,total);
    var min_order = 5;
    if(App.currentRestaurant){
        min_order = parseFloat(App.currentRestaurant.minimum_delivery) ; 
    }
    if((min_order >0)&&(orderType==='delivery')){
        if(subtotal< min_order){ 
            $('.t-min-order').removeClass('hide');
            $('.t_min_order').html(min_order);
        }else{
            $('.t-min-order').addClass('hide');           
        }
    }else{
        $('.t-min-order').addClass('hide');
    }
    if(order_items.length>0){
        $('.t-no-order, .y-additems').addClass('hide');
    }else{
        if((orderType==='delivery') && (min_order >0)){
            $('.t-min-order').removeClass('hide');
        }

        $('.t-no-order, .y-additems').removeClass('hide');
    } 
    $('.y-checkoutBtn').html('checkout for '+ $.jStorage.get('order_type_'+restId));
};
App.getApplicableDeal= function(orderType, subTotal) {
            if(!App.restaurantDeal || App.restaurantDeal.length ===0){
                return false ; 
            }
            if(!orderType || _.isEmpty(orderType) || _.isUndefined(orderType) || !subTotal || _.isEmpty(subTotal) || _.isUndefined(subTotal)) {
                return [];
            }
            var filteredDeals = App.restaurantDeal.filter(function(model) {
                return (model.deal_for.indexOf(orderType.toLowerCase()) !== -1);
            });
            filteredDeals = _.filter(filteredDeals, function(model) {
                return parseFloat(model.minimum_order_amount) <= parseFloat(subTotal);
            });
            var decidedDiscount = 0;
            App.selectedDeal =  false;
            _.each(filteredDeals, function(deal) {
                if(deal.type !=='offer'){
                    if(App.parseDate(App.currentRestaurant.current_dateTime) >= App.parseDate(deal.start_on)){
                        if(deal.discount_type.toLowerCase() === "flat") {
                            var discount = parseFloat(deal.discount);
                            if(decidedDiscount < discount) {
                                decidedDiscount = discount;
                                App.selectedDeal = deal; 
                            }
                        }
                        if(deal.discount_type.toLowerCase() === "percent") {
                            var discount = App.getNumber(parseFloat(deal.discount) * parseFloat(subTotal) / 100, 2);
                            discount = parseFloat(discount);
                            if(decidedDiscount < discount) {
                                decidedDiscount = discount;
                                App.selectedDeal = deal;
                            }
                        }
                    }
                }    
            });
            return App.selectedDeal;
        };
App.bindcartEvent=function(){
    $(".t-edit-order").off('click');
    $(".t-delete-order").off('click');       
    $(".t-confirm-delete-order").off('click');
    $(".t-cancel-delete-order").off('click');            
    $(".t-edit-order").on('click', $.proxy(App.editOrder,App));
    $(".t-delete-order").on('click', $.proxy(App.deleteOrder,App));       
    $(".t-confirm-delete-order").on('click', $.proxy(App.confirmDeleteOrder,App));
    $(".t-cancel-delete-order").on('click', $.proxy(App.cancelDeleteOrder,App));    
};
App.editOrders=function(){
    $('#menu > ._960px > .sectiontitle').html("Menu");
    dataLayer.push({
        'event':'Edit Order',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_Edit_order_Button',
        'RestaurantID':restId
    });
    $('html, body').stop().animate({scrollTop: $('#menu').offset().top -55}, "slow");
    $('.ordersummarystep1').css({'bottom': '','position': '','right': ''});
    $('.menutab').removeClass('hide');
    $('.checkoutDiv').addClass('hide');
    App.renderCart(); 
    App.menupanel();
};
App.deleteOrder=function(e){
    var id = $(e.currentTarget).attr('data-id');
    var itemname = $(e.currentTarget).attr('data-name');
    $('.tooltip').addClass('hide');
    $('.t-tooltip_'+id).removeClass('hide');
    $('.itemName_'+id).html(itemname);
}; 
App.confirmDeleteOrder=function(e){
    var id = $(e.currentTarget).attr('data-id');
    var order_items = $.jStorage.get('order_items_'+restId);
    $('.t-tooltip_'+id).addClass('hide');
    order_items = _.reject(order_items, function(el) { return el.uid === id; });    
    $.jStorage.set('order_items_'+restId,order_items);
    App.renderItems();
    if($.jStorage.get('order_items_'+restId).length<1){
        App.cartCalution();
        App.bindcartEvent();
    }
    dataLayer.push({
        'event':'Delete dish',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_delete_order_Button',
        'RestaurantID':restId
    });
}; 
App.cancelDeleteOrder=function(e){
    var id = $(e.currentTarget).attr('data-id');
    $('.t-tooltip_'+id).addClass('hide');
};
App.addOrder=function(model){ 
    
    App.popuphide();
    model.addons=[];    
    App.itemPrices = model.prices ;     
    var url = apiUrl+'/restaurant/menu-addons/'+model.item_id+'?token='+$.jStorage.get('oauth.token');
    $.ajax({url:url,cache: false,type: 'get', success: function(mdl, xhr, response) {            
            App.popupshow();
            var tmpl = _.template($("#tmpl-popup").html());
            $('.t-popupdata').html(tmpl(model));
            window.addOnsModel=mdl ;
            App.renderAddOns(model.prices[0].id,[],mdl);
            App.editOrderEvents();
            setTimeout(function(){
                if(!$('body').attr('st')){
                    $('body').attr('st', $('#menu').offset().top);
                }
            },130);
        }
    }); 
};
App.editOrder=function(e){
    var id = $(e.currentTarget).attr('data-id');
    var order_items = $.jStorage.get('order_items_'+restId);
    var model =_.find(order_items, function(el) { return el.uid === id; });   
    var url = apiUrl+'/restaurant/menu-addons/'+model.item_id+'?token='+$.jStorage.get('oauth.token');
    $.ajax({url:url,cache: false,type: 'get', success: function(mdl, xhr, response) {            
            App.popupshow();
            var tmpl = _.template($("#tmpl-popup").html());
            $('.t-popupdata').html(tmpl(model));
            window.addOnsModel=mdl ;
            App.renderAddOns(model.price_id,model.addons,mdl);
            App.editOrderEvents();   
        }
    });   
    dataLayer.push({
        'event':'Edit Dish',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_edit_dish',
        'RestaurantID':restId
    });
};
App.editOrderEvents = function(){
    $(".close").off('click');
    $(".add-to-order").off('click');       
    $(".add-multiplier").off('click');
    $(".subtract-multiplier").off('click');
    $(".close").on('click',function(){
       App.popuphide();
    });
    $(".y_price_select").off('change');
    $(".y_price_select").on('change', $.proxy(App.changeItemPrice,App));
    $(".add-to-order").on('click', $.proxy(App.addToOrder,App));       
    $(".add-multiplier").on('click', $.proxy(App.addMultipler,App));
    $(".subtract-multiplier").on('click', $.proxy(App.subtractMultipler,App));
    
    $(".menu_special_instruction_item").off('click');
    $(".menu_special_instruction_item").off('keyup');
    $(".menu_special_instruction_item").off('blur');
    $(".menu_special_instruction_item").on('click', $.proxy(App.textCounter,App));
    $(".menu_special_instruction_item").on('keyup', $.proxy(App.textCounter,App));
    $(".menu_special_instruction_item").on('blur', $.proxy(App.textCounterHide,App)); 
};
App.text_max=255;
App.textCounterHide=function(){
    var text_length = $('.menu_special_instruction_item').val().length;
    var text_remaining = App.text_max - text_length;                    
    $('.txt_word_count').html(text_remaining + ' character(s) remaining');
    $('.txt_word_count').css('visibility', 'hidden');
};
App.textCounter=function(){
    var text_length = $('.menu_special_instruction_item').val().length;
    var text_remaining = App.text_max - text_length;                    
    $('.txt_word_count').html(text_remaining + ' character(s) remaining');
    $('.txt_word_count').css('visibility', '');
};
App.addToOrder=function(){ 
    /* Radio Checkbox Validation with respective to its Selection Type */
        var radioValidated = true;
        var i=0;
        _.each($(".addon-collection[data-selection-type=0]"),function(addonGroup){
            var parent = $(addonGroup);
            if(!$(":checked",parent).length) {
                $(".addon-error-message",parent).removeClass("hide");                   
                if(i===0){                   
                    var container = $('.a_area'),
                    scrollTo = $(".addon-error-message",parent);
                    container.stop().animate({
                        scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()-50
                    });
                    i++;                        
                }                    
                radioValidated = false;
            }else{
                $(".addon-error-message",parent).addClass("hide");                    
            }
        });

        if(!radioValidated) {
            return false;
        }                    
        /**************end validation**************/
    if($.jStorage.get('order_items_'+restId).length>0){
       var order_items = $.jStorage.get('order_items_'+restId);
    } 
    var special_instruction = $(".menu_special_instruction_item").val();
        special_instruction = $('<div />').text(special_instruction).html();
    var uid = $('#uid').val();
    var model =_.find(order_items, function(el) { return el.uid === uid; });   
    if(model){        
        model.item_price=$('#item_price').val();     
        model.price_id=$('#price_id').val();
        model.price_desc= $('#price_desc').val();
        model.quantity=$('#quantity').val();     
        model.sub_total=$('.sub-total').html();    
        model.total_item_price= $('.total').html();
        model.special_instruction=special_instruction;        
        var addons = [];
         App.addons=[];
        _.each($(".addon-collection"),function(addons){
            var addon = $(addons);
            var data = addon.data();
            var selectionType = data['selectionType'];
            var inputType = "checkbox";
            if(parseInt(selectionType,10) === 0){
                inputType = "radio";           
            }
            var options = $("input[type="+inputType+"]:checked",addon);
            
            if(options.length){ 
                var cnt = 0 ,i=0;
                var addonId = 0;
                _.each(options,function(option){                
                    var freeAddons =parseInt($(option).data().freeAddons) ;
                    var addons = $(option).data() ;
                    if(freeAddons >0){                    
                        if((addonId === 0) || (addonId == $(option).data().addonId)){                       
                            if(cnt < freeAddons){                          
                                addons.isFree=true ;                           
                                addons.priority=cnt+1 ;
                                cnt++ ;
                            }else{
                                addons.isFree=false ;
                                addons.priority=i+1 ;
                            }                        
                        }else{                      
                            addons.isFree=false ;
                            addons.priority=i+1 ;
                        }                   
                    }else{                   
                        addons.isFree=false ;
                        addons.priority=i+1 ;
                    }
                    addonId = addons.addonId ; 
                    App.addons.push(addons);               
                    i++ ; 
                },this);            
            }            
        });
        if(App.addons){
            addons=App.addons;
        }
        model.addons=addons;       
        $.jStorage.set('order_items_'+restId,order_items);
        App.addons=[];
    }else{        
        var order_items = [];
        if($.jStorage.get('order_items_'+restId).length>0){
            order_items = $.jStorage.get('order_items_'+restId);
        }
        var addons = [];
        if(App.addons){
            addons=App.addons;
        }
        var items={  
            "uid": $('#uid').val(),
            "id": order_items.length,
            "item_id": $('#item_id').val(),
            "item_image_url":$('#item_image_url').val(),
            "item_name": $('#item_name').val(),
            "item_desc": $('#item_desc').val(),
            "prices":App.itemPrices,
            "quantity": $('#quantity').val(),
            "price_id": $('#price_id').val(),
            "price_desc": $('#price_desc').val(),
            "item_price": $('#item_price').val(),
            "sub_total": $('.sub-total').html(),                        
            "total_item_price": $('.total').html(),
            "special_instruction": special_instruction,
            "addons": addons
        };
        order_items.push(items);
        addMenuTrackingCodes(items);
        $.jStorage.set('order_items_'+restId,order_items); 
        App.showTooltip($('#item_name').val());
        App.addons=[];
        App.itemPrices=[];
    }
    App.popuphide();   
    App.renderItems();
};
App.addMultipler=function(){
    var nowValue = parseInt($('#quantity').val())+1 ;
    $('.multiplier').html(nowValue);
    var total = parseFloat($('.sub-total').html()) * nowValue ; 
    total= (Math.round(total * 100) / 100).toFixed(2) ;
    $('.total').html(total); 
    $('#quantity').val(nowValue);
};
App.subtractMultipler=function(){
    var nowValue = parseInt($('#quantity').val()) ;
    if(nowValue>1){
        nowValue = parseInt($('#quantity').val())-1 ;
        $('.multiplier').html(nowValue);
        var total = parseFloat($('.sub-total').html()) * nowValue ; 
        total= (Math.round(total * 100) / 100).toFixed(2) ;
        $('.total').html(total); 
        $('#quantity').val(nowValue); 
    } 
};

App.locationPopup = function(event){
    var tmpl = _.template($("#tmpl-locationPopup").html());
    App.popupshow();
    $('.close').on('click',$.proxy(App.closePop,App)); 
    var currentTarget = $(event.currentTarget);
    $.ajax({
        url: 'restaurant.json',
        type: 'get',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data){
            console.log(data);
            $('.t-popupdata').html(tmpl({resContacts:data})); 
            $('.panel_button').addClass(currentTarget.attr('dataid'));
            if($('.panel_button').hasClass('link_reserveTable')){
                $('.y-popup-title').html('Choose your reservation location.');
            }else{
                $('.y-popup-title').html('Select a location to place your delivery or takeout order');
            }
            $('.y-resUrl').on('click', function(e) {
                var resid = $(this).attr('data-resid');
                var resname = $(this).attr('data-resname');
                $.jStorage.set('selected_restaurant',resid);
                if($('.panel_button').hasClass('link_reserveTable')){
                    dataLayer.push({
                        'event': resname +" Click",
                        'restname': App.currentRestaurant.name,
                        'ev_label': 'Click_on_delivery_lacations',
                        'RestaurantID':restId
                    });
                    $.jStorage.set('selected_action','r');
                    // window.open($(this).attr('reservationurl'),'_blank');
                    if(App.checkPrivateMode()){
                        window.location.href='home.html?id='+resid+'&act=r';
                    }else{
                        window.location.href='home.html';
                    }
                    App.popuphide();                                      
                }else{
                    dataLayer.push({
                        'event': resname +" Click",
                        'restname': App.currentRestaurant.name,
                        'ev_label': 'Click_on_delivery_lacations',
                        'RestaurantID':restId
                    });
                    $.jStorage.set('selected_action','o');
                    $.jStorage.set('third_party_reservation', $(e.target).attr('reservationurl'));
                    if(App.checkPrivateMode()){
                        window.location.href='home.html?id='+resid+'&act=o';
                    }else{
                        window.location.href='home.html';
                    }
                }
            });
        },
        error: function(response) {
            console.log(response);         
        }
    }); 

};


App.thirdpartyreservation = function(){
    dataLayer.push({
        'event': 'Third Party Reservation click',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_delivery_lacations',
        'RestaurantID':restId
    });
    window.open($.jStorage.get('third_party_reservation'),'_blank');
};
App.reserveATable=function(){
    $('.link_mobilemenu').removeClass('active');
    $('.dropdown_mobile').removeClass('active');
    $('body').removeClass('a_modal_open');
    
    var tmpl = _.template($("#tmpl-bookTable").html());
    setTimeout(function(){$('#people').focus()},100);
    $('.a_modal').addClass('scrollview');
    App.popupshow();
    $('.t-popupdata').html(tmpl());   
    var cD = new Date();
    if(App.currentRestaurant){
        cD = App.parseDate(App.currentRestaurant.current_dateTime);
    }
    var currentDatetime = [('0' + (cD.getMonth() + 1)).slice(-2),('0' + cD.getDate()).slice(-2),cD.getFullYear()].join('-');
    var maxDate = new Date(cD.getTime()+(60*24*60*60*1000));
    
    setTimeout(function(){
        $('#datepicker1').val(currentDatetime);
        $('#datepicker1').datetimepicker({      
            timepicker:false,
            format:'m-d-Y',
            formatDate:'m-d-Y',
            maxDate:maxDate,
            minDate: currentDatetime,
            value: currentDatetime,
            scrollMonth : false,
            onSelectDate:function(){
                $('#datepicker1').blur(); 
               
                App.populate_time();                
            },
            onShow:function(){
                $('.timepicker_custom').hide();
                $('#timepicker1').removeClass('active');
                             
              }  
        });
        App.populate_time();
        App.initTags();
    },500);
    
    $('#people').bind('focus' , function() {

        $('.timepicker_custom').hide();
        $('#timepicker1').removeClass('active');
    });

    $('#timepicker1').bind('click' , function() {
        if($('#timepicker1').hasClass('active')){
            $('.timepicker_custom').hide();
            $(this).removeClass('active');
        }else{
            $(this).addClass('active');
            $('.timepicker_custom').show();
            $('.t_timepicker li').removeClass('current');
            var aa = $('#timepicker1').val();
            $('.t_timepicker li[timeslot_book="'+aa+'"]').addClass('current');
        }
    });
    App.bindEventsReservation();
    dataLayer.push({
        'event':'Reserve a table Click',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_Reserve_a_table_',
        'RestaurantID':restId
    });
};
App.calendarClick=function(event) {
    event.stopPropagation();
    var container = $(".hasICalendar", this.$el);
    container.show();
    container.removeClass("hide");
    var currentTarget = $(event.currentTarget);
    var currentData = currentTarget.data();
   // var calendarStartDate = currentData.starttime;
    var calendarEndDate = currentData.endtime;
    var calendarTitle = currentData.title;
    var calendarDescription = currentData.description;
    var calendarLocation = currentData.location;
    $('.googleCalender').icalendar({ sites: ['google', 'icalendar', 'outlook'],
        start: App.parseDate(calendarEndDate),
        end: App.parseDate(calendarEndDate),
        title: calendarTitle,
        description: calendarDescription,
        location: calendarLocation,
        timezone:"America/New_York",
        count:1});
    $('.googleCalender ul').addClass('unstyled');
};

 App.initTags = function(){ 
    App.selectedEmail = new Array();
    $('#emails').tagsInput({
        width:'auto',
        defaultText:'',
        onAddTag: function(value){
            App.selectedEmail.push(value);
            App.displayContacts(App.selectedEmail);
        },
        onRemoveTag: function(value){
            App.selectedEmail.splice(App.selectedEmail.indexOf(value), 1);
            App.displayContacts(App.selectedEmail);
        },
        validate: function(value){
            App.emailFormat= /(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?: \r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:( ?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[  \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\ ](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+ (?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?: (?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n) ?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\ r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[  \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n) ?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t] )*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[  \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])* )(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t] )+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*) *:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+ |\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r \n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?: \r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t ]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031 ]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\]( ?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)? [ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\]  \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]| \\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<> @,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|" (?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t] )*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[ \]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000- \031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|( ?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,; :\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([ ^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\" .\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\ ]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\ [\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\ r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\]  \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\] |\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\ .|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@, ;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])* (?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\". \[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[ ^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\] ]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*( ?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:( ?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[ \["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t ])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t ])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+| \Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?: [^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\ ]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n) ?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[" ()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n) ?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<> @,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[  \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@, ;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t] )*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\ ".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)? (?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\". \[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?: \r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[ "()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t]) *))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]) +|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\ .(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z |(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:( ?:\r\n)?[ \t])*))*)?;\s*)/;
            if(value == '') {
                if(_.size(App.selectedEmail) == 0){                  
                    return false;
                }else{
                    $(".emails-error").html('').fadeIn("slow").addClass("hide");
                    return true;
                }
            }
            if(!App.emailFormat.test(value)){
                $(".send_invites .emails-error").html('worng email format').fadeIn("slow").removeClass("hide");
                return false;
            }else{
                $(".send_invites .emails-error").html('').fadeIn("slow").addClass("hide");
                return true;
            }
        }
    });
    $('.calendarClick').off('click');
    $('.calendarClick').on('click',$.proxy(App.calendarClick,App));
};
App.validateEmailBlur = function(){
    var val = $('.email_tag').val();
    if(val && (val !=='')){
        if(!App.emailFormat.test(val)){
            $(".send_invites .emails-error").html('worng email format').fadeIn("slow").removeClass("hide");
            //$('.without-friend').addClass('errorinputglobal'); 
            return false;
        }else{
            $(".send_invites .emails-error").html('').fadeIn("slow").addClass("hide");
           // $('.without-friend').removeClass('errorinputglobal'); 
            return true;
        }
    }
    
};
App.displayContacts = function(contactList){
    var len = _.size(contactList) ;
    $('.toBeSendContact').html('');
    if(len >0){
        var i=1;
        $.each(contactList, function(key, value) {
            if(value){
                $('.toBeSendContact').append(value);
            }else{
                $('.toBeSendContact').append(key);
            }
            if(i== len -1){
                $('.toBeSendContact').append(' and ');
            }else{
                if(i != len)
                    $('.toBeSendContact').append(', ');
            }                       
            i++ ;
        });
    }
};
App.sendInvitation = function(){
    $('.send_invites .error-color').addClass('hide').html(''); 
    if(App.selectedEmail.length===0){
        $('.emails-error').removeClass('hide').html('Hey, you forgot something');
       return false ; 
    }
    if($('#send-reservation-msg').val()===''){
       $('.msg-error').removeClass('hide').html('Hey, you forgot something');
       return false ; 
    }
    if(App.validateEmailBlur()===false){
        return false ;
    }
    $('#emails_addTag input').prop('disabled', true);
    $('.close_removeTag').unbind("click");
    $('.send_invites .lineloader').removeClass('hide');
    
    $('#y-send-invitation').addClass('disabled'); 
    $('.emails_tag').prop('disabled', true);
    $('.email_tag').prop('disabled', true);
    $('#send-reservation-msg').prop('disabled', true);
    
    var data = {       
        'reservation_id': $('#y-reservation-id').val(),
        'message': $('#send-reservation-msg').val(),
        'token': $.jStorage.get('oauth.token'),
        'friendsEmailAddress': App.selectedEmail.toString(),
        'host_name' : window.location.protocol+"//"+window.location.host
        };    
    $.ajax({
        url: apiUrl + '/user/reservation/sendinvitation',
        type: 'post',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function() {
            $('.send_invites').addClass('hide');            
            $('.sendinvite-thank').removeClass('hide');           
            $('#y-send-invitation').removeClass('disabled'); 
            $('.invitemore').off('click');
            $('.invitemore').on('click',$.proxy(App.invitemore,App));
            $('.send_invites .lineloader').addClass('hide');
            $('#emails_addTag input').prop('disabled', false);
            $('.emails_tag').prop('disabled', false);
            $('.email_tag').prop('disabled', false);
            $('#send-reservation-msg').prop('disabled', false);
            $('.close_removeTag').bind("click");
        },
        error: function(response) {
            console.log(response);
            response = $.parseJSON(response['responseText']);
            var error = response["error"];
            if (!error) {
                error = "Something apparently went wrong.";
            }
            $('.send_invites .error-color').removeClass('hide').html(error); 
            $('.send_invites .lineloader').addClass('hide');
            $('#y-send-invitation').removeClass('disabled');   
            $('#emails_addTag input').prop('disabled', false);
            $('#emails_tag').prop('disabled', false);
            $('.email_tag').prop('disabled', false);
            $('#send-reservation-msg').prop('disabled', false);
            $('.close_removeTag').bind("click");
        }
    }); 
} ;
App.invitemore = function(){
    App.selectedEmail = new Array();
    $('.send_invites').removeClass('hide');            
    $('.sendinvite-thank').addClass('hide');           
    $('#y-send-invitation').removeClass('disabled'); 
};
App.populate_time= function () {
    $(' #btnbook').addClass('disabled');
    $('.error_time_slot').addClass('hide');    
    var people = $("#people").val();    
    var format_date = App.queryDateFormate($("#datepicker1").val());    
    $.ajax({
        url: apiUrl + '/restaurant/timeslot/' + restId + '?date=' + format_date + '&partysize=' + people + '&type=reservation&token=' + $.jStorage.get('oauth.token'),
        dataType: 'json',
        success: function(data) {
            $('.t_timepicker').empty();            
            if (data.timeslots != null) {
                var timeslots = _.filter(data.timeslots, function(r) {
                    return r.status==1;
                });
                if(timeslots.length ===0){
                    $('#timepicker1').val('NA');
                    $('.error_time_slot').removeClass('hide').empty().html('Sorry, we are fully booked for this day.');
                    $('#timepicker1, #btnbook').addClass('disabled');
                }else{
                    $.each(data.timeslots, function(key, value) {
                        if (value['status'] === 1) {
                            $('.t_timepicker').append('<li timeslot_book="' + App.get12HourTime(value['time']) + '">' + App.get12HourTime(value['time']) + '</li>');
                        }
                    });
                    $('#timepicker1').val($('.t_timepicker li:first-child').attr('timeslot_book'));
                    $('.t_timepicker li:first-child').addClass('current');
                    $('#timepicker1').val($('.t_timepicker li:first-child').attr('timeslot_book'));
                    $('.error_time_slot').addClass('hide');
                    $('#timepicker1, #btnbook').removeClass('disabled');
                    $('.popform.bookform').removeClass('disabledform');
                    $('.t_timepicker li').on('click', function() {
                        var crrtimeslot = $(this).attr('timeslot_book');
                        $('.t_timepicker li').removeClass('current');
                        $('#timepicker1').val(crrtimeslot).removeClass('active');
                        $(this).addClass('current');
                        $('.timepicker_custom').hide();

                    });
                }    
            } else {
                $('#timepicker1').val('');
                $('.error_time_slot').removeClass('hide').empty().html('Sorry, we do not accept reservations at this time.');
                $('#timepicker1, #btnbook').addClass('disabled');                
            }

        },
        error: function() {}
    });
};
App.geoSearchAddress=function(){
    var tmpl = _.template($("#tmpl-search-geoaddress").html());
    App.popupshow();
    $('.t-popupdata').html(tmpl());
    $('.pac-container').remove();
    $('#searchTextField').on('keydown',$.proxy(App.seoAddressSeachByLocation,App));
    $('#searchTextField').on('keyup',$.proxy(App.gotoverify,App));    
    $('.t-verify_proceed').on('click',$.proxy(App.getLatByAddress,App));
    $('.close').on('click',$.proxy(App.closePop,App)); 
    $('.t_proceed_takeout').on('click',$.proxy(App.continueWithTakeout,App));
    var bodytop = $('#searchTextField').offset().top + Math.abs(parseInt($('body').css('margin-top')));    
    setTimeout(function(){ 
        $('.pac-container').css('top', bodytop);       
    },500);
};
App.closePop =function(){    
    App.popuphide();
    if($.jStorage.get('addtoOrder') && $.jStorage.get('addtoOrder')!==''){
        $.jStorage.set('addtoOrder','');
    }
    if($.jStorage.get('select_delivery_'+restId) && $.jStorage.get('select_delivery_'+restId)!==''){
        $.jStorage.set('select_delivery_'+restId,'');
    }
};
App.seoAddressSeachByLocation=function(e){
    var bodytop = Math.abs(parseInt($('body').css('margin-top')));
        $('.pac-container').css('margin-top', bodytop);
        if($('.pac-container').length==0){
        var options = {types: ['geocode'],componentRestrictions: {country: "us"}};
        var input = document.getElementById('searchTextField');        
        var autocomplete = new google.maps.places.Autocomplete(input,options);
        
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace(); 
            $('.t_proceed_takeout , .t-verify_proceed').addClass('disable_actions'); 
            $('.t-invalid_address').addClass('hide');
            $('.t-right_address').addClass('hide');
            $('.t-wrong_address').addClass('hide');
            
            if(place.address_components){
                var addressType = App.getAddressType(place);
                if(addressType ==='street'){
                    $('#fullAddress').val(place.formatted_address);
                    $('#addressLat').val(place.geometry.location.lat());
                    $('#addressLng').val(place.geometry.location.lng());
                    $('#addressType').val(place.geometry.location.lng());
                    App.verifyDeliveryAddress();
                }else{
                    $('.lineloader').addClass('hide'); 
                    $('.t_proceed_takeout').removeClass('disable_actions');
                    $('.t-invalid_address').removeClass('hide');
                    $('.t-right_address').addClass('hide');
                    $('.t-wrong_address').addClass('hide');
                    $('#fullAddress').val('');
                    $('#addressLat').val('');
                    $('#addressLng').val('');
                    $('#addressType').val('');
                    return false;
                } 
            }else{ 
                $('.lineloader').addClass('hide'); 
                $('.t_proceed_takeout').removeClass('disable_actions');
                $('.t-invalid_address').removeClass('hide');
                $('.t-right_address').addClass('hide');
                $('.t-wrong_address').addClass('hide');
                $('#fullAddress').val('');
                $('#addressLat').val('');
                $('#addressLng').val('');
                $('#addressType').val('');
                return false;
            }                 
        });
    }
};


App.checkMap = function(){
    var menuCheckInterval = setInterval(function(){
        if(google != undefined){
            App.geoCode = App.geoCode || new google.maps.Geocoder();
            if($('#viewmap').length){
                App.renderMap();
            }
            clearInterval(menuCheckInterval);
        }
    }, 2000);
 }
 
 
App.streetCase = [
        'street_address',
        'route',
        'premise',
        'subpremise',
        'natural_feature',
        'airport',
        'park',
        'establishment'
    ];
App.getAddressType = function(response) {
        var types = _.pluck(response['address_components'], 'types');
        var extractedTypes = [];
        _.each(types, function(type) {
            extractedTypes = extractedTypes.concat(type);
        });
        extractedTypes = _.union(extractedTypes);
        if (_.intersection(extractedTypes, App.streetCase).length) {
            return 'street';
        }else{
            return 'others';
        }       
    };
App.gotoverify=function(e){
    if (e.keyCode === 13) {
        e.stopImmediatePropagation();
        $('.t_proceed_takeout , .t-verify_proceed').addClass('disable_actions');        
        var lat = $('#addressLat').val(), lng= $('#addressLng').val();
        if((lat !=='') && (lng!=='')){
            $('.bg_grey .lineloader').removeClass('hide');            
            App.verifyDeliveryAddress();
        }else{            
            App.getLatByAddress();
        }
    }    
};
App.getLatByAddress=function(){ 
    if($('#searchTextField').val()===''){
        $('.t-invalid_address').removeClass('hide');
        $('.t-right_address').addClass('hide');
        $('.t-wrong_address').addClass('hide');
        $('#fullAddress').val('');
        $('#addressLat').val('');
        $('#addressLng').val('');
        $('#addressType').val('');
        $('.t_proceed_takeout , .t-verify_proceed').removeClass('disable_actions');        
        return false;
    }
    $('.t_proceed_takeout , .t-verify_proceed').addClass('disable_actions'); 
    $('.bg_grey .lineloader').removeClass('hide');    
    App.geoCode.geocode({
        address: $('#searchTextField').val(),
        componentRestrictions: {country: "us"}
    }, function(results, status) {  
        if (status === google.maps.GeocoderStatus.OK) {
            var addressType = App.getAddressType(results[0]);
            if (addressType === 'street') {
                var latLong = {};
                _.each(results, function(result) {
                    latLong.lat = result["geometry"]["location"]["lat"]().toFixed(5);
                    latLong.lng = result["geometry"]["location"]["lng"]().toFixed(5);
                    latLong.address = result["formatted_address"];
                    latLong.type = addressType;
                }); 
                $('#fullAddress').val(latLong.address);
                $('#addressLat').val(latLong.lat);
                $('#addressLng').val(latLong.lng);
                $('#addressType').val(latLong.type);                
                App.verifyDeliveryAddress();
            }else{
               $('.t-invalid_address').removeClass('hide');
               $('.lineloader').addClass('hide'); 
               $('.lineloader_menu').addClass('hide');
               $('.t_proceed_takeout , .t-verify_proceed').removeClass('disable_actions');      
            } 
        }
    });     
};
App.verifyDeliveryAddress=function(){ 
    dataLayer.push({
        'event':'Verify & Proceed To order',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_Verify_&_proceed_to_order_Button',
        'RestaurantID':restId
    });
    if($('#searchTextField').val()==='' || (($('#searchTextField').val()).length < 5)){
        $('.lineloader').addClass('hide');
        $('.t-invalid_address').removeClass('hide');
        $('.t-right_address').addClass('hide');
        $('.t-wrong_address').addClass('hide');
        $('#fullAddress').val('');
        $('#addressLat').val('');
        $('#addressLng').val('');
        $('#addressType').val('');
        $('.t_proceed_takeout , .t-verify_proceed').removeClass('disable_actions');        
        return false;
    }
    var lat = $('#addressLat').val(), lng= $('#addressLng').val(),addressType=$('#addressType').val();
    var fullAddress=$('#fullAddress').val();
    if((lat !=='') && (lng!=='')){
        $('.lineloader').removeClass('hide');
        $('.error-message').addClass('hide');
        var distance= App.getDistance({
            point1: {
                latitude: App.currentRestaurant['latitude'],
                longitude: App.currentRestaurant['longitude']
            },
            point2: {
                latitude: lat,
                longitude: lng
            }
        }); 
        $.ajax({
            url:apiUrl+'/restaurant/candeliver/'+restId+'?lat='+lat+'&lng='+lng+'&token='+$.jStorage.get('oauth.token'),
            cache: false,
            type: 'get',
            async:false,
            success: function(data) { 
                $('.lineloader').addClass('hide');                
                if(data.can_deliver==true){
                    $.jStorage.set("can_deliver_"+restId, data.can_deliver);
                    $('.m_location_verify').removeClass('errow'); 
                    $('.t-right_address').removeClass('hide');
                    $.jStorage.set("can_deliver_"+restId, true);                    
                    $.jStorage.set("address_value_"+restId, fullAddress);
                    $.jStorage.set("address_distance_"+restId, distance);
                    $.jStorage.set("address_lat_"+restId,lat);
                    $.jStorage.set("address_lng_"+restId,lng);
                    $.jStorage.set("address_type_"+restId,addressType);
                    App.renderDeliveryAddress();
                    setTimeout(function(){
                    
                        if($.jStorage.get('addtoOrder') && $.jStorage.get('addtoOrder')!==''){
                            App.addOrder($.jStorage.get('addtoOrder'));
                            setTimeout(function(){
                                $.jStorage.set('addtoOrder','');
                            },10000);
                        }else{
                            App.popuphide();
                        }
                        if($.jStorage.get('select_delivery_'+restId) && $.jStorage.get('select_delivery_'+restId)!==''){
                            $('#t_takeout').prop( "checked",false);
                            $("#t_delivery").prop( "checked",true);                            
                            App.setJStorage("order_type_"+restId,'delivery');
                            App.renderDateTime();
                            App.cartCalution();
                            App.getTipOptions();
                            $.jStorage.set('select_delivery_'+restId,'');
                        } 
                        $('.t_proceed_takeout , .t-verify_proceed').removeClass('disable_actions');                        
                    }, 2000);
                    App.cartCalution();
                }else{                    
                    $('.m_location_verify').addClass('errow'); 
                    $('.t-wrong_address').removeClass('hide'); 
                    $('.y-closeError').removeClass('hide');
                    $.jStorage.set("can_deliver_"+restId, false);
                    $.jStorage.set("address_value_"+restId, fullAddress);
                    $.jStorage.set("address_distance_"+restId, distance);
                    $.jStorage.set("address_lat_"+restId,lat);
                    $.jStorage.set("address_lng_"+restId,lng);
                    $.jStorage.set("address_type_"+restId,addressType);                    
                    App.renderDeliveryAddress(); 
                    $('.y-closeError').off('click',$.proxy(App.closeError,App)); 
                    $('.y-closeError').on('click',$.proxy(App.closeError,App)); 
                    $('.t_proceed_takeout , .t-verify_proceed').removeClass('disable_actions');
                    dataLayer.push({
                        'event':'Outside Delivery zone',
                        'restname': App.currentRestaurant.name,
                        'ev_label': 'Outside_delivery_zone',
                        'RestaurantID':restId
                    });
                }
            },
            error: function() {
               $('.lineloader').addClass('hide'); 
               $('.t-wrong_address').addClass('hide');
               $('.t_proceed_takeout , .t-verify_proceed').removeClass('disable_actions');              
            }
        });
    }else{
        App.getLatByAddress();
    }    
};
App.closeError = function(){
    $('#searchTextField').val('');
    $('.y-closeError').addClass('hide');
    $('.m_location_verify').removeClass('errow');
    $('.error_delivery_zone').addClass('hide');
};
App.renderDeliveryAddress=function(){
    if($.jStorage.get("address_value_"+restId) && $.jStorage.get("address_value_"+restId)!==''){
      $('.ordertype_location').removeClass('hide');
      $('.t_distance_text').html('This restaurant is about '+$.jStorage.get("address_distance_"+restId)+' mile from'); 
      $('.t_delivery_address').html($.jStorage.get("address_value_"+restId)); 
      if($.jStorage.get("can_deliver_"+restId)){
          $('.y-deleiver-yes').removeClass('hide');
          $('.y-deleiver-no').addClass('hide');
      }else{
          $('.y-deleiver-yes').addClass('hide');
          $('.y-deleiver-no').removeClass('hide');
      }
       $('.t_change_address').removeClass('hide'); 
    }else{
        $('.t_change_address').addClass('hide'); 
    }
};
App.digitToString = function(digit) {
        digit = parseInt(digit, 10);
        var string = "";
        switch (digit) {
            case 1:
                string = "one";
                break;
            case 2:
                string = "two";
                break;
            case 3:
                string = "three";
                break;
            case 4:
                string = "four";
                break;
            case 5:
                string = "five";
                break;
            case 6:
                string = "six";
                break;
            case 7:
                string = "seven";
                break;
            case 8:
                string = "eight";
                break;
            case 9:
                string = "nine";
                break;
            case 10:
                string = "ten";
                break;
        }
        return string;
    };
App.getNumber = function(num, decimal) {
    
    var afterDecimal = (num + "").split(".");
    
    if (!_.isEmpty(afterDecimal[1]) && afterDecimal[1].length > decimal) {
        num = Number(Math.round(num+'e2')+'e-2');
    }else{
        num = (num * 100) / 100 ;
    }
    var reg = new RegExp('^\\d+(?:\\.\\d{0,' + decimal + '})?');
    var number = Number(parseFloat(num).toString().match(reg));
    return parseFloat(number).toFixed(decimal);
};

App.validateFirstName=function() {
    var hasError = false;
    var firstName = $("input[name=first_name]");
    var errorMessage = firstName.closest("div").find(".error-message");
    if ($.trim(firstName.val()) === "") {
        errorMessage.removeClass("hide");
        hasError = true;
    } else {
        errorMessage.addClass("hide");
    }
    var value = $.trim(firstName.val());
    $("input[name=first_name]").val(value);
    return hasError;
};
App.validateAddress1=function() {
        var hasError = false,
        address1 = $("input[name=address_1]");
            if ($.trim(address1.val())==="") {
                address1.closest("div").find(".error-message").removeClass("hide");
                hasError = true;
            } else {
                address1.closest("div").find(".error-message").addClass("hide");
            }
        return hasError;
};
App.validateShippingZipCode = function() {
        var hasError = false,
            zipCode = $("input[name=zipcode]");        
            if (zipCode.val()==='') {
                zipCode.closest("div").find(".error-message").removeClass("hide").html('Come on, you gave us all the other info. Why you holding out?');
                hasError = true;
            } else {              
                zipCode.closest("div").find(".error-message").addClass("hide");
                zipCode.closest("div").find(".error-message1").addClass("hide");
            }       
        return hasError;
};
App.validatePhoneR=function() {
    var hasError = false,
        phoneNo = $("input[name=phone_no_r]"),
        phoneVal = $.trim(phoneNo.val().replace(/([*()'-\/ ])/g, ''));
    if (phoneVal === '') {
        $(".y_error_phone").html("We promise; No prank calls").fadeIn("slow").removeClass("hide");
        hasError = true;
    } else if (phoneVal.length < 10) {
       $(".y_error_phone").html('You know, there\'s a cadence to phone numbers. They usually go xxx-xxx-xxxx').fadeIn("slow").removeClass("hide");
        hasError = true;
    } else {
       $(".y_error_phone").html("").fadeOut("slow").addClass("hide");
    }
    return hasError;
};

App.validateEmailR=function() {
    var hasError = false,
        email = $("input[name=email_r]");
    var emailFormat = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

    if ($.trim(email.val()) === "") {
        email.closest("div").find(".error-message").removeClass("hide").html('Hey, you forgot something');
        hasError = true;
    } else {
        if (!emailFormat.test(email.val())) {
            email.closest("div").find(".error-message").removeClass("hide").html('That don\'t look like any e-mail I ever seen. Maybe the "@" or the "." are in the wrong spot. This isn\'t cubism, put things where they belong!');
            hasError = true;
        } else {
            email.closest("div").find(".error-message").addClass("hide");
        }
    }
    return hasError;
};
App.validatePhone=function() {
    var hasError = false,
        phoneNo = $("input[name=phone_no]"),
        phoneVal = $.trim(phoneNo.val().replace(/([*#&%@!~|:;()'-\/ ])/g, ''));
    if (phoneVal === '') {
        $(".error-phoneNo").html("We promise; No prank calls").fadeIn("slow").removeClass("hide");
        hasError = true;
    } else if (phoneVal.length < 10) {
        $(".error-phoneNo").html('You know, there\'s a cadence to phone numbers. They usually go xxx-xxx-xxxx').fadeIn("slow").removeClass("hide");
        hasError = true;
    } else {
        $(".error-phoneNo").html("").fadeOut("slow").addClass("hide");
    }
    return hasError;
};

App.validateEmail=function() {
    var hasError = false,
        email = $("input[name=email]");
    var emailFormat = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

    if ($.trim(email.val()) === "") {
        email.closest("div").find(".error-message").removeClass("hide").html('Hey, you forgot something');
        hasError = true;
    } else {
        if (!emailFormat.test(email.val())) {
            email.closest("div").find(".error-message").removeClass("hide").html('That don\'t look like any e-mail I ever seen. Maybe the "@" or the "." are in the wrong spot. This isn\'t cubism, put things where they belong!');
            hasError = true;
        } else {
            email.closest("div").find(".error-message").addClass("hide");
        }
    }
    return hasError;
};

App.validateCardName=function() {
    var hasError = false,
        cardName = $("input[name=card_name]");

    if ($.trim(cardName.val()) === "") {
        cardName.closest("div").find(".error-message").removeClass("hide");
        hasError = true;
    } else {
        cardName.closest("div").find(".error-message").addClass("hide");
    }
    return hasError;
};

App.validateCardNumber=function() {
    var hasError = false,
        cardNumber = $("input[name=card_number]");
    if ($.trim(cardNumber.val()) ==="") {
        cardNumber.closest("div").find(".error-message").removeClass("hide").html('Try rubbing your fingers over the numbers, that helps us get \'em right');
        hasError = true;
    } else {
        if (!App.isValidCardNumber(cardNumber)) {
            cardNumber.closest("div").find(".error-message").removeClass("hide").html("We need all of the numbers on the card. All of \'em");
            hasError = true;
        } else {
            cardNumber.closest("div").find(".error-message").addClass("hide");
        }
    }
    return hasError;
};
App.validateCVVCode=function() {
    var hasError = false,
        cvv = $("input[name=cvv_code]");
    if ($.trim(cvv.val()) === "") {
        cvv.closest("div").find(".error-message").removeClass("hide").html('It would be irresponsible of us not to require this.');
        hasError = true;
    } else {
        if (!App.isValidCVVCode(cvv)) {
            cvv.closest("div").find(".error-message").removeClass("hide").html("Hmm, that\'s not it. Try looking a little closer at the card  or maybe your card  number is wrong.");
            hasError = true;
        } else {
            cvv.closest("div").find(".error-message").addClass("hide");
        }
    }
    return hasError;
};
App.validateZipCode=function() {
    var hasError = false;
    var zip = $("input[name=zip]");
    if ($.trim(zip.val()) === "") {
        zip.closest("div").find(".error-message").removeClass("hide");
        hasError = true;
    } else if($.trim(zip.val()).length < 5){
        zip.closest("div").find(".error-message").removeClass("hide").html('Billing zip should be 5 digits.');
        hasError = true;
    }else{
        zip.closest("div").find(".error-message").addClass("hide");
        hasError = false;
    }
    return hasError;
};
App.checkZipCode=function() {   
    var key = event.which;
    if(key ===37 || key ===38 || key ===39 ||key ===40 || key === 8 || key === 46 || key === 9){
        return true ;
    }
    var zip = $("input[name=zip]");
    if ($.trim(zip.val()) === "") {
        zip.closest("div").find(".error-message").removeClass("hide");      
    } else if($.trim(zip.val()).length < 5){
       // zip.closest("div").find(".error-message").removeClass("hide").html('Billing zip should be 5 digits.');      
    }else{
        zip.closest("div").find(".error-message").addClass("hide");
        
    }
   
};
App.checkZipCodeblur=function() {   
    var zip = $("input[name=zip]");
    if ($.trim(zip.val()) === "") {
        zip.closest("div").find(".error-message").removeClass("hide");      
    } else if($.trim(zip.val()).length < 5){
       zip.closest("div").find(".error-message").removeClass("hide").html('Billing zip should be 5 digits.');      
    }else{
        zip.closest("div").find(".error-message").addClass("hide");
        
    }
   
};
App.validateMonth=function() {
    var hasError = false;
    var month = $('.card_expire_month').val();
    var year = $('.card_expire_year').val();
    var currentDateObj = new Date();
    var currentMonth = currentDateObj.getMonth() + 1;
    var currentYear = currentDateObj.getFullYear();
    if (year == currentYear) {
        if (month < currentMonth) {
            $('.card-validity').removeClass("hide");
            hasError = true;
        } else {
            $('.card-validity').addClass("hide");
        }
    } else {
        $('.card-validity').addClass("hide");
    }
    return hasError;
};
App.isValidCardNumber=function(element) {
    var cardNumber = element.val();
    cardNumber = cardNumber.replace(/ /g, '');
    return cardNumber.length > 13 && cardNumber.length < 19 && App.getCardType(cardNumber);
};
App.isValidCVVCode=function(element) {
    var cvvCode = element.val();
    return (isNaN(cvvCode) === true || cvvCode.length < 3 || cvvCode.length > 4) ? false : true;
};
App.detectCardType=function(event) {
    App.cardNumberFormat(event);
    var $element = $("input[name=card_number]");
    var value = $element.val();
    var cardType = App.getCardType(value);
    $("ul.credit_cards li").removeClass('correct');
    if (cardType) {
        $("ul.credit_cards li[data-type='" + cardType + "']").addClass('correct');
    }
};
App.getCardType=function(card_no) {    
    var card_number = card_no.replace(/ /g, '');
    try {
        var intCardNumber4 = parseInt(card_number.substr(0, 4), 10);
        var intCardNumber6 = parseInt(card_number.substr(0, 6), 10);
        var strCardNumber = card_number + "";
    } catch (ex) {
        var intCardNumber4 = 0;
        var intCardNumber6 = 0;
        var strCardNumber = "";
    }
    var isVISA = (new RegExp("^4.*")).test(strCardNumber);
    var isMASTER = (new RegExp("^(51|52|53|54|55).*")).test(strCardNumber);
    var isAMEX = (new RegExp("^(34|37).*")).test(strCardNumber);
    var isDISC = (((new RegExp("^(6011|644|645|646|647|648|649|65).*")).test(strCardNumber)) || (intCardNumber6 > 622127 && intCardNumber6 < 622925));
    var isDINN = (new RegExp("^(54|36|38|300|301|302|303|304|305).*")).test(strCardNumber);
    var isJCB = intCardNumber4 >= 3528 && intCardNumber4 <= 3589;
    if (isVISA) {
        return "visa";
    }
    if (isMASTER) {
        return "master";
    }
    if (isAMEX) {
        return "amex";
    }
    if (isDISC) {
        return "disc";
    }
    if (isDINN) {
        return "dinn";
    }
    if (isJCB) {
        return "jcb";
    }
    return false;
};
App.resetForm=function(){
    $('#bookform')[0].reset();
    $('.inputfield').removeClass('ticked');
    $('input[type=checkbox]').attr('checked',false);
    $('#people').prop('selected', function() {
        return this.defaultSelected;
    });
    $('#people').closest('div').find('span').text($('#people').val());
};
App.parseDate = function(date) {
        if (typeof date === 'string') {
            date = date.replace(/\-/g, '/');
        }
        var dummyDate = new Date(date);
        if (Object.prototype.toString.call(dummyDate) === "[object Date]" && !isNaN(dummyDate.getTime())) {
            return dummyDate;
        }
        return new Date(date);
};
App.paddLeft = function(str, char, length) {
        if (str.length >= length) return str;
        var padding = char + "";
        for (var i = 1; i < length; i++) {
            padding += char;
        }
        var a = padding + str;
        return a.slice(-length);
    };
App.get24HourTime = function(time) {
        var date = App.parseDate('1970-01-01 ' + time, true);
        return App.paddLeft(date.getHours(), 0, 2) + ":" + App.paddLeft(date.getMinutes(), 0, 2);
};
App.editReservation = function(){
    dataLayer.push({
        'event':'edit reservation',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_edit_reservation_Button',
        'RestaurantID':restId
    });
    $('.error_time_slot').html('');
    $('.formstep2').addClass('hide');
    $('.formstep1').removeClass('hide');
    $('.a_modal').addClass('scrollview');
    if($.jStorage.get("changeRSlot"+restId) && $.jStorage.get("changeRSlot"+restId)==1){
        App.setJStorage("changeRSlot"+restId,0);
        App.populate_time();
    }    
};
App.getValidTimeSlot = function(){
    dataLayer.push({
        'event':'Reserve It',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_reserve_it_Button',
        'RestaurantID':restId
    });
    $('.formstep1').addClass('hide');
    $('.a_modal').addClass('scrollview');
    $('.formstep2').removeClass('hide');
    $('.a_modal').removeClass('scrollview');
};
App.continueWithTakeout=function(){ 
    dataLayer.push({
        'event':'Order Takeout',
        'restname': App.currentRestaurant.name,
        'ev_label': 'Click_on_order_takeout_Button',
        'RestaurantID':restId
    });
    $('.t_proceed_takeout , .t-verify_proceed').addClass('disable_actions'); 
    $('.lineloader_menu').addClass('hide');
    App.popuphide();
    if($.jStorage.get('addtoOrder') && $.jStorage.get('addtoOrder')!==''){
        setTimeout(function(){
            App.addOrder($.jStorage.get('addtoOrder'));
            $.jStorage.set('addtoOrder','');    
        },150);
    }
    $("#t_delivery").removeAttr("checked");
    $('#t_takeout').prop("checked",true);
    App.setJStorage('order_type_'+restId,'takeout');
    App.renderDateTime();
    App.cartCalution();
    if($.jStorage.get('addtoOrder_'+restId) && $.jStorage.get('addtoOrder_'+restId)!==''){
        $.jStorage.set('addtoOrder_'+restId,'');
    }
    if($.jStorage.get('select_delivery_'+restId) && $.jStorage.get('select_delivery_'+restId)!==''){
        $.jStorage.set('select_delivery_'+restId,'');
    }
   $('.t_proceed_takeout , .t-verify_proceed').removeClass('disable_actions');   
};
App.getDistance = function(options) {
        var point1 = typeof options['point1'] != "undefined" ? options['point1'] : {},
            point2 = typeof options['point2'] != "undefined" ? options['point2'] : {},
            return_type = typeof options['return_type'] != 'undefined' ? options['return_type'].toLowerCase() : "mi",
            precision = typeof options['precision'] != 'undefined' && !isNaN(options['precision']) ? parseInt(options['precision'], 10) : 2,
            distance = NaN;
        if (!_.isEmpty(point1) && !_.isEmpty(point2)) {
            var p1 = new google.maps.LatLng(point1["latitude"], point1["longitude"]),
                p2 = new google.maps.LatLng(point2["latitude"], point2["longitude"]);
            distance =google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000;
        }
        if (isNaN(distance)) {
            throw "-- Cannot Calculate Distance --";
        }
        if (return_type === "mi") {
            distance = distance * 0.621371;
        } else if (return_type === "km") {}

        var precisionNumber = Math.pow(10, precision);
        distance = Math.round(distance * precisionNumber) / precisionNumber;
        return distance;
    };
App.reserveTable = function(e) {   
    if (e && e.isDefaultPrevented) {
        e.preventDefault();
    }    
    $('#btnconfirm').addClass('disabled'); 
    $('.popup_reservetable .lineloader').removeClass('hide');    
    App.reserveTableNow();
    /* $.ajax({
        url:apiUrl+'/restaurant/details/'+restId+'?token='+$.jStorage.get('oauth.token'),
        cache: false,
        type: 'get',
        success: function(data) { 
            App.currentRestaurant = data;
            var date = $("#datepicker1").val();
            var time = $("#timepicker1").val();
            var selectedTime = date + " " + App.get24HourTime(time);
            var currentTime = App.currentRestaurant.current_dateTime;    
            var currentDateTime = App.parseDate(currentTime);
            var selectedDateTime = App.parseDate(selectedTime);
            var diff_date =  parseInt(selectedDateTime.getTime() - currentDateTime.getTime());
            if(diff_date < 14400000){
               App.showSlotChange();
               $('#btnconfirm').removeClass('disabled');
               $('.popform.bookform').removeClass('disabledform');
               $('.confirm_loader').addClass('hide');
               return false ; 
            }else{
                App.reserveTableNow();
            }
        }
    });*/
};

App.reserveTableNow = function() {   
    var reserve_seat = $("#people").val(),
        date = $("#datepicker1").val(),
        time = $("#timepicker1").val(),
        firstName = $("input[name=first_name_r]"),
        lastName = $("input[name=last_name_r]"),
        phoneNo = $("input[name=phone_no_r]"),
        email = $("input[name=email_r]"),       
        instructions = [];
    $("input[name='instructions[]']:checked").each(function() {
        instructions.push($(this).val());
    });
    if ($(".own_instruction").val() !== '') {
        instructions.push($(".own_instruction").val());
    }
    var hasError = App.validateFirstNameR(),
        hasError1 = App.validatePhoneR(),
        hasError2 = App.validateEmailR();       
    if (hasError || hasError1 || hasError2) {
        var top = $(".error-message:not(.hide):first").offset().top;
        $(".a_modal-dialog").stop().animate({
            scrollTop: top
        });
        $('#btnconfirm').removeClass('disabled');       
        $('.popup_reservetable .confirm_loader').addClass('hide');
        return false;
    }
    $('.popup_reservetable').addClass('form_disable');
    $(".close").off('click');
    $(document).off('keyup');
    var data = {
        'restaurant_id': restId,
        'restaurant_name': App.currentRestaurant.name,
        'date': App.queryDateFormate(date),
        'time': App.get24HourTime(time),
        'time_slot': App.queryDateFormate(date) + " " + App.get24HourTime(time),
        'reserved_seats': reserve_seat,
        'first_name': $.trim(firstName.val()),
        'last_name': $.trim(lastName.val()),
        'phone': $.trim(phoneNo.val().replace(/([*()'-\/ ])/g, '')),
        'email': $.trim(email.val()),
        'user_instruction': instructions.join("||"),
        'token': $.jStorage.get('oauth.token'),       
        "restshortkey": shortKey,
        "host_name" : window.location.protocol+"//"+window.location.host
    };  
    var dt = App.parseDate(date);
    var msgtoSendFriend =  $.trim(firstName.val())+" sent you an invitation to dine at "+App.currentRestaurant.name+" "+App.currentRestaurant.address+" on "+ dt.dateFormat('D, M d, Y') +" at "+time+". Drinks will be drank, eats will be eaten, and good times will be had by all. That's the plan anyway.";
    $('.y-expectedTime').html(dt.dateFormat('D, M d') + " at " + App.get12HourTime($.jStorage.get('delivery_order_time_'+restId)));
    
    $.ajax({
        url: apiUrl + '/restaurant/reservation',
        type: 'post',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            $(".close").on('click', $.proxy(App.popuphide, App));
            $(document).on('keyup', $.proxy(App.closeOnEscape, App));
            if(App.closeReservation){
                App.closeReservation =0 ; 
                delete App.closeReservation;
                return false ; 
            }
            if (data['reservation_status'] == 1) {
                $('.popup_reservetable .confirm_loader').addClass('hide');
                $('.formstep2').addClass('hide');
                $('.formstep2').addClass('hide');
                $('.formstep3').removeClass('hide');
                $('#y-party-size').html(reserve_seat);
                $('.y-reserve-date').html(date);
                $('.y-reserve-time').html(time);
                $('.y-recieptN').html(data['receipt_no']);
                $('#y-reservation-id').val(data['reservation_id']); 
                $('#send-reservation-msg').text(msgtoSendFriend);
                $('.a_modal-dialog').animate({scrollTop:0}, "slow");
                 var rtime = date + " " + time;
                //var rtime = "7/16/2017 9:55 pm" ;
                $("#calendarClick-1").attr("data-id", data.reservation_id)
                        .attr("data-starttime",rtime)
                        .attr("data-endtime", rtime)
                        .attr("data-title", "Reservation in "+App.currentRestaurant.name)
                        .attr("data-description", "Reservation in "+App.currentRestaurant.name+" for "+reserve_seat)
                        .attr("data-location", App.currentRestaurant.address+", "+App.currentRestaurant.city+", "+App.currentRestaurant.zipcode);
                
               
                dataLayer.push({
                    'event':'Request Reservation',
                    'restname': App.currentRestaurant.name,
                    'ev_label': 'Click_on_request_reservation_Button',
                    'RestaurantID':restId
                });
            } else {
                $('#btnconfirm').removeClass('disabled');
                $('.popform.bookform').removeClass('disabledform');
                $('.confirm_loader').addClass('hide');
                $('.error_time_slot').empty().html(data['msg']);
                $('.error_time_slot').removeClass('hide');
            }
            if(data['error'] == 1){
                $('#btnconfirm').removeClass('disabled');
                $('.error_time_slot').removeClass('hide');
                App.setJStorage("changeRSlot"+restId,1);
                $('.error_time_slot').empty().html(data['msg']);
            }
            $('.popup_reservetable .confirm_loader').addClass('hide');
            $('.popup_reservetable').removeClass('form_disable');
        },
        error: function(response) {
            $(".close").on('click', $.proxy(App.popuphide, App));
            $(document).on('keyup', $.proxy(App.closeOnEscape, App));
            response = $.parseJSON(response['responseText']);
            var error = response["error"];
            if (!error) {
                error = "Something apparently went wrong.";
            }
            $('#btnconfirm').removeClass('disabled');
            $('.popform.bookform').removeClass('disabledform');
            $('.confirm_loader').addClass('hide');
            $(".stripe-error").html(error);
            $(".stripe-error").closest('.row').removeClass("hide");
            $('.popup_reservetable .confirm_loader').removeClass('hide');
            $('.popup_reservetable').removeClass('form_disable');
        }
    });
};
App.goForOrder=function(e){
    if (e && e.isDefaultPrevented) {
        e.preventDefault();
    }
    App.popuphide();
    
    if($.jStorage.get('order_items_'+restId).length === 0){
        App.editOrders();        
        setTimeout(function(){
            App.renderCart();
            App.MinAmount('t-no-order');
        },300);        
        return false;
    }
    App.renderItems();
    
    var hasError = App.validateFirstName(),
        hasError1 = App.validatePhone(),
        hasError2 = App.validateEmail(),
        hasError3 = App.validateCardName(),
        hasError4 = App.validateCardNumber(),
        hasError5 = App.validateCVVCode(),
        hasError6 = App.validateZipCode(),
        hasError7 = App.validateMonth();
        if (hasError || hasError1 || hasError2 || hasError3 || hasError4 || hasError5 || hasError6 || hasError7) {
            var top = $(".error-message:not(.hide):first").offset().top - 200;            
            if(App.mobileDevice()){
                $('body').addClass('a_modal_open');
                $("html,body").stop().animate({
                    scrollTop: top
                }); 
            }else{
               $("html,body").stop().animate({
                    scrollTop: top
                }); 
            }
            return false;
        }
    $('.placemyorder').addClass('disabled');
    $('.y-go-to-menu,.y-reserveTable,.pagejump').addClass('disabled');  
    $('.y-go-to-checkout').addClass('disabled'); 
    $('#menu').addClass('form_disable');
    $('.confirm_loader').removeClass('hide');
    $('.t-edit_order_link').addClass('hide');
    
    
    App.validateOrderTime('placeOrder');
};
App.placeOrder = function() {
    var firstName = $("input[name=first_name]"),
        lastName = $("input[name=last_name]"),
        address1 = $("input[name=address_1]"),
        address2 = $("input[name=address_2]"),
        city = $("input[name=city]"),
        stateCode = $("input[name=state_code]"),
        phoneNo = $("input[name=phone_no]"),
        email = $("input[name=email]"),
        cardName = $("input[name=card_name]"),
        cardNumber = $("input[name=card_number]"),
        cvv = $("input[name=cvv_code]"),
        zip = $("input[name=zip]"),
        month = $(".card_expire_month"),
        year = $(".card_expire_year"),
        zipCode = $("input[name=zipcode]").val(),
        instructions = [];
    $("input[name='instructions[]']:checked").each(function() {
        instructions.push($(this).val());
    });
    if ($(".own_instruction").val() !== '') {
        instructions.push($(".own_instruction").val());
    }
    var deliveryDate = $.jStorage.get("takeout_order_date_"+restId);
    var deliveryTime = $.jStorage.get("takeout_order_time_"+restId);
        var address_lat = 0,combinedAddress='';
        var address_lng = 0;       
        var tipPercent = 0;        
    if ($.jStorage.get('order_type_'+restId) === "delivery") {
        address1 = $("input[name=address_1]").val();
        address2 = $("input[name=address_2]").val();
        city = $("input[name=city]").val();
        stateCode = $("input[name=state_code]").val();
        address_lat = $.jStorage.get("address_lat_"+restId);
        address_lng = $.jStorage.get("address_lng_"+restId);
        combinedAddress = (address2) ? address1 + ", " + address2 : address1;
        deliveryDate = $.jStorage.get("delivery_order_date_"+restId);
        deliveryTime = $.jStorage.get("delivery_order_time_"+restId);
        App.validateAddress1();
        App.validateShippingZipCode();
        tipPercent = $.jStorage.get("tip_"+restId);       
    } else {

        city = ""; address1 = ""; address2 = ""; stateCode = stateCode ; zipCode = ""; combinedAddress = "";

    }
    
    var orderDetailsObj = {
        'restaurant_id': restId,
        'delivery_address': combinedAddress,
        'delivery_time': deliveryTime,
        'delivery_date': deliveryDate,
        'special_instruction': instructions,              
        'own_instruction': $(".own_instruction").val(),
        'order_type': $.jStorage.get("order_type_"+restId),
        'email': email.val(),
        'order_type1': 'I',
        'order_type2': "P",
        'discount': "",
        'discount_type': "",
        'tip_percent': tipPercent,
        'tax': $.jStorage.get("order_tax_"+restId),
        'items': App.getFormattedItems(),
        'user_comments': "",
        'restshortkey': shortKey
    };
    var userDetailsObj = {
        'fname': $.trim(firstName.val()),
        'lname': $.trim(lastName.val()),
        'email': email.val(),
        'city': $.trim(city),
        'apt_suit': $.trim(address2),
        'address': $.trim(address1),
        'phone': phoneNo.val().replace(/([*()'-\/ ])/g, ''),
        'state_code': $.trim(stateCode),
        'zipcode': $.trim(zipCode),
        'address_lat': address_lat,
        'address_lng': address_lng
    };
    var cardDetails = {
        'card_type': App.getCardType(cardNumber.val()) || "Unknown",
        "card_no": cardNumber.val().replace(/ /g, ''),
        "expiry_month": month.val(),
        "expiry_year": year.val(),
        "name_on_card": cardName.val(),
        "cvc": cvv.val(),
        "billing_zip": zip.val(),
        "card_id":0,
        "save_card":0
    };
    var data = {
        user_details: userDetailsObj,
        card_details: cardDetails,
        order_details: orderDetailsObj,
        user_address_id: "",
        order_pass_through: 0,
        cod:0,
        reservation_details: {},
        token: $.jStorage.get('oauth.token'),
        host_name : window.location.protocol+"//"+window.location.host
    };
    if(App.selectedDeal){
        data["deal_id"] = App.selectedDeal.id;
    }
    data["promocode"] ='';
    if($.jStorage.get("promocode_status")==="valid"){
        data["promocode"] = $.jStorage.get("promocode");
    }
    
    
    $.ajax({
        url: apiUrl + '/restaurant/place-order',
        type: 'post',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            App.orderPlace = true ; 
            $('.confirm_loader').addClass('hide');
            var tmpl = _.template($("#tmpl-checkout-thankyou").html());

            $('.checkoutsection').html(tmpl(data));         
          if(App.mobileDevice()){
            $('body').addClass('modalblackbg a_modal_open');
            $('.ordersummarystep2').removeClass('hide');
            $('.checkoutsection').addClass('outerDIVclose_mobile');
            $('html, body').stop().animate({scrollTop: $('.checkoutDiv').offset().top-55 }, "slow");
          }else{
            $('#menu > ._960px > .sectiontitle').html("Thank You");
            $('body').removeClass('modalblackbg a_modal_open');
            $('html, body').stop().animate({
                scrollTop: ($('#menu').offset().top)
            }, 800);
          } 
            $('.y-go-to-menu,.y-reserveTable,.pagejump').removeClass('disabled');
            $('.placemyorder').removeClass('disabled');  
            $('.y-go-to-checkout').removeClass('disabled');         
            $('#menu').removeClass('form_disable');
            
            /* start final summery*/
            $('.y-paymentDetails').removeClass('hide');
            $('.y-cardNo').html(data.card_number);
            $('.y-cardType').html(data.card_type);
            $('.y-expOn').html(data.expired_on);
            if ($.jStorage.get('order_type_'+restId) === "delivery") {
                $('.y-deliveryTo').removeClass('hide');
                /*$('.y-deliveryAddress').html($.jStorage.get("address_value_"+restId));*/
                $('.y-deliveryAddress').html(combinedAddress+', '+city+', '+stateCode+' '+zipCode+', USA');
                
            }            
            App.analyticsAddProduct(data);
            /* end final summery */
            $.jStorage.set('order_items_'+restId,[]);           
            $.jStorage.set("order_subtotal_"+restId,"");
            $.jStorage.set("order_tax_"+restId,"");
            $.jStorage.set("order_total_"+restId,"");
            
            $.jStorage.set("delivery_order_date_"+restId,"");
            $.jStorage.set("delivery_order_time_"+restId,"");
            $.jStorage.set("takeout_order_date_"+restId,"");
            $.jStorage.set("takeout_order_time_"+restId,"");  
            
            $.jStorage.set("promocode","");
            $.jStorage.set("promocode_data","");
            $.jStorage.set("promocode_status","");
            App.setJStorage("tip_"+restId,15);            
            App.selectedDeal=false ;           
            delete App.chkoutProcess;            
            $('.cartCount').html('0');
            $('.y-no-item').addClass('disabledcard');
            dataLayer.push({
                'event':'Place my order',
                'restname': App.currentRestaurant.name,
                'ev_label': 'Click_on_Place_my_order_Button',
                'RestaurantID':restId
            });
            App.renderDateTime();
            if(App.updateTimer){
                clearTimeout(App.updateTimer);
            }
        },
        error: function(response) {
            response = $.parseJSON(response['responseText']);
            var error = $.trim(response["error"]);
            if (!error) {
                error = "Something apparently went wrong.";
            }
            if(error==="We could not charge your credit card, please ensure all fields are entered correctly."){
                error = "The numbers you provided are not valid credit card numbers.";
            }
            $('.placemyorder').removeClass('disabled');          
            $('.confirm_loader').addClass('hide');
            $('.y-go-to-menu,.y-reserveTable,.pagejump').removeClass('disabled');
            $('.t-edit_order_link').removeClass('hide');
            $('.y-go-to-checkout').removeClass('disabled');
            $('#menu').removeClass('form_disable');
            $(".stripe-error").html(error);
            $(".stripe-error").closest('.row').removeClass("hide");
            if(App.updateTimer){
                clearTimeout(App.updateTimer);
            }
        }
    });
};
App.escape = function(){
    var text = $('textarea').val();
    var opt = text.replace(/[-{}()*+?:~!@%&_=";></\\^$|#]/g, "");
    $('textarea').val(opt);
};

App.validateName=function(evt){
    var keyCode = (evt.which) ? evt.which : evt.keyCode
    if ((keyCode < 65 || keyCode > 90) && (keyCode < 97 || keyCode > 123)  && keyCode != 32 && keyCode != 8 && keyCode != 9 && keyCode != 0)
          return false;

   }

App.validateFirstNameR=function() {
    var hasError = false;
    var firstName = $("input[name=first_name_r]");
    var errorMessage = firstName.closest("div").find(".error-message");
    if ($.trim(firstName.val()) === "") {
        errorMessage.removeClass("hide");
        hasError = true;
    } else {
        errorMessage.addClass("hide");
    }
    var value = $.trim(firstName.val());
    $("input[name=first_name_r]").val(value);
    return hasError;
};

App.bindEventsReservation = function(){
    $(".close").on('click', $.proxy(App.popuphide, App));
    $("#btnbook").on('click', $.proxy(App.getValidTimeSlot, App));
    $(".y-editReservation").on('click', $.proxy(App.editReservation, App));
    $("#btnconfirm").on('click', $.proxy(App.reserveTable, App));
    $("input[name=first_name_r]").on('keypress', $.proxy(App.validateName, App)); 
    $("input[name=first_name_r]").on('blur', $.proxy(App.validateFirstNameR, App));
    $("input[name=last_name_r]").on('keypress', $.proxy(App.validateName, App)); 
    $("input[name=phone_no_r]").on('blur', $.proxy(App.validatePhoneR, App));
    $("input[name=phone_no_r]").on('keypress', $.proxy(App.phoneNumberFormat, App));
    $("input[name=email_r]").on('blur', $.proxy(App.validateEmailR, App));    
    $("input[name=email_r]").on("keydown", function (e) {
        return e.which !== 32;
    });
    $(".y-send-invitation").on('click', $.proxy(App.sendInvitation, App)); 
  
 $("#bookform").on('click', function(){
        if (/iPad|iPhone|iPod/i.test(navigator.userAgent)) {
            $('#datepicker1').blur();
        }
    });
 
   };
App.bindEvents = function(){
    $(".close").on('click', $.proxy(App.popuphide, App));   
    $("input[name=first_name]").on('blur', $.proxy(App.validateFirstName, App));
    $("input[name=first_name]").on('keypress', $.proxy(App.validateName, App));
    $("input[name=last_name]").on('keypress', $.proxy(App.validateName, App));
    $("input[name=address_1]").on('blur', $.proxy(App.validateAddress1, App));
    $("input[name=zipcode]").on('blur', $.proxy(App.validateShippingZipCode,App));
    
    $("input[name=phone_no]").off('blur');
    $("input[name=phone_no]").on('blur', $.proxy(App.validatePhone, App));
    $("input[name=phone_no]").off('keypress');
    $("input[name=phone_no]").on('keypress', $.proxy(App.phoneNumberFormat, App));
    
    $("input[name=email]").on('blur', $.proxy(App.validateEmail, App));
    $("input[name=card_name]").on('keypress', $.proxy(App.validateName, App));
    $("input[name=card_name]").on('blur', $.proxy(App.validateCardName, App));
    $("input[name=card_number]").on('keyup', $.proxy(App.detectCardType, App));
    $("input[name=card_number]").on('blur', $.proxy(App.validateCardNumber, App));
    $("input[name=cvv_code]").on('blur', $.proxy(App.validateCVVCode, App));
    $("input[name=zip]").on('keyup', $.proxy(App.checkZipCode, App));
    $("input[name=zip]").on('blur', $.proxy(App.checkZipCodeblur, App));
    
    $("input[name=cvv_code]").on('keyup', $.proxy(App.onlyNumber, App));
    $("input[name=zip]").on('keypress', $.proxy(App.phoneNumberFormat, App));  
    $("input[name=email]").on("keydown", function (e) {
        return e.which !== 32;
    });
}; 
App.nameFormat = function(event){
    var key = event.which;
    if (key === 37 || key === 38 || key === 39 || key === 40 || key === 8 || key === 46) {
        return true;
    }
    var value = $(event.currentTarget).val().replace(/[^A-Za-z0-9._\s'-]/gi, "");
    if (value.substr(0, 1).match(/[A-Za-z]/) === null) {
        value = '';
    }
    $(event.currentTarget).val(value);
};
App.onlyNumber = function(event){
    var key = event.which;
    if(key ===37 || key ===38 || key ===39 ||key ===40 || key === 8 || key === 46){
        return true ;
    }
    var value = $.trim($(event.currentTarget).val());
    value =value.replace(/[^-0-9 !@#$%^&*()+,:;.",]/g, "");
    value = value.replace(/\./g,'');
    $(event.currentTarget).val(value);
     
};
App.phoneNumberFormat = function(event){
    var key = event;
    if(key.charCode != 8 && key.charCode != 0 && (key.charCode < 48 || key.charCode > 57)) {
        return false;
    }
};
App.cardNumberFormat = function(event){
     var key = event.which;
    if(key ===37 || key ===38 || key ===39 ||key ===40 || key === 8 || key === 46){
        return true ;
    }
    App.onlyNumber(event);       
    var valc = $(event.currentTarget).val().split(" ").join("");
    if (valc.length > 16) {
       valc = valc.substr(0, 16);
    }  
    if (valc.length > 0) {
      valc = valc.match(new RegExp('.{1,4}', 'g')).join(" ");
    }
    $(event.currentTarget).val(valc);       
};
App.inputFormatter = function(){
    var currentDateObj = App.parseDate(App.currentRestaurant.current_dateTime);
    var currentMonth = ('0' + (currentDateObj.getMonth() + 1)).slice(-2);
    var currentYear = currentDateObj.getFullYear();
    var n = currentDateObj.getMonth();
    $('#m_selectMonthVaue').text(currentMonth);
    $('#m_selectYearVaue').text(currentYear);
    $('.select_expiry select option:eq('+n+')').prop('selected', true);    
};
App.getFormattedItems = function() {
        var items = [];
        var i=0;
        $.each($.jStorage.get('order_items_'+restId), function( key, value ) {
            items.push({
                id: i,
                item_id: value['item_id'],
                quantity: value['quantity'],
                price_id: value['price_id'],
                special_instruction: value['special_instruction'],
                addons: value['addons']
            });
            i++ ; 
        });
    return items;
};
App.getFormattedAddress = function(fullAddress) {
    var formattedAddress = [];
    if(fullAddress !== ""){
        var address = fullAddress.split(',');
        formattedAddress['addressValue'] = address[0];
        formattedAddress['city'] = $.trim(address[1]);
        if(address[2] !== ""){
            formattedAddress['zipCode'] = address[2].replace(/[a-zA-Z-&\/\s]/gi, '');
        }else{
            formattedAddress['zipCode'] = "";
        }

        formattedAddress['stateCode'] = stateCode;

        return formattedAddress;
    }else{
        return formattedAddress;
    }
};
App.checkoutValidate = function() {
    var flag = false;
    if($.jStorage.get('order_type_'+restId)==='delivery' && $.jStorage.get('delivery_order_date_'+restId) !=="" && $.jStorage.get('delivery_order_time_'+restId) !=="" && $.jStorage.get('address_value_'+restId) !==""){
        flag = true;
    }
    if($.jStorage.get('order_type_'+restId)==='takeout' && $.jStorage.get('takeout_order_date_'+restId) !=="" && $.jStorage.get('takeout_order_time_'+restId) !==""){
        flag = true;
    }    
    return flag ; 
};
App.setDeliveryTakeoutTime = function() {   
    var newDt = App.parseDate(App.currentRestaurant.current_dateTime);
    if($.jStorage.get('order_type_'+restId)==='delivery'){
        var dt = App.parseDate($.jStorage.get('delivery_order_date_'+restId));
         $('.y-expectedTime').html(dt.dateFormat('D, M d') + " at " + App.get12HourTime($.jStorage.get('delivery_order_time_'+restId)));
    }else{
        var dt = App.parseDate($.jStorage.get('takeout_order_date_'+restId));
         $('.y-expectedTime').html(dt.dateFormat('D, M d') + " at " + App.get12HourTime($.jStorage.get('takeout_order_time_'+restId)));
    }   
    $('.y-timeOfOrder').html(newDt.dateFormat('D, M d')+ " at " + App.get12HourTime(newDt.getHours() +":"+ newDt.getMinutes()));
    
};
App.queryDateFormate=function(date){
    var dt = App.parseDate(date);
    return dt.dateFormat('Y-m-d');    
};
App.tooltipselecttimehide = function(){
    $('.tooltipselecttime').addClass('hide');
    if(App.mobileDevice()){

    }else{
        $('body').removeClass('a_modal_open');
    }
};
App.tooltipselecttimeshow = function(){
    var order_type = $.jStorage.get('order_type_'+restId) ; 
    var order_time = order_type==='delivery'?$.jStorage.get('delivery_order_time_'+restId):$.jStorage.get('takeout_order_time_'+restId) ;
    if(order_time == undefined || order_time===''){
        $('.tooltipselecttime').removeClass('hide');
        if($(window).width() > 767){
            $('.box_ordersummary').stop().animate({
                scrollTop: 0
            }, 800);
        }else{
            $('html, body').stop().animate({
                scrollTop: $('.t-orderDateTimePanel').offset().top - $(window).height()/2
            }, 800);
        }
        //console.log(scrolltop)
    }
    $(".tooltipselecttime .btn_close").off('click');
    $(".tooltipselecttime .btn_close").on('click', $.proxy(App.tooltipselecttimehide, App)); 
     
};
App.closeBookaTable = function(){
    $('.bookform').html('');
};
App.validateNoOfPeoples = function(peoples){
    var no_of_people = (window.shortKey === "hk")?5:6;
    if(peoples < no_of_people){
        $('#btnconfirm').removeClass('disabled');
        $('.popform.bookform').removeClass('disabledform');
        $('.confirm_loader').addClass('hide');
        $('.error_time_slot').empty().html("Reservations will not be honored for parties with less than " +no_of_people+" people.");
        $('.error_time_slot').removeClass('hide');
        $(".stripe-error").closest('.row').removeClass("hide");
        $('#bookform').removeClass('secondform');
        setTimeout(function(){
                var offset = $('#booktable').offset();
                var h = $('#booktable').height();
                $('html, body').stop().animate({
                    scrollTop: (offset.top - 250)
                }, 200);
        }, 500);
        return true;
    }else{
        return false;
    }    
};

App.popupshow = function(){
    App.closeReservation=0;
    $('body').attr('st' , $(window).scrollTop());
    if (App.mobileDevice() || /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
        $('body').addClass('mobilepopup');
        setTimeout(function(){
            $('body').addClass('popupfixed');
        }, 700);
        window.scrollTo(0, 0);
    }
    App.closeReservation=0;
    $('body').addClass('a_modal_open');
    $('.a_modal').removeClass('hide');
    $('.t-popupdata').html('');
    $(document).keyup(function(e) {
        if (e.keyCode === 27) { 
            $('#datepicker1').datetimepicker('hide');
            App.popuphide();
        }
    });
};

App.popuphide = function(){
    if (App.mobileDevice() || /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
        $('body').removeClass('mobilepopup popupfixed');
        var stPos = $('body').attr('st');
        if(stPos){
            var fmHeight = 0;
            if($(window).width >= 1024) {
                fmHeight = $('.navbarcontainer').height();
            }
            $(window).scrollTop(stPos-fmHeight);
        }
        setTimeout(function(){
            // if(stPos){
            //     $('html, body').stop().animate({scrollTop: stPos-fmHeight}, "slow");
            // }
            $('body').removeAttr('st');
        }, 100);
    };

    window.addOnsModel='';
    App.closeReservation = 1 ;
    $('.lineloader_menu').addClass('hide');
    $('.a_modal').addClass('hide');
    $('.t-popupdata').html('');
    $('body').removeClass('a_modal_open');
    $('.a_modal').removeClass('scrollview');
    $('body').removeClass('a_scrollactive');
    $('#datepicker1').datetimepicker('hide');
    //App.handleCartPopup();
};

App.validateCardExpiry = function(){
    var hasError = false;
    var reservationDate = $("#datepicker1").val().split('-');
    var reserveMonth = reservationDate[1];
    var reserveYear = reservationDate[0];
    var cardExpiryMonth = $('#m_selectMonthVaue').text();
    var cardExpiryYear = $('#m_selectYearVaue').text();
    var reserveDate = reserveYear + reserveMonth / 12;
    var cardExpiryDate = cardExpiryYear + cardExpiryMonth / 12;
    if (cardExpiryDate < reserveDate) {
        $('.card-validity').removeClass("hide");
        $(".card-validity").empty().html("Reservation not allowed. Please enter the credit card which is valid for the reservation date.");
        hasError = true;
    }else{
        hasError = false;
    }
    return hasError;
};
App.formattedPhoneNo = function(phone){  
    var ph  = $.trim(phone);
    if(ph.length===10){
        return ph.substr(0, 3) + '-' + ph.substr(3, 3) + '-' + ph.substr(6,4);
    }
    return ph ;
};
App.applyPromocode=function (){
    var promocode = $('#promocode').val();
    if (promocode === '') {     
        $(".promo_code .error-message").removeClass("hide").html('Invalid Promo code');
        return false;
    }    
    $.ajax({
        url:apiUrl+'/home/promocode?token='+$.jStorage.get('oauth.token')+'&promocode='+promocode+'&restaurantid='+restId,
        cache: false,
        type: 'get',
        success: function(data) { 
            dataLayer.push({
                'event':'Enter Promo Code',
                'restname': App.currentRestaurant.name,
                'ev_label': 'Click_on_enter_button_promo_code',
                'RestaurantID':restId
            });
            if(data.success){            
                App.setJStorage("promocode_data",data);
                App.setJStorage("promocode",promocode);
                App.setJStorage("promocode_status","valid");
                if ( $.jStorage.get('order_subtotal_'+restId) >= parseFloat(data.minimum_order_amount)) {                     
                     App.cartCalution();
                }else{                  
                   $('.promo_code .error-message').removeClass('hide').html('Minimum order must exceed $' + data.minimum_order_amount + ' to redeem this Promo Code');
                }
            }else{
                App.setJStorage("promocode_data",data);
                $(".promo_code .error-message").removeClass("hide").html(data.message);
                App.setJStorage("promocode_status","invalid");       
            }
        },
        error: function() {}
    });
};
App.analyticsAddProduct = function (data){
    var transactionId = data.receipt;
    var i = 0;
    var productArray = [];
    $.each($.jStorage.get('order_items_' + restId), function (key, value) {
        console.log(value);
        productArray.push({
            'name': value['item_name'],
            'price': value['item_price'],
            'category': '',
            'brand': '',
            'quantity': value['quantity']
        });
        i++;
    });
    dataLayer.push({
        'event':'ecomm_event',
        'transactionId': data.id,
        'transactionAffiliation': App.currentRestaurant.name,
        'transactionTotal': data.finalTotal,
        'transactionProducts': productArray,
        'RestaurantID':restId
    });
};
App.floodLightpixelTracking = function(url) {};

