var changed; // for table row color
var locker = false;
var tOut;

function open_window (w, h, t, d) {
	var w, h, t, d;
	t == 'undefined' ? 'Новое окно' : t;
	d == 'undefined' ? '' : d;
	var content = '<html><head><title>' + t + '</title>';
	content += '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
	content += '<link type="text/css" rel="stylesheet" href="/css/main.css" />';
    content += '</head><body><table cellspacing="0" cellpadding="0" border="0" width="100%" height="100%">'; // onblur="window.close();"
    content += '<tr><td align="center" valign="middle">' + d;
    content += '</td></tr></table></body></html>';
    var newWin = window.open('', '', 'width=' + w + ',height=' + h);
    if (newWin) {
        newWin.document.write(content);
        newWin.document.close();
        newWin.focus();
    }
}

function reformat_date (str, dev, reverse) {
	var str, dev, res = '';
	var months = new Array('января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
                           'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
    var tmp = str.split(dev);
    if (tmp[0] == 'undefined' || tmp[1] == 'undefined' || tmp[2] == 'undefined') return str;
    if (reverse) {
    	return tmp[0].replace(/^0{1}/, '') + ' ' + months[parseInt(tmp[1].replace(/^0{1}/, '')) - 1] + ' ' + tmp[2] + ' года';
    }
    res += (parseInt(tmp[0]) < 10) ? '0' + tmp[0] : tmp[0];
    for (var i = 0; i < months.length; i++) {
    	if (tmp[1].match(months[i])) {
    		var month = (i + 1 < 10) ? '0' + (i + 1) : i + 1;
    		res += '.' + tmp[1].replace(months[i], month);
    	}
    }
    return res += '.' + tmp[2];
}

function show_note (obj, kit, pretext) {
    var obj, pretext;
    var kit = parseInt(kit);
    var Notes = new Array ( '',
                            'НАЖМИТЕ, ЧТОБЫ СКАЧАТЬ',
                            'ЗАКАЗАТЬ БИЛЕТ НА ЭТОТ РЕЙС');
    var separator = '<hr style="width:175px;" \/>';
    var text = (pretext ? pretext + (kit != 0 ? separator : '') : '') + Notes[kit];
    if (!locker) {
        $(obj).mousemove(function (e) {
            if ( e.pageY && e.pageX ) {
                $('#floating').css('top', e.pageY + 20);
                $('#floating').css('left', e.pageX + 15);
            } else {
                $('#floating').css('top', e.clientY + 20);
                $('#floating').css('left', e.clientX + 15);
            }
        });
        $('#floating').html(text).show(50);
        window.setTimeout('hide_note()', 10000);
    }
}

function hide_note () {
    $('#floating').hide(100);
}

function hider () {
	$('#alert, .alert').empty().hide();
	clearTimeout(tOut);
}

function alert_show () {
	var t = (location.href.indexOf('admin') != -1) ? 12000 : 4000;
	tOut = window.setTimeout('hider()', t);
}

function show_block (str) {
	var str;
	$('#' + str).toggle();
	$('#add').hide();
}

function make_width () {
    if (location.pathname.indexOf('admin') == -1) {
        var label, textarea, input, width = parseInt($('body').width());
        if (width > 1275) {
            label = '200px';
            textarea = (width - 740) + 'px';
            input = '250px';
        }
        else {
            label = '150px';
            textarea = (width > 750) ? (width - 675) + 'px' : '150px';
            input = (width > 800) ? (width - 725) / 2 + 'px' : '50px';
        }
        $('label').width(label);
        $('textarea').width(textarea);
    }
}

$(document).ready( function () {

	// различные иконки
    $('#home, #mail, #tree, #add, #adm_mail, #exit, .pen, .cutter, .cross, .closer, .cutter_news').hover( function() {
        var src = $(this).attr('src');
        var note = '';
        switch ( $(this).attr('id') ) {
        	case 'home': note = 'НА ГЛАВНУЮ'; break;
        	case 'mail': note = 'ОТПРАВИТЬ ПИСЬМО'; break;
        	case 'adm_mail': note = 'ОТПРАВИТЬ ПИСЬМО АДМИНИСТРАТОРУ САЙТА'; break;
        	case 'tree': note = 'КАРТА САЙТА'; break;
        	case 'add': note = 'ДОБАВИТЬ ЗАПИСЬ В ГОСТЕВУЮ'; break;
        	case 'exit': note = 'ВЫХОД'; break;
        }
        switch ( $(this).attr('class') ) {
        	case 'pen': note = 'ДОБАВИТЬ/РЕДАКТИРОВАТЬ ОТВЕТ'; break;
        	case 'cutter': note = 'РЕДАКТИРОВАТЬ ТЕКСТ'; break;
        	case 'cross': note = 'УДАЛИТЬ'; break;
        	case 'closer': note = 'ЗАКРЫТЬ ФОРМУ'; break;
        	case 'cutter_news': note = 'РЕДАКТИРОВАТЬ НОВОСТЬ'; break;
        }
        $(this).attr('src', src.replace('.png', '_h.png'));
        show_note($(this), 0, note);
    }, function() {
        var src = $(this).attr('src');
        $(this).attr('src', src.replace('_h.png', '.png'));
        hide_note();
    });

    // убирает окно ошибки
    alert_show();

    // подсветка строчек таблицы
	$('.t_1, .t_2').hover(
    function () {
        changed = $(this).css('background-color');
        $(this).css('background-color', '#eeeeee');
    },
    function () {
        $(this).css('background-color', changed);
        hide_note();
    });

    // закрывающий крестик
    $('.closer').click( function() {
    	$('#plus_news').show();
    	$('#hide_field').hide();
    	$('#add_div').hide();
    	$('#add').show();
    });

    // ресет каптчи
    $('#reset_btn').click( function() {
    	$('#captcha').attr('src', '/inc/captcha.php?r=' + Math.round(Math.random() * 100000));
    	return false;
    });

    // подписи над файлами
    $('.files img').hover( function() {
        var info = $(this).attr('info').split('|');
        var str = '';
        if (info[0] != 'undefined') str += 'Размер ' + info[0] + '.';
        if (info[0] != 'undefined' && info[1] != 'undefined') str += '<br />';
        if (info[1] != 'undefined') str += 'Файл в формате *.' + info[1];
        show_note($(this), 1, str);
    }, function() {
        hide_note();
    });

    // подсвечивание фона таблицы
    $('.elem, table.files tr').hover( function() {
    	$(this).css('background', '#ededed');
    }, function() {
    	$(this).css('background', '#fafafa');
    });

    // открывание схем маршрутов, возможно сделать готовый документ
    $('[@name=region]').change( function() {
    	var regExp = /ий$/;
    	var curSch = $(this).val();
    	if (!curSch) return false;
    	var curName = $(this).find('option[@value=\'' + curSch + '\']').text();
    	var title = 'Схема маршрутов по ' + curName.replace(regExp, 'ому') + ' району';
    	var content = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ';
        content += 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" ';
        content += 'width="640" height="480">';
        content += '<param name="movie" value="/img/schemes.swf" />';
        content += '<param name="quality" value="high" />';
        content += '<param name="FlashVars" value="outer=' + curSch + '" />';
        content += '<embed src="/img/schemes.swf" quality="high" ';
        content += 'pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" ';
        content += 'FlashVars="outer=' + curSch + '" type="application/x-shockwave-flash" width="640" height="480">';
        content += '</embed></object>';
        content += '<script type="text/javascript" language="JavaScript">';
        //content += 'document.onBlur = function () {window.close();}';
        content += '</script>';
    	open_window(640, 480, title, content);
    	$(this).find('option[@value=\'\']').attr('selected', 'selected');
    });

    // для маленького разрешения
    make_width();
    $(window).resize( function () { make_width(); });

});