//Customization of bufer time for DAN
var time_buffer_value = 0;

// Highlighting range days at calendar
var td_mouse_over = '';
var payment_request_id = 0;

if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(obj, start) {
         for (var i = (start || 0), j = this.length; i < j; i++) {
             if (this[i] === obj) { return i; }
         }
         return -1;
    }
}


// Check is this day booked or no
function is_this_day_booked(bk_type, td_class, i){ // is is not obligatory parameter

    if ( ( jWPDev('#calendar_booking'+bk_type+' .cal4date-' + td_class).hasClass('date_user_unavailable') ) || ( jWPDev('#calendar_booking'+bk_type+' .cal4date-' + td_class).hasClass('datepick-unselectable') )){ // If we find some unselect option so then make no selection at all in this range
                     document.body.style.cursor = 'default';return true;
    }

    //Check if in selection range are reserved days, if so then do not make selection
    if(typeof(date_approved[ bk_type ]) !== 'undefined')
        if(typeof(date_approved[ bk_type ][ td_class ]) !== 'undefined') { //alert(date_approved[ bk_type ][ td_class ][0][5]);
              for (var j=0; j < date_approved[ bk_type ][ td_class ].length ; j++) {
                    if ( ( date_approved[ bk_type ][ td_class ][j][3] == 0) &&  ( date_approved[ bk_type ][ td_class ][j][4] == 0) )  {document.body.style.cursor = 'default';return true;}
                    if ( ( (date_approved[ bk_type ][ td_class ][j][5] * 1) == 2 ) && (i!=0)) {document.body.style.cursor = 'default';return true;}
              }
        }

    if(typeof( date2approve[ bk_type ]) !== 'undefined')
        if(typeof( date2approve[ bk_type ][ td_class ]) !== 'undefined') {
              for ( j=0; j < date2approve[ bk_type ][ td_class ].length ; j++) {
                    if ( ( date2approve[ bk_type ][ td_class ][j][3] == 0) &&  ( date2approve[ bk_type ][ td_class ][j][4] == 0) )  {document.body.style.cursor = 'default';return true;}
                    if ( ( (date2approve[ bk_type ][ td_class ][j][5] * 1) == 2 ) && (i!=0)) {document.body.style.cursor = 'default';return true;}
              }
        }

    return false;
}



