<commit_before>// To use this file:
// @import 'MovingImages.js';

function hexDigitToNumber(digit) {
  var hexDigitTable = '0123456789ABCDEF'
  for (i = 0 ; i < 16 ; ++i) {
    if (hexDigitTable[i] == digit) {
      return i
    }
  }
  return 0
}

// Assumes string is not prefixed with a #
function redComponent(hexString) {
  var number1 = hexDigitToNumber(hexString[0]) * 16.0
  var number2 = hexDigitToNumber(hexString[1])
  return (number1 + number2) / 255.0
}

function greenComponent(hexString) {
  var number1 = hexDigitToNumber(hexString[2]) * 16.0
  var number2 = hexDigitToNumber(hexString[3])
  return (number1 + number2) / 255.0
}

function blueComponent(hexString) {
  var number1 = hexDigitToNumber(hexString[4]) * 16.0;
  var number2 = hexDigitToNumber(hexString[5]);
  return (number1 + number2) / 255.0;
}

function miConvertAlphaColor(msColor) {
  var hexString = String(msColor.hexValue())
  var dictionary = {
    red: redComponent(hexString),
    green: greenComponent(hexString),
    blue: blueComponent(hexString),
    alpha: msColor.alpha(),
    colorcolorprofilename: 'kCGColorSpaceSRGB'
  };
  return dictionary;
}

function miConvertMSColor(msColor) {
  if (msColor.alpha() < 0.997) {
    return miConvertAlphaColor(msColor);
  }
  else {
    return msColor.hexValue();
  }
}

function miConvertMSRect(msRect) {
  return {
    size: {
      width: msRect.width(),
      height: msRect.height()
    },
    origin: {
      x: msRect.x(),
      y: msRect.y()
    }
  };
}

function miConvertStringToPoint(pointString) {
  var charactersToRemove = NSCharacterSet.characterSetWithCharactersInString('{} ');
  var strippedString = pointString.stringByTrimmingCharactersInSet(charactersToRemove);
  var commaSet = NSCharacterSet.characterSetWithCharactersInString(',');
  var components = strippedString.componentsSeparatedByCharactersInSet(commaSet);
  var x = components[0].doubleValue();
  var y = components[1].doubleValue();
  return {
    x: x,
    y: y
  };
}

function miConvertPointsToLine(pointsArray) {
  // MSGradientPointArray
  var thePoints = pointsArray.points();
  var startPoint = miConvertStringToPoint(thePoints[0]);
  var endPoint = miConvertStringToPoint(thePoints[1]);
  return {
    startpoint: startPoint,
    endpoint: endPoint
  };
}

/*
@import 'MovingImages.sketchplugin';

miLog('This is the mi log text');

log(context);

var documentName = context.document.displayName();
log('The current document is named: ' + documentName);

var selectedLayers = context.selection;
var selectedCount = selectedLayers.count();

if (selectedCount == 0) {
  log('No layers are selected.');
} else {
  log('Selected layers:');
  for (var i = 0; i < selectedCount; i++) {
    var layer = selectedLayers[i];
    log((i+1) + '. ' + layer.class());
    if (layer.class() == 'MSShapeGroup') {
      var frame = layer.frame()
      miLog('Frame origin.x: ' + frame.x() + ' .y: ' + frame.y())
      miLog(miConvertMSRect(frame))
      // miLog(layer.layers())
      miLog(layer.treeAsDictionary())
      // var subLayers = layer.layers()
      // var subLayersCount = subLayers.count()
      // miLog(subLayers)
      // miLog('Num subLayers: ' + subLayersCount)
      // miLog(subLayers.treeAsDictionary())
      // subLayer = subLayers[0]
      // miLog(subLayer)
      // miLog(subLayer.class())
//      for (var j = 0; j < subLayersCount; ++j) {
//        miLog('i: ' + i 'j: ' + j + subLayers[j].class())
//      }
    }
    miLog('I am here')
    fill = layer.style().fills().objectAtIndex(0);
    miLog(fill.color())
    // fill.color = MSColor.colorWithSVGString("#d00");
    miLog(miConvertMSColor(fill.color()))
    var newColor = fill.color().colorWithAlpha(0.5);
    miLog(miConvertMSColor(newColor))
    miLog(newColor);
    miLog(newColor.hexValue());
    miLog(newColor.alpha());
  }
};

{
    "<class>" = MSShapeGroup;
    clippingMaskMode = 0;
    exportOptions =     {
        "<class>" = MSExportOptions;
        exportFormats =         {
            "<class>" = MSArray;
            "<items>" =             (
            );
        };
        includedLayerIds =         {
            "<class>" = MSArray;
            "<items>" =             (
            );
        };
        layerOptions = 0;
        shouldTrim = 0;
    };
    frame =     {
        "<class>" = MSRect;
        constrainProportions = 0;
        height = 14;
        objectID = "3D0A661B-176B-4AFC-9744-FFB212CD3E02";
        width = 117;
        x = "-1";
        y = "-112";
    };
    hasClickThrough = 0;
    hasClippingMask = 0;
    isFlippedHorizontal = 0;
    isFlippedVertical = 0;
    isLocked = 0;
    isVisible = 1;
    layerListExpandedType = 1;
    layers =     {
        "<class>" = MSArray;
        "<items>" =         (
                        {
                "<class>" = MSRectangleShape;
                booleanOperation = "-1";
                edited = 0;
                exportOptions =                 {
                    "<class>" = MSExportOptions;
                    exportFormats =                     {
                        "<class>" = MSArray;
                        "<items>" =                         (
                        );
                    };
                    includedLayerIds =                     {
                        "<class>" = MSArray;
                        "<items>" =                         (
                        );
                    };
                    layerOptions = 0;
                    shouldTrim = 0;
                };
                fixedRadius = 0;
                frame =                 {
                    "<class>" = MSRect;
                    constrainProportions = 0;
                    height = 14;
                    width = 117;
                    x = 0;
                    y = 0;
                };
                hasConvertedToNewRoundCorners = 1;
                isFlippedHorizontal = 0;
                isFlippedVertical = 0;
                isLocked = 0;
                isVisible = 1;
                layerListExpandedType = 0;
                name = Path;
                nameIsFixed = 0;
                objectID = "822F2FC3-36F1-43D7-B945-A53100E64E3F";
                path =                 {
                    "<class>" = MSShapePath;
                    isClosed = 1;
                    points =                     {
                        "<class>" = MSArray;
                        "<items>" =                         (
                                                        {
                                "<class>" = MSCurvePoint;
                                cornerRadius = 0;
                                curveFrom =                                 {
                                    x = 0;
                                    y = 0;
                                };
                                curveMode = 1;
                                curveTo =                                 {
                                    x = 0;
                                    y = 0;
                                };
                                hasCurveFrom = 0;
                                hasCurveTo = 0;
                                point =                                 {
                                    x = 0;
                                    y = 0;
                                };
                            },
                                                        {
                                "<class>" = MSCurvePoint;
                                cornerRadius = 0;
                                curveFrom =                                 {
                                    x = 1;
                                    y = 0;
                                };
                                curveMode = 1;
                                curveTo =                                 {
                                    x = 1;
                                    y = 0;
                                };
                                hasCurveFrom = 0;
                                hasCurveTo = 0;
                                point =                                 {
                                    x = 1;
                                    y = 0;
                                };
                            },
                                                        {
                                "<class>" = MSCurvePoint;
                                cornerRadius = 0;
                                curveFrom =                                 {
                                    x = 1;
                                    y = 1;
                                };
                                curveMode = 1;
                                curveTo =                                 {
                                    x = 1;
                                    y = 1;
                                };
                                hasCurveFrom = 0;
                                hasCurveTo = 0;
                                point =                                 {
                                    x = 1;
                                    y = 1;
                                };
                            },
                                                        {
                                "<class>" = MSCurvePoint;
                                cornerRadius = 0;
                                curveFrom =                                 {
                                    x = 0;
                                    y = 1;
                                };
                                curveMode = 1;
                                curveTo =                                 {
                                    x = 0;
                                    y = 1;
                                };
                                hasCurveFrom = 0;
                                hasCurveTo = 0;
                                point =                                 {
                                    x = 0;
                                    y = 1;
                                };
                            }
                        );
                    };
                };
                rotation = 0;
                shouldBreakMaskChain = 0;
            }
        );
    };
    name = "Rectangle 3";
    nameIsFixed = 0;
    objectID = "9FF2A2BB-D9E0-45E6-910A-22DCED315D65";
    rotation = 0;
    shouldBreakMaskChain = 0;
    style =     {
        "<class>" = MSStyle;
        blur =         {
            "<class>" = MSStyleBlur;
            center =             {
                x = "0.5";
                y = "0.5";
            };
            isEnabled = 0;
            motionAngle = 0;
            radius = 10;
            type = 0;
        };
        borderOptions =         {
            "<class>" = MSStyleBorderOptions;
            dashPattern =             (
            );
            isEnabled = 0;
            lineCapStyle = 0;
            lineJoinStyle = 0;
        };
        borders =         {
            "<class>" = MSArray;
            "<items>" =             (
                                {
                    "<class>" = MSStyleBorder;
                    color =                     {
                        "<class>" = MSColor;
                        value = "#979797";
                    };
                    contextSettings =                     {
                        "<class>" = MSGraphicsContextSettings;
                        blendMode = 0;
                        opacity = 1;
                    };
                    fillType = 1;
                    gradient =                     {
                        "<class>" = MSGradient;
                        elipseLength = 0;
                        from =                         {
                            x = "0.5";
                            y = "-1.002232142857143";
                        };
                        gradientType = 0;
                        points =                         {
                            "<class>" = MSGradientPointArray;
                            "<points>" =                             (
                                "{0.5, -1.0022321428571428}",
                                "{0.5, 1.8655133928571428}"
                            );
                        };
                        shouldSmoothenOpacity = 0;
                        stops =                         {
                            "<class>" = MSArray;
                            "<items>" =                             (
                                                                {
                                    "<class>" = MSGradientStop;
                                    color =                                     {
                                        "<class>" = MSColor;
                                        value = "#C8C8C8";
                                    };
                                    position = 0;
                                },
                                                                {
                                    "<class>" = MSGradientStop;
                                    color =                                     {
                                        "<class>" = MSColor;
                                        value = "#979797";
                                    };
                                    position = 1;
                                }
                            );
                        };
                        to =                         {
                            x = "0.5";
                            y = "1.865513392857143";
                        };
                    };
                    isEnabled = 1;
                    position = 2;
                    thickness = 13;
                }
            );
        };
        colorControls =         {
            "<class>" = MSStyleColorControls;
            brightness = 0;
            contrast = 1;
            hue = 0;
            isEnabled = 0;
            saturation = 1;
        };
        contextSettings =         {
            "<class>" = MSGraphicsContextSettings;
            blendMode = 0;
            opacity = 1;
        };
        endDecorationType = 0;
        fills =         {
            "<class>" = MSArray;
            "<items>" =             (
                                {
                    "<class>" = MSStyleFill;
                    color =                     {
                        "<class>" = MSColor;
                        value = "#9B9B9B";
                    };
                    contextSettings =                     {
                        "<class>" = MSGraphicsContextSettings;
                        blendMode = 0;
                        opacity = 1;
                    };
                    fillType = 0;
                    gradient =                     {
                        "<class>" = MSGradient;
                        elipseLength = 1;
                        from =                         {
                            x = "0.5000527501106262";
                            y = 1;
                        };
                        gradientType = 0;
                        points =                         {
                            "<class>" = MSGradientPointArray;
                            "<points>" =                             (
                                "{0.50005275011062622, 1}",
                                "{0.5, 0}"
                            );
                        };
                        shouldSmoothenOpacity = 0;
                        stops =                         {
                            "<class>" = MSArray;
                            "<items>" =                             (
                                                                {
                                    "<class>" = MSGradientStop;
                                    color =                                     {
                                        "<class>" = MSColor;
                                        value = "#ECECF3";
                                    };
                                    position = 0;
                                },
                                                                {
                                    "<class>" = MSGradientStop;
                                    color =                                     {
                                        "<class>" = MSColor;
                                        value = "rgba(49,50,49,0.57)";
                                    };
                                    position = 1;
                                }
                            );
                        };
                        to =                         {
                            x = "0.5";
                            y = 0;
                        };
                    };
                    isEnabled = 1;
                    noiseIndex = 0;
                    noiseIntensity = 0;
                    patternFillType = 1;
                    patternTileScale = 1;
                }
            );
        };
        innerShadows =         {
            "<class>" = MSArray;
            "<items>" =             (
            );
        };
        miterLimit = 10;
        reflection =         {
            "<class>" = MSStyleReflection;
            distance = 1;
            isEnabled = 0;
            strength = "0.5";
        };
        shadows =         {
            "<class>" = MSArray;
            "<items>" =             (
            );
        };
        startDecorationType = 0;
    };
    windingRule = 1;
}
*/<commit_msg>Removing unnecessary code.<commit_after>// To use this file:
// @import 'MovingImages.js';

