/*
	FILE AND FUNCTIONS ADDED BY BRANDON HANSEN (http://melissa-brandon.com)
*/
$(function(){

	/********************* TOPICS START ******************************/


	// Stripes
	$('.category_list li:even').addClass('alternate');

	// Load search
	$('.ajax_category_search_button').live('click',function(){

		$('#category_search_list').css("display", "block"); 
		
		var url = document.getElementById("category_search_term_url").value + escape(document.getElementById("category_search_term").value);
		$('#category_search_list').html('Loading...').load(url);
		
		return false;
	});

	// Get sub categories
	$('.ajax_select_parent_category').live('click',function(){
		
		document.getElementById('browse_topics_div').style.visibility = "hidden";
		document.getElementById('browse_topics_div').style.display = "none";
		document.getElementById('single_topic_div').style.visibility = "visible";
		document.getElementById('single_topic_div').style.display = "block";


		$('#the_choosen_category').html( $(this).text() );
		$('#new_child_cat').html('Loading...').load($(this).attr('href'));

		return false;
	
	});

	$('.ajax_parent_category_close').live('click',function(){
		
		document.getElementById('browse_topics_div').style.visibility = "visible";
		document.getElementById('browse_topics_div').style.display = "block";
		document.getElementById('single_topic_div').style.visibility = "hidden";
		document.getElementById('single_topic_div').style.display = "none";

		$('#new_child_cat').html('');


		return false;
	});


	$('.ajax_add_topic').live('click', function(){

		$.ajax({
			url: $(this).attr('href'),
			success : function(html){
				$('#selected_topics').html(html);
			}
		});

		return false;
	});

	$('.ajax_remove_topic').live('click', function(){

		if (confirm('Are you sure that you want to remove this item?')) {

			$.ajax({
				url : $(this).attr('href')
			});
			$(this).parent().fadeOut('slow', function(){
				$(this).remove();
			});
		}
		return false;
	});

	/********************* TOPICS END ********************************/



	$('.ajax_toggle_recommendations_green_text').live('click',function(){
		
		$.ajax({
			url: $(this).attr('value') + '/' + $(this).attr('checked')
		});
		
		return true;
	});

	$('.ajax_toggle_review_green_text').live('click',function(){
		
		$.ajax({
			url: $(this).attr('value') + '/' + $(this).attr('checked')
		});
		
		return true;
	});

// Add more fields via ajax
	$('.ajax_add_fields').live('click',function(){
	
		var place_holder = $(this).text();
		$(this).text('Loading...');
		
		// Get the requested data from the site
		var response = $.ajax({
							url : $(this).attr('href'),
							async : false
						}).responseText;
		$(this).before(response);
		
		// Convert back to the original text
		$(this).text(place_holder);
		
		// Do not allow the click method to bubble up any longer
		return false;
	});
	
	
	
	
	
	
	
	
	
	
	
	$('.ajax_remove_possible_combination').live('click', function(){
				
		$.ajax({
			url: $(this).attr('value')
		});

		$(this).parent().parent().remove();
		
		return false;
	});
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	// Remove a parent item
	$('.remove_parent').live('click', function(){
		
		if (confirm('Are you sure that you want to remove this item?')) {
			
			// Make an ajax call first
			$.ajax({
				url: $(this).attr('href')
			});
			
			// Add a yellow highlight to the div when it is being removed
			$(this).parent().css('background-color', '#ffffcc');
			
			$(this).parent().fadeOut(1500, function(){
				// It has faded out, but we need to remove it from the DOM
				$(this).remove();
			});
		}
		
		// Do not allow the click method to bubble up any longer
		return false;
	});
	
	/*
	// Save topics
	$('.save_topics_form').live('submit', function(){
		// Save all of the subtopics
		save_subtopics();
		
		$.ajax({
			url : $(this).attr('action'),
			async : false,
			data : $(this).serialize(),
			type : 'POST',
			success : function(){
				alert('Topics were saved');
				// Now get rid of all the form fields
				$('#root_topic_input').val('0');
				$('.sub_topic_input').each(function(){
					$(this).remove();
				});
				
				$('.selected_sub_topic').removeClass('selected_sub_topic');
			}
		});
		
		return false;
	});
	*/
	
	// Client keywords and descriptions form submission.
	// Validate to make sure that everything is filled in
	$('#client_keywords_descriptions_form').submit(function(){
	
		// Validate
		if(validate_fields('client_keywords_descriptions_form') == false) {
			return false;
		}
		
	});
	

	$('.remove_order_baskets_qty_ajax').click(function(){
		$.ajax({
			url : $(this).attr('href')
		});
		
		$(this).parent().parent().fadeOut();
		return false;
	});
	
	// Make sure that there is a single radio checked
	$('#order_overview_form input[name = action]').click(function(){
		
		if ($(this).val() !== 'New Order') {
			var $continue = false;
			$('#order_overview_form input[type = radio]').each(function(){
				if ($(this).attr('checked') == true) {
					$continue = true;
				}
			});
			if ($continue == false) {
				alert('You must first select an order');
				return false;
			}
		}
	});
		
	$('.recommendation_qty').live('keyup',function(){
		// Calculate single price
		calculate_single_price($(this));
		calculate_subtotal_quantity();
		calculate_subtotal_price();
		//$(this).select();
	});

});