function hoverDayPro(value, date, bk_type) {

    if (date == null) return;

    var i=0 ;var j=0;
    var td_class;
    var td_overs = new Array();
    var td_element=0;

    if (is_select_range == 1) {
        if ( date == null) {return;}

        jWPDev('.datepick-days-cell-over').removeClass('datepick-days-cell-over');                          // clear all selections
        if (range_start_day != -1) {
            if (date.getDay() !=  range_start_day) {
                date.setDate(date.getDate() -  ( date.getDay() -  range_start_day )  );
            }
        }
        for( i=0; i < days_select_count ; i++) {
            td_class =  (date.getMonth()+1) + '-' + date.getDate() + '-' + date.getFullYear();

            if (   is_this_day_booked(bk_type, td_class, i)   ) return ;   // check if day is booked

            td_overs[td_overs.length] = '#calendar_booking'+bk_type+ ' .cal4date-' + td_class;              // add to array for later make selection by class
            date.setDate(date.getDate() + 1);                                                               // Add 1 day to current day
        }

        for ( i=0; i < td_overs.length ; i++) {                                                             // add class to all elements
            td_element = jWPDev( td_overs[i] );
            td_element.addClass('datepick-days-cell-over');
        }
        return ;
    }



    if ( wpdev_bk_is_dynamic_range_selection ) {
        if ( date == null) {return;}
        jWPDev('.datepick-days-cell-over').removeClass('datepick-days-cell-over');                          // clear all highlight days selections

        var inst = jWPDev.datepick._getInst(document.getElementById('calendar_booking'+bk_type));

        if ( (inst.dates.length == 0) || (inst.dates.length>1)  ) {  // Initial HIGHLIGHTING days in Dynamic range selection mode depends from start day and minimum numbers of days
            var selceted_first_day = new Date();
            selceted_first_day.setFullYear(date.getFullYear(),(date.getMonth()), (date.getDate() ) );
            if (range_start_day_dynamic != -1) {
                if (date.getDay() !=  range_start_day_dynamic) {
                    selceted_first_day.setDate(date.getDate() -  ( date.getDay() -  range_start_day_dynamic )  );
                }
            }i=0;
            while(    ( i < days_select_count_dynamic ) ) {
               i++;
               td_class =  (selceted_first_day.getMonth()+1) + '-' + selceted_first_day.getDate() + '-' + selceted_first_day.getFullYear();
               if (   is_this_day_booked(bk_type, td_class, (i-1))   ) return ;   // check if day is booked
               td_overs[td_overs.length] = '#calendar_booking'+bk_type+ ' .cal4date-' + td_class;              // add to array for later make selection by class
               selceted_first_day.setFullYear(selceted_first_day.getFullYear(),(selceted_first_day.getMonth()), (selceted_first_day.getDate() + 1) );
            }
        }

        // First click on days
        if (inst.dates.length == 1) {  // select start date in Dynamic range selection, after first days is selected
            var selceted_first_day = new Date();
            selceted_first_day.setFullYear(inst.dates[0].getFullYear(),(inst.dates[0].getMonth()), (inst.dates[0].getDate() ) ); //Get first Date

            var is_check = true;
            i=0;
            while(  (is_check ) || ( i < days_select_count_dynamic ) ) { // Untill rich MIN days number.
               i++;
               td_class =  (selceted_first_day.getMonth()+1) + '-' + selceted_first_day.getDate() + '-' + selceted_first_day.getFullYear();

                if (   is_this_day_booked(bk_type, td_class, (i-1))   ) return ;   // check if day is booked

                td_overs[td_overs.length] = '#calendar_booking'+bk_type+ ' .cal4date-' + td_class;              // add to array for later make selection by class


                var is_discreet_ok = true;
                if (bk_discreet_days_in_range_slections.length>0) {              // check if we set some discreet dates
                    is_discreet_ok = false;
                    for (var di = 0; di < bk_discreet_days_in_range_slections.length; di++) {   // check if current number of days inside of discreet one
                         if ( (  i % bk_discreet_days_in_range_slections[di] ) == 0 ) {
                             is_discreet_ok = true;
                             di = (bk_discreet_days_in_range_slections.length + 1);
                         }
                    }
                }

                if (   ( date.getMonth() == selceted_first_day.getMonth() )  &&
                       ( date.getDate() == selceted_first_day.getDate() )  &&
                       ( date.getFullYear() == selceted_first_day.getFullYear() )  && ( is_discreet_ok )  )
                {is_check =  false;}

                if ((selceted_first_day > date ) && ( i >= days_select_count_dynamic ) && ( i < bk_max_days_in_range_slections )  && (is_discreet_ok)  )   {
                    is_check =  false;
                }
                if ( i >= bk_max_days_in_range_slections ) is_check =  false;
                selceted_first_day.setFullYear(selceted_first_day.getFullYear(),(selceted_first_day.getMonth()), (selceted_first_day.getDate() + 1) );
            }
        }
        for ( i=0; i < td_overs.length ; i++) {                                                             // add class to all elements
            td_element = jWPDev( td_overs[i] );
            td_element.addClass('datepick-days-cell-over');
        }
        return ;
    }



}

// Check if this IE and get version of IE otherwise setversion of IE to 0
var isIE_4_bk = (navigator.appName=="Microsoft Internet Explorer");
var IEversion_4_bk = navigator.appVersion;
if(isIE_4_bk) { IEversion_4_bk = parseInt(IEversion_4_bk.substr(IEversion_4_bk.indexOf("MSIE")+4));
} else { IEversion_4_bk = 0; }


// Make range select
function updateAvailableTimeSlots(all_dates, bk_type) {

	var range_time_object = jWPDev('select[name="rangetime' + bk_type + '"] option:first');
	if (range_time_object == undefined)
		return; // WE DO NOT HAVE RANGE SELECTIONS AT THIS FORM SO JUST
	// RETURN

	if (jWPDev('select[name="rangetime' + bk_type + '"]').length == 0)
		return; // WE DO NOT HAVE RANGE SELECTIONS AT THIS FORM SO JUST
	// RETURN

	jWPDev('select[name="rangetime' + bk_type + '"] option:disabled')
			.removeAttr('disabled'); // Make active all times

	if (typeof (prepare_tooltip) == 'function') {
		setTimeout("prepare_tooltip(" + bk_type + ");", 1000);
	}

	var dates_being_reserved = all_dates.split(',');
	var unavailable_time_slots = [];
	
	for ( var u = 0; u < dates_being_reserved.length; u++) {
		var current_single_day_selections = dates_being_reserved[u].split('.');

		var reservedDate = (current_single_day_selections[1] * 1) + '-'
				+ (current_single_day_selections[0] * 1) + '-'
				+ (current_single_day_selections[2] * 1);

		var reserved_times = getReservedTimes(bk_type, reservedDate);

		var time_slots = get_unavailable_time_slots(bk_type, reservedDate, reserved_times);
		for ( var p = 0; p < time_slots.length; p++) {
			if (unavailable_time_slots.indexOf(time_slots[p]) == -1) {
				unavailable_time_slots.push(time_slots[p]);
			}
		}
	}

	for (j = 0; j < unavailable_time_slots.length; j++) {
		jQuery('select[name="rangetime' + bk_type + '"] option[value="' + unavailable_time_slots[j] + '"]').attr('disabled', 'disabled'); // Make
		jQuery('select[name="rangetime' + bk_type + '"] option[value="' + unavailable_time_slots[j] + '"]').removeAttr('selected');
	}
	
	if (IEversion_4_bk == 7) { // Emulate disabling option in selectboxes
		// for IE7 - its set grayed text options,
		// which is disabled
		set_selected_first_not_disabled_option_IE7(document
				.getElementsByName("rangetime" + bk_type)[0]);
		
		emulate_disabled_options_to_gray_IE7(document
				.getElementsByName("rangetime" + bk_type)[0]);
	}

}