function hexDigitToNumber(digit) {
  var hexDigitTable = '0123456789ABCDEF'
  for (i = 0 ; i < 16 ; ++i) {
    if (hexDigitTable[i] == digit) {
      return i
    }
  }
  return 0
}

// Assumes string is not prefixed with a #
function redComponent(hexString) {
  var number1 = hexDigitToNumber(hexString[0]) * 16.0
  var number2 = hexDigitToNumber(hexString[1])
  return (number1 + number2) / 255.0
}

// Assumes string is not prefixed with a #
function greenComponent(hexString) {
  var number1 = hexDigitToNumber(hexString[2]) * 16.0
  var number2 = hexDigitToNumber(hexString[3])
  return (number1 + number2) / 255.0
}

// Assumes string is not prefixed with a #
function blueComponent(hexString) {
  var number1 = hexDigitToNumber(hexString[4]) * 16.0;
  var number2 = hexDigitToNumber(hexString[5]);
  return (number1 + number2) / 255.0;
}

function miConvertAlphaColor(msColor) {
  var hexString = String(msColor.hexValue())
  var dictionary = {
    red: redComponent(hexString),
    green: greenComponent(hexString),
    blue: blueComponent(hexString),
    alpha: msColor.alpha(),
    colorcolorprofilename: 'kCGColorSpaceSRGB'
  };
  return dictionary;
}

function miConvertMSColor(msColor) {
  if (msColor.alpha() < 0.997) {
    return miConvertAlphaColor(msColor);
  }
  else {
    return msColor.hexValue();
  }
}

function miConvertMSRect(msRect) {
  return {
    size: {
      width: msRect.width(),
      height: msRect.height()
    },
    origin: {
      x: msRect.x(),
      y: msRect.y()
    }
  };
}

function miConvertStringToPoint(pointString) {
  var charactersToRemove = NSCharacterSet.characterSetWithCharactersInString('{} ');
  var strippedString = pointString.stringByTrimmingCharactersInSet(charactersToRemove);
  var commaSet = NSCharacterSet.characterSetWithCharactersInString(',');
  var components = strippedString.componentsSeparatedByCharactersInSet(commaSet);
  var x = components[0].doubleValue();
  var y = components[1].doubleValue();
  return {
    x: x,
    y: y
  };
}

function miConvertPointsToLine(pointsArray) {
  // MSGradientPointArray
  var thePoints = pointsArray.points();
  var startPoint = miConvertStringToPoint(thePoints[0]);
  var endPoint = miConvertStringToPoint(thePoints[1]);
  return {
    startpoint: startPoint,
    endpoint: endPoint
  };
}

/*
{
    "<class>" = MSShapeGroup;
    clippingMaskMode = 0;
    exportOptions =     {
        "<class>" = MSExportOptions;
        exportFormats =         {
            "<class>" = MSArray;
            "<items>" =             (
            );
        };
        includedLayerIds =         {
            "<class>" = MSArray;
            "<items>" =             (
            );
        };
        layerOptions = 0;
        shouldTrim = 0;
    };
    frame =     {
        "<class>" = MSRect;
        constrainProportions = 0;
        height = 14;
        objectID = "3D0A661B-176B-4AFC-9744-FFB212CD3E02";
        width = 117;
        x = "-1";
        y = "-112";
    };
    hasClickThrough = 0;
    hasClippingMask = 0;
    isFlippedHorizontal = 0;
    isFlippedVertical = 0;
    isLocked = 0;
    isVisible = 1;
    layerListExpandedType = 1;
    layers =     {
        "<class>" = MSArray;
        "<items>" =         (
                        {
                "<class>" = MSRectangleShape;
                booleanOperation = "-1";
                edited = 0;
                exportOptions =                 {
                    "<class>" = MSExportOptions;
                    exportFormats =                     {
                        "<class>" = MSArray;
                        "<items>" =                         (
                        );
                    };
                    includedLayerIds =                     {
                        "<class>" = MSArray;
                        "<items>" =                         (
                        );
                    };
                    layerOptions = 0;
                    shouldTrim = 0;
                };
                fixedRadius = 0;
                frame =                 {
                    "<class>" = MSRect;
                    constrainProportions = 0;
                    height = 14;
                    width = 117;
                    x = 0;
                    y = 0;
                };
                hasConvertedToNewRoundCorners = 1;
                isFlippedHorizontal = 0;
                isFlippedVertical = 0;
                isLocked = 0;
                isVisible = 1;
                layerListExpandedType = 0;
                name = Path;
                nameIsFixed = 0;
                objectID = "822F2FC3-36F1-43D7-B945-A53100E64E3F";
                path =                 {
                    "<class>" = MSShapePath;
                    isClosed = 1;
                    points =                     {
                        "<class>" = MSArray;
                        "<items>" =                         (
                                                        {
                                "<class>" = MSCurvePoint;
                                cornerRadius = 0;
                                curveFrom =                                 {
                                    x = 0;
                                    y = 0;
                                };
                                curveMode = 1;
                                curveTo =                                 {
                                    x = 0;
                                    y = 0;
                                };
                                hasCurveFrom = 0;
                                hasCurveTo = 0;
                                point =                                 {
                                    x = 0;
                                    y = 0;
                                };
                            },
                                                        {
                                "<class>" = MSCurvePoint;
                                cornerRadius = 0;
                                curveFrom =                                 {
                                    x = 1;
                                    y = 0;
                                };
                                curveMode = 1;
                                curveTo =                                 {
                                    x = 1;
                                    y = 0;
                                };
                                hasCurveFrom = 0;
                                hasCurveTo = 0;
                                point =                                 {
                                    x = 1;
                                    y = 0;
                                };
                            },
                                                        {
                                "<class>" = MSCurvePoint;
                                cornerRadius = 0;
                                curveFrom =                                 {
                                    x = 1;
                                    y = 1;
                                };
                                curveMode = 1;
                                curveTo =                                 {
                                    x = 1;
                                    y = 1;
                                };
                                hasCurveFrom = 0;
                                hasCurveTo = 0;
                                point =                                 {
                                    x = 1;
                                    y = 1;
                                };
                            },
                                                        {
                                "<class>" = MSCurvePoint;
                                cornerRadius = 0;
                                curveFrom =                                 {
                                    x = 0;
                                    y = 1;
                                };
                                curveMode = 1;
                                curveTo =                                 {
                                    x = 0;
                                    y = 1;
                                };
                                hasCurveFrom = 0;
                                hasCurveTo = 0;
                                point =                                 {
                                    x = 0;
                                    y = 1;
                                };
                            }
                        );
                    };
                };
                rotation = 0;
                shouldBreakMaskChain = 0;
            }
        );
    };
    name = "Rectangle 3";
    nameIsFixed = 0;
    objectID = "9FF2A2BB-D9E0-45E6-910A-22DCED315D65";
    rotation = 0;
    shouldBreakMaskChain = 0;
    style =     {
        "<class>" = MSStyle;
        blur =         {
            "<class>" = MSStyleBlur;
            center =             {
                x = "0.5";
                y = "0.5";
            };
            isEnabled = 0;
            motionAngle = 0;
            radius = 10;
            type = 0;
        };
        borderOptions =         {
            "<class>" = MSStyleBorderOptions;
            dashPattern =             (
            );
            isEnabled = 0;
            lineCapStyle = 0;
            lineJoinStyle = 0;
        };
        borders =         {
            "<class>" = MSArray;
            "<items>" =             (
                                {
                    "<class>" = MSStyleBorder;
                    color =                     {
                        "<class>" = MSColor;
                        value = "#979797";
                    };
                    contextSettings =                     {
                        "<class>" = MSGraphicsContextSettings;
                        blendMode = 0;
                        opacity = 1;
                    };
                    fillType = 1;
                    gradient =                     {
                        "<class>" = MSGradient;
                        elipseLength = 0;
                        from =                         {
                            x = "0.5";
                            y = "-1.002232142857143";
                        };
                        gradientType = 0;
                        points =                         {
                            "<class>" = MSGradientPointArray;
                            "<points>" =                             (
                                "{0.5, -1.0022321428571428}",
                                "{0.5, 1.8655133928571428}"
                            );
                        };
                        shouldSmoothenOpacity = 0;
                        stops =                         {
                            "<class>" = MSArray;
                            "<items>" =                             (
                                                                {
                                    "<class>" = MSGradientStop;
                                    color =                                     {
                                        "<class>" = MSColor;
                                        value = "#C8C8C8";
                                    };
                                    position = 0;
                                },
                                                                {
                                    "<class>" = MSGradientStop;
                                    color =                                     {
                                        "<class>" = MSColor;
                                        value = "#979797";
                                    };
                                    position = 1;
                                }
                            );
                        };
                        to =                         {
                            x = "0.5";
                            y = "1.865513392857143";
                        };
                    };
                    isEnabled = 1;
                    position = 2;
                    thickness = 13;
                }
            );
        };
        colorControls =         {
            "<class>" = MSStyleColorControls;
            brightness = 0;
            contrast = 1;
            hue = 0;
            isEnabled = 0;
            saturation = 1;
        };
        contextSettings =         {
            "<class>" = MSGraphicsContextSettings;
            blendMode = 0;
            opacity = 1;
        };
        endDecorationType = 0;
        fills =         {
            "<class>" = MSArray;
            "<items>" =             (
                                {
                    "<class>" = MSStyleFill;
                    color =                     {
                        "<class>" = MSColor;
                        value = "#9B9B9B";
                    };
                    contextSettings =                     {
                        "<class>" = MSGraphicsContextSettings;
                        blendMode = 0;
                        opacity = 1;
                    };
                    fillType = 0;
                    gradient =                     {
                        "<class>" = MSGradient;
                        elipseLength = 1;
                        from =                         {
                            x = "0.5000527501106262";
                            y = 1;
                        };
                        gradientType = 0;
                        points =                         {
                            "<class>" = MSGradientPointArray;
                            "<points>" =                             (
                                "{0.50005275011062622, 1}",
                                "{0.5, 0}"
                            );
                        };
                        shouldSmoothenOpacity = 0;
                        stops =                         {
                            "<class>" = MSArray;
                            "<items>" =                             (
                                                                {
                                    "<class>" = MSGradientStop;
                                    color =                                     {
                                        "<class>" = MSColor;
                                        value = "#ECECF3";
                                    };
                                    position = 0;
                                },
                                                                {
                                    "<class>" = MSGradientStop;
                                    color =                                     {
                                        "<class>" = MSColor;
                                        value = "rgba(49,50,49,0.57)";
                                    };
                                    position = 1;
                                }
                            );
                        };
                        to =                         {
                            x = "0.5";
                            y = 0;
                        };
                    };
                    isEnabled = 1;
                    noiseIndex = 0;
                    noiseIntensity = 0;
                    patternFillType = 1;
                    patternTileScale = 1;
                }
            );
        };
        innerShadows =         {
            "<class>" = MSArray;
            "<items>" =             (
            );
        };
        miterLimit = 10;
        reflection =         {
            "<class>" = MSStyleReflection;
            distance = 1;
            isEnabled = 0;
            strength = "0.5";
        };
        shadows =         {
            "<class>" = MSArray;
            "<items>" =             (
            );
        };
        startDecorationType = 0;
    };
    windingRule = 1;
}
*/<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009, 2010, 2011, 2012, B3log Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview ease js.
 *
 * @author Liyuan Li
 * @version 1.0.1.5, Jan 29, 2013
 */
