// JavaScript Document
var map;
var geocoder;
var admin = false;
var uploadified = false;

  function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
	geocoder = new google.maps.Geocoder();
    var myOptions = {
      zoom: 12,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.HYBRID 
    };
    map = new google.maps.Map(document.getElementById("map"),
        myOptions);
  }
  
  function codeAddress() {

    var address = 'Fleet, Hampshire, GU51';
    geocoder.geocode( { 'address': address}, function(results, status) {
		
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        /*var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
        });*/
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }

  
$(document).ready(function(){
	
	initialize();
	codeAddress();
	
	
	var fields = jQuery('.contactForm').find('input');
	
	
	
	var originals = [];
	
	fields.each(function(x) {
	  
	  var obj = this;
	  
	  if(jQuery(obj).attr('type') != 'submit')
	  {
	    originals[x] = jQuery(obj).val();
	    
	    jQuery(obj).focus(function() {
	      if(jQuery(obj).val() == originals[x])
	      {
		jQuery(obj).val('');
	      }
	    });
	    
	    jQuery(obj).blur(function() {
	      if(jQuery(obj).val() == '')
	      {
		jQuery(obj).val(originals[x]);
	      }
	    })
	  }
	});
	
	
	if(!admin) return;
	$('#cancelButton').click(function() {
		$(".addNewCar").slideUp("fast");
	});
	
	$('#saveButton').click(function() {
		
		 var message  = $.ajax({
			  
			  url: "car_admin.php",
			  global: false,
			  beforeSend : function(){
				  $( "#form-start" ).dialog({
					modal: true,
					
				});},
			  type: "POST",
			  data: ({id : $('#car_id').val() ,action: 'new', title : $('#title').val(), price : $('#price').val(), description : $('#description').val()}),
			  dataType: "html",
			  async:true,
			  scripts:true,
			  success: function(msg){
							 
					$( "#form-start" ).dialog('close');	
					$('#finished').html('Car added, now add photos!');
					$('#form-end').dialog({
						modal: true,
						buttons: {
							Ok: function() {
								$( this ).dialog( "close" );
								$(".addNewCar").slideUp("fast",function(){
									$('#details_form').addClass('displayNone');
									$('#car_id').val(msg)
									if(!uploadified)
									{
										uploadified = true;
										$('#file-upload').uploadify({
											'uploader'  : 'uploadify/uploadify.swf',
											'script'    : 'uploadify/uploadify.php',
											'cancelImg' : 'uploadify/cancel.png',
											'folder'    : 'photos/' + msg,
											
											'multi'	: true,
											'onComplete' : function() { loadImages(msg); }
										  })	
									}
									  $('#upload_photos').removeClass('displayNone');
									  
									  $(".addNewCar").slideDown("fast",function(){
										//Load in the cars
										 if($('#car_id').val() > 0)
										 {
										  loadImages($('#car_id').val());
										 }else{
											  $('#admin_images').html('');
										 }
									  });
								});
								
							}
						}
					})
				
				},
			  
			   error: function(msg){
				   alert('fail');
				
			  }
		   }
		  ).responseText;
		  
		  
		
	});
	
	
	$('#completeButton').click(function() {
		
		 var message  = $.ajax({
			  
			  url: "list_cars.php",
			  global: false,
			  beforeSend : function(){
				  $( "#cars_load" ).slideUp('fast');
			  },
			  type: "GET",
			  dataType: "html",
			  async:true,
			  scripts:true,
			  success: function(msg){
				  document.location.href = 'cars.php';
				  return;
				  $( "#cars_load" ).html(msg);
				  $( "#cars_load" ).slideDown('fast');
				  $( ".addNewCar" ).slideUp('fast');
				  $('#upload_photos').addClass('displayNone');
				  $('#details_form').removeClass('displayNone');
				  reOrder();
				  $('.edit').click(function() {
						var car_id = $(this).attr('car_id');
						editAdd(car_id);
					});
				 $('.delete').click(function(e) {
					 e.preventDefault();
								var car_id = $(this).attr('car_id');
								deleteAdd(car_id);
							});
				  }
				  })
	});
	
	
	
	function reOrderImages()
	{
		$( "#admin_images_sort" ).sortable({
			placeholder: "image-place",
			stop: function() {
				var this_array = $( "#admin_images_sort" ).sortable('toArray');
				
				 var message  = $.ajax({
			  
				  url: "car_admin.php",
				  global: false,
				  
				  type: "POST",
				  dataType: "html",
				  async:true,
				  scripts:true,
				  data: ({action: 'order_images', order : this_array.toString()}),
				  success : function(msg) {
					  
				  },
				  error: function(msg)
				  {	
				  alert(msg);
				  }
				 });
			}
		});
		$( "#sortable" ).disableSelection();		
	}
	
	
	function reOrder()
	{
		$( "#sortable" ).sortable({
			placeholder: "car-place",
			stop: function() {
				var this_array = $( "#sortable" ).sortable('toArray');
				
				 var message  = $.ajax({
			  
				  url: "car_admin.php",
				  global: false,
				  
				  type: "POST",
				  dataType: "html",
				  async:true,
				  scripts:true,
				  data: ({action: 'order', order : this_array.toString()}),
				  success : function(msg) {
					  
				  }
				 });
			}
		});
		$( "#sortable" ).disableSelection();
	}
	
	$('.edit').click(function() {
		var car_id = $(this).attr('car_id');
		editAdd(car_id);
	});
	
	$('.delete').click(function(e) {
		e.preventDefault();
		var car_id = $(this).attr('car_id');
		deleteAdd(car_id);
	});
	
	function editAdd(car_id)
	{
		$('#car_id').val(car_id);
		$('#title').val($('#title_'+car_id).val());
		$('#price').val($('#price_'+car_id).val());
		$('#description').val($('#description_'+car_id).val());
		
		$(".addNewCar").slideDown("fast");	
	}
	
	function deleteAdd(car_id)
	{
		if(confirm('Are you sure you wish to delete this car?'))
		{
			 var message  = $.ajax({
			  
			  url: "car_admin.php",
			  global: false,
			  beforeSend : function(){
				  $( "#cars_load" ).slideUp('fast');
			  },
			  type: "POST",
			  dataType: "html",
			  async:true,
			  scripts:true,
			  data: ({id : car_id, action : 'delete_car'}),
			  success: function(msg){
				  var message2  = $.ajax({
			  
					  url: "list_cars.php",
					  global: false,
					 
					  type: "GET",
					  dataType: "html",
					  async:true,
					  scripts:true,
					  success: function(msg){
						  $( "#cars_load" ).html(msg);
						  $( "#cars_load" ).slideDown('fast');
						  
						  reOrder();
						  $('.edit').click(function() {
								var car_id = $(this).attr('car_id');
								editAdd(car_id);
							});
						 $('.delete').click(function() {
								var car_id = $(this).attr('car_id');
								deleteAdd(car_id);
							});
						  }
						  })	
				  }
				  })	
		}
	}
	
	function deleteImageAdd(image_id)
	{
		if(confirm('Are you sure you wish to delete this image?'))
		{
			 var message  = $.ajax({
			  
			  url: "car_admin.php",
			  global: false,
			  type: "POST",
			  dataType: "html",
			  async:true,
			  scripts:true,
			  data: ({id : image_id, action : 'delete_image'}),
			  success: function(msg){
				  	loadImages($('#car_id').val());
				  }
			 })	
		}
	}
	
	function unUploadify(element){
		if(!element){var element="*";};
		$(element).next(element+"Uploader").remove();
		$(element).css("display","inline");
	
	
	};
	
	function loadImages(car_id)
	{
		var images  = $.ajax({
			  
			  url: "car_admin.php",
			  global: false,
			 
			  type: "POST",
			  data: ({action: 'images', id : car_id}),
			  dataType: "html",
			  async:true,
			  scripts:true,
			  success: function(msg){
				  $('#admin_images').html(msg);
				  reOrderImages();
				  $('.image_delete').click(function(e) {
					e.preventDefault();
					var image_id = $(this).attr('image_id');
					deleteImageAdd(image_id);
				});
			  }
		  });	
	}
	
	function resetForm()
	{
		$('#title').val('');
		$('#price').val('');
		$('#description').val('');
		$('#car_id').val('0');
	}
	
	$('.new_car').click(function() {
		resetForm();
		$( ".addNewCar" ).slideDown('fast');	
	});
	
	$(function() {
			if(admin)
			{
				reOrder();
			}
		})
	
	
	
	
	
});


