// {{{

// ***
// Our jQuery Ready event
// ***

$(document).ready(function(){
  
	// Table sorter functions
	$("#partsResults").tablesorter({
		// Default sort settings (column 2, desc)
        sortList: [[2,0]],
		// pass the headers argument and assing a object 
        headers: { 
            // assign the secound column (we start counting zero) 
            0: { 
                // disable it by setting the property sorter to false 
                sorter: false 
            } 
        } 
		
	}); 
	
	// Assign the sortStart event 
    $('#partsResults').bind('sortStart', function() { 
        // Do something?
    }).bind('sortEnd', function() { 
        // Do something?
    });
	
	$("#dealersResults").tablesorter({
		// Default sort settings (column 1, desc)
        sortList: [[0,0]]
	}); 
	
	$("#partsFolder").tablesorter({
		// Default sort settings (column 2, desc)
        sortList: [[2,0]],
		// pass the headers argument and assing a object 
        headers: { 
            0: { 
                // disable column 0 by setting the property sorter to false 
                sorter: false 
            } ,
			1: { 
                // disable column 1 by setting the property sorter to false 
                sorter: false 
            } 
        } 
	});
	
	$("#enquiriesList").tablesorter({
		// Default sort settings (column 2, desc)
        // sortList: [[0,0]]
		 
	});
	
}); 

// }}}
// {{{

// user.next uses a set of codes to remember what action needs to be carried out after a login
// This is replicated in a session variable.
// sf = Save Folder
// se = Single Enqiry
// me = Multi Enquiry

var user = {
	loggedin : false,
	firstname : false,
	lastname : false,
	email : false,
	next : false
}

// }}}
// {{{

var images = {
	location : false
}

// }}}
// {{{

var join = {
	form : function(which) {
				
				// Show the modal layer
				this.modal();
				
				// Show the Login/ Join Popup
				$('#joinPopup').show();
				
				// Make sure that we are showing the correct div
				if (which == 'join') {
					
					this.change('join');
					
				} else {
				
					this.change('login');
				
				}
				
			},
	modal : function() {
				
				// Get the screen height and width
				var maskHeight 	= $(document).height();
				var maskWidth 	= $(window).width();
			
				// Set height and width to mask to fill up the whole screen
				$('#mask').css({'width':maskWidth, 'height':maskHeight});
				
				// Transition effect		
				$('#mask').fadeIn();	
				
			},		
	close : function() {
				
				// Hide the popup
				$('#joinPopup').hide();
				
				// Hide the modal mask
				$('#mask, .window').hide();
				
			},
	change : function(toWhere) {
				
				if (toWhere == 'join') {
				
					$('#joinPopup').css({height:'300px'});
				
					$('#loginSection').hide();	
					$('#joinSection').show();
					
				} else {
				
					$('#joinPopup').css({height:'240px'});
				
					$('#joinSection').hide();	
					$('#loginSection').show();	
				
				}
				
			}
}

// }}}
// {{{

var search = {
	url : false,
	restrict : function(location) {
					
						if (location == 'dealers') {
						
							var brandID 	= $('#restrictDealers').val();
					   	
						} else if (location == 'parts') {
						
							var brandID 	= $('#restrictParts').val();
		   				
						}
						
						window.location.href 	= this.url + '&brandID=' + brandID;
						
					}
	
}

// ***
// Object to do stuff with the main search form
// ***

var formStuff = {
	submit		: function() {
						
						if ($('#q').val() == '') { 
						
							alert('Please enter something to search for.');
						
						} else {
						
							$('#searchForm').submit();
						
						}
						
					}
};	

// }}}
// {{{

// ***
// Manage the help information layers.
// ***

