/******** An Tribute to Andy Gilmore (AKA Reverse-engineering) **********
Check out Andy Gilmore's inspiring works: http://crowquills.com/

**********Scripts sketched by Shanfan Huang (http://shanfan.tumblr.com)***************/

//Creating the hexagonal grid //

/**** Set the universal style ****/
myStyle = {
    fillColor: '#ffffff',
    strokeColor: '#ffffff',
    strokeWeight: 1
}

/**** Create the mother hexagon ****/
var gridSize = 200;
var center = document.bounds.topLeft;
var myHex = new Path.RegularPolygon(center, 6, gridSize/2);
myHex.rotate(90);

var wStep = myHex.bounds.width/2;
var hStep = myHex.bounds.height/2;

myHex.position = new Point(wStep, hStep);
myHex.style = myStyle;
myHex.opacity=.5;
myHex.blendMode='multiply';

/**** Create a matrix of the hexagons to cover the whole artboard ****/
var myHexs = [];
for (i = 0; i< document.bounds.width/wStep; i++){
    for (j=0; j< document.bounds.height/hStep; j++){   
        if (i==0 && j==0){
            myHexs[i,j] = myHex;
        }else{
            myHexs[i,j] = myHex.clone();
            myHexs[i,j].position = new Point((i+1)*wStep, (j+1)*hStep);
        }
        
    /**** Create a smaller hexagon set around the mother hexagon ****/
        for (n = 0; n < myHexs[i,j].segments.length; n++){
            if (n%3 == 0){
                var hex = new Path.RegularPolygon(myHexs[i,j].segments[n].point, 6, gridSize/16);
                hex.style = myStyle;
                hex.rotate(90);
                hex.opacity = .2;
                hex.blendMode = 'overlay'
            }else if (n%2 ==0){
                var hex = new Path.RegularPolygon(myHexs[i,j].segments[n].point, 6, gridSize/8);
                hex.style = myStyle;
                hex.rotate(90);
                hex.opacity = .2;
                hex.blendMode = 'overlay'
            }
            var hex = new Path.RegularPolygon(myHexs[i,j].segments[n].point, 6, gridSize/4);
            hex.style = myStyle;
            hex.rotate(90);
            hex.opacity = .2;
            hex.blendMode = 'overlay'
        }
    }
}

// Pickup colors from a raster//
//NOTE: An image must be placed within the artboard and rastered//
document.selectAll();
var rasters = document.getItems({
    type: Raster,
    selected: true
});

var paths = document.getItems({
    type: Path,
    selected: true
});

if(rasters.length >0 && paths.length >0){
    var raster = rasters[0];
    for(var i=0; i<paths.length; i++) {
        var path = paths[i];
        var color = raster.getAverageColor(path);
        path.fillColor = color;
    }
}else{
    Dialog.alert('Please place an image within the artboard, and rasterize it before executing the script.');
}