var goTranslate = function () {
    window.open("http://translate.google.com/translate?sl=auto&tl=auto&u=" + location.href);
};

var getNextPage = function () {
    var $more = $(".article-next");
    currentPage += 1;
    var path = "/articles/";
    if($("#tag").length === 1) {
        var pathnames = location.pathname.split("/");
        path = "/articles/tags/" + pathnames[pathnames.length - 1] + "/";
    } else if ($("#archive").length === 1) {
        var pathnames = location.pathname.split("/");
        path = "/articles/archives/" + pathnames[pathnames.length - 2] + "/" + pathnames[pathnames.length - 1] + "/";
    } else if ($("#author").length === 1) {
        var pathnames = location.pathname.split("/");
        path = "/articles/authors/" + pathnames[pathnames.length - 1] + "/";
    }

    $.ajax({
        url: latkeConfig.servePath + path + currentPage,
        type: "GET",
        beforeSend: function () {
            $more.css("background",
                "url(" + latkeConfig.staticServePath + "/skins/ease/images/ajax-loader.gif) no-repeat scroll center center #fefefe");
        },
        success: function(result, textStatus){
            if (!result.sc) {
                console.log("[B3log-Solo Err]: " + result);
                return;
            }

            var articlesHTML = "",
            pagination = result.rslts.pagination;

            // append articles
            for (var i = 0; i < result.rslts.articles.length; i++) {
                var article = result.rslts.articles[i],
                lastClass = "";
                if (result.rslts.articles.length - 1 === i) {
                    lastClass = " article-last";
                }

                articlesHTML += '
' +
                '
' +
                '
' +
                '' +
                article.articleTitle +
                '';
                if (article.hasUpdated) {
                    articlesHTML += '' + Label.updatedLabel + '';
                }

                if (article.articlePutTop) {
                    articlesHTML += '' + Label.topArticleLabel + '';
                }

                articlesHTML += '
' +
                '
' +
                '' +
                + article.articleCommentCount + '  ' + Label.commentLabel +
                '  ' +
                '' +
                article.articleViewCount + '  ' + Label.viewLabel +
                '' +
                '
' +
                '

' +
                '
' +
                '
' +
                '
' +
                article.articleAbstract +
                '
' +
                '

' +
                '
' +
                '
';
                if (article.hasUpdated) {
                    articlesHTML += Util.toDate(article.articleUpdateTime, 'yy-MM-dd HH:mm');
                } else {
                    articlesHTML +=  Util.toDate(article.articleCreateTime, 'yy-MM-dd HH:mm');
                }

                articlesHTML += ' ' + article.authorName + '' +
                '
' +
                '
' +
                Label.tag1Label + " ";

                var articleTags = article.articleTags.split(",");
                for (var j = 0; j < articleTags.length; j++) {
                    articlesHTML +=  '' +
                    articleTags[j] + '';

                    if (j < articleTags.length - 1) {
                        articlesHTML += ", ";
                    }
                }

                articlesHTML += '
' +
            '

' +
            '
';
            }

            $(".article-last").removeClass("article-last");
            $(".main>.wrapper>ul").append(articlesHTML);

            // 最后一页处理
            if (pagination.paginationPageCount === currentPage) {
                $more.remove();
            } else {
                $more.css("background", "none");
            }
        }
    });
};

var ease = {
    $header: $(".header"),
    headerH: 103,
    $body: $(".main > .wrapper"),
    $nav: $(".nav"),
    getCurrentPage: function () {
        var $next = $(".article-next");
        if ($next.length > 0) {
            window.currentPage = $next.data("page");
        }
    },

    setNavCurrent: function () {
        $(".nav ul a").each(function () {
            var $this = $(this);
            if ($this.attr("href") === latkeConfig.servePath + location.pathname) {
                $this.addClass("current");
            } else if (/\/[0-9]+$/.test(location.pathname)) {
                $(".nav ul li")[0].className = "current";
            }
        });
    },

    initCommon: function () {
        Util.init();
        Util.replaceSideEm($(".recent-comments-content"));
        Util.buildTags("tagsSide");
    },

    initArchives: function () {
        var $archives = $(".archives");
        if ($archives.length < 1) {
            return;
        }

        $(".footer").css("marginTop", "30px");
        var years = [],
        $archiveList = $archives.find("span").each(function () {
            var year = $(this).data("year"),
            tag = true;
            for (var i = 0; i < years.length; i++) {
                if (year === years[i]) {
                    tag = false;
                    break;
                }
            }
            if (tag) {
                years.push(year);
            }
        });

        var yearsHTML = "";
        for (var j = 0; j < years.length; j++) {
            var monthsHTML = "";
            for (var l = 0; l < $archiveList.length; l++) {
                var $month = $($archiveList[l]);
                if ($month.data("year") === years[j]) {
                    monthsHTML += $month.html();
                }
            }

            yearsHTML += "

" + years[j] + "
" + monthsHTML + "
";
        }

        $archives.html(yearsHTML);

        // position
        var $items = $(".archives>div"),
        line = 0,
        top = 0,
        heights = [];

        for (var m = 0; m < $items.length; m++) {
            for (var n = 0; n < 3; n++) {
                if (m >= $items.length) {
                    break;
                }

                $items[m].style.left = (n * 310) + "px";

                if (line > 0) {
                    if ($items[m - 3].style.top !== "") {
                        top = parseInt($items[m - 3].style.top);
                    }
                    $items[m].style.top = $($items[m - 3]).height() + 60 + top + "px";

                    heights[n] = parseInt($items[m].style.top) + $($items[m]).height() + 60;
                } else {
                    heights[n] = $($items[m]).height() + 60;
                }

                if (n < 2) {
                    m += 1;
                }
            }
            line += 1;
        }

        // archive height
        $archives.height(heights.sort()[heights.length - 1]);
    },

    scrollEvent: function () {
        var _it = this;
        $(window).scroll(function () {
            var y = $(window).scrollTop(),
            topH = 0;
            if ($("#top").css("display") === "block") {
                topH = $("#top").height();
            }

            // header event
            if (y >= _it.headerH + topH) {
                _it.$nav.css("position", "fixed");
                _it.$body.css("marginTop", "55px");
            } else {
                _it.$nav.css("position" ,"inherit");
                _it.$body.css("marginTop", "0");
            }

            // go top icon show or hide
            if (y > _it.headerH) {
                var bodyH = $(window).height();
                var top =  y + bodyH - 21;
                if ($("body").height() - 58 <= y + bodyH) {
                    top = $(".footer").offset().top - 21;
                }
                $("#goTop").fadeIn("slow").css("top", top);
            } else {
                $("#goTop").hide();
            }
        });
    },

    setDynamic: function () {
        var $dynamic = $(".dynamic");
        if ($(".dynamic").length < 1) {
            return;
        }

        var $comments = $dynamic.find(".side-comments"),
        $tags = $dynamic.find(".side-tags"),
        $mostComment = $dynamic.find(".side-most-comment"),
        $mostView = $dynamic.find(".side-most-view");

        if ($comments.height() > $tags.height()) {
            $tags.height($comments.height());
        } else {
            $comments.height($tags.height());
        }

        if ($mostComment.height() > $mostView.height()) {
            $mostView.height($mostComment.height());
        } else {
            $mostComment.height($mostView.height());
        }

        // emotions
        $(".article-body").each(function () {
            this.innerHTML = Util.replaceEmString($(this).html());
        });
    },

    /**
     * @description 纠正评论滚动位置偏差
     */
    scrollToCmt: function () {
        if ($(window.location.hash).length == 1) {
            $(window).scrollTop($(window.location.hash).offset().top - 60);
        }
    }
};