// IE7 select box emulate functions for disabling select boxes:
if (IEversion_4_bk == 7) {

            window.onload = function() {
                    if (document.getElementsByTagName) {
                            var s = document.getElementsByTagName("select");

                            if (s.length > 0) {
                                    window.select_current = new Array();

                                    for (var i=0, select; select = s[i]; i++) {
                                            select.onfocus = function(){ window.select_current[this.id] = this.selectedIndex; }
                                            select.onchange = function(){ set_selected_previos_selected_option_IE7(this); }
                                            emulate_disabled_options_to_gray_IE7(select);
                                    }
                            }
                    }
            }

            function set_selected_previos_selected_option_IE7(e) {
                    if (e.options[e.selectedIndex].disabled) {
                            e.selectedIndex = window.select_current[e.id];
                    }
            }

            function set_selected_first_not_disabled_option_IE7(e) {

                    if (e.options[e.selectedIndex].disabled) {
                        for (var i=0, option; option = e.options[i]; i++) {
                                if (! option.disabled) {
                                    e.selectedIndex = i;
                                    return 0;
                                }
                        }
                    }
                    return 0;
            }

            function emulate_disabled_options_to_gray_IE7(e) {
                    for (var i=0, option; option = e.options[i]; i++) {

                            if (option.disabled) { option.style.color = "graytext";}
                            else {                 option.style.color = "menutext";}
                    }
            }
}

function getReservedTimes(bk_type, td_class) {
	
	var reserved_times = [];
	// Get dates and time from aproved dates
	if (typeof (date_approved[bk_type]) !== 'undefined') {
		if (typeof (date_approved[bk_type][td_class]) !== 'undefined') {
			for (i = 0; i < date_approved[bk_type][td_class].length; i++) {
				if ((date_approved[bk_type][td_class][0][3] != 0)
						|| (date_approved[bk_type][td_class][0][4] != 0)) {
					h = date_approved[bk_type][td_class][i][3];
					m = date_approved[bk_type][td_class][i][4];
					reserved_times[reserved_times.length] = [ h, m ];
				}
			}
		}
	}

	// Get dates and time from pending dates
	if (typeof (date2approve[bk_type]) !== 'undefined') {
		if (typeof (date2approve[bk_type][td_class]) !== 'undefined') {
			for (i = 0; i < date2approve[bk_type][td_class].length; i++) {
				if ((date2approve[bk_type][td_class][0][3] != 0)
						|| (date2approve[bk_type][td_class][0][4] != 0)) {
					h = date2approve[bk_type][td_class][i][3];
					m = date2approve[bk_type][td_class][i][4];
					reserved_times[reserved_times.length] = [ h, m ];
				}
			}
		}
	}
	return reserved_times;
}

// Times

function isDayFullByTime(bk_type, date) {
	var reserved_times = getReservedTimes(bk_type, date);
	var unavailTimesSlots = get_unavailable_time_slots(bk_type, date, reserved_times);
	
	var my_timerange_value = jWPDev('select[name="rangetime' + bk_type + '"] option');
	return unavailTimesSlots.length == my_timerange_value.length;
}

