
// *****************************************************
// handle car wishlist
// *****************************************************
// TODO expand for different style wishlists

(function(jQuery){
	jQuery.fn.wishList = function(options){
		var defaults = {
            button:'.addWishlist',         
            buttonAdd:'.addWishlist',
            buttonSave:'.saveWishlist,#saveWishlist',
            buttonCompare:'#btnCompare,.btnCompare',
            buttonRetreieve:'#btnRetrieve,.btnRetrieve,.retrieveWishlist',
            buttonRemove:'.removeWishlist',
            buttonExchange:'#valueMy',
            wishlistImage:'.box.saveCompare .item a', //the wishlist thumbnail class
            detailSelector:'#usedVehiclePhoto',
            listingSelector:'#usedVehiclePhoto',
            defaultImage:'/local/images/noImage88x66.gif',
            frameImage:'',
            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();
			itEvent('usedSaveFavourites');
			showForm('saveFavourites');
			return false;
		})
		
		jQuery(options.buttonRetreieve).click(function(e){
			e.preventDefault();
			itEvent('retrieveFavourites');
			showForm('retrieveFavourites');
			return false;
		})
		
		jQuery(options.buttonCompare).click(function(e){
			itEvent('compareFavourites');
			e.preventDefaults();
			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){
								if(item.capimage){
									vehicleImage = item.capimage;	
								}else{
									vehicleImage = options.defaultImage;
								}
							}
							
							
							
							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+= options.frameImage;
							text+= '</a>';
							
							jQuery(options.wishlistImage+':eq('+i+')',container).html('');
							jQuery(options.wishlistImage+':eq('+i+')',container).append(text);
							count++;
						});

                        $('#saveWishlist').show();
				        $('.btnCompare').show();
				        $('.btnRetrieve').hide();
					} else {
                        $('#saveWishlist').hide();
                        $('.btnCompare').hide();
                        $('.btnRetrieve').show();
                    }


				}
			});
		}
		$('body').css('cursor', 'default');
		
		function render(item){
			text='<a id="wl'+vehicleId+'" nd:carId="'+vehicleId +'" href="' + vehicleLink + '" title="' + vehicleTitle + '">';
			text+= options.frameImage;
			text+='<img src="' + vehicleImage + '" alt="' + vehicleTitle + '" style="width:'+options.width+'px;height:'+options.height+'px;position:absolute;" />';
			text+='</a>';
		}
		
		//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 > a > 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){
				$('#wishlistMsg').dialog('open');
				$('#wishlistMsg').dialog("option", "title", 'Please Wait');
				$('#wishlistMsg').html('Adding vehicle to your wishlist.');
                
                var carExists=false;
                jQuery('.box.saveCompare .item a').each(function(){
                    if($(this).attr('id')=='wl'+vehicleId){
                        carExists=true;
                    }
                })

                if( carExists == true ) {
                    $('#wishlistMsg').dialog("option", "title", 'Already Exists');
                    $('#wishlistMsg').html('This car was not added because it exists in your wishlist.');

                } else {
                    
                    
                    $.ajax({
                        url: '/frontend-operations/save-vehicle-to-favourites/',
                        dataType: 'json',
                        data: 'auto_car_detail_id=' + vehicleId,
                        success: function(data){
                            var imageChanged=false;
                            //check if the car exists
    
                            if( data != 0){
                                jQuery(options.wishlistImage,container).each(function(i){
                                    var hasImage=jQuery('a > 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:'+options.width+'px;height:'+options.height+'px;position:absolute;" />';
                                        text+= options.frameImage;
                                        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.');
    
                            }else{
                                $('#wishlistMsg').dialog("option", "title", 'Already Exists');
                                $('#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('open');
				$('#wishlistMsg').dialog("option", "title", 'Request Failed');
				$('#wishlistMsg').html('Your wishlist is already full.');
			}

            showMyFavourites();
			
			setTimeout(function(){$('#wishlistMsg').dialog('close')},4000);
			$('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);