(function () {
    ease.getCurrentPage();
    ease.initCommon();
    ease.scrollEvent();
    ease.setNavCurrent();

    ease.initArchives();
    ease.setDynamic();
})();
<commit_msg>replace console.log with alert<commit_after>/*
 * Copyright (c) 2009, 2010, 2011, 2012, B3log Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview ease js.
 *
 * @author Liyuan Li
 * @version 1.0.1.5, Jan 29, 2013
 */
var goTranslate = function () {
    window.open("http://translate.google.com/translate?sl=auto&tl=auto&u=" + location.href);
};

var getNextPage = function () {
    var $more = $(".article-next");
    currentPage += 1;
    var path = "/articles/";
    if($("#tag").length === 1) {
        var pathnames = location.pathname.split("/");
        path = "/articles/tags/" + pathnames[pathnames.length - 1] + "/";
    } else if ($("#archive").length === 1) {
        var pathnames = location.pathname.split("/");
        path = "/articles/archives/" + pathnames[pathnames.length - 2] + "/" + pathnames[pathnames.length - 1] + "/";
    } else if ($("#author").length === 1) {
        var pathnames = location.pathname.split("/");
        path = "/articles/authors/" + pathnames[pathnames.length - 1] + "/";
    }

    $.ajax({
        url: latkeConfig.servePath + path + currentPage,
        type: "GET",
        beforeSend: function () {
            $more.css("background",
                "url(" + latkeConfig.staticServePath + "/skins/ease/images/ajax-loader.gif) no-repeat scroll center center #fefefe");
        },
        success: function(result, textStatus){
            if (!result.sc) {
                alert("[B3log-Solo Err]: " + result);
                return;
            }

            var articlesHTML = "",
            pagination = result.rslts.pagination;

            // append articles
            for (var i = 0; i < result.rslts.articles.length; i++) {
                var article = result.rslts.articles[i],
                lastClass = "";
                if (result.rslts.articles.length - 1 === i) {
                    lastClass = " article-last";
                }

                articlesHTML += '
' +
                '
' +
                '
' +
                '' +
                article.articleTitle +
                '';
                if (article.hasUpdated) {
                    articlesHTML += '' + Label.updatedLabel + '';
                }

                if (article.articlePutTop) {
                    articlesHTML += '' + Label.topArticleLabel + '';
                }

                articlesHTML += '
' +
                '
' +
                '' +
                + article.articleCommentCount + '  ' + Label.commentLabel +
                '  ' +
                '' +
                article.articleViewCount + '  ' + Label.viewLabel +
                '' +
                '
' +
                '

' +
                '
' +
                '
' +
                '
' +
                article.articleAbstract +
                '
' +
                '

' +
                '
' +
                '
';
                if (article.hasUpdated) {
                    articlesHTML += Util.toDate(article.articleUpdateTime, 'yy-MM-dd HH:mm');
                } else {
                    articlesHTML +=  Util.toDate(article.articleCreateTime, 'yy-MM-dd HH:mm');
                }

                articlesHTML += ' ' + article.authorName + '' +
                '
' +
                '
' +
                Label.tag1Label + " ";

                var articleTags = article.articleTags.split(",");
                for (var j = 0; j < articleTags.length; j++) {
                    articlesHTML +=  '' +
                    articleTags[j] + '';

                    if (j < articleTags.length - 1) {
                        articlesHTML += ", ";
                    }
                }

                articlesHTML += '
' +
            '

' +
            '
';
            }

            $(".article-last").removeClass("article-last");
            $(".main>.wrapper>ul").append(articlesHTML);

            // 最后一页处理
            if (pagination.paginationPageCount === currentPage) {
                $more.remove();
            } else {
                $more.css("background", "none");
            }
        }
    });
};

var ease = {
    $header: $(".header"),
    headerH: 103,
    $body: $(".main > .wrapper"),
    $nav: $(".nav"),
    getCurrentPage: function () {
        var $next = $(".article-next");
        if ($next.length > 0) {
            window.currentPage = $next.data("page");
        }
    },

    setNavCurrent: function () {
        $(".nav ul a").each(function () {
            var $this = $(this);
            if ($this.attr("href") === latkeConfig.servePath + location.pathname) {
                $this.addClass("current");
            } else if (/\/[0-9]+$/.test(location.pathname)) {
                $(".nav ul li")[0].className = "current";
            }
        });
    },

    initCommon: function () {
        Util.init();
        Util.replaceSideEm($(".recent-comments-content"));
        Util.buildTags("tagsSide");
    },

    initArchives: function () {
        var $archives = $(".archives");
        if ($archives.length < 1) {
            return;
        }

        $(".footer").css("marginTop", "30px");
        var years = [],
        $archiveList = $archives.find("span").each(function () {
            var year = $(this).data("year"),
            tag = true;
            for (var i = 0; i < years.length; i++) {
                if (year === years[i]) {
                    tag = false;
                    break;
                }
            }
            if (tag) {
                years.push(year);
            }
        });

        var yearsHTML = "";
        for (var j = 0; j < years.length; j++) {
            var monthsHTML = "";
            for (var l = 0; l < $archiveList.length; l++) {
                var $month = $($archiveList[l]);
                if ($month.data("year") === years[j]) {
                    monthsHTML += $month.html();
                }
            }

            yearsHTML += "

" + years[j] + "
" + monthsHTML + "
";
        }

        $archives.html(yearsHTML);

        // position
        var $items = $(".archives>div"),
        line = 0,
        top = 0,
        heights = [];

        for (var m = 0; m < $items.length; m++) {
            for (var n = 0; n < 3; n++) {
                if (m >= $items.length) {
                    break;
                }

                $items[m].style.left = (n * 310) + "px";

                if (line > 0) {
                    if ($items[m - 3].style.top !== "") {
                        top = parseInt($items[m - 3].style.top);
                    }
                    $items[m].style.top = $($items[m - 3]).height() + 60 + top + "px";

                    heights[n] = parseInt($items[m].style.top) + $($items[m]).height() + 60;
                } else {
                    heights[n] = $($items[m]).height() + 60;
                }

                if (n < 2) {
                    m += 1;
                }
            }
            line += 1;
        }

        // archive height
        $archives.height(heights.sort()[heights.length - 1]);
    },

    scrollEvent: function () {
        var _it = this;
        $(window).scroll(function () {
            var y = $(window).scrollTop(),
            topH = 0;
            if ($("#top").css("display") === "block") {
                topH = $("#top").height();
            }

            // header event
            if (y >= _it.headerH + topH) {
                _it.$nav.css("position", "fixed");
                _it.$body.css("marginTop", "55px");
            } else {
                _it.$nav.css("position" ,"inherit");
                _it.$body.css("marginTop", "0");
            }

            // go top icon show or hide
            if (y > _it.headerH) {
                var bodyH = $(window).height();
                var top =  y + bodyH - 21;
                if ($("body").height() - 58 <= y + bodyH) {
                    top = $(".footer").offset().top - 21;
                }
                $("#goTop").fadeIn("slow").css("top", top);
            } else {
                $("#goTop").hide();
            }
        });
    },

    setDynamic: function () {
        var $dynamic = $(".dynamic");
        if ($(".dynamic").length < 1) {
            return;
        }

        var $comments = $dynamic.find(".side-comments"),
        $tags = $dynamic.find(".side-tags"),
        $mostComment = $dynamic.find(".side-most-comment"),
        $mostView = $dynamic.find(".side-most-view");

        if ($comments.height() > $tags.height()) {
            $tags.height($comments.height());
        } else {
            $comments.height($tags.height());
        }

        if ($mostComment.height() > $mostView.height()) {
            $mostView.height($mostComment.height());
        } else {
            $mostComment.height($mostView.height());
        }

        // emotions
        $(".article-body").each(function () {
            this.innerHTML = Util.replaceEmString($(this).html());
        });
    },

    /**
     * @description 纠正评论滚动位置偏差
     */
    scrollToCmt: function () {
        if ($(window.location.hash).length == 1) {
            $(window).scrollTop($(window.location.hash).offset().top - 60);
        }
    }
};

(function () {
    ease.getCurrentPage();
    ease.initCommon();
    ease.scrollEvent();
    ease.setNavCurrent();

    ease.initArchives();
    ease.setDynamic();
})();
<|endoftext|>


