var values = {
		sampleSize:					8,
		channel:					'RGB',
		invert:						false,
		crossHatchSize:				3,
		rasterize:					'Rasterize'
}

var components = {
		sampleSize:{
			type:					'number',
			label: 					'Size',
			steppers:				true,
		},
		channel:{
			type:					'list',
			label:					'Channel',
			options:				['RGB', 'Red', 'Green', 'Blue', 'Gray'],
		},
		invert:{
			type:					'boolean',
			label:					'Invert Colors',
		},
		crossHatchSize:{
			type:					'number',
			label:					'Size Divider',
			steppers:				true,
			increment:				0.5,
			units:					'point',
			min:					0.5,
		},
		rasterize:{
			type:					'button',
			onClick:				function(){
										var getRasters 						= document.getItems([Raster, PlacedFile], {selected: true})
										raster 								= getRasters.first
										if(raster instanceof PlacedFile && !raster.eps) raster = raster.embed(false)
										
										if(!raster) return

										var size					= values.sampleSize
										var sampleSize				= new Size(size, size)
										var rasterWidth				= raster.bounds.width
										var rasterHeight			= raster.bounds.height
										var offset					= raster.bounds.topLeft
										var columns					= Math.round(rasterWidth / size)
										var rows					= Math.round(rasterHeight / size)
								
										for(var y = 0; y < rows; y++){
											for(var x = 0; x < columns; x++){
							
										        var topLeft 	= offset + new Point(x, y) * sampleSize
												var rectangle 	= new Rectangle(topLeft, sampleSize)
												var color 		= raster.getAverageColor(rectangle)
							
												CrossHatch(x, y, sampleSize, color, values.channel, values.invert, values.crossHatchSize)
											}
										}
									}
		}

}

var palette = new Palette('Cross Hatch Raster', components, values)


function CrossHatch(x_coord, y_coord, size, color, channel, inverted, strokeSize){
		var r 						= (channel == 'Red') ? color.red : 0
		var g 						= (channel == 'Green') ? color.green : 0
		var b 						= (channel == 'Blue') ? color.blue : 0
	
		var col
		if(channel == 'RGB'){
			col 					= new RGBColor(color)
		} else if(channel == 'Gray'){
			col 					= new RGBColor(1 - color.gray, 1 - color.gray, 1 - color.gray)
		} else {
			col 					= new RGBColor(r, g, b)	
		}
	
		if(inverted){
			col.red 				= 1 - col.red
			col.green 				= 1 - col.green
			col.blue 				= 1 - col.blue
		}
		
		var pixel 					= new Path([
										new Point(x_coord + 0.5, y_coord) * size,
										new Point(x_coord + 0.5, y_coord + 1) * size
									])

		pixel.strokeWidth			= size.width / strokeSize
		pixel.strokeColor 			= col
		pixel.fillColor				= null
		pixel.rotate(Math.round(Math.random() * 4) * 90)
}