$(document).ready(function() {
	// make our jquery ajax calls compatible with the rails respond_to js
	$.ajaxSetup({ 
	  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
	});

  $('a[id^=delete-]').livequery('click', function() {
    var parts = $(this).attr('id').split('-');
    var thing = wordToUpper(parts[1]);
    if (confirm('You are about to DELETE this ' + thing + '.  This operation is PERMANENT and CAN NOT be undone.  Are you sure you wish to proceed?')) {
      var url = $(this).attr('href');
      var id = parts[2];
			var opts = {'authenticity_token':AUTH_TOKEN, '_method':'delete'};
			$.post(url, opts, function(data) {
			  var str = '#' + parts[1] + '-row-' + parts[2];
			  $(str).remove();
			});
    }
    return false;
  });
  
  $('a[id^=destroy-oil-]').livequery('click', function() {
    var parts = $(this).attr('id').split('-');
    if (confirm('You are about to DELETE this Oil.  This operation is PERMANENT and CAN NOT be undone.  Are you sure you wish to proceed?')) {
      var url = $(this).attr('href');
      var id = parts[2];
			var opts = {'authenticity_token':AUTH_TOKEN, '_method':'delete'};
			$.post(url, opts, function(data) {
			  var str = '#oil-cell-' + parts[2];
			  $(str).replaceWith("<td width='233' height='233' valign='bottom' align='center'>&nbsp;</td>");
			});
    }
    return false;
  });

  $('a[id^=destroy-veggie-]').livequery('click', function() {
    var parts = $(this).attr('id').split('-');
    if (confirm('You are about to DELETE this Vegetable and the Product Codes associated with it.  This operation is PERMANENT and CAN NOT be undone.  Are you sure you wish to proceed?')) {
      var url = $(this).attr('href');
      var id = parts[2];
			var opts = {'authenticity_token':AUTH_TOKEN, '_method':'delete'};
			$.post(url, opts, function(data) {
			  var str = '#vegetable-cell-' + parts[2];
			  $(str).replaceWith("<td width='155' height='155' valign='bottom' align='center'>&nbsp;</td>");
			});
    }
    return false;
  });

  $('#prepared-veggies').livequery('click', function() {
    window.location.href = vegetables_path();
  });
  
  $('#infused-oils').livequery('click', function() {
    window.location.href = oils_path();
  });

  $('#fetch-new-vegetable-processing').livequery('click', function() {
    var new_id = new Date().getTime();
    var template = vegetable_processing.replace(/NEW_RECORD_VEGETABLE_PROCESSING/g, new_id);
    $(this).siblings('.vegetable-processings').append(template);
    return false;
  });
  
  $('#remove-this-vegetable-processing').livequery('click', function() {
    $(this).parents('.vegetable-processing-div').remove();
    return false;
  });

  $('#fetch-new-product-code').livequery('click', function() {
    var new_id = new Date().getTime();
    var veggie_id = $(this).parents('.vegetable-processing-div').attr('id');
    var tmp = product_code.replace(/NEW_RECORD_VEGETABLE_PROCESSING/g, veggie_id);
    var template = tmp.replace(/NEW_RECORD_PRODUCT_CODE/g, new_id);
    $(this).siblings('.product-codes').append(template);
    return false;
  });
  
  $('#remove-this-product-code').livequery('click', function() {
    $(this).parents('.product-code-div').remove();
    return false;
  });

	$('.home-logo').livequery('click', function() {
		window.location.href = '/';
	})
	
	$('div#view-all-vegetables').livequery('click', function() {
		window.location.href = vegetables_path();
	});

	$('div[id^=back_to_vegetable_]').livequery('click', function() {
	  var slug = $(this).attr('id').split('_')[3];
		window.location.href = vegetable_path(slug);
	});

	$('div#view-all-oils').livequery('click', function() {
		window.location.href = oils_path();
	});
	
	$('#full-report').livequery('click', function() {
		window.location.href = crop_reports_path();
	});
	
	$('#about-us-innovation').livequery('click', function() {
		window.location.href = innovation_path();
	});

	$('#about-us-family').livequery('click', function() {
		window.location.href = family_path();
	});

	$('#about-us-company').livequery('click', function() {
		window.location.href = company_path();
	});
	
	$('.au-back-to-main-page').livequery('click', function() {
		window.location.href = about_us_path();
	});
	
	$('#family-next-page').livequery('click', function() {
		window.location.href = innovation_path();
	});

	$('#company-next-page').livequery('click', function() {
		window.location.href = family_path();
	});
	
	$('#back-button').livequery('click', function() {
		window.location.href = entry_pins_path();
	});
	
	$('#capabilities-button').livequery('click', function() {
		window.location.href = capabilities_path('index');
	});
	
	$('#learn-more').livequery('click', function() {
		window.location.href = capabilities_path('index');
	});
	
	$('#recipe-image').livequery('click', function() {
	  var url = $(this).find('#current-recipe-link').attr('href');
	  window.location.href = url;
	});
	
	// ajaxify the paginate links on the company page
	$('#company-cell-3 .pagination a').livequery('click', function() {
	  $.get($(this).attr('href'), function(data) {
	    $('.company-news-row').remove();
	    $('#company-news').append(data);
	  });
	  return false;
	});
	
	$('#products-prepared_veggies,#products-infused_oils').livequery('mouseover', function() {
		var name = $(this).attr('id').split('-')[1];
		var img = '/images/' + name + '_over.jpg';
		$(this).attr('src', img);
	}).livequery('mouseout', function() {
		var name = $(this).attr('id').split('-')[1];
		var img = '/images/' + name + '.jpg';
		$(this).attr('src', img);
	});

	$('#infused_oils_button,#infused_oils_ad,#roasting_button,#roasting_ad,#shelf_stable_button,#shelf_stable_ad,#freezing_button,#freezing_ad').livequery('click', function() {
		var name = extractNameAndTypeFromId($(this).attr('id'), '_').name;
		window.location.href = capabilities_path(name);
	}).livequery('mouseover', capabilitiesMenu).livequery('mouseout', capabilitiesMenu);

	$('#register-button').livequery('click', function() {
		window.location.href = new_user_path();
	});
	
	markDownState();
});

