var gulp = require('gulp'),
    util = require('gulp-util'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    livereload = require('gulp-livereload'),
    // combine = require('gulp-combine-media-queries'),
    group = require('gulp-group-css-media-queries'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),

    paths = {
        sass : ['sass/**/*.scss'],
        templates: ['*.html'],
        js: [
            'mysite/javascript/jquery-1.7.2.min.js',
            'mysite/javascript/google-maps-api.js',

            'job-ads/text-fill.js',
            'joboffers/javascript/joboffers.js',

            'contact/javascript/contactform.js',
            'contact/javascript/contactformemployee.js',

            'mysite/javascript/common.js'
        ]
    };

var res = 'mysite/';
// var res = 'lorem-ipsum/';

function errorHandler(err) {
    'use strict';

    util.log(err.message);
    this.emit('end');
}

// gulp.task('reloadJS', function(){
//     'use strict';

//     return gulp.src(paths.js)
//         .pipe(livereload()).on('error', errorHandler);
// });

gulp.task('concatJS', function() {
    'use strict';

    return gulp.src(paths.js)
    .pipe(concat('main.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest(res + 'javascript/'));

});

gulp.task('reloadHTML', function(){
    'use strict';

    return gulp.src(paths.templates)
        .pipe(livereload()).on('error', errorHandler);
});

gulp.task('compass', function(){
    'use strict';

    return gulp.src(paths.sass)
        .pipe(sass({compass: true, sourcemap: false, style: 'expanded'})).on('error', errorHandler)
        .pipe(autoprefixer({browsers: ['Firefox > 25', 'last 2 Chrome versions', 'Safari 5', 'IE > 8', 'iOS > 3', 'Android > 2', 'last 2 ExplorerMobile versions']})).on('error', errorHandler)
        .pipe(group()).on('error', errorHandler)
        .pipe(minifycss()).on('error', errorHandler)
        .pipe(gulp.dest(res + 'css')).on('error', errorHandler)
        .pipe(livereload()).on('error', errorHandler);

});

gulp.task('watch', function(){
    'use strict';

    livereload.listen();

    util.log(livereload.server);

    gulp.watch(paths.sass, ['compass']).on('error', errorHandler);
    gulp.watch(paths.templates, ['reloadHTML']).on('error', errorHandler);
});

gulp.task('default', ['concatJS', 'compass', 'watch']);
// gulp.task('default', ['compass', 'watch']);
