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

(function(jQuery){

	jQuery.fn.wishList = function(options){
		var defaults = {
            button:'.addWishlist',         
            buttonAdd:'.addWishlist',
            buttonSave:'.saveWishlist',
            buttonCompare:'#btnCompare,.btnCompare',
            buttonRetreieve:'#btnRetrieve,.btnRetrieve,.retrieveWishlist',
            buttonRemove:'.removeWishlist',
            buttonExchange:'#valueMy',
            wishlistImage:'.thumb', //the wishlist thumbnail class
            detailSelector:'#usedVehiclePhoto',
            listingSelector:'#usedVehiclePhoto',
            defaultImage:'/local/images/viewThumb.jpg',
            frameImage:'',
            width:61,
            height:46,
            carId:0,
            carMake:0,
            carModel:0,
            carImage:'',
            attribute:'nd:carid',
            limit:6
		};

		var options = jQuery.extend(defaults, options);
		var container=this;
		var limit=jQuery(options.wishlistImage,this).length;
		var pos=0;
		
		jQuery(options.buttonSave).click(function(e){
			e.preventDefault();
			showForm('saveFavourites');
			return false;
		})
		
		jQuery(options.buttonRetreieve).click(function(e){
			e.preventDefault();
			showForm('retrieveFavourites');
			return false;
		})
		
		jQuery(options.buttonCompare).click(function(){
			if(jQuery(options.wishlistImage+' a',container).length==0){
				$('#wishlistMsg').dialog("option", "title", 'Nothing to compare');
				$('#wishlistMsg').html('You need to add used cars to your wishlist 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',container).click(function(){
			//TODO call remove function here
		});
		
		showMyFavourites();
		count=0;
		function showMyFavourites(){
			$.ajax({
				url: '/frontend-operations/view-my-favourites/',
				dataType: 'json',
				data: 'limit=' + options.limit,
				success: function(data){
					if( data != 0 ){
						var vehicleTitle, text;
						// Add Options
						$.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( ' ', '-' )
							if(!item.imageSrc){
								vehicleImage = options.defaultImage;
							}
							
							text= options.frameImage;
							text+= '<a id="wl'+item.id+'" nd:carId="'+item.id +'" href="' + vehicleLink + '" title="' + vehicleTitle + '">';
							text+= '<img src="' + vehicleImage + '" alt="' + vehicleTitle + '" style="width:'+options.width+'px;height:'+options.height+'px;position:absolute;" />';
							text+= '</a>';
							
							jQuery(options.wishlistImage+':eq('+i+')',container).html('');
							jQuery(options.wishlistImage+':eq('+i+')',container).append(text);
							count++;
						});
					}
				}
			});
		}
		$('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');
			if(jQuery(options.detailSelector).length==0){
				var vehicleImage=jQuery('.listItem:eq('+index+') .thumb > img:first').attr('src');	
			}else{
				var vehicleImage=jQuery(options.detailSelector+' img:first').attr('src');
			}

					
			//add the vehicle to the list but first check there is room

			if(count<=options.limit-1){
				$.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,container).each(function(){
							if($('a:first',this).attr('id')=='wl'+vehicleId){
								carExists=true;
							}
						})

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

										//append image to wishlist allowing for multiple wishlists on one page
										jQuery(options.wishlistImage+':eq('+i+')',container).append(text);	
										imageChanged=true;	
									}
								});
								if(imageChanged==true){
									count++;
								}
								$('#wishlistMsg').dialog("option", "title", 'Added');
								$('#wishlistMsg').html('This car has now been added to your wishlist.');

								itEvent( 'favourites' );
							}

						}else{
							$('#wishlistMsg').dialog("option", "title", 'Request Failed');
							//$('#wishlistMsg').html('The request to submit failed, please try again.');
                            $('#wishlistMsg').html('This car was not added because it exists in your wishlist.');
						}

					},
				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 wishlist 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');
			
			$('#wishlistMsg').dialog("option", "title", 'Vehicle Removed');
			$('#wishlistMsg').html('Vehicle has been removed from your wishlist.');		
			// 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',container).each(function(){
							if(jQuery('div > a',this).attr('id')=='wl'+vehicleId){
								jQuery('div > a',this).fadeOut('slow',function(){
									jQuery(this).remove();
								});
								count--;
							}
						});
		
					}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;
		});

        
	}	
})(jQuery);

$(document).ready(function(){
	$('.wishList').wishList({width:88,height:66,frameImage:'<span class="frame"><img src="/local/images/frame88x66.png" alt=""></span>'});
});

