// *****************************************************
// handle car wishlist
// *****************************************************
// TODO expand for different style wishlists

(function(jQuery){

	jQuery.fn.wishList = function(options){
		var defaults = {
            button:'.addWishlist',         
            buttonAdd:'.addWishlist, #btnAddToWishlist', 
            buttonSave:'.saveWishlist',
            buttonCompare:'#btnCompare, .btnCompare',
            buttonRetrieve:'#favouritesRetrieve',
            buttonRemove:'.removeWishlist',
            buttonRemoveAll:'.clearWishlist',
            sliderContainer:'.sliderContainer',
            sliderNext:'.btnNext',
            sliderPrev:'.btnPrevious',
            slider:'.slider',
            wishlistCount:'#wishlistCount', //the wishlist thumbnail class
            wishlistImage:'.thumb', //the wishlist thumbnail class
            carId:0,
            carMake:0,
            carModel:0,
            carImage:'',
            attribute:'nd:carid',
            visibleLimit:0,
            limit:8
		};

		var options = jQuery.extend(defaults, options);
		var wishlist=this;
		var limit=jQuery(options.wishlistImage,this).length;
		var pos=0;
		
		jQuery(options.wishlistCount).html('0'+'&nbsp;Vehicles');
		jQuery(options.wishlistCount).fadeIn();
		
		jQuery(options.buttonSave).click(function(){
			openDialogForm( 'dialogSaveFavourites', 'formSaveFavourites', 'alertBoxSaveFavourites' );
			return false;
		})
		
		jQuery(options.buttonRetrieve).click(function(){
			openDialogForm( 'dialogRetrieveFavourites', 'formRetrieveFavourites', 'alertBoxRetrieveFavourites' );
			return false;
		})
		
		jQuery(options.buttonCompare).click(function(){
			if(jQuery(options.wishlistImage+' a',wishlist).length==0){
				$('#wishlistMsg').dialog("option", "title", 'Nothing to compare');
				$('#wishlistMsg').html('You need to add used cars to your Showroom to compare.');
				$('#wishlistMsg').dialog('open');
				return false;
			}else{
				return true;
			}
		})
		
		//append an alert box if we need it
		if(! $('body #alertBoxSaveFavourites').length){
			$('body').append('<div id="alertBoxSaveFavourites" class="ui-corner-all" ></div>');
		}
		
		if(! $('body #wishlistMsg').length){
			$('body').append('<div id="wishlistMsg" class="ui-corner-all" ></div>');
			$('#wishlistMsg').dialog({autoOpen: false});
		}
		
		//remove item from the wishlist
		jQuery('.box',wishlist).click(function(){
			//TODO call remove function here
		});
		
		showMyFavourites();
		count=0;
		function showMyFavourites(){
			$.ajax({
				url: '/frontend-operations/view-my-favourites/',
				dataType: 'json',
				data: 'limit=' + limit,
				success: function(data){
					if( data != 0 ){
						var vehicleTitle, text;
						// Add Options
						var width=jQuery(options.wishlistImage+':first',wishlist).innerWidth();
						var height=jQuery(options.wishlistImage+':first',wishlist).innerHeight();
						$.each(data, function(i,item){
							
							vehicleTitle = item.references.marque_name + ' ' + item.references.model_name + ' ' + item.variant;
							vehicleImage = netdirector.baseUrl + '/upload/images/stock/small/' + item.imageSrc;
							vehicleLink = netdirector.baseUrl + '/' + netdirector.franchiseUrl + 'used-cars/' + item.id + '/' + vehicleTitle.toLowerCase().replace( ' ', '-' )
							text ='<a id="wl'+item.id+'" nd:carId="'+item.id +'" href="' + vehicleLink + '" title="' + vehicleTitle + '">';
							text+='<img src="' + vehicleImage + '" alt="' + vehicleTitle + '" style="width:'+width+'px;height:'+height+'px;position:absolute;" />';
							text+='</a>';
							
							jQuery(options.wishlistImage+':eq('+i+')',wishlist).html('');
							jQuery(options.wishlistImage+':eq('+i+')',wishlist).append(text);
							count++;
							
						});
						wishlist.data('count',count);
						jQuery(options.wishlistCount).html(wishlist.data('count')+'&nbsp;Vehicles');
					}
				}
			});
		}
		$('body').css('cursor', 'default');

		//attach click event to the wishlist add button
		jQuery(options.buttonAdd).click(function(){
			var index = $(options.buttonAdd).index(this);
			var vehicleId=jQuery(this).attr(options.attribute);
			var vehicleLink=jQuery(this).attr('href');
			var vehicleTitle=jQuery(this).attr('title');
			var width=jQuery(options.wishlistImage+':first',wishlist).innerWidth();
			var height=jQuery(options.wishlistImage+':first',wishlist).innerHeight();
			
			if(jQuery('#mainImg').length==0){
				var vehicleImage=jQuery('.thumb:eq('+index+') img:first').attr('src');	
			}else{
				var vehicleImage=jQuery('#mainImg img:first').attr('src');
			}


			//add the vehicle to the list but first check there is room
			if(count<=limit){
				$.ajax({
					url: '/frontend-operations/save-vehicle-to-favourites/',
					dataType: 'json',
					data: 'auto_car_detail_id=' + vehicleId,
					success: function(data){
						var carExists=false;
						var imageChanged=false;
						//check if the car exists
						jQuery(options.wishlistImage,wishlist).each(function(){
							if($('a:first',this).attr('id')=='wl'+vehicleId){
								carExists=true;
							}
						})

						if( data != 0 && carExists==false){
							jQuery(options.wishlistImage,wishlist).each(function(){
								var hasImage=jQuery('img',this).length;
								if(imageChanged==false && hasImage==0){
									jQuery(this).html('');	
									text ='<a id="wl'+vehicleId+'" nd:carId="'+vehicleId +'" href="' + vehicleLink + '" title="' + vehicleTitle + '">';
									text+='<img src="' + vehicleImage + '" alt="' + vehicleTitle + '" style="width:'+width+'px;height:'+height+'px;position:absolute;" />';
									text+='</a>';
									jQuery(this).append(text);	
									imageChanged=true;	
									count++;
									wishlist.data('count',wishlist.data('count')+1);
									
								}
							});
							if(carExists==true){
								$('#wishlistMsg').dialog("option", "title", 'Already Exists');
								$('#wishlistMsg').html('This car was not added because it already exists in your Showroom.');
							}else{
								$('#wishlistMsg').dialog("option", "title", 'Added');
                                $('#favouritesSave').show();
                                $('#favouritesCompare').show();
                                $('#favouritesRetrieve').show();
								$('#wishlistMsg').html('This car has now been added to your Showroom.');
							}

						}else{
							$('#wishlistMsg').dialog("option", "title", 'Request Failed');
							$('#wishlistMsg').html('The request to submit failed, please try again.');
						}
						jQuery(options.wishlistCount).html(wishlist.data('count') +'&nbsp;Vehicles');
					},
				error: function( objRequest ){
						$('#wishlistMsg').dialog("option", "title", 'Request Failed');
						$('#wishlistMsg').html('The request to submit failed, please try again.');
					}
				});
			}else{
				$('#wishlistMsg').dialog("option", "title", 'Request Failed');
				$('#wishlistMsg').html('Your Showroom is already full.');
			}
			$('#wishlistMsg').dialog('open');
			$('body').css('cursor', 'default'); 
			return false;
		});

		//attach click event to the wishlist add button
		jQuery(options.buttonRemove).click(function(){
			var index = $(options.buttonRemove).index(this);
			var vehicleId=jQuery(this).attr(options.attribute);
			var vehicleLink=jQuery(this).attr('href');
			var vehicleTitle=jQuery(this).attr('title');
					
			// Check if form is valid before proceeding
			$('body').css('cursor', 'progress'); 
			$.ajax({
				url: '/frontend-operations/remove-vehicle-from-favourites/',
				dataType: 'json',
				data: 'auto_car_detail_id=' + vehicleId,
				success: function(data){
					if( data != 0 ){
						
						//remove the image if we match the id of a remove item
						jQuery('.box',wishlist).each(function(){
							if(jQuery('div > a',this).attr('id')=='wl'+vehicleId){
								jQuery('div > a',this).fadeOut('slow',function(){
									jQuery(this).remove();
								});
								count--;
								wishlist.data('count',wishlist.data('count')-1);
							}
						});
						jQuery(options.wishlistCount).html(wishlist.data('count')+'&nbsp;Vehicles');
					}else{
						$('#wishlistMsg').dialog("option", "title", 'Request Failed');
						$('#wishlistMsg').html('The requested action failed, please try again.');
					}
					//window.location.reload();
					$('body').css('cursor', 'default'); 
				},
			error: function( objRequest ){
					$('#wishlistMsg').dialog("option", "title", 'Request Failed');
					$('#wishlistMsg').html('The requested action failed, please try again.');
					$('body').css('cursor', 'default'); 
				}
			});
			$('#wishlistMsg').dialog('open');
			return false;
		});

		//attach remove all cars from wishlist
		jQuery(options.buttonRemoveAll).click(function(){
			//update the dialog message
			$('#wishlistMsg').dialog("option", "title", 'Items removed');
            $('#favouritesSave').hide();
            $('#favouritesCompare').hide();
            $('#favouritesRetrieve').show();
			$('#wishlistMsg').html('All items have been cleared from your Showroom.');
			jQuery(options.wishlistImage,wishlist).each(function(){
				vehicleId=jQuery('a:first',this).attr(options.attribute);
				if (vehicleId){
					$.ajax({
						url: '/frontend-operations/remove-vehicle-from-favourites/',
						dataType: 'json',
						data: 'auto_car_detail_id=' + vehicleId
					});
				}
			});
			
			//clear the images
            //$('.slider .thumb a').remove();
            $('.slider .thumb a').replaceWith('<div id="favouriteItem" style="background-color: #f7f7f7; width: 47px; height: 35px; border:1px solid #89888a;" class="float_left"></div>');
			//jQuery(options.wishlistImage+' a:first',wishlist).remove();
			wishlist.data('count',0);
			jQuery(options.wishlistCount).html(wishlist.data('count')+'&nbsp;Vehicles');
			$('#wishlistMsg').dialog('open');

			return false;
		});

	// ***** handle the slider if we have a large wishlist *****
	if($(options.sliderContainer,wishlist).length>0){
		var sliderWidth=$(options.wishlistImage+':first',wishlist).outerWidth(true);
		var sliderPos=0;
		
		// slider next
		$(options.sliderNext,wishlist).click(function(){
			if(sliderPos<options.limit-options.visibleLimit){
				$(options.slider,wishlist).animate({left:'-='+sliderWidth+'px'});
				sliderPos++;
			}
		});
		
		// slider previous
		$(options.sliderPrev,wishlist).click(function(){
			if(sliderPos>0){
				$(options.slider,wishlist).animate({left:'+='+sliderWidth+'px'});
				sliderPos--;
			};
		});
	}


	}	
})(jQuery);

$(document).ready(function(){
	$('#myShowroom').wishList({'visibleLimit':4});
});