function get_unavailable_time_slots(bk_type, date, reserved_times) {
	
	reserved_times.sort(function (a, b) {
		var result = a[0] - b[0];
		return result == 0 ? a[1] - b[1] : result;
	});

	var time_slots = [];
	var my_timerange_value = jWPDev('select[name="rangetime' + bk_type + '"] option');

	for ( var j = 0; j < my_timerange_value.length; j++) {
		time_slots.push(my_timerange_value[j].value);
	}

	var unavailTimeSlots = [];
	for ( var y = 0; y < reserved_times.length; y += 2) {
		for ( var x = 0; x < time_slots.length; x++) {
			var time_slot = time_slots[x].split(' - ');
			var startTimeParts = time_slot[0].split(':');
			var endTimeParts = time_slot[1].split(':');

			var startingHour = parseInt(startTimeParts[0], 10);
			var startingMinute = parseInt(startTimeParts[1], 10);
			var endingHour = parseInt(endTimeParts[0], 10);
			var endingMinute = parseInt(endTimeParts[1], 10);
			
			var reservedTimeStartsBeforeAvailTime = (reserved_times[y][0] < startingHour)
					|| ((reserved_times[y][0] == startingHour) && (reserved_times[y][1] <= startingMinute));
			var reservedTimeEndsBeforeAvailTime = (reserved_times[y + 1][0] < startingHour)
					|| ((reserved_times[y + 1][0] == startingHour) && (reserved_times[y + 1][1] <= startingMinute));
			var reservedTimeStartsAfterAvailTime = (reserved_times[y][0] > endingHour)
					|| ((reserved_times[y][0] == endingHour) && (reserved_times[y][1] >= endingMinute));
			var reservedTimeOverlapsAvailTime = !((reservedTimeStartsBeforeAvailTime && reservedTimeEndsBeforeAvailTime) || reservedTimeStartsAfterAvailTime);
			if ((reservedTimeOverlapsAvailTime) && (unavailTimeSlots.indexOf(time_slots[x]) == -1)) {
				unavailTimeSlots.push(time_slots[x]);
			}
		}
	}
	
	if (getIsSaturdayBooking(date)) {
		if (unavailTimeSlots.indexOf("06:00 - 16:00") == -1) {
			unavailTimeSlots.push("06:00 - 16:00");
		}		
		if (unavailTimeSlots.indexOf("06:00 - 10:00") == -1) {
			unavailTimeSlots.push("06:00 - 10:00");
		}
		if (unavailTimeSlots.indexOf("06:00 - 14:00") == -1) {
			unavailTimeSlots.push("06:00 - 14:00");
		}
	}
	return unavailTimeSlots;	
}

