jQuery.ajaxSetup({
	'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

$(document).ready(function(){
	if ($("#MapContainer").length > 0) 
		load_map("MapContainer");
	if ($("#LargeMapContainer").length > 0) 
		load_map("LargeMapContainer");

	//Winery Admin page popups, AJAX, etc.
	do_winery_admin();
	
	//Comments popups, AJAX, etc.
	do_comments();
	
	//Adds Datepicker functionality for searches
	if ($(".date").length > 0) 	
		$(".date").datepicker();
		
	//Order.new recalculation functionality
	if ($("#order_tax_rate").length > 0)
		$("#shipping_combo").change( function (event) {
			recalculate_totals();
		});
	
	//Event_edit datepicker convenience function
	if ($("#start_date").length > 0)
		$("#start_date").change( function (event) {
			$("#end_date").attr("value", $(this).attr("value"));
		});
	
	//Amex/visa selectors, just for fun
	$("#visa").click( function () {
		$("#order_payment_type").children().each( function (index) {
			if (index != 0)
				$(this).removeAttr("selected");
			else
				$(this).attr("selected", "selected")
		})
	});
	$("#amex").click( function () {
		$("#order_payment_type").children().each( function (index) {
			if (index != 1)
				$(this).removeAttr("selected");
			else
				$(this).attr("selected", "selected")
		})
	});
	$("#mc").click( function () {
		$("#order_payment_type").children().each( function (index) {
			if (index != 2)
				$(this).removeAttr("selected");
			else
				$(this).attr("selected", "selected")
		})
	});
	$("#disc").click( function () {
		$("#order_payment_type").children().each( function (index) {
			if (index != 3)
				$(this).removeAttr("selected");
			else
				$(this).attr("selected", "selected")
		})
	});
	
	
	//Shows Winetrail's wineries on click
	$("#winetrailWineriesLink").click(function (event) {
		event.preventDefault();
		$("#winetrailWineries").fadeIn();
		$("#winetrailWineriesLink").slideUp();
	})
	//Enables State selector only if js is enabled
	enable_state_selector();
	
	manage_calendar();
	//Fancybox settings for maps and pictures
	if ($(".zoom").length > 0) 
		$(".zoom").fancybox({"scrolling": "no", "autoDimensions": true });
	if ($(".mapZoom").length > 0) 
		$(".mapZoom").fancybox({scrolling: "no", autoDimensions: false, width: 500, height: 500, "hideOnContentClick": false });
	
	$("#same").change(autofill_shipping);
	

});

/*################# Order recalculation ###########################*/
function recalculate_totals() {
	var shipping = parseFloat($("#shipping_combo").attr("value").split("|")[1]);
	var discount = to_number($("#discount").html());
	var tax_rate = parseFloat($("#order_tax_rate").attr("value"));
	
	var subtotal = 0;
	$(".subtotal").each( function () {
		subtotal += to_number($(this).html())
	});
	
	var tax = (subtotal + shipping - discount) * tax_rate
	var total = subtotal + shipping - discount + tax
	
	$("#tax").html(to_money(tax))
	$("#total").html(to_money(total))
	 
	//alert("Shipping=" + shipping + " discount=" + discount + " tax_rate=" + tax_rate + " subtotal=" + subtotal + " tax=" + tax + " total=" + total);
}

function to_number(original) {
	return parseFloat(original.substring(1)) * 100
}

function to_money(original) {
	return "$" + (Math.round(original) / 100).toFixed(2)
}

/*################# Winery Admin junk ##############################*/
function do_winery_admin() {
	//Attach popup behavior to click events
	$("#editBasicInfo").click(function (event) {
			event.preventDefault();
			$("#basicInfo").dialog({close: function(event, ui) { $("#currentEdit").removeAttr("id") }, modal: true, title: "<h2>EDITING: BASIC INFO</h2>", width: 520, height: 545});
			$(this).attr("id", "currentEdit");
		});
	$("#addNewAddress").click(function (event) {
			event.preventDefault();
			$("#newAddress").dialog({close: function(event, ui) { $("#currentEdit").removeAttr("id") }, modal: true, title: "<h2>ADDING: NEW ADDRESS</h2>", width: 520});
		});
	$("#addNewEvent").click(function (event) {
			event.preventDefault();
			$("#newEvent").dialog({close: function(event, ui) { $("#currentEdit").removeAttr("id") }, modal: true, title: "<h2>ADDING: NEW EVENT</h2>", width: 520});
		});
	$("#changeDirections").click(function (event) {
			event.preventDefault();
			$("#requestChanges").dialog({close: function(event, ui) { $("#currentEdit").removeAttr("id"); }, open: function(event, ui) { $(".changeForm").attr("value", ""); $("#field").attr("value", "directions"); }, modal: true, title: "<h2>REQUESTING CHANGES TO DIRECTIONS</h2>", width: 520, height: 478});
			$(this).attr("id", "currentEdit");
		});
    $("#changeDescription a").click(function (event) {
    		event.preventDefault();
    		$("#requestChanges").dialog({close: function(event, ui) { $("#currentEdit").removeAttr("id") }, open: function(event, ui) { $(".changeForm").attr("value", ""); $("#field").attr("value", "description"); }, modal: true, title: "<h2>REQUESTING CHANGES TO DESCRIPTION</h2>", width: 520, height: 478});
			$(this).attr("id", "currentEdit");
    	});
	attach_events_for_address_edits();
	attach_events_for_event_edits();
	
	//Attach a function to clicking a submit button in a modal dialog that modifies the original link clicked in the page, closes the dialog, and opens the confirmation dialog
	$(".modal").click(function (event) {
		$("#currentEdit").parent().html("Changes Submitted");
		$(".noDisplay").dialog('close')
		$("#confirmation").dialog({modal: true, title: "<h2>CONFIRMATION</h2>", width: 450});
	});
	
	//Winery, address, event AJAX (new_event_edits are submitted directly to the event_edits controller)
	$("form.new_address_edit, form.new_winery_edit, form.new_change_request").submit(function (){
		$.post($(this).attr('action'), $(this).serialize(), null);
		return false;
	});
	$(".delete_address_edit").removeAttr('onClick');
	$(".delete_address_edit").click(function (event){
		event.preventDefault();
		$.post($(this).attr('href'), "_method=delete&authenticity_token=" + auth_token, null);
	});
	$(".delete_event_edit").removeAttr('onClick');
	$(".delete_event_edit").click(function (event){
		event.preventDefault();
		$.post($(this).attr('href'), "_method=delete&authenticity_token=" + auth_token, null);
	});
	
	//Validation for new_event_edits
	$("form.new_event_edit").submit( function () {
		results = "";
		if ($("#event_edit_name").attr("value") == "") results += "Event Name must be filled out.<br />";
		if ($("#event_edit_description").attr("value") == "") results += "Description must be filled out.<br />";
		if ($("#event_edit_phone").attr("value") == "") results += "Phone must be filled out.<br />";
		if ($("#start_date").attr("value") == "") results += "Start Date must be filled out.<br />";
		if ($("#end_date").attr("value") == "") results += "End Date must be filled out.<br />";
		if (results) {
			$("#validation").html(results);
			return false;
		}
	})
}

function attach_events_for_address_edits() {
	$(".addressEdit").each( function(index) {
		$(this).click( function(event) {
			event.preventDefault();
			$("#address" + index).dialog({close: function(event, ui) { $("#currentEdit").removeAttr("id") }, modal: true, title: "<h2>EDITING: ADDRESS</h2>", width: 520});
			$(this).attr("id", "currentEdit");
		});
	});
}

function attach_events_for_event_edits() {
	$(".eventEdit").each( function(index) {
		$(this).click( function(event) {
			event.preventDefault();
			$("#event" + index).dialog({close: function(event, ui) { $("#currentEdit").removeAttr("id") }, modal: true, title: "<h2>EDITING: EVENT</h2>", width: 520});
			$(this).attr("id", "currentEdit");
		});
	});
}

/*############### Comments popup and AJAX ####################*/
function do_comments() {
	$(".commentComplain").click(function (event) {
		event.preventDefault();
		$("#comment_id").attr("value", $(this).attr("title"));
		$("#reportAbuse").dialog({modal: true, title: "<h2>Report Abuse</h2>", width: 520, height: 545});
	});
	
	$(".report_abuse").click(function (event){
		event.preventDefault();
		$.post($(this).attr('action'), $(this).serialize(), null);
	});
}
/*############### Autofill for Shipping Address ####################*/
function autofill_shipping() {
	$("#order_payment_first_name").attr("value", $("#order_first_name").attr("value"));
	$("#order_payment_last_name").attr("value", $("#order_last_name").attr("value"));
	$("#order_payment_street").attr("value", $("#order_street").attr("value"));
	$("#order_payment_city").attr("value", $("#order_city").attr("value"));
	$("#order_payment_state").attr("value", $("#order_state").attr("value"));
	$("#order_payment_zip").attr("value", $("#order_zip").attr("value"));
	$("#same").unbind().change(unautofill_shipping);	
}

function unautofill_shipping() {
	$("#order_payment_first_name").attr("value", "");
	$("#order_payment_last_name").attr("value", "");
	$("#order_payment_street").attr("value", "");
	$("#order_payment_city").attr("value", "");
	$("#order_payment_state").attr("value", "");
	$("#order_payment_zip").attr("value", "");
	$("#same").unbind().change(autofill_shipping);	
}

/*############### Search Functions ################*/
function reset_adv_search() {
	$("#advSearch")[0].reset();
}

/*############## State/region selector for region ####################*/
function enable_state_selector() {
	$("#state").attr("disabled", "").change(disable_regions);
	$("#region").change(disable_winetrails);
	disable_regions();
	disable_winetrails();
}

function disable_regions() {
	var state = $("#state").attr("value");
	if (state != "") {
		$("#region #state" + state).attr("disabled", "");
		$("#region optgroup[id!=state" + state + "]").attr("disabled", "disabled");
	}
	else {
		$("#region optgroup").attr("disabled", "");
	}
	
}

function disable_winetrails() {
	var region = $("#region").attr("value");
	if (region != "") {
		$("#winetrail #region" + region).attr("disabled", "");
		$("#winetrail optgroup[id!=region" + region + "]").attr("disabled", "disabled");
	}
	else {
		$("#winetrail optgroup").attr("disabled", "");
	}
}


/*############## Global Variables ##############*/
var map;
var directions;



/*############## Create Map ##############*/
function load_map(id)
{
	var locations = new Array(); 
	var bounds = new GLatLngBounds(); //Accessed by load_map()
	/*##### Check to make sure components are in place #####*/
	if (!GBrowserIsCompatible()) return false;
	var addresses = getElementsByClass('vcard', null, null);
	var map_container = document.getElementById(id);
	if (!map_container) return false;
	if (addresses.length < 1)
	{
		map_container.parentNode.removeChild(map_container);
		return false;
	}

	/*##### Parse addresses for locations[] #####*/
	for (var i=0; i<addresses.length; i++)
	{
		/*##### Get Lat+Lon #####*/
		var longitude_nodes = getElementsByClass('longitude', addresses[i], 'span');
		var latitude_nodes = getElementsByClass('latitude', addresses[i], 'span');
		
		if(longitude_nodes.length > 0 && latitude_nodes.length > 0)
		{
			var longitude = parseFloat(longitude_nodes[0].firstChild.nodeValue);
			var latitude = parseFloat(latitude_nodes[0].firstChild.nodeValue);
			var point = new GLatLng(latitude, longitude);
			var name = addresses[i].getAttribute('id');
			
			locations.push(new the_location(name, addresses[i].cloneNode(true), point));
			bounds.extend(point);
		}
	}
	
	/*##### Load GMap into Map Container #####*/
	map = new GMap2(map_container);
	var center = bounds.getCenter();
	var zoom = map.getBoundsZoomLevel(bounds);
	map.setCenter(center, zoom);
	map.addControl(new GSmallMapControl());
	

	/*##### Load Markers onto GMap #####*/
	for (var i=0; i<locations.length; i++)
	{
		map.addOverlay(locations[i].marker);
	}
	
	/*##### Add unload action to decrease memory leakage #####*/
	$(window).unload(GUnload);
	
	/*##### Make text smaller #####*/
	setTimeout('$("#MapContainer > div:eq(2)").css("font-size", "6px");', 500);
	setTimeout('$("#MapContainer > div:eq(2)").css("font-size", "6px");', 1000);
	setTimeout('$("#MapContainer > div:eq(2)").css("font-size", "6px");', 1500);
	setTimeout('$("#MapContainer > div:eq(2)").css("font-size", "6px");', 2000);
}

/*############## the_location Constructor ##############*/
/*############## (Firefox doesn't like "location") ##############*/
function the_location(name, address, point)
{
	this.name = name;
	this.point = point;
	var hours = getElementsByClass("hours", address, "div");
	if(hours.length > 0)
	{
		for(var i = 0; i < hours.length; i++)
		{
			hours[i].parentNode.removeChild(hours[i]);
		}
	}
	this.marker = createMarker(this.point, address, this.name);
}

/*##### GMarker Constructor w/ attached Functions #####*/
function createMarker(point, address, name)
{
	var marker = new GMarker(point); //GMarker(point, icon)
	GEvent.addListener(marker, "click", function() //attach infoWindow to marker
	{
		map.panTo(point);
		marker.openInfoWindowHtml(address);
	});
	GEvent.addDomListener(document.getElementById(name), "click", function()
	{
		map.panTo(point);
		marker.openInfoWindowHtml(address);
	});
	
	return marker;
}

function manage_calendar()
{
	if (!document.getElementById('MonthTable')) return false;
	var month_table = document.getElementById('MonthTable');
	var month_title = month_table.getAttribute('title');
	
	var current_year = new Number(month_title.match(/^\d{4}/));
	var current_month = new Number(month_title.match(/\d{2}$/));
	
	if (current_month == 12)
	{
		var previous_year = current_year;
		var previous_month = current_month - 1;
		var following_year = current_year + 1;
		var following_month = 1;
	}
	else if (current_month == 1)
	{
		var previous_year = current_year - 1;
		var previous_month = 12;
		var following_year = current_year;
		var following_month = current_month + 1;
	}
	else
	{
		var previous_year = current_year;
		var previous_month = current_month - 1;
		var following_year = current_year;
		var following_month = current_month + 1;
	}
	if (previous_month < 10) previous_month = '0' + previous_month;
	if (following_month < 10) following_month = '0' + following_month;

	var previous_month_link = document.createElement('a');
	previous_month_link.appendChild(document.createTextNode('<<'));
	previous_month_link.setAttribute('title', previous_year+'-'+previous_month);
	previous_month_link.onclick = load_month;

	var following_month_link = document.createElement('a');
	following_month_link.appendChild(document.createTextNode('>>'));
	following_month_link.setAttribute('title', following_year+'-'+following_month);
	following_month_link.onclick = load_month;
	
	month_table.getElementsByTagName('caption')[0].insertBefore(previous_month_link, month_table.getElementsByTagName('caption')[0].firstChild);
	month_table.getElementsByTagName('caption')[0].appendChild(following_month_link);
}
function load_month()
{	
	var this_year = this.getAttribute('title').match(/^\d{4}/); //first four digits
	var this_month = this.getAttribute('title').match(/\d{2}$/); //last two digits
	var request = getHTTPObject();
	if (request)
	{
		request.onreadystatechange = function() { parseCalendarResponse(request); };
		request.open('GET', '/events/browse/'+this_year+'/'+this_month+'?js=1', true);
		request.send(null);
	}
}
function parseCalendarResponse(request)
{
	if (request.readyState == 4)
	{
		if (request.status == 200 || request.status == 304)
		{
			var calendar_container = document.getElementById("calendar_container");
			calendar_container.innerHTML = request.responseText;
			manage_calendar();
		}
	}
}
/*##### Supporting Functions #####*/
function getElementsByClass(searchClass,node,tag)
{
	//Taken from http://www.dustindiaz.com/getelementsbyclass/
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function getHTTPObject()
{
	//Taken from Jeremy Keith's Bulletproof Ajax. Example can be found at http://bulletproofajax.com/code/chapter05/people/ajax.js
	var xhr = false;
	if (window.XMLHttpRequest)
	{
		xhr = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		try
		{
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				xhr = false;
			}
		}
	}
	return xhr;
}