var help = {
	alert : function(info) {
	
		// Utlise the join modal screen
		join.modal();
		
		// Show the help data
		$('#helpInfo').html(info);
		$('#helpPopup').show();
	
	},
	
	close : function() {
	
		// Hide the help window
		$('#helpPopup').hide();
		
		// Hide the modal mask
		$('#mask, .window').hide();
		
	},
		
	search : function() {
					
						$('#helpSave').toggle();
						
						setTimeout("$('#helpView').toggle()", 600);
					
					},
	
	folder : function() {
					
						$('#helpSaveFolder').toggle();
						
						setTimeout("$('#helpSmall').toggle()", 600);
						setTimeout("$('#helpContact').toggle()", 1200);
												
					},
					
	page: function(page) {
	
					if (typeof(page) == 'undefined') {
					
						alert('Sorry, no help available for this page.');
					
					} else {
					
						switch(page) {
							case 'code':
								var helpHTML = '<ul><li>The Security Code is an important feature that prevents automated requests.</li><li>By filling in the security code you prove that you are a human making a genuine enquiry, and not a robot sending SPAM.</li></ul>';
								this.alert(helpHTML);
							break;
							case '/requests':
								var helpHTML = '<ul><li>Bullet points required</li></ul>';
								this.alert(helpHTML);
							break;
							case '/suppliers':
								var helpHTML = '<ul><li>Bullet points required</li></ul>';
								this.alert(helpHTML);
							break;
							case '/advertise':
								var helpHTML = '<ul><li>Bullet points required</li></ul>';
								this.alert(helpHTML);
							break;
							case '/charges':
								var helpHTML = '<ul><li>Bullet points required</li></ul>';
								this.alert(helpHTML);
							break;
							case '/about':
								var helpHTML = '<ul><li>Bullet points required</li></ul>';
								this.alert(helpHTML);
							break;
							case '/benefits':
								var helpHTML = '<ul><li>Bullet points required</li></ul>';
								this.alert(helpHTML);
							break;
							case '/contact':
								var helpHTML = '<ul><li>Please fill in all parts of the help form.</li><li>Someone from Auto Parts Finder will reply to you shortly.</li><li>The security code is required to ensure that this is an human enquire and not SPAM.</li><li>Your privacy is important to us and your detals will never be shared or sold to any third party.</li></ul>';
								this.alert(helpHTML);
							break;
							case '/':
							case '/home':
							default:
								var helpHTML = '<ul><li>Use the search facility to search for Parts or Dealers.</li><li>Select either &quot;Parts&quot; or &quot;Dealers&quot; underneath to specify what you would like to search for.</li><li>Use the &quot;Save Parts&quot; icon <img src="' + images.location + 'save.png"> to save a part to your parts folder.</li><li>You may make enquiries directly to dealers about the parts in your your parts folder.</li><li>Access your parts folder by clicking the parts folder icon <img src="' + images.location + 'partsFolderSmall.png"></li></ul>';
								this.alert(helpHTML);
							break;
							
						}
						
					}
					
	}
	
};

// }}}
// {{{

// ***
// Manage parts.
// ***
	
