// *****************************************************
// image fade between images
// *****************************************************

(function(jQuery){
	jQuery.fn.imageCycle = function(options){
		var defaults = {
            imageList:Array(),
			speed:5000
		};

		var options = jQuery.extend(defaults, options);
		var fader=this;
		tmpimg=jQuery('img:eq(0)',fader).css('position','absolute');
		var pos=0;

		if(options.imageList.length>0){
			var interval = setInterval(change,options.speed);
		}


		function change(){
			pos++;

			if(pos>options.imageList.length-1){
				pos=0;
			}
			tmpimg=jQuery('img:eq(0)',fader);
			tmpimg.css('z-index','1');
			jQuery(fader).prepend('<img alt="'+options.imageList[pos][3]+'" src="'+options.imageList[pos][0]+'" style="position:absolute;z-index:0;">');
			jQuery(tmpimg).animate({opacity:0.50},300,function(){
				jQuery(tmpimg).remove();
				//jQuery(fader).attr('src',options.imageList[pos][0]);
				//jQuery(fader).attr('alt',options.imageList[pos][3]);
				//jQuery(fader).animate({opacity:1},300);
			})
		}

	}
})(jQuery);

// *****************************************************
// image carasoul
// *****************************************************
// TODO add width height toggle currently only handles height movement

(function(jQuery){
	jQuery.fn.carasoul = function(options){
		var defaults = {
            childNode:'model',
            thumbsView:3,
			selectedModel: ""
		};

		var options = jQuery.extend(defaults, options);

		slider=this;
		pos=0;
		total=jQuery('.thumb',this).length;
		height=jQuery('.thumb:eq(0)',this).outerHeight();

		jQuery('.thumb',this).each(function(){
			jQuery(this).click(function(){
				jQuery('#usedMain > img').attr('src',rootUrl+'images/global_auto/medium/'+jQuery('> img',this).attr('alt'));
			});
		});

        jQuery('.next',this).click(function(){
			if(pos<total-options.thumbsView){
				jQuery('#thumbSlider').animate({top:'-='+height+'px'});
				pos++;
			}
            return false;
        });
        jQuery('.prev',this).click(function(){
			if(pos>0){
				jQuery('#thumbSlider').animate({top:'+='+height+'px'});
				pos--;
			}
            return false;
        });
	}
})(jQuery);

// *****************************************************
// image cycle
// *****************************************************
// TODO cycle between images and text on clicking next previos buttons

(function(jQuery){
	jQuery.fn.cycleIt = function(options){
		var defaults = {
			imageContainer:'.thumb',
			textContainer:'.thumbtext',
            nextButton:'.next',
            prevButton:'.prev',
            imageNode:'> img',
            speed:4000,
            fadeSpeed:800,
            auto:false,

            fade:true
		};

		var options = jQuery.extend(defaults, options);



		jQuery('.frame',this).css('z-index','2');
		var cycleImages=jQuery(options.imageContainer,this);
		var cycleText=jQuery(options.textContainer,this);

		var pos=0;
		var total=jQuery(options.imageNode,cycleImages).length-1;

		jQuery(options.imageNode,cycleImages).css('position','absolute');
		jQuery(cycleImages).css('position','relative');

		jQuery('>div',cycleText).css('position','absolute');
		jQuery(cycleText).css('position','relative');

		if(options.auto==true && total>0){
			var interval = setInterval(change,options.speed);
		}


		function change(){
			currentPos=pos;

			//handle the image fading
			jQuery(options.imageNode,cycleImages).each(function(i){
				if(i==pos){
					jQuery(this).css('z-index','1');
				}else{
					jQuery(this).css('z-index','0');
					jQuery(this).hide();
				}
			})

			//handle the text fading
			jQuery('>div',cycleText).each(function(i){
				if(i==pos){
					jQuery(this).css('z-index','1');
				}else{
					jQuery(this).css('z-index','0');
					jQuery(this).hide();
				}
			})

			pos++;
			if(pos>total){
				pos=0;
			}

			jQuery(options.imageNode +':eq('+pos+')',cycleImages).show();
			jQuery('>div:eq('+pos+')',cycleText).show();
			if(options.fade==true){
				jQuery(options.imageNode+':eq('+currentPos+')',cycleImages).fadeOut(options.fadeSpeed,function(){jQuery('>div:eq('+currentPos+')',cycleText).hide();});
			}else{
				jQuery(options.imageNode+':eq('+currentPos+')',cycleImages).hide();
				jQuery('>div:eq('+currentPos+')',cycleText).hide();
			}

		}

        jQuery(options.nextButton,this).click(function(){
			if(pos<total){
				//handle the image fading
				jQuery(options.imageNode,cycleImages).each(function(i){
					if(i==pos){
						jQuery(this).css('z-index','1');
					}else{
						jQuery(this).css('z-index','0');
						jQuery(this).hide();
					}
				})

				//handle the text fading
				jQuery('>div',cycleText).each(function(i){
					if(i==pos){
						jQuery(this).css('z-index','1');
					}else{
						jQuery(this).css('z-index','0');
						jQuery(this).hide();
					}
				})
				pos++;

				jQuery(options.imageNode+':eq('+pos+')',cycleImages).show();
				jQuery('>div:eq('+pos+')',cycleText).show();
				if(options.fade==true){
					jQuery(options.imageNode+':eq('+(pos-1)+')',cycleImages).fadeOut(options.fadeSpeed,function(){jQuery('>div:eq('+(pos-1)+')',cycleText).hide();});
					//jQuery('>div:eq('+(pos-1)+')',cycleText).fadeOut('slow');
				}else{
					jQuery(options.imageNode+':eq('+(pos-1)+')',cycleImages).hide();
					jQuery('>div:eq('+(pos-1)+')',cycleText).hide();
				}

			}
            return false;
        });
        jQuery(options.prevButton,this).click(function(){
			if(pos>0){
				//handle the image fading
				jQuery(options.imageNode,cycleImages).each(function(i){

					if(i==pos){
						jQuery(this).css('z-index','1');
					}else{
						jQuery(this).css('z-index','0');
						jQuery(this).hide();
					}
				})

				//handle the text fading
				jQuery('>div',cycleText).each(function(i){
					if(i==pos){
						jQuery(this).css('z-index','1');
					}else{
						jQuery(this).css('z-index','0');
						jQuery(this).hide();
					}
				})

				pos--;
				jQuery(options.imageNode+':eq('+pos+')',cycleImages).show();
				jQuery('>div:eq('+pos+')',cycleText).show();
				if(options.fade==true){
					jQuery(options.imageNode+':eq('+(pos+1)+')',cycleImages).fadeOut(options.fadeSpeed,function(){jQuery('>div:eq('+(pos+1)+')',cycleText).hide();});
					//jQuery('>div:eq('+(pos+1)+')',cycleText).fadeOut('slow');
				}else{
					jQuery(options.imageNode+':eq('+(pos+1)+')',cycleImages).hide();
					jQuery('>div:eq('+(pos+1)+')',cycleText).hide();
				}
			}
            return false;
        });
	}
})(jQuery);