function hoverDayTime(value, date, bk_type) {

    if (date == null) return;

    var i=0 ;var h ='' ;var m ='' ;var s='';
    var td_class;


   // Gathering information hint for tooltips ////////////////////////////////
   var tooltip_time = '';
   var times_array = [];
   td_class =  (date.getMonth()+1) + '-' + date.getDate() + '-' + date.getFullYear();

   // Get dates and time from aproved dates
   if(typeof(date_approved[ bk_type ]) !== 'undefined')
   if(typeof(date_approved[ bk_type ][ td_class ]) !== 'undefined') {
     if( ( date_approved[ bk_type ][ td_class ][0][3] != 0) ||  ( date_approved[ bk_type ][ td_class ][0][4] != 0) ) {
         for ( i=0; i< date_approved[ bk_type ][ td_class ].length; i++){
            h = date_approved[ bk_type ][ td_class ][i][3];if (h < 10) h = '0' + h;if (h == 0) h = '00';
            m = date_approved[ bk_type ][ td_class ][i][4];if (m < 10) m = '0' + m;if (m == 0) m = '00';
            s = date_approved[ bk_type ][ td_class ][i][5];if (s == 2) s = '02';
            times_array[ times_array.length ] = [h,m,s];
         }
     }
   }

   // Get dates and time from pending dates
   if(typeof( date2approve[ bk_type ]) !== 'undefined')
   if(typeof( date2approve[ bk_type ][ td_class ]) !== 'undefined')
     if( ( date2approve[ bk_type ][ td_class ][0][3] != 0) ||  ( date2approve[ bk_type ][ td_class ][0][4] != 0) ) //check for time here
       {for ( i=0; i< date2approve[ bk_type ][ td_class ].length; i++){
            h = date2approve[ bk_type ][ td_class ][i][3];if (h < 10) h = '0' + h;if (h == 0) h = '00';
            m = date2approve[ bk_type ][ td_class ][i][4];if (m < 10) m = '0' + m;if (m == 0) m = '00';
            s = date2approve[ bk_type ][ td_class ][i][5];if (s == 2) s = '02';
            times_array[ times_array.length ] = [h,m,s];
          }
       }

//alert(times_array);
   // Time availability
   if (typeof( hover_day_check_global_time_availability ) == 'function') {times_array = hover_day_check_global_time_availability( date, bk_type ,times_array);}

    times_array.sort();
// if (times_array.length>0) alert(times_array);
    for ( i=0; i< times_array.length; i++){  // s = 2 - end time,   s = 1 - start time
       s = parseInt( times_array[i][2] );
       if (s == 2) {if (tooltip_time == '') tooltip_time = '&nbsp;&nbsp;&nbsp;&nbsp;...&nbsp;&nbsp;&nbsp; - ';}      // End time and before was no dates so its start from start of date
       if ( (tooltip_time == '') && (times_array[i][0]=='00') && (times_array[i][1]=='00') )
           tooltip_time = '&nbsp;&nbsp;&nbsp;&nbsp;...&nbsp;&nbsp;&nbsp;';  //start date at the midnight
       else if ( (i == ( times_array.length-1)) && (times_array[i][0]=='23') && (times_array[i][1]=='59') )
        tooltip_time += ' &nbsp;&nbsp;&nbsp;&nbsp;... ';
       else {
        var hours_show = times_array[i][0];
        var hours_show_sufix = '';
        if (is_am_pm_inside_time) {
            if (hours_show>=12) {
                hours_show = hours_show - 12;
                if (hours_show==0) hours_show = 12;
                hours_show_sufix = ' pm';
            } else {
                hours_show_sufix = ' am';
            }
        }
//Customization of bufer time for DAN
if (times_array[i][2] == '02' ) {
    times_array[i][1] = ( times_array[i][1]*1)  + time_buffer_value ;
    if (times_array[i][1] > 59 ) {
        times_array[i][1] = times_array[i][1] - 60;
        hours_show = (hours_show*1) + 1;
    }
    if (times_array[i][1] < 10 ) times_array[i][1] = '0'+times_array[i][1];
}

        tooltip_time += hours_show + ':' + times_array[i][1] + hours_show_sufix;
       }


       if (s == 1) {
    	   tooltip_time += ' - ';
    	   if (i == ( times_array.length-1)) 
    		   tooltip_time += ' &nbsp;&nbsp;&nbsp;&nbsp;... ';
       }
       if (s == 2) {
           tooltip_time += '<br />';
       } /**/
    }

    // jWPDev( '#calendar_booking'+bk_type+' td.cal4date-'+td_class )  // TODO: continue working here, check unshow times at full booked days
    if ( tooltip_time.indexOf("undefined") > -1 ) {tooltip_time = '';}
    if(typeof( getDayPrice4Show ) == 'function') {tooltip_time = getDayPrice4Show(bk_type, tooltip_time, td_class);}  
    if(typeof( getDayAvailability4Show ) == 'function') {tooltip_time = getDayAvailability4Show(bk_type, tooltip_time, td_class);}  


    
    jWPDev( '#demotip'+bk_type ).html( tooltip_time );
    
    ////////////////////////////////////////////////////////////////////////

}

function isTimeTodayGone(myTime, sort_date_array){
    if (parseInt(sort_date_array[0][0]) < parseInt(wpdev_bk_today[0])) return true;
    if (( parseInt(sort_date_array[0][0]) == parseInt(wpdev_bk_today[0])  ) && ( parseInt(sort_date_array[0][1]) < parseInt(wpdev_bk_today[1])  ) )
        return true;
    if (( parseInt(sort_date_array[0][0]) == parseInt(wpdev_bk_today[0])  ) && ( parseInt(sort_date_array[0][1]) == parseInt(wpdev_bk_today[1])  ) && ( parseInt(sort_date_array[0][2]) < parseInt(wpdev_bk_today[2])  ) )
        return true;
    if (( parseInt(sort_date_array[0][0]) == parseInt(wpdev_bk_today[0])  ) &&
        ( parseInt(sort_date_array[0][1]) == parseInt(wpdev_bk_today[1])  ) &&
        ( parseInt(sort_date_array[0][2]) == parseInt(wpdev_bk_today[2])  )) {
        var mytime_value = myTime.split(":");
        mytime_value = mytime_value[0]*60 + parseInt(mytime_value[1]);

        var current_time_value = wpdev_bk_today[3]*60 + parseInt(wpdev_bk_today[4]);

        if ( current_time_value  > mytime_value ) return true;

    }
    return false;
}


var start_time_checking_index;

function checkTimeInside( mytime, is_start_time, bk_type ) {

        // Check time availability for global filters
        if(typeof( check_entered_time_to_global_availability_time ) == 'function') {if (! check_entered_time_to_global_availability_time(mytime, is_start_time, bk_type) ) return false;}

        var my_dates_str = document.getElementById('date_booking'+ bk_type ).value;                 // GET DATES From TEXTAREA

        return checkTimeInsideProcess( mytime, is_start_time, bk_type, my_dates_str );

}

