/******************************************************************************/
/******************************************************************************/

;(function($,doc,win) 
{
	"use strict";
	
	var CBSPlugin=function(object,option)
	{
		/**********************************************************************/
		
		var $self=this;
		var $this=$(object);
		var $option=option;
		
		var prevWidth=0;
		
		/**********************************************************************/

		this.build=function() 
		{
			$this.find('.cbs-form-field').bind('click',function()
			{
				$(this).children(':input').focus();
			});
			
			$self.prepare();
		};
		
		/**********************************************************************/
		/**********************************************************************/
		
		this.prepare=function()
		{
			$self.setWidthClass();
			
			$self.toogleServiceHeader(0);
			
			$this.find('.cbs-vehicle-list>li').live('click',function(e) 
			{
				e.preventDefault();
				
				$self.setButtonSelected(this,null,false,false);
				
				var vehicleId=$self.getSelectedVehicleList();
				
				$self.createPackage(vehicleId);
			});	
			
			$this.find('.cbs-package-list>li>.cbs-button-box>.cbs-button').live('click',function(e) 
			{
				e.preventDefault();
				
				$self.setButtonSelected($(this).parents('li:first'),null,true,false);
								
				var vehicleId=$self.getSelectedVehicleList();
				var packageId=$self.getSelectedPackageList();
				
				$self.toogleServiceHeader(packageId);
				
				$self.createService(vehicleId,packageId);
				$self.createCalendar();
			});	
			
			$this.find('.cbs-service-list>li>.cbs-button-box>.cbs-button').live('click',function(e) 
			{
				e.preventDefault();
				
				$self.setButtonSelected($(this).parents('li:first'),null,true,true);
				
				var i=0;
				var serviceId=[];
				
				$(this).parents('.cbs-service-list').children('li.cbs-state-selected').each(function()
				{			
					serviceId.push($self.getValueFromClass($(this),'cbs-service-id-'));
				});
				
				var vehicleId=$self.getSelectedVehicleList();
				var packageId=$self.getSelectedPackageList();	
				
				$self.createCost(vehicleId,packageId,serviceId);
				$self.createCalendar();
			});	
			
			$this.find('.cbs-button-service-more').live('click',function(e) 
			{
				e.preventDefault();
				$(this).prev('ul').toggleClass('cbs-state-to-hidden');
				$(this).children('span').toggleClass('cbs-state-hidden');
			});
			
			$this.find('.cbs-more-link').live('click',function(e) 
			{
				e.preventDefault();
				$(this).next().toggle();
				$(this).children('span').toggleClass('cbs-state-hidden');
			});
			
			$this.find('table.cbs-calendar .cbs-calendar-data a:not(.cbs-calendar-data-button-more)').live('click',function(e) 
			{
				e.preventDefault();
				$self.setButtonSelected($(this).parent('li'),$(this).parents('.cbs-calendar-data').find('li'),true,false);
				
				var selected=$this.find('table.cbs-calendar .cbs-calendar-data li.cbs-state-selected');
				
				if(selected.length===1)
				{
					var index=selected.parents('td:first').index();
					var date=$this.find('.cbs-calendar-subheader th:eq('+index+')').attr('data-date-full');

					$this.find('.cbs-booking-summary-date h5 span:first').html(date);
					$this.find('.cbs-booking-summary-time h5 span:first').html(selected.text());
					
					$this.find('.cbs-booking-summary-date h5 span+span').css({'display':'none'});
					$this.find('.cbs-booking-summary-time h5 span+span').css({'display':'none'});
				}
				else
				{
					$this.find('.cbs-booking-summary-date h5 span:first').html('');
					$this.find('.cbs-booking-summary-time h5 span:first').html('');	
					
					$this.find('.cbs-booking-summary-date h5 span+span').css({'display':'inline'});
					$this.find('.cbs-booking-summary-time h5 span+span').css({'display':'inline'});
				}
			});	
			
			$this.find('table.cbs-calendar .cbs-calendar-data a.cbs-calendar-data-button-more').live('click',function(e) 
			{
				e.preventDefault();
				$(this).parent('li').parent('ul').toggleClass('cbs-state-to-hidden');
				$(this).children('span').toggleClass('cbs-state-hidden');
			});
		
			$this.children('form').bind('submit',function()
			{
				var data={};
				
				data.action='cbs_create_booking';
				
				data.locationId=$option.locationId;
				
				data.dateId=$self.getSelectedDateTime();
				data.vehicleId=$self.getSelectedVehicleList();
				data.packageId=$self.getSelectedPackageList();
				data.serviceId=$self.getSelectedServiceList();
				
				data.clientFirstName=$('.cbs-main-list-item-booking input[name="client_first_name"]').val();
				data.clientSecondName=$('.cbs-main-list-item-booking input[name="client_second_name"]').val();
				data.clientVehicle=$('.cbs-main-list-item-booking input[name="client_vehicle"]').val();
				data.clientEmailAddress=$('.cbs-main-list-item-booking input[name="client_email_address"]').val();
				data.clientPhoneNumber=$('.cbs-main-list-item-booking input[name="client_phone_number"]').val();
				data.clientMessage=$('.cbs-main-list-item-booking textarea[name="client_message"]').val();
				
				$self.post(data,$self.createBookingResponse);
				
				return(false);
			});
			
			$this.find('.cbs-calendar-header-arrow-left').live('click',function(e)
			{
				$self.moveCalendar(e,-1);
			});
			
			$this.find('.cbs-calendar-header-arrow-right').live('click',function(e)
			{
				$self.moveCalendar(e,1);
			});
		};
		
		/**********************************************************************/
		
		this.toogleServiceHeader=function(packageId)
		{			
			if($this.hasClass('cbs-location-content-type-3'))
			{
				var header=$this.find('.cbs-main-list-item-service-list .cbs-main-list-item-section-header-header');
				var subheader=$this.find('.cbs-main-list-item-service-list .cbs-main-list-item-section-header-subheader');
					
				var element=[header.find('span:eq(0)'),header.find('span:eq(1)'),subheader.find('span:eq(0)'),subheader.find('span:eq(1)')];
					
				if(packageId===0)
				{
					element[0].removeClass('cbs-state-hidden');
					element[2].removeClass('cbs-state-hidden');
					
					element[1].addClass('cbs-state-hidden');
					element[3].addClass('cbs-state-hidden');
				}
				else
				{
					element[1].removeClass('cbs-state-hidden');
					element[3].removeClass('cbs-state-hidden');
					
					element[0].addClass('cbs-state-hidden');
					element[2].addClass('cbs-state-hidden');				
				}
			}	
		};
		
		/**********************************************************************/
		
		this.createBookingResponse=function(response)
		{
			var notice=$('.cbs-notice');
			var noticeIcon=notice.children('.cbs-notice-icon');
			
			notice.removeClass('cbs-notice-error cbs-notice-success');
			noticeIcon.removeClass('cbs-meta-icon-error cbs-meta-icon-success');
			
			if(response.error===0) 
			{	
				notice.addClass('cbs-notice-success');
				noticeIcon.addClass('cbs-meta-icon-success');
			}
			else 
			{	
				notice.addClass('cbs-notice-error');
				noticeIcon.addClass('cbs-meta-icon-error');
			}

			notice.find('.cbs-notice-text').html(response.notice.text);
			notice.find('.cbs-notice-header').html(response.notice.header);
			
			notice.css('display','block');
			
			if((parseInt(response.error)===0) && (parseInt(response.reset)===1)) 
			{
				$this.find('.cbs-main-list-item-booking').find('input[type=text],textarea').val('');
				$this.find('.cbs-vehicle-list>li:first-child').trigger('click');
				$self.createCalendar(0);
				$self.toogleServiceHeader();
			}
			
			if(typeof(response.form)!=='undefined')
			{
				$('#cbs-paypal-form').remove();
				$('body').append(response.form);
				
				$this.find('.cbs-paypal-link').on('click',function(e)
				{
					e.preventDefault();
					
					$self.selectPayment(response.bookingId,'paypal');
					$('#cbs-paypal-form').submit();
				});
			}
			
			$.scrollTo($this);
		};
		
		/**********************************************************************/
		
		this.selectPayment=function(bookingId,paymentType)
		{
			var data={};
				
			data.action='cbs_select_payment';
				
			data.bookingId=bookingId;
			data.paymentType=paymentType;

			$self.post(data,$self.selectPaymentResponse);
				
			return(false);			
		};
		
		/**********************************************************************/
		
		this.selectPaymentResponse=function()
		{
			
		};
		
		/**********************************************************************/
		
		this.moveCalendar=function(event,step)
		{
			event.preventDefault();
			
			var calendarBox=$this.find('.cbs-calendar-table-wrapper');
			var calendar=calendarBox.find('.cbs-calendar');
				
			var columnActive=Math.abs($('th.cbs-active').index());
			
			if(step===1)
			{
				if($self.isVisibleColumn('last'))
				{
					$self.createCalendar(1);
					return;
				}
			}
			else
			{
				if($self.isVisibleColumn('first'))
				{
					$self.createCalendar(-1);
					return;
				}
			}
					
			if((columnActive===6) && (step===1)) return;
			if((columnActive===0) && (step===-1)) return;
				
			columnActive+=step;
			
			calendar.find('th').removeClass('cbs-active');
			calendar.find('th:eq('+columnActive+')').addClass('cbs-active');
			
			$self.hideCalendarColumn();
		};
		
		/**********************************************************************/
		
		this.hideCalendarColumn=function()
		{
			var j=0,tag=['th','td'];
			var calendarBox=$this.find('.cbs-calendar-table-wrapper');
			var calendar=calendarBox.find('.cbs-calendar');
			
			var columnActive=calendar.find('th.cbs-active').index();
			var columnCount=parseInt($this.find('input[name="cbs-calendar-column-count"]').val());
			
			$(tag).each(function(i)
			{
				calendar.find(tag[i]).css('display','none');
				
				for(j=columnActive;j<(columnActive+columnCount);j++)
					calendar.find(tag[i]+':eq('+j+')').css('display','table-cell');
			});
			
			$self.manageCalendarHeader();
		};
		
		/**********************************************************************/
		
		this.isVisibleColumn=function(number)
		{
			var calendarBox=$this.find('.cbs-calendar-table-wrapper');
			var calendar=calendarBox.find('.cbs-calendar');
			
			if((calendar.find('th:first').css('display')!=='none') && (number==='first')) return(true);
			if((calendar.find('th:last').css('display')!=='none') && (number==='last')) return(true);
			
			return(false);
		};
		
		/**********************************************************************/
		/**********************************************************************/
		
		this.getSelectedVehicleList=function()
		{
			var list=$this.find('.cbs-vehicle-list>li.cbs-state-selected');
			
			if(list.length!==1) return(0);
			
			return($self.getValueFromClass(list[0],'cbs-vehicle-id-'));
		};
		
		/**********************************************************************/
		
		this.getSelectedPackageList=function()
		{
			var list=$this.find('.cbs-package-list>li.cbs-state-selected');
			
			if(list.length!==1) return(0);
			
			return($self.getValueFromClass(list[0],'cbs-package-id-'));
		};
		
		/**********************************************************************/
		
		this.getSelectedServiceList=function()
		{
			var data=[];
			
			var list=$this.find('.cbs-service-list>li.cbs-state-selected');
			
			list.each(function()
			{
				data.push($self.getValueFromClass($(this),'cbs-service-id-'));
			});
			
			return(data);
		};	
		
		/**********************************************************************/
		
		this.getSelectedDateTime=function()
		{
			var list=$this.find('.cbs-date-list>li.cbs-state-selected');
			
			if(list.length!==1) return('');
			
			return($self.getValueFromClass(list[0],'cbs-date-id-'));			
		};

		/**********************************************************************/
		/**********************************************************************/
		
		this.createPackage=function(vehicleId)
		{
			var data={};
			
			data.action='cbs_create_package';
			
			data.vehicleId=vehicleId;
			data.locationId=$option.locationId;
			
			$self.post(data,function(response)
			{
				$self.createPackageResponse(response);
			});
		};
		
		/**********************************************************************/
		
		this.createPackageResponse=function(response)
		{
			var serviceListItem=$this.find('.cbs-main-list-item-service-list');
			var packageListItem=$this.find('.cbs-main-list-item-package-list');
			
			serviceListItem.removeClass('cbs-state-disable');
			if(!response.serviceCount) serviceListItem.addClass('cbs-state-disable');
			
			packageListItem.removeClass('cbs-state-disable');
			if(!response.packageCount) packageListItem.addClass('cbs-state-disable');
			
			packageListItem.children('.cbs-main-list-item-section-content').html(response.package);
			serviceListItem.children('.cbs-main-list-item-section-content').html(response.service);
		};
		
		/**********************************************************************/
		/**********************************************************************/
		
		this.createCalendar=function(step)
		{
			var data={};
			
			data.action='cbs_create_calendar';
			
			data.step=step;
			data.locationId=$option.locationId;

			data.packageId=$self.getSelectedPackageList();
			data.serviceId=$self.getSelectedServiceList();
			data.vehicleId=$self.getSelectedVehicleList();
			
			data.startDate=$self.getValueFromClass($this.find('.cbs-calendar .cbs-calendar-subheader th.cbs-active'),'cbs-date-id-');
			
			$self.post(data,function(response)
			{
				$self.createCalendarResponse(response);
			});					
		};
		
		/**********************************************************************/
		
		this.createCalendarResponse=function(response)
		{
			if(response.error===1) return; 
			
			$this.find('.cbs-booking-summary-date h5 span:first').html('');
			$this.find('.cbs-booking-summary-time h5 span:first').html('');
					
			$this.find('.cbs-booking-summary-date h5 span+span').css({'display':'block'});
			$this.find('.cbs-booking-summary-time h5 span+span').css({'display':'block'});
			
			$this.find('.cbs-main-list-item-calendar .cbs-main-list-item-section-content').html(response.calendar);
			$self.calculateCalendarColumnWidth();
		};
		
		/**********************************************************************/
		/**********************************************************************/		
		
		this.createCost=function(vehicleId,packageId,serviceId)
		{
			var data={};
			
			data.action='cbs_create_cost';
			
			data.vehicleId=vehicleId;
			data.packageId=packageId;
			data.serviceId=serviceId.join('.');
			data.locationId=$option.locationId;
			
			$self.post(data,function(response)
			{
				$self.createCostResponse(response);
			});		
		};
		
		/**********************************************************************/
		
		this.createCostResponse=function(response)
		{
			$this.find('.cbs-booking-summary-duration>h5>span:eq(0)').html(response.cost.duration.hour);
			$this.find('.cbs-booking-summary-duration>h5>span:eq(2)').html(response.cost.duration.minute);
			
			$this.find('.cbs-booking-summary-price>h5>span.cbs-booking-summary-price-value').html(response.cost.price.unit+'.'+response.cost.price.decimal);
		};
		
		/**********************************************************************/
		/**********************************************************************/
		
		this.createService=function(vehicleId,packageId)
		{
			var data={};
			
			data.action='cbs_create_service';
			
			data.vehicleId=vehicleId;
			data.packageId=packageId;
			data.locationId=$option.locationId;
			
			$self.post(data,function(response)
			{
				$self.createServiceResponse(response);
			});		
		};
		
		/**********************************************************************/
		
		this.createServiceResponse=function(response)
		{
			var serviceListItem=$this.find('.cbs-main-list-item-service-list');
			
			serviceListItem.removeClass('cbs-state-disable');
			
			if(!response.serviceCount) serviceListItem.addClass('cbs-state-disable');
			
			serviceListItem.children('.cbs-main-list-item-section-content').html(response.service);
			
			$this.find('.cbs-booking-summary-duration>h5>span:eq(0)').html(response.cost.duration.hour);
			$this.find('.cbs-booking-summary-duration>h5>span:eq(2)').html(response.cost.duration.minute);
			
			$this.find('.cbs-booking-summary-price>h5>span.cbs-booking-summary-price-value').html(response.cost.price.unit+response.cost.price.separator+response.cost.price.decimal);
		};
		
		/**********************************************************************/
		/**********************************************************************/
		
		this.setButtonSelected=function(object,group,unchecked,multiple)
		{
			object=$(object);
			
			if(!unchecked)
			{
				if(object.hasClass('cbs-state-selected')) return;
			}
			
			if(!multiple)
			{
				if(group===null) group=object.siblings();
				group.removeClass('cbs-state-selected');
			}
			
			object.toggleClass('cbs-state-selected');
		};
		
		/**********************************************************************/
		
		this.getValueFromClass=function(object,pattern)
		{
			try
			{
				var reg=new RegExp(pattern);
				var className=$(object).attr('class').split(' ');

				for(var i in className)
				{
					if(reg.test(className[i]))
						return(className[i].substring(pattern.length));
				}
			}
			catch(e) {}

			return(false);		
		};	
		
		/**********************************************************************/
		
		this.post=function(data,callback)
		{
			$self.preloader();
			
			data.pageId=$option.pageId;
			
			$.post(pluginOption.config.ajaxurl,data,function(response)
			{ 
				callback(response); 
				$self.preloader();
			},'json');
		};
		
		/**********************************************************************/
		
		this.preloader=function()
		{
			var preloader=$('#cbs-preloader');
			
			if(preloader.length!==1) return;
			
			preloader.toggleClass('cbs-state-enable');
		};
		
		/**********************************************************************/
		
		this.setWidthClass=function()
		{
			var width=$this.parent().width();
			
			var className=null;
			var classPrefix='cbs-width-';
			
			if(width>=1170) className='1170';
			else if(width>=960) className='960';
			else if(width>=768) className='768';
			else if(width>=480) className='480';
			else if(width>=300) className='300';
			else if(width>=0) className='0';
			
			var oldClassName=$self.getValueFromClass($this,classPrefix);
			if(oldClassName!==false) $this.removeClass(classPrefix+oldClassName);
			
			$this.addClass(classPrefix+className);
			
			if($self.prevWidth!==width)
			{
				$self.prevWidth=width;
				$self.calculateCalendarColumnWidth();
			}
			
			setTimeout($self.setWidthClass,500);
		};
		
		/**********************************************************************/
		
		this.calculateCalendarColumnWidth=function()
		{
			var calendarBox=$this.find('.cbs-calendar-table-wrapper');
			var calendar=calendarBox.find('table');
			
			calendarBox.width('');
			calendar.width('');
			
			var calendarWidth=calendarBox.width();
			
			var columnCount=parseInt(calendarBox.find('input[name="cbs-calendar-column-count"]').val());
			var columnWidth=140;
			
			columnCount=Math.floor(calendarWidth/columnWidth);
			if(columnCount===0) columnCount=1;
			
			var calendarHeader=$this.find('.cbs-calendar-table-wrapper table th');

			calendarHeader.first().addClass('cbs-active');
			
			calendarBox.width(calendarBox.parent().width()+1);
			calendarBox.find('input[name="cbs-calendar-column-count"]').val(columnCount);
			
			$self.hideCalendarColumn();
		};
		
		/**********************************************************************/
		
		this.manageCalendarHeader=function()
		{
			var calendar=$this.find('.cbs-calendar-table-wrapper .cbs-calendar');
			var calendarHeaderCaption=$this.find('.cbs-calendar-header-caption');
		
			var columnActive=calendar.find('th.cbs-active').index();
			var columnCount=parseInt($this.find('input[name="cbs-calendar-column-count"]').val());
		
			var monthNumber=[];
		
			for(var i=columnActive;i<(columnActive+columnCount);i++)
			{
				var date=$self.getValueFromClass(calendar.find('th:eq('+i+')'),'cbs-date-id-');
				if(date===false) continue;
				var month=date.substring(2,4);
				monthNumber.push(month);
			}
			
			monthNumber=jQuery.unique(monthNumber);
		
			calendarHeaderCaption.children('span').css('display','none');
		
			if(monthNumber.length>1)
				calendarHeaderCaption.children('span.cbs-calendar-month-number-0').css('display','inline');
			
			for(var i in monthNumber)
				calendarHeaderCaption.children('span.cbs-calendar-month-number-'+monthNumber[i]).css('display','inline');
		};
		
		/**********************************************************************/
	};
	
	/**************************************************************************/
	
	$.fn.CBSPlugin=function(option) 
	{
		var plugin=new CBSPlugin(this,option);
		plugin.build();
	};
	
	/**************************************************************************/

})(jQuery,document,window);

/******************************************************************************/
/******************************************************************************/