$(function(){
		   
	$(window)._scrollable(); // When scrolling the window
	var x; 
	
	jQuery.ajaxSetup({
		cache: false,
		xhr: function() {
				//return new window.XMLHttpRequest();
				try{
					if(window.ActiveXObject)
						return new window.ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) { }

				return new window.XMLHttpRequest();
			}
	});
		 
	/* add items to cart */
	$(".add-item").click(function(){
								  
		try {
			jQuery.ajax({
				type: 'post',
				url: '/elements/includes/cart.cfm',
				dataType: 'html',
				data: $(this).parent('form').serialize(),
				success: function(data) {
					$.scrollTo(10,300);
					clearTimeout(x);
					x = setTimeout(function(){
					$("#cartstuff").fadeTo(500,0,function(){
						$(this).replaceWith(data).fadeTo(500,1);	
					});
					},400);
				},
				error:function(XMLHttpRequest,status,error){
				   // do nothing
				}
			});	
		} catch(e) {
			//console.log(e);
		}
		return false
	});
	
	/* remove items from cart */
	$(".remove-item").live('click',function(){
		$("form#removeItem").find('input[name=productid]').val($(this).attr('rel'));
		
		
		jQuery.ajax({
			type: 'post',
			url: '/elements/includes/cart.cfm',
			data: $("form#removeItem").serialize(),
			dataType: 'html',
			success: function(data) {
				$("#cartstuff").fadeTo(0,0,function(){
					$(this).replaceWith(data).fadeTo(0,1);
				});	
			}
		});
		
		/*
		$.post("/elements/includes/cart.cfm", $("form#removeItem").serialize(),
		function(data){
			$("#cartstuff").fadeTo(0,0,function(){
				$(this).replaceWith(data).fadeTo(0,1);
			});
		});
		*/
		
		return false
	});
	
	/* checkout */
	$("a.checkout").live('click',function(){
		var shipping = $(".cart [name=xshipping]:checked").val();
		/*var message = "Please Note: Inventory cannot be gauranteed until completion of payment. ";*/
		var message = "";
		$.ajax({
			url: '/elements/ajax/check-inventory.cfm',
			dataType: 'json',
			success: function(response) {
				$.get('/elements/includes/cart.cfm?shipping='+shipping,function(data){
					$("#cartstuff").replaceWith(data);
					if(!response.STATUS) {
						/* cannot fulfill order, no inventory */ 
						alert(response.MESSAGE);
						window.location.reload();
					} else {
						/* cart inventory may have been updated */ 
						/* order can still be fulfilled */
						var foo = response.MESSAGE;
						if(foo.length==0) {
							$('form.cart').trigger('submit');
						} else {
							var conf = confirm(response.MESSAGE + " " + message);
							if(conf) {
								$('form.cart').trigger('submit');
							}	
						}
					}
				})
			}
		})
		return false
	});
	
	
	/* fancybox */
	$(".fancybox").fancybox({hideOnOverlayClick:true});
	
	/* find city by postcode */
	$("form#find-city").bind('submit',function(){
		$("#find-city-paragraph").text('Looking for the nearest city...');
		$.ajax({
			url:'/elements/ajax/set-city.cfm',
			type: 'post',
			dataType: 'json',	
			data: {
				postcode: $("[name=postcode]").val()
			},
			success: function(response){
				if(response.STATUS) {
					$("#find-city-paragraph").text('The nearest city '+ response.CITY.NAME + ' has now been selected.');
					//$("#region-name").text(response.CITY.NAME);	
					setTimeout(function(){
						$.fancybox.close();
						window.location='/';
					},1000);
				}
			}
		});
		return false
	});
	
	/* select region */
	$(".select-region").live('click',function(){
		$.get('/elements/ajax/get-markets.cfm?regionid=' + $(this).attr('rel'),
			function(html){
				$("#regions").hide();
				$("#markets").html(html).show();				  
			}
		);
	});
	
	/* set city by link */
	$(".select-city").live('click',function(){
											
		$.ajax({
			url:'/elements/ajax/set-city.cfm',
			type: 'post',
			dataType: 'json',	
			data: {
				id: $(this).attr('rel')
			},
			success: function(response){
				if(response.STATUS) {
					$("#set-city-paragraph").text('The city '+ response.CITY.NAME + ' has now been selected.');
					//$("#region-name").text(response.CITY.NAME);	
					setTimeout(function(){
						$.fancybox.close();
						window.location='/';
					},1000);
				}
			}
		});
		return false
	});
	
	/* geolocate city */
	var geoFound = function(position){
			
			//$("#region-name").text("...");
			
			$("#detect-location-paragraph").text('Detecting your location...');
			
			/* find nearest city in db */
			$.ajax({
				url:'/elements/ajax/detect-nearest-city.cfm',
				type: 'post',
				dataType: 'json',
				data: {
					lat: position.coords.latitude,
					lng: position.coords.longitude
				},
				success: function(response) {
					/* update selected region */
					if(response.STATUS) {
						//$("#region-name").text(response.CITY.NAME);
						$("#detect-location-paragraph").text('Location detected! The nearest city '+ response.CITY.NAME + ' has been selected.');
						setTimeout(function(){
							$.fancybox.close();
							window.location='/';
						},1000);
					} else {
						
					$("#detect-location-paragraph").text('Could not detect your location.');
					}
				}
			});

		},
		error = function(message){

			message = typeof message == 'string' ? message : "failed";

					$("#detect-location-paragraph").text('Could not detect your location. ' + message);

		}
		
		$("#detect-location").live('click',function(){
			
			if (!Modernizr.geolocation){
	
				//$('#content').html('This browser does not support geolocation');
				$("#detect-location-paragraph").text('Your browser does not support geolocation');
	
				return;	
	
			} else {
	
				
				navigator.geolocation.getCurrentPosition(geoFound, error);
	
			}
			
			return false
			
		});

		

	
});