// *****************************************************
// Graphical body Style selector
// *****************************************************

(function(jQuery){
	jQuery.fn.bodyStyle = function(options){
		var defaults = {
			inputField:'#auto_body_style_detail_id',
            nextButton:'.next',
            prevButton:'.prev,.back',
            slider:'#modelSlider'
		};

		var options = jQuery.extend(defaults, options);

		var pos=0;
		var slider=jQuery(options.slider);
		var total=jQuery('div',slider).length-1;
		
		// Explicitly set the width as it seems to sometimes calculate it wrongly. 
		//var width=jQuery('div:eq(0)',slider).outerWidth(true);
		var width = 143;


		$('#modelSlider img').click(function(){
			$('#category_search').val( $(this).attr('alt') );
			$('#frmSearchUsedCars').submit();
		});

        jQuery(options.nextButton,this).click(function(){
			if(pos<total){
				$(options.slider).animate({left:'-='+width+'px'})
				pos++;
			}
			jQuery(options.inputField).val(jQuery('div:eq('+pos+') img',slider).attr('alt'));
            return false;
        });

        jQuery(options.prevButton,this).click(function(){
			if(pos>0){
				$(options.slider).animate({left:'+='+width+'px'})
				pos--;
			}
			jQuery(options.inputField).val(jQuery('div:eq('+pos+') img',slider).attr('alt'));
            return false;
        });
	}
})(jQuery);

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