// Function calculate single price
function calculate_single_price(obj){
	
	// Check to make sure that a number was entered
	if(!validate_number(obj.val())) obj.val(0);
	//remove leading zeros
	obj.val(remove_front_zeros(obj.val()));
	// check to see if it's blank
	if(obj.val().length == 0) obj.val(0);
	// check that it's not more than recommended qty
	//currently don't need: if(obj.val() > parseInt(obj.attr('jquery_var_qty'))) { alert("Value cannot exceed recommended quanity."); obj.val(parseInt(obj.attr('jquery_var_qty'))); obj.focus(); }

	// Do price
	var new_price = obj.val() * parseFloat(obj.attr('jquery_var_cost'));
        new_price = new_price.toFixed(2);
    var formatted_price = number_format(new_price, 2, ".",",");
	obj.parent().next().html('$' + formatted_price);
	obj.parent().next().attr('id', new_price);
}

function calculate_subtotal_quantity(){
	var total_quantity = 0;
	$('.recommendation_qty').each(function(){
		total_quantity += parseInt($(this).val());
	});
	
	$('#recommendation_subtotal_quantity').html(total_quantity);
}

function calculate_subtotal_price(){
	var temp_total_price = 0;
	$('.totals').each(function(){
		temp_total_price += parseFloat($(this).attr('id'));
                total_price = temp_total_price.toFixed(2);
	});

	var formatted_total = number_format(total_price, 2, ".",",");
   
	$('#recommendation_subtotal_cost').html('$' + formatted_total);
}
function number_format (number, decimals, dec_point, thousands_sep) {

	var n = number, prec = decimals;

	var toFixedFix = function (n,prec) {
		var k = Math.pow(10,prec);
		return (Math.round(n*k)/k).toString();
	};

	n = !isFinite(+n) ? 0 : +n;
	prec = !isFinite(+prec) ? 0 : Math.abs(prec);
	var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
	var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

	var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

	var abs = toFixedFix(Math.abs(n), prec);
	var _, i;

	if (abs >= 1000) {
		_ = abs.split(/\D/);
		i = _[0].length % 3 || 3;

		_[0] = s.slice(0,i + (n < 0)) +
			  _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
		s = _.join(dec);
	} else {
		s = s.replace('.', dec);
	}

	var decPos = s.indexOf(dec);
	if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
		s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
	}
	else if (prec >= 1 && decPos === -1) {
		s += dec+new Array(prec).join(0)+'0';
	}
	return s;
}


// Check to see that a positive integer (no floats) was entered in
function validate_number(num){
	//this doesn't work... if( !isNaN(num) ) return false;
	if( num >= 0 && num.indexOf('.') == -1 ) return true;
	return false;
}
function remove_front_zeros(num){
	 return num.replace(/^[0]+/g,"");
}
	 
function validate_fields(form_id){
	var valid = true;
	$('form#' + form_id + ' input').each(function(){
		if($(this).val() == ''){
			$(this).addClass('error');
			valid = false;
			window.scrollTo(0,0);
			$('#validation_errors').show();
		}
		else {
			$(this).removeClass('error');
		}
	});
	
	return valid;
}

/*
// Save the subtopics
function save_subtopics(){
	$('.selected_sub_topic').each(function(){
		$(this).after('<input type="hidden" name="sub_topic[]" class="sub_topic_input" value="' + $(this).attr('id') + '" />');
	});
}
*/

