window.MapAddresses = [];
var mapWindow = null;

function MapSingleProperty(address){
	if ($.inArray(this.value, window.MapAddresses) == -1)
				window.MapAddresses.push(address);
		
	OpenPropertiesMap();
}

function OpenPropertiesMap(){
	if (mapWindow != null && !mapWindow.closed){
		mapWindow.close();
		mapWindow = null;
	}
	
	if (window.MapAddresses.length == 0)
		return;
		
	mapWindow = window.open("PropertyMap.html", "mapWindow");
}

$(document).ready(function(){
	//ID for the "save properties" checkbox: cbxSaveProp
	//name of map property checkboxes: cbxMapProp
	$("[name='cbxMapProp']").click(function(){
		if (this.checked)
			if ($.inArray(this.value, window.MapAddresses) == -1)
				window.MapAddresses.push(this.value);
		else
			window.MapAddresses = $.grep(window.MapAddresses, function(itm){
				return itm != this.value;
			});
	});

	var savedProperties = [];
	var TJCCart = $.cookies.get('TJCCart');
	if (TJCCart && TJCCart.Properties)
			savedProperties = TJCCart.Properties.split(",");
			
	var mappedProperties = [];
	var mapCookie = $.cookies.get('MappedProperties');
	if (mapCookie && mapCookie.Properties)
			mappedProperties = mapCookie.Properties.split(",");
	
	$("input[name='cbxSaveProp']").each(function(){
		this.checked = $.inArray(this.value, savedProperties) != -1;
	});
	
	$("input[name='cbxMapProp']").each(function(){
		this.checked = $.inArray($(this).attr('propID'), mappedProperties) != -1;
	});
	
	$("input[name='cbxSaveProp']").click(function(){
		var savedProperties = [];
		var checkedItem = this;
		var TJCCart = $.cookies.get('TJCCart');
		if (TJCCart && TJCCart.Properties)
			savedProperties = TJCCart.Properties.split(",");
		
		if (checkedItem.checked && $.inArray(checkedItem.value, savedProperties) == -1)
			savedProperties.push(checkedItem.value);
		else if (!checkedItem.checked && $.inArray(checkedItem.value, savedProperties) != -1)
			savedProperties = $.grep(savedProperties, function(itm){
				return itm != checkedItem.value;
			});

		$.cookies.set('TJCCart', { Properties : savedProperties.join(",") },
			{
				domain: window.location.hostname,
				hoursToLive: 24 * 21
			});
	});
	
	$("input[name='cbxMapProp']").click(function(){
		var el = $(this);
		var mappedProperties = [];
		var mapCookie = $.cookies.get('MappedProperties');
		if (mapCookie && mapCookie.Properties)
			mappedProperties = mapCookie.Properties.split(",");
		
		if (this.checked && $.inArray(el.attr('propID'), mappedProperties) == -1)
			mappedProperties.push(el.attr('propID'));
		else if (!this.checked && inArray(el.attr('propID'), mappedProperties) != -1)
			mappedProperties = $.grep(mappedProperties, function(itm){
				return itm != el.attr('propID');
			});

		$.cookies.set('MappedProperties', { Properties : mappedProperties.join(",") },
			{
				domain: window.location.hostname,
				hoursToLive: 24 * 21
			});
	});
});