﻿jQuery.makeBooking = function() {
    var dataArr = {};
    var selectedTime = {};
	var selectedDate;
	var duration0 = 0;
	var duration1 = 0;
	var duration2 = 0;
	var duration3 = 0;
	var duration4 = 0;
	var availability = 0;
	var defaultNumberOfGuests = 2;
	var restaurantID;
	var initPositions = false;
	var direction = 0;
	var editDate = '';
	var editTime = 0;
	
	// lock control mechanism to avoid double clicking problems
	var priv = {
        padlock : false,
        
        setLock : function(){
            priv.padlock = true;
            $("body").css("cursor", "wait");
        },
        
        unLock : function(){
            priv.padlock = false;
            $("body").css("cursor", "default");
        },
        
        isLocked : function(){
//            try {
//                console.log("lineup is locked = " + priv.padlock);
//            }
//            catch(err){
//                //nothing here, simply test whether console.log exists
//            }
            return priv.padlock;
        }
    }
	
	var _setEditTime = function(date, time) {
	    editDate = date;
	    editTime = time;
	};
	
	var _getTimeStr = function(time) {
	    var h = parseInt(time/60,10) % 24;
	    return (h < 10 ? "0" + h : h).toString() +":"+ ((time%60) == 0 ? "00" : time%60).toString();
	};
	
	var _getHourStr = function(hour){
	    hour = hour % 24;
	    return (hour < 10 ? "0" + hour : hour);
	};
	
	var _changeHomePageSearchLink = function(){
	    // find selected values
	    var personCount = $('select.personCount').find('option').filter(':selected').val();
	    var selectedTime = $('select.timesDDL').find('option').filter(':selected').val();
	    // on home page calendar selected day will not be changed when next/prev month is clicked
	    // So selectedDate is being taken from hidden field, not from calendar
	    //var selectedDate = jQuery.jcalendar.getstringdate();
	    var selectedDate = $('input.hdnSelectedDate').val();
        
        // make an AJAX call to compose link
        $.ajax({
            type: "POST",
            url: messages.path_prefix + "/handlers/createHomePageSearchLink.ashx",
            data: "date="+selectedDate+"&person="+personCount+"&time="+selectedTime,
            async: false,
            success: function(result){                                               
                //assign this link to button
                $('a.findTableBTN').attr('href', result);
            },
            error: function(data){
            }
        });
	};
	
    var _checkAvailability = function(date, startTime, rid, selectedTime, index) {
        // checking if the function is currently active
        // double calling is not permitted
        if(priv.isLocked() && direction != 0){
                return;
        }
        //set lock
        if (direction != 0)
            priv.setLock();
        
        
        restaurantID = rid;
        selectedDate = date;
        if(startTime == -1)
        {
            if(selectedTime == null)
               selectedTime = $("ul.time div.first").html();
            var time = 0;
            if(selectedTime != null)
            {
                var selected = selectedTime.split(':');        
                time = jQuery.makeBooking.getTime(selected[0], selected[1])
            }
            startTime = time;
        }
        personCount = $('select.personCount').find('option').filter(':selected').val();
        
        if (dataArr[0] != null)
        {
            duration0 = dataArr[0].duration0;
            duration1 = dataArr[0].duration1;
            duration2 = dataArr[0].duration2;
            duration3 = dataArr[0].duration3;
            duration4 = dataArr[0].duration4;
            availability = dataArr[0].available;
        }
        else
        {
            duration0 = 0;
            availability = 0;
        }
        
	    var available = false;
	    
	    var duration = 0;
	    switch (index)
        {
            case 0:
                duration = duration0;
                break;
            case 1:
                duration = duration1;
                break;
            case 2:
                duration = duration2;
                break;
            case 3:
                duration = duration3;
                break;
            case 4:
                duration = duration4;
                break;
        }

	    $.ajax({
            type: "POST",
            url: messages.path_prefix + "/handlers/checkTimeAvailability.ashx",
            data: "resdate=" + selectedDate + "&nog="+personCount+ "&time="+ startTime + "&dur="+ duration + "&avl="+ availability+"&rid="+restaurantID,
            async: false,
            success: function(data){
                dataArr = eval('['+data+']');
                // set 'back to search page' link
                $('.grey-box a.btn').attr('href', dataArr[0].fhquery);
                
                if(dataArr[0].noschedule == undefined)
                {
                    $("div#NoTimesForSelection").css({display : "none"});
                    $("div#timesForSelection").css({display : "block"});
                    
                    //selected time is available
                    if(dataArr[0].available == 1)
                    {
                        available = true;
                    }
                    else //selected time is unavailable
                    {
                        available = false;
                    }
                    if(index == undefined){
                        
                        // direction == 0 means there is no movement
                        // so we have to add hour data into the old list and color it.
                        if (direction == 0)
                        {
                            // remove green1, green2 classes and reassign for each time
                            $('ul.time li').removeClass('green1').removeClass('green2').removeClass('green-edit');
                            $('ul.time li').unbind('click');
                            
                            $('div#time1').html(dataArr[0].time0);
                            $('div#time2').html(dataArr[0].time1);
                            $('div#time3').html(dataArr[0].time2);    
                            $('div#time4').html(dataArr[0].time3);        
                            $('div#time5').html(dataArr[0].time4);
                            
                            if(dataArr[0].available0 == 1){
                                $('div#time1').parent().addClass('green2');
                                $('div#time1').parent().unbind('click').bind('click', {time: dataArr[0].time0, index: 0}, _goNext);
                            }
                            if(dataArr[0].time0 == editTime)
                                $('div#time1').parent().addClass('green-edit');
                            
                            if(dataArr[0].available1 == 1){
                                $('div#time2').parent().addClass('green2');
                                $('div#time2').parent().unbind('click').bind('click', {time: dataArr[0].time1, index: 1}, _goNext);
                            }
                            if(dataArr[0].time1 == editTime)
                                $('div#time2').parent().addClass('green-edit');
                                    
                            if(dataArr[0].available2 == 1){
                                $('div#time3').parent().addClass('green2');
                                $('div#time3').parent().unbind('click').bind('click', {time: dataArr[0].time2, index: 2}, _goNext);
                            }
                            if(dataArr[0].time2 == editTime)
                                $('div#time3').parent().addClass('green-edit');
                                   
                            if(dataArr[0].available3 == 1){
                                $('div#time4').parent().addClass('green2');
                                $('div#time4').parent().unbind('click').bind('click', {time: dataArr[0].time3, index: 3}, _goNext);
                            }
                            if(dataArr[0].time3 == editTime)
                                $('div#time4').parent().addClass('green-edit');
                            
                            if(dataArr[0].available4 == 1){
                                $('div#time5').parent().addClass('green2');
                                $('div#time5').parent().unbind('click').bind('click', {time: dataArr[0].time4, index: 4}, _goNext);
                            }
                            if(dataArr[0].time4 == editTime)
                                $('div#time5').parent().addClass('green-edit');
                        }
                        // if any movement exists, then we have to fill the new list with new hours and color it.
                        else 
                        {
                            $('ul.time li').removeClass('green-edit');
                            
                            // the action is a left or right movement to see other available hours
                            // newList will contain the new hours
                            var newList = "<li id=\"newLi1\" class=\"newTimeItem\">"
							    +	"<div class=\"top\"><!--<strong> </strong> pts--></div>"
							    +	"<div id=\"newTime1\" class=\"first\"></div>"
							    + "</li>"
							    + "<li id=\"newLi2\" class=\"newTimeItem\">"
							    +	"<div class=\"top\"><!--<strong> </strong> pts--></div>"
							    +	"<div id=\"newTime2\"></div>"
							    + "</li>"
							    + "<li id=\"newLi3\" class=\"newTimeItem\">"
							    +	"<div class=\"top\"><!--<strong> </strong> pts--></div>"
							    +	"<div id=\"newTime3\"></div>"
							    + "</li>"
							    + "<li id=\"newLi4\" class=\"newTimeItem\">"
							    +	"<div class=\"top\"><!--<strong> </strong> pts--></div>"
							    +	"<div id=\"newTime4\"></div>"
							    + "</li>"
							    + "<li id=\"newLi5\" class=\"newTimeItem\">"
							    +	"<div class=\"top\"><!--<strong> </strong> pts--></div>"
							    +	"<div id=\"newTime5\"></div>"
							    + "</li>";
                            
                            // checking the direction of movement
                            // -1 is left, so we need to add the new items before the current items
                            // also we need to update the position; the new items have to be in the
                            // left of the old start point.
                            if (direction == -1)
                            {
                                $('ul#timeList').prepend(newList);
                                $('ul#timeList').css("left", -325);
                            }
                            // 1 is right, so we need to add the new items after the current items
                            else if (direction == 1)
                            {
                                $('ul#timeList').append(newList);
                                $('ul#timeList').css("left", 0);
                            }
                            
                            // filling the hour values
                            $('div#newTime1').html(dataArr[0].time0);
                            $('div#newTime2').html(dataArr[0].time1);
                            $('div#newTime3').html(dataArr[0].time2);    
                            $('div#newTime4').html(dataArr[0].time3);        
                            $('div#newTime5').html(dataArr[0].time4);
                            
                            // coloring items
                            if(dataArr[0].available0 == 1){
                                $('div#newTime1').parent().addClass('green2');
                                $('div#newTime1').parent().unbind('click').bind('click', {time: dataArr[0].time0, index: 0}, _goNext);
                            }
                            if(dataArr[0].time0 == editTime){
                                $('div#newTime1').parent().addClass('green-edit');
                            }
                            
                            if(dataArr[0].available1 == 1){
                                $('div#newTime2').parent().addClass('green2');
                                $('div#newTime2').parent().unbind('click').bind('click', {time: dataArr[0].time1, index: 1}, _goNext);
                            }
                            if(dataArr[0].time1 == editTime){
                                $('div#newTime2').parent().addClass('green-edit');
                            }
                                
                            if(dataArr[0].available2 == 1){
                                $('div#newTime3').parent().addClass('green2');
                                $('div#newTime3').parent().unbind('click').bind('click', {time: dataArr[0].time2, index: 2}, _goNext);
                            }
                            if(dataArr[0].time2 == editTime){
                                $('div#newTime3').parent().addClass('green-edit');
                            }
                                
                            if(dataArr[0].available3 == 1){
                                $('div#newTime4').parent().addClass('green2');
                                $('div#newTime4').parent().unbind('click').bind('click', {time: dataArr[0].time3, index: 3}, _goNext);
                            }
                            if(dataArr[0].time3 == editTime){
                                $('div#newTime4').parent().addClass('green-edit');
                            }
                                
                            if(dataArr[0].available4 == 1){
                                $('div#newTime5').parent().addClass('green2');
                                $('div#newTime5').parent().unbind('click').bind('click', {time: dataArr[0].time4, index: 4}, _goNext);
                            }
                            if(dataArr[0].time4 == editTime){
                                $('div#newTime5').parent().addClass('green-edit');
                            }
                            
                            // animating the slide
                            // deleting old time values
                            // changing new time values' classes into current
                            // fixing the position of the element if needed
                            if (direction == -1)
                                $('ul#timeList').animate({"left": "+=325px"}, "slow", function(){
                                    $('li.currentTimeItem').remove();
                                    $('li.newTimeItem').addClass('currentTimeItem');
                                    $('li.currentTimeItem').removeClass('newTimeItem');
                                    $('ul#timeList').css("left", 0);
                                    priv.unLock();
                                });
                            else if (direction == 1)
                                $('ul#timeList').animate({"left": "-=325px"}, "slow", function(){
                                    $('li.currentTimeItem').remove();
                                    $('li.newTimeItem').addClass('currentTimeItem');
                                    $('li.currentTimeItem').removeClass('newTimeItem');
                                    $('ul#timeList').css("left", 0);
                                    priv.unLock();
                                });
                            $('div#newTime1').attr("id", "time1");
                            $('div#newTime2').attr("id", "time2");
                            $('div#newTime3').attr("id", "time3");
                            $('div#newTime4').attr("id", "time4");
                            $('div#newTime5').attr("id", "time5");
                        }                       
                        
                    }
                }
                else
                {
                    // remove green1, green2 classes and reassign for each time
                    $('ul.time li').removeClass('green1').removeClass('green2');
                    $('ul.time li').unbind('click');
                    
                    $('div#time1').html('&nbsp;');
                    $('div#time2').html('&nbsp;');
                    $('div#time3').html('&nbsp;');
                    $('div#time4').html('&nbsp;');
                    $('div#time5').html('&nbsp;');
                    $("div#timesForSelection").css({display : "none"});
                    $("div#NoTimesForSelection").css({display : "block"});
                    $("div#NoTimesForSelection").html(dataArr[0].times);
                }
                //*****************************************
                if(index == undefined){
                    var lower = dataArr[0].vanlowertimeh;
                    var now = Number(dataArr[0].time.split(':')[0]);
                    now = now < messages.MIN_HOUR_OF_DAYSCHEDULE_START ? now + 24 : now; 
                    var upper = dataArr[0].vanuppertimeh;
                        
                    var lowerHours = false;
                    var upperHours = false;
                    
                    for(var i= lower; i <= upper; i++)
                    {
                        if (i < now)
                        {
                            lowerHours = true;
                        }
                        else if (i > now)
                        {
                            upperHours = true;
                        }
                    }
                    // if any available lowerhours
                    // bind "earlier" link's bind event with _showEarlierTimes
                    // Don't set color or css using JS please change to link or no link
                    if(lowerHours){
                        if (!integration) {
                            $('a#linkearlier').css({
                                color : "#fff",
                                cursor: "pointer"
                            });
                        } else {
                            $('a#linkearlier').css({
                                color : "#fff", // integration will use same default css
                                cursor: "pointer"
                                });
                        }
                        var arrTime = dataArr[0].time0.split(':');
                        var totMinute = _getTime(arrTime[0],arrTime[1]);
                        $('a#linkearlier').unbind('click').bind('click', {time: (totMinute-60)}, _showEarlierTimes);
                    }else{  // no available lowerhours, unbind click event
                        $('a#linkearlier').css({
                            color : "#ccc",
                            cursor: "normal"
                        });
                        $('a#linkearlier').unbind('click');
                    }
                    // if any available upperhours
                    // bind "later" link's bind event with _showLaterTimes
                    if(upperHours){
                        if (!integration) {
                            $('a#linklater').css({
                                color : "#fff",
                                cursor: "pointer"
                            });
                        } else {
                            $('a#linklater').css({
                                color : "#fff", // integration will use same default css
                                cursor: "pointer"
                            });
                        }
                        var arrTime = dataArr[0].time4.split(':');
                        var totMinute = _getTime(arrTime[0],arrTime[1]);
                        $('a#linklater').unbind('click').bind('click', {time: totMinute}, showLaterTimes);
                    }else{  // no available upperhours, unbind click event
                        $('a#linklater').css({
                            color : "#ccc",
                            cursor: "normal"
                        });
                        $('a#linklater').unbind('click');
                    }
                }                
                
                //*****************************************
                
                /*$("div#times div.unavailable").unbind('click');
                $("div#times div.available").unbind('click').bind('click', function() {
                    $("div#times div.selected").removeClass("selected");
                    $(this).filter('div').addClass("selected");
                    
                    //---------------------------
                    personCount = $(this).find('option').filter(':selected').val();
        
                    var selectedTime = $("div#time1").html();
                    var time = 0;
                    if(selectedTime != null)
                    {
                        var selected = selectedTime.split(':');        
                        time = jQuery.makeBooking.getTime(selected[0], selected[1])
                    }
                    jQuery.makeBooking.checkAvailability(jQuery.jcalendar.getstringdate() , time, restaurantID);
                    //---------------------------
                });*/
                
                direction = 0;
            },
            error: function(data){
                priv.unLock();
            }
        });
        return available;
	};
	
	var _loadTimes = function(){
	    $('div#time1').html(dataArr[0].time0);
        $('div#time2').html(dataArr[0].time1);
        $('div#time3').html(dataArr[0].time2);    
        $('div#time4').html(dataArr[0].time3);        
        $('div#time5').html(dataArr[0].time4);
        
        if(dataArr[0].available0 == 1){
            $('div#time1').parent().addClass('green2');
            $('div#time1').parent().unbind('click').bind('click', {time: dataArr[0].time0, index: 0}, _goNext);
        }
        if(selectedDate == editDate && dataArr[0].time0 == editTime)
            $('div#time1').parent().addClass('green-edit');
        
        if(dataArr[0].available1 == 1){
            $('div#time2').parent().addClass('green2');
            $('div#time2').parent().unbind('click').bind('click', {time: dataArr[0].time1, index: 1}, _goNext);
        }
        if(selectedDate == editDate && dataArr[0].time1 == editTime)
            $('div#time2').parent().addClass('green-edit');
                
        if(dataArr[0].available2 == 1){
            $('div#time3').parent().addClass('green2');
            $('div#time3').parent().unbind('click').bind('click', {time: dataArr[0].time2, index: 2}, _goNext);
        }
        if(selectedDate == editDate && dataArr[0].time2 == editTime)
            $('div#time3').parent().addClass('green-edit');
               
        if(dataArr[0].available3 == 1){
            $('div#time4').parent().addClass('green2');
            $('div#time4').parent().unbind('click').bind('click', {time: dataArr[0].time3, index: 3}, _goNext);
        }
        if(selectedDate == editDate && dataArr[0].time3 == editTime)
            $('div#time4').parent().addClass('green-edit');
        
        if(dataArr[0].available4 == 1){
            $('div#time5').parent().addClass('green2');
            $('div#time5').parent().unbind('click').bind('click', {time: dataArr[0].time4, index: 4}, _goNext);
        }
        if(selectedDate == editDate && dataArr[0].time4 == editTime)
            $('div#time5').parent().addClass('green-edit');
	};
	
    var _goNext = function(event){
        var selectedTime = event.data.time;
        var time = 0;
        if(selectedTime != null)
        {
            var selected = selectedTime.split(':');        
            time = jQuery.makeBooking.getTime(selected[0], selected[1])
        }
        if(_checkAvailability(jQuery.jcalendar.getstringdate(), time, restaurantID, selectedTime, event.data.index)){
            var personCount = $('select.personCount').find('option').filter(':selected').val();
            var selectedTime = event.data.time;
            
            // find duration: each time may be in a different ds, so duration may differ
            var dur = 0;
            switch (event.data.index)
            {
                case 0:
                    dur = dataArr[0].duration0;
                    break;
                case 1:
                    dur = dataArr[0].duration1;
                    break;
                case 2:
                    dur = dataArr[0].duration2;
                    break;
                case 3:
                    dur = dataArr[0].duration3;
                    break;
                case 4:
                    dur = dataArr[0].duration4;
                    break;
            }
            $.ajax({
                type: "POST",
                url: messages.path_prefix + "/handlers/bookingStep1to2.ashx",
                data: "date="+jQuery.jcalendar.getstringdate()+"&person="+personCount+"&time="+selectedTime+"&schid="+dataArr[0].schid+"&duration="+ dur +"&rid="+restaurantID,
                success: function(result){
                    if(result.indexOf("goBackStepOne") != -1){
                        if (!integration) {
                            location.href = messages.path_prefix + '/restaurant/detail.aspx?rid='+restaurantID;
                        } else {
                            location.href = integration.AFF_PREFIX +
                                            '/restaurant/detail.aspx?rid=' +
                                            restaurantID;
                        }
                    }
                    else if(result.indexOf("goLogin") != -1) {
                        if (!integration) {
                            location.href = messages.path_prefix + '/my/login2.aspx';
                        } else {
                            location.href = integration.AFF_PREFIX +
                                            '/login2.htm';
                        }
                    }
                    else if(result.indexOf("success") != -1){
                        var locationToDirect = '/booking/overview.aspx';
                        if(result.split(";")[1] == 'POWER')
                            locationToDirect = '/booking/customer.aspx';
                        if (!integration) {
                            location.href = messages.path_prefix +
                                            locationToDirect;
                        } else {
                            location.href = integration.AFF_PREFIX +
                                            locationToDirect;
                        }
                    }
                },
                error: function(data){
                }
            });
        }
    };
    
	var _getTime = function(hour,min) {
	    var h = Number(hour);
	    h = h < messages.MIN_HOUR_OF_DAYSCHEDULE_START ? h + 24 : h; 
	    return (h*60) + (Number(min));
	};
    
    // initialize earlier and later link's click popup top and left values
    // also add mousedown method to page to unvisible times containers
    var _initPositions = function(){
        var link = $('div#earlier');
        var control = $('div#lowerTimes');
        var offset = link.offset();
        // set top,left values for 'div#lowerTimes'
        control.css({
			top: offset.top,
			left: offset.left
		}).css("position", "absolute");
		
		link = $('div#later');
		control = $('div#upperTimes');       
        offset = link.offset();  
        // set top,left values for 'div#upperTimes'      
        control.css({
			top: offset.top,
			left: offset.left
		}).css("position", "absolute");
		
		// page mousedown event
		$(document).mousedown(function(event){
		    // get the clicked target
		    var element = event.target;
		    
		    // if elemet is not inside lowerTimes or upperTimes
		    // then hide the times container
            if(element && element.parentNode){
                if(element.id != 'lowerTimes' && element.parentNode.id != 'lowerTimes' && 
                    element.id != 'upperTimes' && element.parentNode.id != 'upperTimes'){
                    $('div#lowerTimes').hide();
                    $('div#upperTimes').hide();
                }
            }
        });
    };
    
    // show earlier times
	var	_showEarlierTimes = function(event){
	    direction = -1;
        _checkAvailability(jQuery.jcalendar.getstringdate(), event.data.time, restaurantID);
	};
	
	// show later times
	var showLaterTimes = function(event){
	    direction = 1;
        _checkAvailability(jQuery.jcalendar.getstringdate(), event.data.time, restaurantID);
	};
        
	return {
	    setEditTime: function(date, time) {
		    _setEditTime(date, time);
		},
	    loadDayHours: function(date) {
		    _loadDayHours(date);
		},
		checkAvailability: function(date, time, rid){
		    _checkAvailability(date, time, rid);
		},
		getTime: function(hour,min) {
		    return _getTime(hour,min);
		},
		changeHomePageSearchLink: function() {
		    return _changeHomePageSearchLink();
		}
	};
}();