<commit_before>define([
	'dojo/_base/declare',
	'dojo/_base/array',
	'dojo/Deferred',
	'dojo/store/util/QueryResults'
	/*=====, "dstore/api/Store" =====*/
], function (declare, arrayUtil, Deferred, QueryResults /*=====, Store =====*/) {
// module:
//		An adapter mixin that makes a dstore store object look like a legacy Dojo object store.

	function passthrough(data) {
		return data;
	}

	// No base class, but for purposes of documentation, the base class is dstore/api/Store
	var base = null;
	/*===== base = Store; =====*/

	var adapterPrototype = {

		// store:
		//		The dstore store that is wrapped as a Dojo object store
		store: null,

		constructor: function (store) {
			this.store = store;

			if (this.store.queryEngine) {
				var queryEngine = this.store.queryEngine;
				this.queryEngine = function (query, options) {
					options = options || {};

					var filter = queryEngine.filter(query);
					var sort = passthrough;
					var range = passthrough;

					if (queryEngine.sort && options.sort) {
						sort = queryEngine.sort(arrayUtil.map(options.sort, function (criteria) {
							return {
								property: criteria.attribute,
								descending: criteria.descending
							};
						}));
					}

					if (!isNaN(options.start) || !isNaN(options.count)) {
						range = queryEngine.range({
							start: options.start,
							end: (options.start || 0) + (isNaN(options.count) ? Infinity : options.count)
						});
					}

					return function (data) {
						return range(sort(filter(data)));
					};
				};
			}
			var objectStore = this;
			// we call notify on events to mimic the old dojo/store/Observable
			store.on('add,update,remove', function (event) {
				var type = event.type;
				var target = event.target;
				objectStore.notify(
					(type === 'add' || type === 'update') ? target : undefined,
					(type === 'remove' || type === 'update') ?
						('id' in event ? event.id : store.getIdentity(target)) : undefined);
			});
		},

		query: function (query, options) {
			// summary:
			//		Queries the store for objects. This does not alter the store, but returns a
			//		set of data from the store.
			// query: String|Object|Function
			//		The query to use for retrieving objects from the store.
			// options: dstore/api/Store.QueryOptions
			//		The optional arguments to apply to the resultset.
			// returns: dstore/api/Store.QueryResults
			//		The results of the query, extended with iterative methods.
			//
			// example:
			//		Given the following store:
			//
			//	...find all items where "prime" is true:
			//
			//	|	store.query({ prime: true }).forEach(function(object){
			//	|		// handle each object
			//	|	});
			var results = this.store.filter(query);

			if (options) {
				// Apply sorting
				var sort = options.sort;
				if (sort) {
					if (Object.prototype.toString.call(sort) === '[object Array]') {
						var sortOptions;
						while ((sortOptions = sort.pop())) {
							results = results.sort(sortOptions.attribute, sortOptions.descending);
						}
					} else {
						results = results.sort(sort);
					}
				}
				// Apply a range
				if ('start' in options) {
					var start = options.start || 0;
					// object stores support sync results, so try that if available
					var queryResults = results[results.fetchRangeSync ? 'fetchRangeSync' : 'fetchRange']({
						start: start,
						end: options.count ? (start + options.count) : Infinity
					});
					queryResults.total = queryResults.totalLength;
					return new QueryResults(queryResults);
				}
 			}
 			var tracked;
			if (results.track) {
				// if it is trackable, always track, so that observe can
				// work properly.
				results = results.track();
				tracked = true;
			}
			var queryResults = new QueryResults(results[results.fetchSync ? 'fetchSync' : 'fetch']());
			queryResults.observe = function (callback, includeObjectUpdates) {
				// translate observe to event listeners
				function convertUndefined(value) {
					if (value === undefined && tracked) {
						return -1;
					}
					return value;
				}
				var addHandle = results.on('add', function (event) {
					callback(event.target, -1, convertUndefined(event.index));
				});
				var updateHandle = results.on('update', function (event) {
					if (includeObjectUpdates || event.previousIndex !== event.index || !isFinite(event.index)) {
						callback(event.target, convertUndefined(event.previousIndex), convertUndefined(event.index));
					}
				});
				var removeHandle = results.on('remove', function (event) {
					callback(event.target, convertUndefined(event.previousIndex), -1);
				});
				var handle = {
					remove: function () {
						addHandle.remove();
						updateHandle.remove();
						removeHandle.remove();
					}
				};
				handle.cancel = handle.remove;
				return handle;
			};
			return queryResults;
		},
		notify: function () {

		}
	};

	var delegatedMethods = [ 'get', 'put', 'add', 'remove', 'getIdentity' ];
	arrayUtil.forEach(delegatedMethods, function (methodName) {
		adapterPrototype[methodName] = function () {
			var store = this.store;
			// try sync first, since dojo object stores support that directly
			return (store[methodName + 'Sync'] || store[methodName]).apply(store, arguments);
		};
	});

	return declare(base, adapterPrototype);
});
<commit_msg>Properly check for fetchSync<commit_after>define([
	'dojo/_base/declare',
	'dojo/_base/array',
	'dojo/store/util/QueryResults'
	/*=====, "dstore/api/Store" =====*/
], function (declare, arrayUtil, QueryResults /*=====, Store =====*/) {
// module:
//		An adapter mixin that makes a dstore store object look like a legacy Dojo object store.

	function passthrough(data) {
		return data;
	}

	// No base class, but for purposes of documentation, the base class is dstore/api/Store
	var base = null;
	/*===== base = Store; =====*/

	var adapterPrototype = {

		// store:
		//		The dstore store that is wrapped as a Dojo object store
		store: null,

		constructor: function (store) {
			this.store = store;

			if (this.store.queryEngine) {
				var queryEngine = this.store.queryEngine;
				this.queryEngine = function (query, options) {
					options = options || {};

					var filter = queryEngine.filter(query);
					var sort = passthrough;
					var range = passthrough;

					if (queryEngine.sort && options.sort) {
						sort = queryEngine.sort(arrayUtil.map(options.sort, function (criteria) {
							return {
								property: criteria.attribute,
								descending: criteria.descending
							};
						}));
					}

					if (!isNaN(options.start) || !isNaN(options.count)) {
						range = queryEngine.range({
							start: options.start,
							end: (options.start || 0) + (isNaN(options.count) ? Infinity : options.count)
						});
					}

					return function (data) {
						return range(sort(filter(data)));
					};
				};
			}
			var objectStore = this;
			// we call notify on events to mimic the old dojo/store/Observable
			store.on('add,update,remove', function (event) {
				var type = event.type;
				var target = event.target;
				objectStore.notify(
					(type === 'add' || type === 'update') ? target : undefined,
					(type === 'remove' || type === 'update') ?
						('id' in event ? event.id : store.getIdentity(target)) : undefined);
			});
		},

		query: function (query, options) {
			// summary:
			//		Queries the store for objects. This does not alter the store, but returns a
			//		set of data from the store.
			// query: String|Object|Function
			//		The query to use for retrieving objects from the store.
			// options: dstore/api/Store.QueryOptions
			//		The optional arguments to apply to the resultset.
			// returns: dstore/api/Store.QueryResults
			//		The results of the query, extended with iterative methods.
			//
			// example:
			//		Given the following store:
			//
			//	...find all items where "prime" is true:
			//
			//	|	store.query({ prime: true }).forEach(function(object){
			//	|		// handle each object
			//	|	});
			var results = this.store.filter(query);

			if (options) {
				// Apply sorting
				var sort = options.sort;
				if (sort) {
					if (Object.prototype.toString.call(sort) === '[object Array]') {
						var sortOptions;
						while ((sortOptions = sort.pop())) {
							results = results.sort(sortOptions.attribute, sortOptions.descending);
						}
					} else {
						results = results.sort(sort);
					}
				}
				// Apply a range
				if ('start' in options) {
					var start = options.start || 0;
					// object stores support sync results, so try that if available
					var queryResults = results[results.fetchRangeSync ? 'fetchRangeSync' : 'fetchRange']({
						start: start,
						end: options.count ? (start + options.count) : Infinity
					});
					queryResults.total = queryResults.totalLength;
					return new QueryResults(queryResults);
				}
 			}
 			var tracked;
			if (results.track) {
				// if it is trackable, always track, so that observe can
				// work properly.
				results = results.track();
				tracked = true;
			}
			var queryResults = new QueryResults(results[results.fetchSync ? 'fetchSync' : 'fetch']());
			queryResults.observe = function (callback, includeObjectUpdates) {
				// translate observe to event listeners
				function convertUndefined(value) {
					if (value === undefined && tracked) {
						return -1;
					}
					return value;
				}
				var addHandle = results.on('add', function (event) {
					callback(event.target, -1, convertUndefined(event.index));
				});
				var updateHandle = results.on('update', function (event) {
					if (includeObjectUpdates || event.previousIndex !== event.index || !isFinite(event.index)) {
						callback(event.target, convertUndefined(event.previousIndex), convertUndefined(event.index));
					}
				});
				var removeHandle = results.on('remove', function (event) {
					callback(event.target, convertUndefined(event.previousIndex), -1);
				});
				var handle = {
					remove: function () {
						addHandle.remove();
						updateHandle.remove();
						removeHandle.remove();
					}
				};
				handle.cancel = handle.remove;
				return handle;
			};
			return queryResults;
		},
		notify: function () {

		}
	};

	var delegatedMethods = [ 'get', 'put', 'add', 'remove', 'getIdentity' ];
	arrayUtil.forEach(delegatedMethods, function (methodName) {
		adapterPrototype[methodName] = function () {
			var store = this.store;
			// try sync first, since dojo object stores support that directly
			return (store[methodName + 'Sync'] || store[methodName]).apply(store, arguments);
		};
	});

	return declare(base, adapterPrototype);
});
<|endoftext|>


<commit_before>angular.module(
		'BindingApp',
		[ 'ngRoute', 'ui.bootstrap', 'MainControllerModule',
				'TemplateServiceModule', 'BindingServiceModule', /*'uiSwitch',*/ 'angular-jwt', 'hc.marked', 'sticky' ]).factory(
		'authInterceptor',
		function($rootScope, $q, $window) {
			return {
				request : function(config) {
					config.headers = config.headers || {};
					if ($window.sessionStorage.token) {
						config.headers.Authorization = 'Bearer '
								+ $window.sessionStorage.token;
					}
					return config;
				},
				response : function(response) {
					if (response.status === 401) {
						// handle the case where the user is not authenticated
					}
					return response || $q.when(response);
				}
			};
		}).config(function($httpProvider) {
	$httpProvider.interceptors.push('authInterceptor');
});
<commit_msg>Added fix for IE, disabled AJAX caching<commit_after>angular
		.module(
				'BindingApp',
				[ 'ngRoute', 'ui.bootstrap', 'MainControllerModule',
						'TemplateServiceModule', 'BindingServiceModule', /* 'uiSwitch', */
						'angular-jwt', 'hc.marked', 'sticky' ])
		.factory(
				'authInterceptor',
				function($rootScope, $q, $window) {
					return {
						request : function(config) {
							config.headers = config.headers || {};
							if ($window.sessionStorage.token) {
								config.headers.Authorization = 'Bearer '
										+ $window.sessionStorage.token;
							}
							return config;
						},
						response : function(response) {
							if (response.status === 401) {
								// handle the case where the user is not
								// authenticated
							}
							return response || $q.when(response);
						}
					};
				})
		.config(
				[
						'$routeProvider',
						'$httpProvider',
						function($routeProvider, $httpProvider) {
							$httpProvider.defaults.cache = false;
							if (!$httpProvider.defaults.headers.get) {
								$httpProvider.defaults.headers.get = {};
							}
							// disable IE ajax request caching
							$httpProvider.defaults.headers.get['If-Modified-Since'] = '0';
							$httpProvider.interceptors.push('authInterceptor');
						} ]);
