var slider_interval = 5; // Interval time per slide in seconds
var timer;

jQuery.fn.exists = function(){return jQuery(this).length>0;}

jQuery.fn.defaultColorbox = function() {
	$(this).colorbox({
		opacity: .4,
		innerWidth: '620px'
	});
};

jQuery.fn.categorySortable = function(){
	$(this).sortable({ handle: $("li.sortable-category > .partsList"), opacity: 0.6, cursor: 'move', update: function(event, ui) {
		var order = $(this).sortable("serialize");
		$.post(global_siteurl+"/ajax/update_category_order/", order, function(data){
			$("#response").html(data.message).stop(true,true).fadeIn(500);
			if(typeof responseTimer != 'undefined') {
				clearTimeout(responseTimer);
			}
			responseTimer = setTimeout(function() { $('#response').fadeOut(1500); }, 4000);
		}, 'json');
	}
	});
	$(this).disableSelection();
};

jQuery.fn.partSortable = function() {
	$(this).sortable({
		handle: $("li.sortable-part"),
		opacity: 0.6,
		cursor: 'move',
		connectWith: ".sortableParts",
		update: function(event, ui) {
		var order = $(this).sortable("serialize");
		var category = $(this).attr('id');
		var postStr = order + "&category=" + category;
		$.post(global_siteurl+"/ajax/update_parts_order/", postStr, function(data){
			$("#response").html(data.message).stop(true,true).fadeIn(500);
			if(typeof responseTimer != 'undefined') {
				clearTimeout(responseTimer);
			}
			responseTimer = setTimeout(function() { $('#response').fadeOut(1500); }, 4000);
		}, 'json');
	}
	});
	$(this).disableSelection();
}

jQuery.fn.updateParts = function(id, category_id, part_num, stock_num, aircraft, description) {
    var o = $(this[0]);
    
    if($('li#part_'+id).exists()) {
    	if($('li#part_'+id).parent('ul').attr('id') != category_id) {
    		var content = $('li#part_'+id).html();
    		$('li#part_'+id).remove();
    		$('ul#'+category_id).append('<li id="part_'+id+'" class="ui-state-default">'+content+'</li>');
			$('a.cboxElement').defaultColorbox();
    	}
    	else {
	    	$('li#part_'+id+' tr td:nth-child(1)').html(part_num);
	    	$('li#part_'+id+' tr td:nth-child(2)').html(stock_num);
	    	$('li#part_'+id+' tr td:nth-child(3)').html(aircraft);
	    	$('li#part_'+id+' tr td:nth-child(4)').html(description);
    	}
    }
    else {
    	$('ul#'+category_id).append('<li class="ui-state-default" id="part_'+id+'"><table class="partsList"><tbody><tr><td width="30%">'+part_num+'</td><td width="30%">'+stock_num+'</td><td width="20%">'+aircraft+'</td><td width="13%">'+description+'</td><td width="7%"><a href="'+global_siteurl+'/ajax/add_part_modal/'+id+'" class="editDelete cboxElement"><img src="'+global_siteurl+'/images/edit-icon.gif"></a><a href="'+global_siteurl+'/ajax/delete_part_modal/'+id+'" class="editDelete cboxElement"><img src="'+global_siteurl+'/images/delete-icon.gif"></a></td></tr></tbody></table></li>');
	
		$('a.cboxElement').defaultColorbox();
    }
    
   	$('li#part_'+id+' td').effect('highlight', {}, 6000);
};

jQuery.fn.updateCategories = function(id, name) {
    var o = $(this[0]);
    
    if($('li#category_'+id).exists()) {
    	$('li#category_'+id+' > table td:nth-child(1)').html(name);
    }
    else {
    	$('ul#sortable').append('<li class="ui-state-default" id="category_'+id+'"><table class="partsList"><tbody><tr><td class="subHeading" width="93%">'+name+'</td><td class="subHeading" width="7%"><a href="'+global_siteurl+'/ajax/add_category_modal/'+id+'" class="editDelete cboxElement"><img src="'+global_siteurl+'/images/edit-icon.gif"></a><a href="'+global_siteurl+'/ajax/delete_category_modal/'+id+'" class="editDelete cboxElement"><img src="'+global_siteurl+'/images/delete-icon.gif"></a></td></tr></tbody></table><ul class="sortableParts" id="'+id+'"> </ul>');
    	
    	$(".sortableParts").partSortable();
    }
    
   	$('li#category_'+id+' > table td').effect('highlight', {}, 6000);
};