function checkRecurentTimeInside( my_rangetime,  bk_type ) {

   var valid_time = true;
   var my_dates_str = document.getElementById('date_booking'+ bk_type ).value;                 // GET DATES From TEXTAREA
    // recurent time check for all days in loop

    var date_array = my_dates_str.split(", ");
    if (date_array.length == 2) { // This recheck is need for editing booking, with single day
        if (date_array[0]==date_array[1]) {
            date_array = [ date_array[0] ];
        }
    }
    var temp_date_str = '';
    for (var i=0; i< date_array.length; i++) {  // Get SORTED selected days array
            temp_date_str = date_array[i];
            if ( checkTimeInsideProcess( my_rangetime[0], true, bk_type, temp_date_str ) == false )   valid_time = false;
            if ( checkTimeInsideProcess( my_rangetime[1], false, bk_type, temp_date_str ) == false )  valid_time = false;

    }

    return valid_time;
}




// Function check start and end time at selected days
function checkTimeInsideProcess( mytime, is_start_time, bk_type, my_dates_str ) {


    var date_array = my_dates_str.split(", ");
    if (date_array.length == 2) { // This recheck is need for editing booking, with single day
        if (date_array[0]==date_array[1]) {
            date_array = [ date_array[0] ];
        }
    }

    var temp_elemnt;var td_class;var sort_date_array = [];var work_date_array = [];var times_array = [];var is_check_for_time;

    for (var i=0; i< date_array.length; i++) {  // Get SORTED selected days array
        temp_elemnt = date_array[i].split(".");
        sort_date_array[i] = [ temp_elemnt[2], temp_elemnt[1] + '', temp_elemnt[0] + '' ]; // [2009,7,1],...
    }
    sort_date_array.sort();                                                                   // SORT    D a t e s
    for (i=0; i< sort_date_array.length; i++) {                                  // trnasform to integers
        sort_date_array[i] = [ parseInt(sort_date_array[i][0]*1), parseInt(sort_date_array[i][1]*1), parseInt(sort_date_array[i][2]*1) ]; // [2009,7,1],...
    }

    if (is_start_time) {

        if ( isTimeTodayGone(mytime, sort_date_array) )  return false;
    }
    //  CHECK FOR BOOKING INSIDE OF     S E L E C T E D    DAY RANGE AND FOR TOTALLY BOOKED DAYS AT THE START AND END OF RANGE
    work_date_array =  sort_date_array;
    for (var j=0; j< work_date_array.length; j++) {
        td_class =  work_date_array[j][1] + '-' + work_date_array[j][2] + '-' + work_date_array[j][0];

        if ( (j==0) || (j == (work_date_array.length-1)) ) is_check_for_time = true;         // Check for time only start and end time
        else                                               is_check_for_time = false;

        // Get dates and time from pending dates
        if(typeof( date2approve[ bk_type ]) !== 'undefined') {
          if ( (typeof( date2approve[ bk_type ][ td_class ]) !== 'undefined') ) {
             if (! is_check_for_time) {return false;} // its mean that this date is booked inside of range selected dates
             if( ( date2approve[ bk_type ][ td_class ][0][3] != 0) ||  ( date2approve[ bk_type ][ td_class ][0][4] != 0) ) {
                 // Evrything good - some time is booked check later
             } else {return false;} // its mean that this date tottally booked
          }
        }

        // Get dates and time from pending dates
        if(typeof( date_approved[ bk_type ]) !== 'undefined') {
          if ( (typeof( date_approved[ bk_type ][ td_class ]) !== 'undefined') ) {
             if (! is_check_for_time) {return false;} // its mean that this date is booked inside of range selected dates
             if( ( date_approved[ bk_type ][ td_class ][0][3] != 0) ||  ( date_approved[ bk_type ][ td_class ][0][4] != 0) ) {
                 // Evrything good - some time is booked check later
             } else {return false;} // its mean that this date tottally booked
          }
        }
    }  ///////////////////////////////////////////////////////////////////////////////////////////////////////


     // Check    START   OR    END   time for time no in correct fee range
     if (is_start_time ) work_date_array =  sort_date_array[0] ;
     else                work_date_array =  sort_date_array[sort_date_array.length-1] ;

     td_class =  work_date_array[1] + '-' + work_date_array[2] + '-' + work_date_array[0];

        // Get dates and time from pending dates
        if(typeof( date2approve[ bk_type ]) !== 'undefined')
          if(typeof( date2approve[ bk_type ][ td_class ]) !== 'undefined')
              for ( i=0; i< date2approve[ bk_type ][ td_class ].length; i++){
                h = date2approve[ bk_type ][ td_class ][i][3];if (h < 10) h = '0' + h;if (h == 0) h = '00';
                m = date2approve[ bk_type ][ td_class ][i][4];if (m < 10) m = '0' + m;if (m == 0) m = '00';
                s = date2approve[ bk_type ][ td_class ][i][5];

//Customization of bufer time for DAN
if (s == '02') {
    m = ( m*1 )  + time_buffer_value ;
    if (m > 59 ) {
        m = m - 60;
        h = (h*1) + 1;
    }
    if (m < 10 ) m = '0'+m;
}

                times_array[ times_array.length ] = [h,m,s];
              }

        // Get dates and time from pending dates
        if(typeof( date_approved[ bk_type ]) !== 'undefined')
          if(typeof( date_approved[ bk_type ][ td_class ]) !== 'undefined')
              for ( i=0; i< date_approved[ bk_type ][ td_class ].length; i++){
                h = date_approved[ bk_type ][ td_class ][i][3];if (h < 10) h = '0' + h;if (h == 0) h = '00';
                m = date_approved[ bk_type ][ td_class ][i][4];if (m < 10) m = '0' + m;if (m == 0) m = '00';
                s = date_approved[ bk_type ][ td_class ][i][5];

//Customization of bufer time for DAN
if (s == '02') {
    m = ( m*1 )  + time_buffer_value ;
    if (m > 59 ) {
        m = m - 60;
        h = (h*1) + 1;
    }
    if (m < 10 ) m = '0'+m;
}


                times_array[ times_array.length ] = [h,m,s];
              }


        times_array.sort();                     // SORT TIMES

        var times_in_day = [];                  // array with all times
        var times_in_day_interval_marks = [];   // array with time interval marks 1- stsrt time 2 - end time


        for ( i=0; i< times_array.length; i++){s = times_array[i][2];         // s = 2 - end time,   s = 1 - start time
           // Start close interval
           if ( (s == 2) &&  (i == 0) ) {times_in_day[ times_in_day.length ] = 0;times_in_day_interval_marks[times_in_day_interval_marks.length]=1;}
           // Normal
           times_in_day[ times_in_day.length ] = times_array[i][0] * 60 + parseInt(times_array[i][1]);
           times_in_day_interval_marks[times_in_day_interval_marks.length]=s;
           // End close interval
           if ( (s == 1) &&  (i == (times_array.length-1)) ) {times_in_day[ times_in_day.length ] = (24*60);times_in_day_interval_marks[times_in_day_interval_marks.length]=2;}
        }

        // Get time from entered time
        var mytime_value = mytime.split(":");
        mytime_value = mytime_value[0]*60 + parseInt(mytime_value[1]);

//alert('My time:'+ mytime_value + '  List of times: '+ times_in_day + '  Saved indexes: ' + start_time_checking_index + ' Days: ' + sort_date_array ) ;

        var start_i = 0;
        if (start_time_checking_index != undefined)
            if (start_time_checking_index[0] != undefined)
                if ( (! is_start_time) && (sort_date_array.length == 1) ) {start_i = start_time_checking_index[0]; /*start_i++;*/}
        i=start_i;

        // Main checking inside a day
        for ( i=start_i; i< times_in_day.length; i++){
            times_in_day[i] = parseInt(times_in_day[i]);
            mytime_value = parseInt(mytime_value);
            if (is_start_time ) {
                if ( mytime_value > times_in_day[i] ){
                    // Its Ok, lets Loop to next item
                } else if ( mytime_value == times_in_day[i] ) {
                    if (times_in_day_interval_marks[i] == 1 ) {return false;     //start time is begin with some other interval
                    } else {
                        if ( (i+1) <= (times_in_day.length-1) ) {
                            if ( times_in_day[i+1] <= mytime_value ) return false;  //start time  is begin with next elemnt interval
                            else  {                                                 // start time from end of some other
                                if (sort_date_array.length > 1)
                                    if ( (i+1) <= (times_in_day.length-1) ) return false;   // Its mean that we make end booking at some other day then this and we have some booking time at this day after start booking  - its wrong
                                start_time_checking_index = [i, td_class,mytime_value];
                                return true;
                            }
                        }
                        if (sort_date_array.length > 1)
                            if ( (i+1) <= (times_in_day.length-1) ) return false;   // Its mean that we make end booking at some other day then this and we have some booking time at this day after start booking  - its wrong
                        start_time_checking_index = [i, td_class,mytime_value];
                        return true;                                            // start time from end of some other
                    }
                } else if ( mytime_value < times_in_day[i] ) {
                    if (times_in_day_interval_marks[i] == 2 ){return false;     // start time inside of some interval
                    } else {
                        if (sort_date_array.length > 1)
                            if ( (i+1) <= (times_in_day.length-1) ) return false;   // Its mean that we make end booking at some other day then this and we have some booking time at this day after start booking  - its wrong
                        start_time_checking_index = [i, td_class,mytime_value];
                        return true;
                    }
                }
            } else {
                if (sort_date_array.length == 1) {

                   if (start_time_checking_index !=undefined)
                       if (start_time_checking_index[2]!=undefined)

                            if ( ( start_time_checking_index[2] == times_in_day[i] ) && ( times_in_day_interval_marks[i] == 2) ) {    // Good, because start time = end of some other interval and we need to get next interval for current end time.
                            } else if ( times_in_day[i] < mytime_value ) return false;                 // some interval begins before end of curent "end time"
                            else {
                                if (start_time_checking_index[2]>= mytime_value) return false;  // we are select only one day and end time is earlythe starttime its wrong
                                return true;                                                    // if we selected only one day so evrything is fine and end time no inside some other intervals
                            }
                } else {
                    if ( times_in_day[i] < mytime_value ) return false;                 // Some other interval start before we make end time in the booking at the end day selection
                    else                                  return true;
                }

            }
        }

        if (is_start_time )  start_time_checking_index = [i, td_class,mytime_value];
        else {
           if (start_time_checking_index !=undefined)
               if (start_time_checking_index[2]!=undefined)
                    if ( (sort_date_array.length == 1) && (start_time_checking_index[2]>= mytime_value) ) return false;  // we are select only one day and end time is earlythe starttime its wrong
        }
        return true;
}