<|endoftext|>


<commit_before>import $ from 'jquery';
import d3 from 'd3';
import colorbrewer from 'colorbrewer';

// Color related utility functions go in this object
const bnbColors = [
  '#ff5a5f', // rausch
  '#7b0051', // hackb
  '#007A87', // kazan
  '#00d1c1', // babu
  '#8ce071', // lima
  '#ffb400', // beach
  '#b4a76c', // barol
  '#ff8083',
  '#cc0086',
  '#00a1b3',
  '#00ffeb',
  '#bbedab',
  '#ffd266',
  '#cbc29a',
  '#ff3339',
  '#ff1ab1',
  '#005c66',
  '#00b3a5',
  '#55d12e',
  '#b37e00',
  '#988b4e',
];
const d3Category10 = d3.scale.category10().range();
const d3Category20 = d3.scale.category20().range();
const d3Category20b = d3.scale.category20b().range();
const d3Category20c = d3.scale.category20c().range();
const googleCategory10c = [
  '#3366cc',
  '#dc3912',
  '#ff9900',
  '#109618',
  '#990099',
  '#0099c6',
  '#dd4477',
  '#66aa00',
  '#b82e2e',
  '#316395',
];
const googleCategory20c = [
  '#3366cc',
  '#dc3912',
  '#ff9900',
  '#109618',
  '#990099',
  '#0099c6',
  '#dd4477',
  '#66aa00',
  '#b82e2e',
  '#316395',
  '#994499',
  '#22aa99',
  '#aaaa11',
  '#6633cc',
  '#e67300',
  '#8b0707',
  '#651067',
  '#329262',
  '#5574a6',
  '#3b3eac',
];
export const ALL_COLOR_SCHEMES = {
  bnbColors,
  d3Category10,
  d3Category20,
  d3Category20b,
  d3Category20c,
  googleCategory10c,
  googleCategory20c,
};

export const spectrums = {
  blue_white_yellow: [
    '#00d1c1',
    'white',
    '#ffb400',
  ],
  fire: [
    'white',
    'yellow',
    'red',
    'black',
  ],
  white_black: [
    'white',
    'black',
  ],
  black_white: [
    'black',
    'white',
  ],
};

export const getColorFromScheme = (function () {
  // Color factory
  const seen = {};
  return function (s, scheme) {
    if (!s) {
      return;
    }
    const selectedScheme = scheme ? ALL_COLOR_SCHEMES[scheme] : ALL_COLOR_SCHEMES.bnbColors;
    let stringifyS = String(s);
    // next line is for superset series that should have the same color
    stringifyS = stringifyS.replace('---', '');
    if (seen[selectedScheme] === undefined) {
      seen[selectedScheme] = {};
    }
    if (seen[selectedScheme][stringifyS] === undefined) {
      seen[selectedScheme][stringifyS] = Object.keys(seen[selectedScheme]).length;
    }
    /* eslint consistent-return: 0 */
    return selectedScheme[seen[selectedScheme][stringifyS] % selectedScheme.length];
  };
}());

export const colorScalerFactory = function (colors, data, accessor) {
  // Returns a linear scaler our of an array of color
  if (!Array.isArray(colors)) {
    /* eslint no-param-reassign: 0 */
    colors = spectrums[colors];
  }
  let ext = [0, 1];
  if (data !== undefined) {
    ext = d3.extent(data, accessor);
  }
  const points = [];
  const chunkSize = (ext[1] - ext[0]) / colors.length;
  $.each(colors, function (i) {
    points.push(i * chunkSize);
  });
  return d3.scale.linear().domain(points).range(colors);
};
<commit_msg>attempt to add color chromatic scale to colors<commit_after>import $ from 'jquery';
import d3 from 'd3';

// Color related utility functions go in this object
const bnbColors = [
  '#ff5a5f', // rausch
  '#7b0051', // hackb
  '#007A87', // kazan
  '#00d1c1', // babu
  '#8ce071', // lima
  '#ffb400', // beach
  '#b4a76c', // barol
  '#ff8083',
  '#cc0086',
  '#00a1b3',
  '#00ffeb',
  '#bbedab',
  '#ffd266',
  '#cbc29a',
  '#ff3339',
  '#ff1ab1',
  '#005c66',
  '#00b3a5',
  '#55d12e',
  '#b37e00',
  '#988b4e',
];
const d3Category10 = d3.scale.category10().range();
const d3Category20 = d3.scale.category20().range();
const d3Category20b = d3.scale.category20b().range();
const d3Category20c = d3.scale.category20c().range();
const googleCategory10c = [
  '#3366cc',
  '#dc3912',
  '#ff9900',
  '#109618',
  '#990099',
  '#0099c6',
  '#dd4477',
  '#66aa00',
  '#b82e2e',
  '#316395',
];
const googleCategory20c = [
  '#3366cc',
  '#dc3912',
  '#ff9900',
  '#109618',
  '#990099',
  '#0099c6',
  '#dd4477',
  '#66aa00',
  '#b82e2e',
  '#316395',
  '#994499',
  '#22aa99',
  '#aaaa11',
  '#6633cc',
  '#e67300',
  '#8b0707',
  '#651067',
  '#329262',
  '#5574a6',
  '#3b3eac',
];
export const ALL_COLOR_SCHEMES = {
  bnbColors,
  d3Category10,
  d3Category20,
  d3Category20b,
  d3Category20c,
  googleCategory10c,
  googleCategory20c,
};

export const spectrums = {
  blue_white_yellow: [
    '#00d1c1',
    'white',
    '#ffb400',
  ],
  fire: [
    'white',
    'yellow',
    'red',
    'black',
  ],
  white_black: [
    'white',
    'black',
  ],
  black_white: [
    'black',
    'white',
  ],
};

export const getColorFromScheme = (function () {
  // Color factory
  const seen = {};
  return function (s, scheme) {
    if (!s) {
      return;
    }
    const selectedScheme = scheme ? ALL_COLOR_SCHEMES[scheme] : ALL_COLOR_SCHEMES.bnbColors;
    let stringifyS = String(s);
    // next line is for superset series that should have the same color
    stringifyS = stringifyS.replace('---', '');
    if (seen[selectedScheme] === undefined) {
      seen[selectedScheme] = {};
    }
    if (seen[selectedScheme][stringifyS] === undefined) {
      seen[selectedScheme][stringifyS] = Object.keys(seen[selectedScheme]).length;
    }
    /* eslint consistent-return: 0 */
    return selectedScheme[seen[selectedScheme][stringifyS] % selectedScheme.length];
  };
}());

export const colorScalerFactory = function (colors, data, accessor) {
  // Returns a linear scaler our of an array of color
  if (!Array.isArray(colors)) {
    /* eslint no-param-reassign: 0 */
    colors = spectrums[colors];
  }
  let ext = [0, 1];
  if (data !== undefined) {
    ext = d3.extent(data, accessor);
  }
  const points = [];
  const chunkSize = (ext[1] - ext[0]) / colors.length;
  $.each(colors, function (i) {
    points.push(i * chunkSize);
  });
  return d3.scale.linear().domain(points).range(colors);
};<|endoftext|>


<commit_before>/*
      LESS mode - http://www.lesscss.org/
      Ported to CodeMirror by Peter Kroon <plakroon@gmail.com>
      Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues
      GitHub: @peterkroon
  */