(function(jQuery){

	jQuery.fn.wishList = function(options){
		var defaults = {
            button:'.addWishlist',
            buttonAdd:'.addWishlist',
            buttonSave:'.btnSave',
            buttonCompare:'.btnCompare',
            buttonRemove:'.removeWishlist',
            carId:0,
            carMake:0,
            carModel:0,
            carImage:'',
            limit:4
		};

		var options = jQuery.extend(defaults, options);
		var container=this;
		var limit=jQuery('.frame',this).length;
		var pos=0;

		jQuery(options.buttonSave).click(function(){
			openDialogForm( 'dialogSaveFavourites', 'formSaveFavourites', 'alertBoxSaveFavourites' );
			return false;
		})

		//remove item from the wishlist
		jQuery('.box',container).click(function(){
			//TODO call remove function here
		});

		$.ajax({
			url: '/frontend-operations/view-my-favourites/',
			dataType: 'json',
			data: 'limit=' + 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;
						if(!vehicleImage){
							vehicleImage = '/local/images/noImage61x46.gif';
						}
						text = '<a id="wl'+item.id+'" href="' + netdirector.baseUrl + '/' + netdirector.franchiseUrl + 'used-cars/' + item.id + '/' + vehicleTitle.toLowerCase().replace( ' ', '-' ) + '" title="' + vehicleTitle + '">';
						text+= '<img onerror="this.src = \'/local/images/noImage61x46.gif\';" src="' + vehicleImage + '" alt="' + vehicleTitle + '" style="width:61px;height:46px;position:absolute;" />';
						text+='</a>';
						jQuery('.box:eq('+i+') ',container).prepend(text);
					});
				}
			},
			error: function( objRequest ){
			}

		});
		$('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('nd:carid');
			var vehicleTitle=jQuery(this).attr('title');
			var vehicleLink=jQuery(this).attr('href');

			if(jQuery('#mainImg').length==0){
				var vehicleImage=jQuery('.thumb:eq('+index+') img:first').attr('src');
			}else{
				var vehicleImage=jQuery('#mainImg img:first').attr('src');
			}


			// Check if form is valid before proceeding
			$('body').css('cursor', 'progress');
			$.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('.box',container).each(function(){
							if($('a:first',this).attr('id')=='wl'+vehicleId){
								carExists=true;
							}
						})

						if(carExists==true){
							console.log('match'+carExists);
							alert("Vehicle is already in your Wishlist.");
						}else{
							if( data != 0){
								jQuery('.box',container).each(function(){
									var hasImage=jQuery('>a',this).length;
									if(imageChanged==false && hasImage==0){

										//if(jQuery('>img',this).length==0){
											text = '<a id="wl'+vehicleId+'" href="' + vehicleLink + '" title="wishlist item">';
											text+= '<img src="' + vehicleImage + '" alt="wishlist thumb" style="width:61px;height:46px;position:absolute;" />';
											text+='</a>';
											jQuery(this).prepend(text);
											//jQuery('img',this).fadeIn('slow');
											imageChanged=true;
											//alert(data);
										//}
									}
								});
								alert("Vehicle has been added to your Wishlist.");
							}else{
								updateTips('Request Failed','The form submit request failed, please try again.','error','','alertBoxSaveFavourites');
							}
						}
						$('body').css('cursor', 'default');

				},
			error: function( objRequest ){
					updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBoxSaveFavourites');
					$('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('nd:carid');

			// 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('a',this).attr('id')=='wl'+vehicleId){
								jQuery('> a',this).fadeOut('slow',function(){
									jQuery('> a',this).remove();
								});
							}
						});

						jQuery('.listItem:nth-child('+(index+1)+')').remove();

					}else{
						alert('Failed to remove car');
						// Show generic message
						updateTips('Request Failed','The form submit request failed, please try again.','error','','alertBoxSaveFavourites');
					}
					$('body').css('cursor', 'default');
				},
			error: function( objRequest ){
					updateTips('Request Failed','The requested action failed, please try again.','error','','alertBoxSaveFavourites');
					$('body').css('cursor', 'default');
				}
			});

			return false;
		});


	}
})(jQuery);




$(document).ready(function(){
	$('#contactDetails').toggle(function(){
		$('#franchiseContactDetails').show();
		jQuery.ajax({
			url: '/frontend-operations/get-all-phone-numbers-by-location-by-franchise/',
			dataType: 'html',
			success: function(data) {
				$('#franchiseContactDetails').html(data);
			},error: function(data){
				alert( 'request failed, please try again' );
			}
		});
	},function(){
		$('#franchiseContactDetails').hide();
	});

	$('#tabVehicleSearch').tabs({
		select: function(event, ui) {
			$('#tabVehicleSearch > .tabContent').each(function(i){
				$('#search'+(i+1)).hide();
				$('#search'+(i+1)+' select,input,textarea',this).attr({'disabled':true});
			})
			if(ui.index==0){				
				$('#advancedSearch select,input,textarea').attr({'disabled':false});
			} else {
				$('#advancedSearch').hide();
			}
			$('#search'+(ui.index+1)).show();
			$('#search'+(ui.index+1)+' select,input,textarea').attr({'disabled':false});
			$('#current_tab').attr('value',ui.index);
		}
	});
	$('#tabVehicleSearch').tabs('select',  parseInt($('#current_tab').attr('value')));

	//budget search tab toggle between 3 options
	$('#budgetOrSelect').change(function(){
		var num=$('option:selected',this).val();
		$('.budgetOr').hide();
		$('#budgetOr'+num).show();
	})

	$('.cycleImages').cycleIt({'imageContainer':'#mainImg','imageNode':'> a'});
	$('.cmsImg').cycleIt({'imageContainer':'.imgList','auto':true});
	//$('.usedImg').cycleIt({'imageContainer':'#mainImg','auto':true});
	$('.usedImg').cycleIt({'imageContainer':'#usedCont'});
//	$('#searchTab1').getModel();
	$('#selectmodel').bodyStyle();
	$('#from_postcode').focus(function(){
		if($(this).val()=='Postcode / Address Details'){
			$(this).val('');
		}
	})

	$('#from_postcode').blur(function(){
		if($(this).val()==''){
			$(this).val('Postcode / Address Details');
		}
	})

	$('.wishList').wishList();
})