function save_this_booking_cost(booking_id, cost){

    if (cost!='') {


            var ajax_bk_message = 'Updating...';
            
            document.getElementById('ajax_working').innerHTML =
            '<div class="info_message ajax_message" id="ajax_message">\n\
                <div style="float:left;">'+ajax_bk_message+'</div> \n\
                <div  style="float:left;width:80px;margin-top:-3px;">\n\
                       <img src="'+wpdev_bk_plugin_url+'/img/ajax-loader.gif">\n\
                </div>\n\
            </div>';

            var wpdev_ajax_path = wpdev_bk_plugin_url+'/' + wpdev_bk_plugin_filename ;
            var ajax_type_action='SAVE_BK_COST';

            jWPDev.ajax({                                           // Start Ajax Sending
                url: wpdev_ajax_path,
                type:'POST',
                success: function (data, textStatus){if( textStatus == 'success')   jWPDev('#ajax_respond' ).html( data ) ;},
                error:function (XMLHttpRequest, textStatus, errorThrown){window.status = 'Ajax sending Error status:'+ textStatus;alert(XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText);if (XMLHttpRequest.status == 500) {alert('Please check at this page according this error:' + ' http://onlinebookingcalendar.com/faq/#faq-13');}},
                // beforeSend: someFunction,
                data:{
                    ajax_action : ajax_type_action,
                    booking_id : booking_id,
                    cost : cost
                }
            });
            return false;
        }
        return true;

}