var parts = {
	home : false,
	unsaved : false,
	count : 0,
					
	gotoFolder : function() {
	
						var url = this.home + '?p=home&folder=true';
						
						location.href = url;
						
					},
	
	gotoEnquiries : function() {
	
						var url = this.home + '?p=home&enquiries=true';
						
						location.href = url;
						
					},
					
	clearFolder : function() {
						
						if (confirm("All parts will be removed from your parts folder.\n\nAre you sure?")) {
							
							location.href = this.home + '?p=home&folder=true&clear=true';
						
						}
						
					},
									
	save : function(partID) {
					
						$('#part' + partID).html('<img src="' + images.location + 'wait.gif" width="16" height="16" alt="Saving Part" title="Saving Part" border="0">');
						
						// Update the Parts counter and the parts folder icon
						// TODO: Put this in the success callback function
						this.updateParts(1);
							
						// Ajax this part into a session
						$.ajax({
							url: "folder/save.php",
							cache: false,
							type: "POST",
      						data: ({partID : partID}),
      						success: function(){
								
								$('#part' + partID).html('<img src="' + images.location + 'unsave.png" style="cursor: pointer; cursor: hand;" width="16" height="16" onclick="parts.unsave(\'' + partID + '\');" alt="Unsave this Part" title="Unsave this Part" border="0">');
							
							},
							error: function() {
								
								alert('Sorry, this part could not be added to your parts folder, please try again.');
							
							}
						});
					
					},
					
	unsave : function(partID) {
					
						$('#part' + partID).html('<img src="' + images.location + 'wait.gif" width="16" height="16" alt="Unsaving Part" title="Unsaving Part" border="0">');
							
						// Update the Parts counter and the parts folder icon
						// TODO: Put this in the success callback function
						this.updateParts(-1);
						
						// Ajax this part into a session
						$.ajax({
							url: "folder/unsave.php",
							cache: false,
							type: "POST",
      						data: ({partID : partID}),
      						success: function(){
								
								// UnAjax this part into a session
								$('#part' + partID).html('<img src="' + images.location + 'save.png" stlke="cursor: pointer; cursor: hand;" width="16" height="16" onclick="parts.save(\'' + partID + '\');" alt="Save this Part" title="Save this Part" border="0">');
					
							},
							error: function() {
								
								alert('Sorry, this part could not be removed from your parts folder, please try again.');
							
							}
						});
									
					},
					
	remove : function(partID) {
					
						$('#remove' + partID).html('<img src="' + images.location + 'wait.gif" width="16" height="16" alt="Removing part from folder" title="Removing part from folder" border="0">');
							
						// Update the Parts counter and the parts folder icon
						// TODO: Put this in the success callback function
						this.updateParts(-1);
					
						// Ajax this part out of the parts folder session
						$.ajax({
							url: "folder/unsave.php",
							cache: false,
							type: "POST",
      						data: ({partID : partID}),
      						success: function(){
								
								// UnAjax this part into a session
								location.href = 'index.php?p=home&folder=true';
					
							},
							error: function() {
								
								alert('Sorry, this part could not be removed from your parts folder, please try again.');
							
							}
						});
									
					},
	
	updateParts : function(no) {
					
						this.count = parseInt(this.count) + parseInt(no);
					
						$('#partsFolderIcon').html('<img src="' + images.location + 'partsFolderSmall.png" alt="View your Parts Folder (' + this.count + ' Parts)" title="View your Parts Folder (' + this.count + ' Parts)" width="16" height="16" border="0">');
								
					},
					
	singleEnquiry : function(partID) {
					
						if (!user.loggedin) {
							
							user.next = 'se';
							join.form();	
							
						} else {
							
							$('#enquiry' + partID).html('<img src="' + images.location + 'wait.gif" width="16" height="16" alt="Enquiring about this part" title="Enquiring about this part" border="0">');
					
							this.doSingleEnqiry(partID);
							
						}
					
					},
					
	singleEnquiryDone : function(result) {
					
						if (result == 'fail') {
						
							alert("This enquiry failed, please contact the dealer directly.");
							
						} else {
						
							alert("An enquiry about this part has been sent\n\nThe dealer will contact you shortly.");
							
						}
						
					},
					
	doSingleEnqiry : function(partID) {
					
						// Ajax this part into a session
						$.ajax({
							url: "folder/enquire.php",
							cache: false,
							type: "POST",
      						data: ({partID : partID}),
      						success: function(result){
								
								data = $.secureEvalJSON(result);
								
								var failHTML = '<img src="' + images.location + 'failSingleContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.singleEnquiryDone(\'fail\');" alt="Enquire failed!" title="Enquiry failed!">';
								var successHTML = '<img src="' + images.location + 'doneSingleContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.singleEnquiryDone(\'done\');" alt="Enquire sent!" title="Enquiry sent!">';
								
								if (data.result == 'login') {
								
									var message = "Enquiry Failed!\n\nPlease make sure that you are logged in.";
									$('#enquiry' + partID).html(failHTML);
								
								} else if (data.result == 'folder') {
									
									var message = "Enquiry Failed!\n\nPlease make sure that have parts in your folder!";
									$('#enquiry' + partID).html(failHTML);
						
								} else if (data.result == 'email') {
								
									var message = "Enquiry Failed!\n\nThis dealer has not provided a valid contact email address, please contact by phone, or in person.";
									$('#enquiry' + partID).html(failHTML);
								
								} else if (data.result == 'send') {
								
									var message = "Enquiry Failed!\n\nThis dealer has not provided a valid contact email address, please contact by phone.";
									$('#enquiry' + partID).html(failHTML);
								
								} else if (data.result == 'previousSuccess') {
								
									var message = "You have already made an enquiry about this part.\n\nThe dealer will contact you soon.";
									$('#enquiry' + partID).html(successHTML);
								
								} else if (data.result == 'previousFail') {
								
									var message = "You have already tried to make enquiry about this part.\n\nThe enquiry failed so please contact the dealer by phone.";
									$('#enquiry' + partID).html(failHTML);
								
								} else {
								
									var message = 'You enquiry has ben successfully sent';
									$('#enquiry' + partID).html(successHTML);
								
								}
								
								alert(message);
										
							},
							error: function() {
								
								$('#enquiry' + partID).html('<img src="' + images.location + 'failSingleContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.singleEnquiryDone(\'fail\');" alt="Enquire failed!" title="Enquiry failed!">');
								alert('Sorry, there was an error making this enquiry.');
							
							}
						});
					
					},
					
	multiEnquiry : function() {
				
						if (!user.loggedin) {
							
							user.next = 'me';
							join.form();	
							
						} else {
							
							$('#multyEnquiryDiv').html('<img src="' + images.location + 'wait.gif" width="24" height="24" alt="Enquiring about all parts in this folder" title="Enquiring about all parts in this folder" border="0">');
					
							this.doMultiEnqiry();
							
						}
					
					},
	
	multiEnquiryDone : function(result) {
					
						if (result == 'fail') {
						
							alert("One or all of these enquireis failed, please contact the dealer[s] directly.");
							
						} else {
						
							alert("An enquiry has been sent about ALL these parts\n\nThe dealer[s] will contact you shortly.");
							
						}
						
					},
					
	doMultiEnqiry : function() {
					
						// Contact dealers about all the part in the folder
						$.ajax({
							url: "folder/enquire.php",
							cache: false,
							type: "POST",
      						data: ({partID : 'all'}),
      						success: function(result){
								
								data = $.secureEvalJSON(result);
								
								var failHTML = '<img src="' + images.location + 'failContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.multiEnquiryDone(\'fail\');" width="32" height="32" alt="Failed enquires!" title="Failed enquires!" border="0">';
								
								if (data.result == 'login') {
									
									var message = "Enquiry Failed!\n\nPlease make sure that you are logged in.";
									$('#multyEnquiryDiv').html(failHTML);
									
								} else if (data.result == 'folder') {
									
									var message = "Enquiry Failed!\n\nPlease make sure that have parts in your folder!";
									$('#multyEnquiryDiv').html(failHTML);
									
								} else if (data.result == 'email') {
									
									var message = "Enquiry Failed!\n\nOne or more dealer[s] have not provided a valid contact email address, please contact by phone.";
									$('#multyEnquiryDiv').html(failHTML);
									
								} else {
									
									var message 			= '';
									
									var someSuccess 		= false;
									var someFailure 		= false;
									var somePreviousSuccess = false;
									var somePreviousFailure = false;
									
									if (typeof(data['success']) != 'undefined') {
										
										var success = data['success'];
										message 	+= data['success'].length + " parts success.";
										someSuccess = true;
										
										for (var id in data['success']) {
											
											var partID = data['success'][id];
											$('#enquiry' + partID).html('<img src="' + images.location + 'doneSingleContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.singleEnquiryDone(\'done\');" alt="Enquire sent!" title="Enquiry sent!">');
											
										}
									}
									
									if (typeof(data['failed']) != 'undefined') {
										
										var failed 	= data['failed'];
										someFailure = true;
										
										if(someSuccess) {
										
											message += "\n\n";
										
										}
										message += data['failed'].length + " part fail.";
										
										for (var id in data['failed']) {
											
											var partID = data['failed'][id];
											$('#enquiry' + partID).html('<img src="' + images.location + 'failSingleContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.singleEnquiryDone(\'fail\');" alt="Enquire failed!" title="Enquiry failed!">');
								
										}
										
									}
									
									if (typeof(data['previousSuccess']) != 'undefined') {
									
										var previousSuccess 	= data['previousSuccess'];
										somePreviousSuccess 	= true;
										
										if(someSuccess || someFailure) {
										
											message += "\n\n";
										
										}
										message += data['previousSuccess'].length + " part[s] previously contacted.";
										
										for (var id in data['previousSuccess']) {
											
											var partID = data['previousSuccess'][id];
											$('#enquiry' + partID).html('<img src="' + images.location + 'doneSingleContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.singleEnquiryDone(\'done\');" alt="Enquiry previously sent." title="Enquiry previously sent.">');
								
										}
									
									}
									
									if (typeof(data['previousFailure']) != 'undefined') {
									
										var previousFailure 	= data['previousFailure'];
										somePreviousFailure 	= true;
										
										if(someSuccess || someFailure || somePreviousSuccess) {
										
											message += "\n\n";
										
										}
										message += data['previousFailure'].length + " part[s] previously failed to contact.";
										
										for (var id in data['previousFailure']) {
											
											var partID = data['previousFailure'][id];
											$('#enquiry' + partID).html('<img src="' + images.location + 'failSingleContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.singleEnquiryDone(\'fail\');" alt="Enquire previously failed." title="Enquire previously failed.">');
								
										}
									
									}
									
									$('#multyEnquiryDiv').html('<img src="' + images.location + 'doneContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.multiEnquiryDone(\'done\');" width="32" height="32" alt="Make enquiry about ALL these parts" title="Make enquiry about ALL these parts" border="0">');
									
								}
								
								alert(message);
										
							},
							error: function() {
								
								var failHTML = '<img src="' + images.location + 'failContact.png" style="cursor: pointer; cursor: hand;" onclick="parts.multiEnquiryDone(\'fail\');" width="32" height="32" alt="Failed enquires!" title="Failed enquires!" border="0">';
								$('#multyEnquiryDiv').html(failHTML);
								alert('Sorry, there was an error making this enquiry.');
							
							}
						});
					
					}
					

}

// }}}
