(function() {
	'use strict';

	var tank_color_map = {
		'gray': '#a2a2a2',
		'green': '#98B266',
		'yellow': '#ffc700', //FEDA5A
		'orange': '#F29400',
		'red': '#D66363' // E2444B
	};
	
	function add_tank(full_name, spec, dc_name) {
	    //(spec ? '* ' : '') +
		if (dc_name !== 'rtc') {
			if (!full_name.match('\.yandex\.net$')) {
	    		full_name = full_name.concat(".yandex.net")
			}
		}
	    var name=full_name.split('.')[0].replace(/-all-rcloud-tanks-30169/g, "");
	    var title = name;
	    var res = '<table id="tank_' + name + '"><tr> \
	        <td style="padding-right:0.1em; vertical-align: top;">';
	    if (spec) {
	    	res += '<img title="Спецтанк" class="tank tankSpec" src="/media/img/tank_gray_spec.svg" height="30" width="45" title=\'Спецтанк\' id="tank_img_' + name + '"/><br/><span id="tank_info_tech_' + name + '"></span>';
	        res += '</td> \
		        <td> \
		            <span class="tankname tank" style="color: '+tank_color_map['gray']+';" id="tank_name_' + name + '">' + title + '</span><br/> \
		            <span class="icons" id="tank_info_' + name + '">&nbsp;</span> \
		        </td> \
		    </tr></table>';
	    }
	    else {
	    	res += '<a href="/firestarter/?use_tank=' + full_name + '"><img class="tank" src="/media/img/tank_gray.svg" height="30" width="45" id="tank_img_' + name + '"/></a><br/><span id="tank_info_tech_' + name + '"></span>';
	    	res += '</td> \
		        <td> \
		            <a class="tankname tank" href="/firestarter/?use_tank=' + full_name + '" style="color: '+tank_color_map['gray']+';" id="tank_name_' + name + '">' + title + '</a><br/> \
		            <span class="icons" id="tank_info_' + name + '">&nbsp;</span> \
		        </td> \
		    </tr></table>';
	    }

	    return res;
    }
    function decrease_brightness(hex, percent){
	    // strip the leading # if it's there
	    hex = hex.replace(/^\s*#|\s*$/g, '');

	    // convert 3 char codes --> 6, e.g. `E0F` --> `EE00FF`
	    if(hex.length === 3){
	        hex = hex.replace(/(.)/g, '$1$1');
	    }

	    var r = parseInt(hex.substr(0, 2), 16),
	        g = parseInt(hex.substr(2, 2), 16),
	        b = parseInt(hex.substr(4, 2), 16);

	    return '#' +
	       ((0|(1<<8) + r - percent).toString(16)).substr(1) +
	       ((0|(1<<8) + g - percent).toString(16)).substr(1) +
	       ((0|(1<<8) + b - percent).toString(16)).substr(1);
    }
    function hexToRgb(hex) {
	    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
	    return result ? ''+parseInt(result[1], 16)+','+parseInt(result[2], 16)+','+parseInt(result[3], 16)+'' : null;
    }
    function add_dc(name, color, tanks, spec) {
		
		var shadow = hexToRgb(decrease_brightness(color, 7));
		
	    var head = '<div class="one-dc" style="background: '+color+';\
		    background-repeat: repeat-x; \
		    box-shadow: 0 2px rgba('+ shadow +', 0.07);\
		    border: 1px solid '+decrease_brightness(color, 7)+'"> \
	    <svg xmlns="//www.w3.org/2000/svg">  \
	    <text x="-30" y="15" transform="rotate(-90)" text-rendering="optimizeSpeed">' + name + '</text> \
	    </svg>';
	    var foot = '</div>';
	
	    var res = '';
	    for (var n = 0; n < tanks.length; n++) {
	        res += add_tank(tanks[n], false, name);
	    }
	
	    for (var n = 0; n < spec.length; n++) {
	        res += add_tank(spec[n], true, name);
	    }
	
	    return head + res + foot;
    }
    function refresh_statuses(blink) {
	    $.ajax('/api/tank/status.html', {
	        success: function(data) {
	            var tanks = $(data);
	            for (var n = 0; n < tanks.length; n++) {
	                var tank = tanks[n];
	                if (tank.tagName !== "TANK")
	                    continue;
	
	                var name = tank_attr(tank, "name").innerHTML;
	                if (name) {
	                    //console.info(name);
	                    refresh_tank_status(tank, blink);
	                }
	            }
	        }
	    });
	    window.setTimeout(function() { refresh_statuses(true); }, 15000);
    }
    function initial_layout() {
	    $.getJSON("/media/tanks_struct.json", function(dcs) {
		    $.getJSON("/api/tanks_map.json", function(data) {
		        for (var n in data){
		            if (dcs[data[n][1]]) {
		            	if (data[n][2]) {
		                    dcs[data[n][1]]['spec'].push(data[n][0]);
						} else {
							dcs[data[n][1]]['tanks'].push(data[n][0]);
						}
					}
		        }
	
		        var res = '';
		        for (var dc in dcs) {
		            res += add_dc(dc, dcs[dc]["color"], dcs[dc]["tanks"], dcs[dc]["spec"]);
		        }
		        
		        $("div.dc").html(res);
		        
	            window.setTimeout(function() { refresh_statuses(false); }, 50);
		    });
	
		});

}
    function tank_attr(tank, name) {
	    for (var n = 0; n < tank.children.length; n++) {
	        if (tank.children[n].tagName === name.toUpperCase()) {
	            return tank.children[n];
	        }
	    }
	
	    return false;
    }
    function refresh_tank_status(tank, blink) {

	    var name = tank_attr(tank, "name").innerHTML;
	    var spec = $("#tank_img_" + name).hasClass('tankSpec');
	    // get values
	    var color = tank_attr(tank, "color").innerHTML;
	    if (color === "grey")
	        color = "gray";
	
	    var fontColor = tank_color_map[color];
	    var msg = tank_attr(tank, "msg").innerHTML.split("<br>");
	
	    // modify values
	    var info_tech = "";
	    var hdd = false;
	    var online = false;
	    var users = {};
	    var proc = "";
	    for (var n = 0; n < msg.length; n++) {
	        if (msg[n] === "")
	            continue;
	
	        if (msg[n].match(/Usage:/)) {
                info_tech += get_icon("hdd", msg[n], color);
	            hdd = true;
	        } else if (msg[n].match(/idle/)) {
	            var user = msg[n].match(/([^ ]+) /)[1];
	            user = user.replace(/(<([^>]+)>)/ig, "").trim();
            	if (!users[user]) {
            		users[user]=[];
            	}
	        } else if (msg[n].match(/CPU/)) {
	            proc += msg[n] + "\n";
	            var user = msg[n].replace(/(<([^>]+)>)/ig, "").match(/\(([^ ]+) /)[1];
            	if (!users[user]) {
            		users[user]=[];
            	}
	        } else if (msg[n].match(/urlopen/)) {
	            info_tech += get_icon("disconnect", msg[n], '');
	        } else if (msg[n].match(/<a href/)) {
	            var job = msg[n].match(/(<a.+<\/a>)/);
	            var user = msg[n].replace(/(<([^>]+)>)/ig, "").match(/\(([^\)]+)\)/);
	            if (user) {
	            	user=user[1];
	            	if (!users[user]) {
	            		users[user]=[];
	            	}
	            	users[user].push("<span>" + job[0] + "</span> ");
	            	//get_user_icon(user, msg[n]) + 
	            	online = true;
	           }
	        } else {
	            ///console.info(msg[n]);
	        }
	    }
	
	    var usr_info = "";
	    for (var user in users) {
	    	if (!users[user].length) {	    		
	        	usr_info += get_user_icon(user, user);
	    	}
	    }
	
	    var info = "";
	    for (var user in users) {
	    	if (users[user].length) {	    		
	        	info += get_user_icon(user, user)+users[user].join(" ");
	    	}
	    }

	    if (proc) {
	        info_tech += get_icon("cpu", proc.trim(), color);
	    }
	
	    info = usr_info + info_tech +(usr_info||info_tech?'<br/>':'') + info;
	
	    if (color === "red" && hdd && !online) {
	        color = "orange";
	        fontColor = tank_color_map[color];
	    }
	
	    if (info === "")
	        info = "&nbsp;";
	
	    // check for blink
	    var modified = false;
	    if (spec === true) {
	        modified |= $("#tank_img_" + name).attr("src") !== "/media/img/tank_" + color + "_spec.svg";
        } else {
	        modified |= $("#tank_img_" + name).attr("src") !== "/media/img/tank_" + color + ".svg";
        }

	    modified |= $("#tank_info_" + name).attr("info") !== info.replace(/(<([^>]+)>)/ig, "");
	    modified |= $("#tank_info_" + name).attr("info_tech") !== info_tech.replace(/(<([^>]+)>)/ig, "");
	    modified |= $("#tank_name_" + name).getCSSColorHex("color").toUpperCase() !== fontColor.toUpperCase();
	
	    // apply
	    if (modified) {
	        if (blink) {
	            $("#tank_" + name).fadeOut(500);
	            //console.info($("#tank_info_" + name).html());
	        }
	
	        $("#tank_name_" + name).css("color", fontColor);
	        if (spec === true) {
                $("#tank_img_" + name).attr("src", "/media/img/tank_" + color + "_spec.svg");
            } else {
                $("#tank_img_" + name).attr("src", "/media/img/tank_" + color + ".svg");
            }
	        $("#tank_info_" + name).html(info);
	        //$("#tank_info_tech_" + name).html(info_tech);
	        $("#tank_info_" + name).attr("info", info.replace(/(<([^>]+)>)/ig, ""));
	        $("#tank_info_" + name).attr("info_tech", info_tech.replace(/(<([^>]+)>)/ig, ""));
	
	        if (blink) {
	            $("#tank_" + name).fadeIn(500);
	            $("#tank_" + name).fadeOut(250);
	            $("#tank_" + name).fadeIn(250);
	            $("#tank_" + name).fadeOut(250);
	            $("#tank_" + name).fadeIn(250);
	        }
        	
	    }
    }
    // http://stackoverflow.com/questions/3048838/jquery-css-color-value-returns-rgb
	$.fn.getCSSColorHex = function(style) {
	    var rgb = $(this).css(style);
	    if (!rgb) {
	        return '#FFFFFF'; //default color
	    }
	    var hex_rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
	    function hex(x) {
	        return ("0" + parseInt(x).toString(16)).slice(-2);
	    }
	    if (hex_rgb) {
	        return "#" + hex(hex_rgb[1]) + hex(hex_rgb[2]) + hex(hex_rgb[3]);
	    } else {
	        return rgb; //ie8 returns background-color in hex format then it will make                 compatible, you can improve it checking if format is in hexadecimal
	    }
	};
	
	function get_icon(type, tooltip, color) {
	    return '<img title="' + tooltip.replace(/(<([^>]+)>)/ig, "") + '" src="/media/img/' + type + '_' + color + '.svg" height="16px"/>';
    }
    function get_user_icon(user, title) {
		var res='<a href="//staff.yandex-team.ru/'+user+'" style="display: inline" class="auto-person-card" data-login="'+user+'" title="'+user+'"><img width="16" height="16" ';
		res+=' class="img-circle" src="//center.yandex-team.ru/user/avatar/' + user + '/32/square" height="16" width="16"';
		res+='style="display: inline" /></a>';
	    return res;
    }
    initial_layout();
	
	function ui_set__show_tanks(value) {
		if (!value) {
			value = ''
		}
		$.get('/ui_set/?param=show_tanks&value='+value)
    }
    $(".mainpage-tanks__switch").click(function(){
    	$(".mainpage-tanks__switch:hidden").show();
    	$(this).hide();
    	
    	var filter = !$(this).data('showtanks');
    	$('#mainpage_tanks').toggle();
        ui_set__show_tanks(filter);
    });
	
})();
	