function sendPaymentRequestByEmail(payment_request_id , request_reason, wpdev_active_locale) {
 
            var ajax_bk_message = 'Sending...';

            document.getElementById('ajax_working').innerHTML =
            '<div class="info_message ajax_message" id="ajax_message">\n\
                <div style="float:left;">'+ajax_bk_message+'</div> \n\
                <div  style="float:left;width:80px;margin-top:-3px;">\n\
                       <img src="'+wpdev_bk_plugin_url+'/img/ajax-loader.gif">\n\
                </div>\n\
            </div>';

            var wpdev_ajax_path = wpdev_bk_plugin_url+'/' + wpdev_bk_plugin_filename ;
            var ajax_type_action='SEND_PAYMENT_REQUEST';

            jWPDev.ajax({                                           // Start Ajax Sending
                url: wpdev_ajax_path,
                type:'POST',
                success: function (data, textStatus){if( textStatus == 'success')   jWPDev('#ajax_respond' ).html( data ) ;},
                error:function (XMLHttpRequest, textStatus, errorThrown){window.status = 'Ajax sending Error status:'+ textStatus;alert(XMLHttpRequest.status + ' ' + XMLHttpRequest.statusText);if (XMLHttpRequest.status == 500) {alert('Please check at this page according this error:' + ' http://onlinebookingcalendar.com/faq/#faq-13');}},
                // beforeSend: someFunction,
                data:{
                    ajax_action : ajax_type_action,
                    booking_id : payment_request_id,
                    reason : request_reason,
                    wpdev_active_locale:wpdev_active_locale
                }
            });
            return false;


}
