function getYearsData(min_year, max_year) {
    var years = [];
    while(min_year <= max_year) {
        years.unshift({"value": min_year, "title": min_year});
        min_year++;
    }

    return years;
}

function select_file(parent) {
    var file = $(parent).next('input[type=file]');
    file.val(null);
    file.click();
}

function convertImage(source, onComplete, maxW, maxH) {
    var img = new Image;
    img.onload = function() {
        var iw=img.width;
        var ih=img.height;
        var scale=Math.min((maxW/iw),(maxH/ih));
        var iwScaled=iw*scale;
        var ihScaled=ih*scale;
        var canvas=document.createElement("canvas");
        canvas.width=iwScaled;
        canvas.height=ihScaled;

        var ctx=canvas.getContext("2d");
        ctx.drawImage(img,0,0,iwScaled,ihScaled);
        var data = canvas.toDataURL();
        onComplete(data);
    };
    img.src = source;
}

function createOption($select, value, text, selected) {
	var option = $('<option/>');
	option.prop('value', value).text(text);
	if (selected) option.prop('selected', true);
	$select.append(option);
	return option;
}

function fillSelect(data, $select, value, text, placeholder, selected) {
	$select.empty();
	if (placeholder) {
		createOption($select, null, placeholder, !selected);
	}

	$.each(data, function(i, obj) {
		createOption($select, obj[value], obj[text], selected == obj[value]);
	});
	$select.prop('disabled', false);
}

function fillSelectWithMore(data, select, value, text, placeholder, showMore, selected, moreText) {
    if ( ! select) throw 'no control';
    fillSelect(data, select, value, text, [placeholder].join(' '), selected);
    if (showMore) createOption(select, 'more', [moreText ? moreText : '---- Показать все'].join(' '));
}

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}

function filedataToMimeType(buffer) {
    var int32View = new Int32Array(buffer);
    switch(int32View[0]) {
        case 1196314761:
            return "image/png";
            break;
        case 944130375:
            return "image/gif";
            break;
        case 544099650:
            return "image/bmp";
            break;
        case -520103681:
            return "image/jpg";
            break;
        default:
            return "unknown";
            break;
    }
}

window.getStrForm = function (count, forms) {
    return count + ' ' + getRussianNounForm(count, forms);
}

function stripTags(html)
{
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || "";
}
function trimString(str, chars) {
    return str.trim().replace("/(^["+ chars +"])|([" + chars + "]$)/g", "").trim();
}
function stringifyHtml(html, stringsCount, containerWidth) {
    var div = document.createElement("div");
    div.innerHTML = html;
    var $img = $(div).find('img');
    var $embed = $(div).find('[data-oembed-url]');
    $(div).remove('[data-oembed-url]');
    $(div).remove('img');

    var $boundBox = $('<div></div>');
    $boundBox.css('position', 'absolute')
        .css('overflow', 'visible')
        .css('white-space', 'normal')
        .width(containerWidth + 'px')
        .height('auto')
        .css('font-size', '14px');
    $('body').after($boundBox);

    function accommodation() {
        return $boundBox.height() < 14 * stringsCount; // line-height * strings-count
    };

    var sourceText = div.innerText;
    var words = sourceText.split(" ");
    var truncatedText = '';
    var chars = "\,\.\;\:\?\!";
    do {
        truncatedText += words.shift() + " ";
        $boundBox.html(trimString(truncatedText, chars) + "...");
    } while (words.length > 0 && accommodation());

    truncatedText = trimString(truncatedText, chars);
    if (words.length > 0) {
        truncatedText = truncatedText.substring(-3);
        truncatedText += '...';
    }
    $boundBox.html(truncatedText);
    $boundBox.remove();

    var text = $boundBox.html();
    text = '<span class="inner-text">' + text + '</span>';
    if ($img.prop('outerHTML')) {
        text += $img.prop('outerHTML');
    }
    if ($embed.prop('outerHTML')) {
        text += $embed.prop('outerHTML');
    }
    return text;
}
/**
 *
 * @param int count количество сущностей от которых зависит окончание существителього
 * @param array	forms формы существительного (3): 0 - для 1(21..), 1 - для 2(22..), 3(23..), 4(24..), 2 - для 0, 5(25..) - 20(30..)
 * @return string существительное в правильной форме
 *
 */
window.getRussianNounForm = function(count, forms) {
    var rest = 0;
    if ((count >= 10 && count <= 20) || (count % 100 >= 10 && count % 100 <= 20)) {
        rest = count;
    } else {
        rest = count % 10;
    }

    var index = 2;

    if (rest > 0) {
        if (rest < 2) {
            index = 0;
        } else if (rest < 5) {
            index = 1;
        }
    }

    return forms[index];
}

function getRatingStr(rating) {
    if (rating > 9) {
        return 'потрясающе';
    } else if (rating > 8) {
        return 'великолепно';
    } else if (rating > 7) {
        return 'отлично';
    } else if (rating > 6) {
        return 'хорошо';
    } else if (rating > 5) {
        return 'выше среднего';
    } else if (rating > 4) {
        return 'удовлетворительно';
    } else if (!rating) {
        return 'нет';
    } else {
        return 'плохо';
    }
};

function openInNewTab(url) {
    var win = window.open(url, '_blank');
    win.focus();
}

//js

function throwError(message) {
    throw new Error(message);
}

window.prettyNumber = function(floatNum) {
    var positive = floatNum >= 0;
    floatNum = Math.abs(floatNum);

    var result = null;
    if (parseInt(floatNum) == floatNum || floatNum - parseInt(floatNum) <= 0) {
        result = $.number(parseInt(floatNum), 0, ',', ' ');
    } else {
        result = $.number(floatNum, 1, ',', ' ');
    }

    return (positive ? '' : '-') + result;
}