CodeMirror.defineMode("less", function(config) {
  var indentUnit = config.indentUnit, type;
  function ret(style, tp) {type = tp; return style;}

  var selectors = /(^\:root$|^\:nth\-child$|^\:nth\-last\-child$|^\:nth\-of\-type$|^\:nth\-last\-of\-type$|^\:first\-child$|^\:last\-child$|^\:first\-of\-type$|^\:last\-of\-type$|^\:only\-child$|^\:only\-of\-type$|^\:empty$|^\:link|^\:visited$|^\:active$|^\:hover$|^\:focus$|^\:target$|^\:lang$|^\:enabled^\:disabled$|^\:checked$|^\:first\-line$|^\:first\-letter$|^\:before$|^\:after$|^\:not$|^\:required$|^\:invalid$)/;

  function tokenBase(stream, state) {
    var ch = stream.next();

    if (ch == "@") {stream.eatWhile(/[\w\-]/); return ret("meta", stream.current());}
    else if (ch == "/" && stream.eat("*")) {
      state.tokenize = tokenCComment;
      return tokenCComment(stream, state);
    }
      else if (ch == "<" && stream.eat("!")) {
        state.tokenize = tokenSGMLComment;
        return tokenSGMLComment(stream, state);
      }
        else if (ch == "=") ret(null, "compare");
          else if (ch == "|" && stream.eat("=")) return ret(null, "compare");
            else if (ch == "\"" || ch == "'") {
              state.tokenize = tokenString(ch);
              return state.tokenize(stream, state);
            }
              else if (ch == "/") { // e.g.: .png will not be parsed as a class
                if(stream.eat("/")){
                  state.tokenize = tokenSComment;
                  return tokenSComment(stream, state);
                }else{
                  if(type == "string" || type == "(") return ret("string", "string");
                  if(state.stack[state.stack.length-1] != undefined) return ret(null, ch);
                  stream.eatWhile(/[\a-zA-Z0-9\-_.\s]/);
                  if( /\/|\)|#/.test(stream.peek() || (stream.eatSpace() && stream.peek() == ")"))  || stream.eol() )return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
                }
              }
                else if (ch == "!") {
                  stream.match(/^\s*\w*/);
                  return ret("keyword", "important");
                }
                  else if (/\d/.test(ch)) {
                    stream.eatWhile(/[\w.%]/);
                    return ret("number", "unit");
                  }
                    else if (/[,+<>*\/]/.test(ch)) {
                      if(stream.peek() == "=" || type == "a")return ret("string", "string");
                      if(ch === ",")return ret(null, ch);
                      return ret(null, "select-op");
                    }
                      else if (/[;{}:\[\]()~\|]/.test(ch)) {
                        if(ch == ":"){
                          stream.eatWhile(/[a-z\\\-]/);
                          if( selectors.test(stream.current()) ){
                            return ret("tag", "tag");
                          }else if(stream.peek() == ":"){//::-webkit-search-decoration
                            stream.next();
                            stream.eatWhile(/[a-z\\\-]/);
                            if(stream.current().match(/\:\:\-(o|ms|moz|webkit)\-/))return ret("string", "string");
                            if( selectors.test(stream.current().substring(1)) )return ret("tag", "tag");
                            return ret(null, ch);
                          }else{
                            return ret(null, ch);
                          }
                        }else if(ch == "~"){
                          if(type == "r")return ret("string", "string");
                        }else{
                          return ret(null, ch);
                        }
                      }
                        else if (ch == ".") {
                          if(type == "(" || type == "string")return ret("string", "string"); // allow url(../image.png)
                          stream.eatWhile(/[\a-zA-Z0-9\-_]/);
                          if(stream.peek() == " ")stream.eatSpace();
                          if(stream.peek() == ")")return ret("number", "unit");//rgba(0,0,0,.25);
                          return ret("tag", "tag");
                        }
                          else if (ch == "#") {
                            //we don't eat white-space, we want the hex color and or id only
                            stream.eatWhile(/[A-Za-z0-9]/);
                            //check if there is a proper hex color length e.g. #eee || #eeeEEE
                            if(stream.current().length == 4 || stream.current().length == 7){
                              if(stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false) != null){//is there a valid hex color value present in the current stream
                                //when not a valid hex value, parse as id
                                if(stream.current().substring(1) != stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false))return ret("atom", "tag");
                                //eat white-space
                                stream.eatSpace();
                                //when hex value declaration doesn't end with [;,] but is does with a slash/cc comment treat it as an id, just like the other hex values that don't end with[;,]
                                if( /[\/<>.(){!$%^&*_\-\\?=+\|#'~`]/.test(stream.peek()) )return ret("atom", "tag");
                                //#time { color: #aaa }
                                else if(stream.peek() == "}" )return ret("number", "unit");
                                //we have a valid hex color value, parse as id whenever an element/class is defined after the hex(id) value e.g. #eee aaa || #eee .aaa
                                  else if( /[a-zA-Z\\]/.test(stream.peek()) )return ret("atom", "tag");
                                //when a hex value is on the end of a line, parse as id
                                    else if(stream.eol())return ret("atom", "tag");
                                //default
                                      else return ret("number", "unit");
                              }else{//when not a valid hexvalue in the current stream e.g. #footer
                                stream.eatWhile(/[\w\\\-]/);
                                return ret("atom", "tag");
                              }
                            }else{//when not a valid hexvalue length
                              stream.eatWhile(/[\w\\\-]/);
                              return ret("atom", "tag");
                            }
                          }
                            else if (ch == "&") {
                              stream.eatWhile(/[\w\-]/);
                              return ret(null, ch);
                            }
                              else {
                                stream.eatWhile(/[\w\\\-_%.{]/);
                                //console.log(type);
                                if(type == "string"){
                                  return ret("string", "string");
                                }else if(stream.current().match(/(^http$|^https$)/) != null){
                                  stream.eatWhile(/[\w\\\-_%.{:\/]/);
                                  return ret("string", "string");
                                }else if(stream.peek() == "<" || stream.peek() == ">" || stream.peek() == "+"){
                                  return ret("tag", "tag");
                                }else if( /\(/.test(stream.peek()) ){
                                  return ret(null, ch);
                                }else if (stream.peek() == "/" && state.stack[state.stack.length-1] != undefined){ // url(dir/center/image.png)
                                  return ret("string", "string");
                                }else if( stream.current().match(/\-\d|\-.\d/) ){ // match e.g.: -5px -0.4 etc... only colorize the minus sign
                                  //commment out these 2 comment if you want the minus sign to be parsed as null -500px
                                  //stream.backUp(stream.current().length-1);
                                  //return ret(null, ch);
                                  return ret("number", "unit");
                                }else if( /\/|[\s\)]/.test(stream.peek() || stream.eol() || (stream.eatSpace() && stream.peek() == "/")) && stream.current().indexOf(".") !== -1){
                                  if(stream.current().substring(stream.current().length-1,stream.current().length) == "{"){
                                    stream.backUp(1);
                                    return ret("tag", "tag");
                                  }//end if
                                  stream.eatSpace();
                                  if( /[{<>.a-zA-Z\/]/.test(stream.peek())  || stream.eol() )return ret("tag", "tag"); // e.g. button.icon-plus
                                  return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
                                }else if( stream.eol() || stream.peek() == "[" || stream.peek() == "#" || type == "tag" ){
                                  if(stream.current().substring(stream.current().length-1,stream.current().length) == "{")stream.backUp(1);
                                  return ret("tag", "tag");
                                }else if(type == "compare" || type == "a" || type == "("){
                                  return ret("string", "string");
                                }else if(type == "|" || stream.current() == "-" || type == "["){
                                  if(type == "|" )return ret("tag", "tag");
                                  return ret(null, ch);
                                }else if(stream.peek() == ":") {
                                  stream.next();
                                  var t_v = stream.peek() == ":" ? true : false;
                                  if(!t_v){
                                    var old_pos = stream.pos;
                                    var sc = stream.current().length;
                                    stream.eatWhile(/[a-z\\\-]/);
                                    var new_pos = stream.pos;
                                    if(stream.current().substring(sc-1).match(selectors) != null){
                                      stream.backUp(new_pos-(old_pos-1));
                                      return ret("tag", "tag");
                                    } else stream.backUp(new_pos-(old_pos-1));
                                  }else{
                                    stream.backUp(1);
                                  }
                                  if(t_v)return ret("tag", "tag"); else return ret("variable", "variable");
                                }else if(state.stack[state.stack.length-1]  === "font-family"){
                                  return ret(null, null);
                                }else{
                                  if(state.stack[state.stack.length-1] === "{" || type === "select-op"  || (state.stack[state.stack.length-1] === "rule" && type === ",") )return ret("tag", "tag");
                                  return ret("variable", "variable");
                                }
                              }
  }

  function tokenSComment(stream, state) { // SComment = Slash comment
    stream.skipToEnd();
    state.tokenize = tokenBase;
    return ret("comment", "comment");
  }

  function tokenCComment(stream, state) {
    var maybeEnd = false, ch;
    while ((ch = stream.next()) != null) {
      if (maybeEnd && ch == "/") {
        state.tokenize = tokenBase;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return ret("comment", "comment");
  }

  function tokenSGMLComment(stream, state) {
    var dashes = 0, ch;
    while ((ch = stream.next()) != null) {
      if (dashes >= 2 && ch == ">") {
        state.tokenize = tokenBase;
        break;
      }
      dashes = (ch == "-") ? dashes + 1 : 0;
    }
    return ret("comment", "comment");
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped)
          break;
        escaped = !escaped && ch == "\\";
      }
      if (!escaped) state.tokenize = tokenBase;
      return ret("string", "string");
    };
  }

  return {
    startState: function(base) {
      return {tokenize: tokenBase,
              baseIndent: base || 0,
              stack: []};
    },

    token: function(stream, state) {
      if (stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);

      var context = state.stack[state.stack.length-1];
      if (type == "hash" && context == "rule") style = "atom";
      else if (style == "variable") {
        if (context == "rule") style = null; //"tag"
        else if (!context || context == "@media{") {
          style = stream.current() == "when"  ? "variable" :
          /[\s,|\s\)|\s]/.test(stream.peek()) ? "tag"      : type;
        }
      }

      if (context == "rule" && /^[\{\};]$/.test(type))
        state.stack.pop();
      if (type == "{") {
        if (context == "@media") state.stack[state.stack.length-1] = "@media{";
        else state.stack.push("{");
      }
      else if (type == "}") state.stack.pop();
        else if (type == "@media") state.stack.push("@media");
          else if (stream.current() === "font-family") state.stack[state.stack.length-1] = "font-family";
            else if (context == "{" && type != "comment" && type !== "tag") state.stack.push("rule");
              else if (stream.peek() === ":" && stream.current().match(/@|#/) === null) style = type;
      return style;
    },

    indent: function(state, textAfter) {
      var n = state.stack.length;
      console.log(n);

      if (/^\}/.test(textAfter))
        n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
      return state.baseIndent + n * indentUnit;
    },

    electricChars: "}"
  };
});

CodeMirror.defineMIME("text/x-less", "less");
if (!CodeMirror.mimeModes.hasOwnProperty("text/css"))
  CodeMirror.defineMIME("text/css", "less");
<commit_msg>Update less.js<commit_after>/*
			LESS mode - http://www.lesscss.org/
			Ported to CodeMirror by Peter Kroon <plakroon@gmail.com>
			Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues
			GitHub: @peterkroon
	*/

CodeMirror.defineMode("less", function(config) {
	var indentUnit = config.indentUnit, type;
	function ret(style, tp) {type = tp; return style;}

	var selectors = /(^\:root$|^\:nth\-child$|^\:nth\-last\-child$|^\:nth\-of\-type$|^\:nth\-last\-of\-type$|^\:first\-child$|^\:last\-child$|^\:first\-of\-type$|^\:last\-of\-type$|^\:only\-child$|^\:only\-of\-type$|^\:empty$|^\:link|^\:visited$|^\:active$|^\:hover$|^\:focus$|^\:target$|^\:lang$|^\:enabled^\:disabled$|^\:checked$|^\:first\-line$|^\:first\-letter$|^\:before$|^\:after$|^\:not$|^\:required$|^\:invalid$)/;

	function tokenBase(stream, state) {
		var ch = stream.next();

		if (ch == "@") {stream.eatWhile(/[\w\-]/); return ret("meta", stream.current());}
		else if (ch == "/" && stream.eat("*")) {
			state.tokenize = tokenCComment;
			return tokenCComment(stream, state);
		}
			else if (ch == "<" && stream.eat("!")) {
				state.tokenize = tokenSGMLComment;
				return tokenSGMLComment(stream, state);
			}
				else if (ch == "=") ret(null, "compare");
					else if (ch == "|" && stream.eat("=")) return ret(null, "compare");
						else if (ch == "\"" || ch == "'") {
							state.tokenize = tokenString(ch);
							return state.tokenize(stream, state);
						}
							else if (ch == "/") { // e.g.: .png will not be parsed as a class
								if(stream.eat("/")){
									state.tokenize = tokenSComment;
									return tokenSComment(stream, state);
								}else{
									if(type == "string" || type == "(") return ret("string", "string");
									if(state.stack[state.stack.length-1] != undefined) return ret(null, ch);
									stream.eatWhile(/[\a-zA-Z0-9\-_.\s]/);
									if( /\/|\)|#/.test(stream.peek() || (stream.eatSpace() && stream.peek() == ")"))  || stream.eol() )return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
								}
							}
								else if (ch == "!") {
									stream.match(/^\s*\w*/);
									return ret("keyword", "important");
								}
									else if (/\d/.test(ch)) {
										stream.eatWhile(/[\w.%]/);
										return ret("number", "unit");
									}
										else if (/[,+<>*\/]/.test(ch)) {
											if(stream.peek() == "=" || type == "a")return ret("string", "string");
											if(ch === ",")return ret(null, ch);
											return ret(null, "select-op");
										}
											else if (/[;{}:\[\]()~\|]/.test(ch)) {
												if(ch == ":"){
													stream.eatWhile(/[a-z\\\-]/);
													if( selectors.test(stream.current()) ){
														return ret("tag", "tag");
													}else if(stream.peek() == ":"){//::-webkit-search-decoration
														stream.next();
														stream.eatWhile(/[a-z\\\-]/);
														if(stream.current().match(/\:\:\-(o|ms|moz|webkit)\-/))return ret("string", "string");
														if( selectors.test(stream.current().substring(1)) )return ret("tag", "tag");
														return ret(null, ch);
													}else{
														return ret(null, ch);
													}
												}else if(ch == "~"){
													if(type == "r")return ret("string", "string");
												}else{
													return ret(null, ch);
												}
											}
												else if (ch == ".") {
													if(type == "(" || type == "string")return ret("string", "string"); // allow url(../image.png)
													stream.eatWhile(/[\a-zA-Z0-9\-_]/);
													if(stream.peek() == " ")stream.eatSpace();
													if(stream.peek() == ")")return ret("number", "unit");//rgba(0,0,0,.25);
													return ret("tag", "tag");
												}
													else if (ch == "#") {
														//we don't eat white-space, we want the hex color and or id only
														stream.eatWhile(/[A-Za-z0-9]/);
														//check if there is a proper hex color length e.g. #eee || #eeeEEE
														if(stream.current().length == 4 || stream.current().length == 7){
															if(stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false) != null){//is there a valid hex color value present in the current stream
																//when not a valid hex value, parse as id
																if(stream.current().substring(1) != stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false))return ret("atom", "tag");
																//eat white-space
																stream.eatSpace();
																//when hex value declaration doesn't end with [;,] but is does with a slash/cc comment treat it as an id, just like the other hex values that don't end with[;,]
																if( /[\/<>.(){!$%^&*_\-\\?=+\|#'~`]/.test(stream.peek()) )return ret("atom", "tag");
																//#time { color: #aaa }
																else if(stream.peek() == "}" )return ret("number", "unit");
																//we have a valid hex color value, parse as id whenever an element/class is defined after the hex(id) value e.g. #eee aaa || #eee .aaa
																	else if( /[a-zA-Z\\]/.test(stream.peek()) )return ret("atom", "tag");
																//when a hex value is on the end of a line, parse as id
																		else if(stream.eol())return ret("atom", "tag");
																//default
																			else return ret("number", "unit");
															}else{//when not a valid hexvalue in the current stream e.g. #footer
																stream.eatWhile(/[\w\\\-]/);
																return ret("atom", "tag");
															}
														}else{//when not a valid hexvalue length
															stream.eatWhile(/[\w\\\-]/);
															return ret("atom", "tag");
														}
													}
														else if (ch == "&") {
															stream.eatWhile(/[\w\-]/);
															return ret(null, ch);
														}
															else {
																stream.eatWhile(/[\w\\\-_%.{]/);
																//console.log(type);
																if(type == "string"){
																	return ret("string", "string");
																}else if(stream.current().match(/(^http$|^https$)/) != null){
																	stream.eatWhile(/[\w\\\-_%.{:\/]/);
																	return ret("string", "string");
																}else if(stream.peek() == "<" || stream.peek() == ">" || stream.peek() == "+"){
																	return ret("tag", "tag");
																}else if( /\(/.test(stream.peek()) ){
																	return ret(null, ch);
																}else if (stream.peek() == "/" && state.stack[state.stack.length-1] != undefined){ // url(dir/center/image.png)
																	return ret("string", "string");
																}else if( stream.current().match(/\-\d|\-.\d/) ){ // match e.g.: -5px -0.4 etc... only colorize the minus sign
																	//commment out these 2 comment if you want the minus sign to be parsed as null -500px
																	//stream.backUp(stream.current().length-1);
																	//return ret(null, ch);
																	return ret("number", "unit");
																}else if( /\/|[\s\)]/.test(stream.peek() || stream.eol() || (stream.eatSpace() && stream.peek() == "/")) && stream.current().indexOf(".") !== -1){
																	if(stream.current().substring(stream.current().length-1,stream.current().length) == "{"){
																		stream.backUp(1);
																		return ret("tag", "tag");
																	}//end if
																	stream.eatSpace();
																	if( /[{<>.a-zA-Z\/]/.test(stream.peek())  || stream.eol() )return ret("tag", "tag"); // e.g. button.icon-plus
																	return ret("string", "string"); // let url(/images/logo.png) without quotes return as string
																}else if( stream.eol() || stream.peek() == "[" || stream.peek() == "#" || type == "tag" ){
																	if(stream.current().substring(stream.current().length-1,stream.current().length) == "{")stream.backUp(1);
																	return ret("tag", "tag");
																}else if(type == "compare" || type == "a" || type == "("){
																	return ret("string", "string");
																}else if(type == "|" || stream.current() == "-" || type == "["){
																	if(type == "|" )return ret("tag", "tag");
																	return ret(null, ch);
																}else if(stream.peek() == ":") {
																	stream.next();
																	var t_v = stream.peek() == ":" ? true : false;
																	if(!t_v){
																		var old_pos = stream.pos;
																		var sc = stream.current().length;
																		stream.eatWhile(/[a-z\\\-]/);
																		var new_pos = stream.pos;
																		if(stream.current().substring(sc-1).match(selectors) != null){
																			stream.backUp(new_pos-(old_pos-1));
																			return ret("tag", "tag");
																		} else stream.backUp(new_pos-(old_pos-1));
																	}else{
																		stream.backUp(1);
																	}
																	if(t_v)return ret("tag", "tag"); else return ret("variable", "variable");
																}else if(state.stack[state.stack.length-1]  === "font-family"){
																	return ret(null, null);
																}else{
																	if(state.stack[state.stack.length-1] === "{" || type === "select-op"  || (state.stack[state.stack.length-1] === "rule" && type === ",") )return ret("tag", "tag");
																	return ret("variable", "variable");
																}
															}
	}

	function tokenSComment(stream, state) { // SComment = Slash comment
		stream.skipToEnd();
		state.tokenize = tokenBase;
		return ret("comment", "comment");
	}

	function tokenCComment(stream, state) {
		var maybeEnd = false, ch;
		while ((ch = stream.next()) != null) {
			if (maybeEnd && ch == "/") {
				state.tokenize = tokenBase;
				break;
			}
			maybeEnd = (ch == "*");
		}
		return ret("comment", "comment");
	}

	function tokenSGMLComment(stream, state) {
		var dashes = 0, ch;
		while ((ch = stream.next()) != null) {
			if (dashes >= 2 && ch == ">") {
				state.tokenize = tokenBase;
				break;
			}
			dashes = (ch == "-") ? dashes + 1 : 0;
		}
		return ret("comment", "comment");
	}

	function tokenString(quote) {
		return function(stream, state) {
			var escaped = false, ch;
			while ((ch = stream.next()) != null) {
				if (ch == quote && !escaped)
					break;
				escaped = !escaped && ch == "\\";
			}
			if (!escaped) state.tokenize = tokenBase;
			return ret("string", "string");
		};
	}

	return {
		startState: function(base) {
			return {tokenize: tokenBase,
							baseIndent: base || 0,
							stack: []};
		},

		token: function(stream, state) {
			if (stream.eatSpace()) return null;
			var style = state.tokenize(stream, state);

			var context = state.stack[state.stack.length-1];
			if (type == "hash" && context == "rule") style = "atom";
			else if (style == "variable") {
				if (context == "rule") style = null; //"tag"
				else if (!context || context == "@media{") {
					style = stream.current() == "when"  ? "variable" :
					/[\s,|\s\)|\s]/.test(stream.peek()) ? "tag"      : type;
				}
			}

			if (context == "rule" && /^[\{\};]$/.test(type))
				state.stack.pop();
			if (type == "{") {
				if (context == "@media") state.stack[state.stack.length-1] = "@media{";
				else state.stack.push("{");
			}
			else if (type == "}") state.stack.pop();
				else if (type == "@media") state.stack.push("@media");
					else if (stream.current() === "font-family") state.stack[state.stack.length-1] = "font-family";
						else if (context == "{" && type != "comment" && type !== "tag") state.stack.push("rule");
							else if (stream.peek() === ":" && stream.current().match(/@|#/) === null) style = type;
			return style;
		},

		indent: function(state, textAfter) {
			var n = state.stack.length;
			console.log(n);

			if (/^\}/.test(textAfter))
				n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1;
			return state.baseIndent + n * indentUnit;
		},

		electricChars: "}"
	};
});

CodeMirror.defineMIME("text/x-less", "less");
if (!CodeMirror.mimeModes.hasOwnProperty("text/css"))
	CodeMirror.defineMIME("text/css", "less");
<|endoftext|>