$(document).ready(function() {
	var slider = $(".slider ul");

	// Generate the slide indicators
	var html = '';
	for (i=1;i<=slider.children("li").length;i++) {
		html += '<li><a href="#">' + i + '</a></li>';
	}
	html = '<div class="navigator"><ul>' + html + '</ul></div>';
	$(".slider_wrapper").append(html);

	var navigator = $(".navigator ul");
	slider.children("li").hide();
	slider.children("li:first-child").show();
	navigator.children("li:first-child").addClass("current");

	$(".navigator li").click(function() {
		if (is_relaxed()) {
			var index = $(this).index();

			// Set the corresponding image
			slider.children("li:visible").fadeOut("slow");
			slider.children("li").eq(index).fadeIn("slow");
			
			// Set the correct indicator
			navigator.children("li").removeClass("current");
			navigator.children("li").eq(index).addClass("current");
			
			// Reset the timer
			reset_timer();
		}
	});
	
	// Scroll to top buttons
	$('.backtotop').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow');

		return false;
	});
	
	$('#pageLinks a').click(function() {
		$('html, body').animate({scrollTop: $($(this).attr('href')).offset().top-50}, 800);
		
		return false;
	});
	
	$('form.twoColForm').live('submit',function() {
		var dataStr = "";
		var formId = $(this).attr('id');
		var valid = true;
		$(this).children().children('input, select, option, textarea').not('input[type="submit"]').each(function() {
			if($(this).attr('required') !== undefined && $(this).val() == "") {
				$(this).addClass('invalid');
				valid = false;
			}
			else $(this).removeClass('invalid');
			dataStr = dataStr + $(this).attr('name') + "=" + $(this).val() + "&";
		});
		
		if(!valid) {
			$('.futureResponse').removeClass('.futureResponse').attr('id','response').css('display','block').html('Please fill in the required fields.');
			return false;
		}
		
		var formAction = $(this).attr('action');
		if(formId == "addCategoryForm") {
			var categoryName = $(this).children().children('input[type="text"]').val();
			if($(this).children().children('input[type="hidden"]').exists()) {
				var categoryId = $(this).children().children('input[type="hidden"]').val();
			}
		}
		else if(formId == "deletePartForm") {
			var partId = $(this).children().children('input[type="hidden"]').val();
		}
		else if(formId == "deleteCategoryForm") {
			var categoryId = $(this).children().children('input[type="hidden"]').val();
		}
		else if(formId == "emailForm") {
			$('.futureResponse').removeClass('.futureResponse').attr('id','response');
			$(this).hide(500);
		}
		
		if(formId != "cancelForm") {
			$.post(formAction, dataStr, function(data) {
				if(jQuery.isFunction($.colorbox)) {
			  		$.colorbox.close();
				}
			  	
			  	if(typeof data.redirect != 'undefined') {
			  		window.location = data.redirect;
			  	}
			  	if(typeof data.message != 'undefined') {
				    $('#response').html(data.message).stop(true,true).fadeIn(500);
					if(typeof responseTimer != 'undefined') {
						clearTimeout(responseTimer);
					}
					responseTimer = setTimeout(function() { $('#response').fadeOut(1500); }, 4000);
			  	}
			  	
				if(formId == "addCategoryForm") {
					$('ul#sortable').updateCategories(data.id,data.name);
				}
				else if(formId == "deleteCategoryForm") {
					$('ul li#category_'+categoryId).fadeOut(1000);
					setTimeout(function() {
						$('ul li#category_'+categoryId).remove();
					}, 1000);
				}
				else if(formId == "deletePartForm") {
					$('ul li#part_'+partId).fadeOut(1000);
					setTimeout(function() {
						$('ul li#part_'+partId).remove();
					}, 1000);
				}
				else if(formId == "addPartForm") {
					$('ul#sortable').updateParts(data.id,data.category_id,data.part_num,data.stock_num,data.aircraft,data.description);
				}
				
			}, 'json');
		}
		else {
			$.colorbox.close();
		}
		
		return false;
	});
	
	// Minimize and maximize the parts list section
	$('a.minMax').click(function() {
		var currentTR = $(this).parent().parent().next();
		var minimizeTD = new Array();
		var currentIndex = 0;
		
		if(currentTR.is(":visible")) var isVisible = true;
		else var isVisible = false;
		
		while(currentTR.children('td').attr('class') != 'subHeading' && currentTR.children() && currentIndex <=20) {
			minimizeTD[currentIndex] = currentTR;
			currentIndex += 1;
			currentTR = currentTR.next();
		}
		
		for(i=0;i<minimizeTD.length;i++) {
			if(isVisible) minimizeTD[i].hide();
			else minimizeTD[i].show();
		}
		
		if(isVisible) $(this).css('background','url(images/maximize.gif) no-repeat 0 9px');
		else $(this).css('background','url(images/minimize.gif) no-repeat 0 9px');
		
		return false;
	});
	
	if($('a.cboxElement').length) {
		$('a.cboxElement').defaultColorbox();
	}
	
	if($('#sortable').length) {
		$( "#sortable" ).categorySortable();
	}
	if($('.sortableParts').length) {
		$(".sortableParts").partSortable();
	}	

	// Set the auto timer
	reset_timer();

	function reset_timer() {
		window.clearInterval(timer);
		timer = window.setInterval(function() {
			navigator.children("li").removeClass("current");
			if (!slider.children("li:visible").is(":last-child")) {
				var index = slider.children("li:visible").fadeOut("slow").next().fadeIn("slow").index();
				navigator.children("li").eq(index).addClass("current");
			} else {
				slider.children("li:visible").fadeOut("slow");
				slider.children("li:first-child").fadeIn("slow").children("a").addClass("current");
				navigator.children("li").eq(0).addClass("current");
			}
		}, slider_interval * 1000);
	}
	
});

// Returns true if animation queue is clear, and false if there's an animation currently playing.
function is_relaxed() {
  var count = $("*:animated").size();
  
  if (count == 0) return true;    
  return false;
}