function extractNameAndTypeFromId(id, delim) {
	var parts = id.split(delim);
	var type = parts.pop();
	var name = parts.join(delim);
	return {'type':type, 'name':name};
}

function capabilitiesMenu(evt) {
	var nt = extractNameAndTypeFromId($(this).attr('id'), '_');
	var button = '#' + nt.name + '_button';
	var ad = '#' + nt.name + '_ad';
	var url = window.location.pathname;
	
	if (evt.type == 'mouseover') {
		var img = '/images/' + nt.name + '_ad_2.jpg';
		var bgpos = '0 -21px';
	} else if (evt.type == 'mouseout') {
		var img = '/images/' + nt.name + '_ad.jpg';
		var bgpos = '0 0';
	}
	
	if (!url.match(nt.name)) {
		$(button).css('background-position', bgpos);
	}
	
	$(ad).attr('src', img);
}

function markDownState() {
  var map = false;
	var name = null;
	var parts = window.location.pathname.split('/');
	var mapping = {
		'products':['vegetables', 'oils'],
		'about_us':['innovation','company','family'],
		'downloads':['product-list','haacp-protocols','kosher-certificate','organic-certificates','primus-audits']
	}

	for (m in mapping) {
		if ($.inArray(parts[1], mapping[m]) >= 0) {
			name = m;
			map = true;
		}
	}

	if (!name) {
		name = parts[1];
	}
	
	var element = '#' + name + '-link';
	
	if (map) {
	  var t = ',#' + parts[1] + '-link';
	  element += t;
	}
	
	$(element).css('text-decoration', 'underline');
	$(element).css('color', '#828282');
}

function wordToUpper(strSentence) {
  var tmp = strSentence.replace('_', ' ');
  return tmp.toLowerCase().replace(/\b[a-z]/g, convertToUpper);

  function convertToUpper() {
    return arguments[0].toUpperCase();
  }
}

function swapCreationThumbnail(ele, img) {
  $('#'+ele).attr('src', img);
}

function makeCenterAd(url, img) {
  $('#center_ad').attr('src', img);
  $('#center_url').attr('href', url);
}
