/*
 * Mantis - a php based bugtracking system
 * Copyright (C) 2000 - 2002  Kenzaburo Ito - kenito@300baud.org
 * Copyright (C) 2002 - 2004  Mantis Team   - mantisbt-dev@lists.sourceforge.net
 * This program is distributed under the terms and conditions of the GPL
 * See the README and LICENSE files for details
 *
 * --------------------------------------------------------
 * $Id: common.js,v 1.1.1.1 2007/05/02 09:07:27 heman Exp $
 * --------------------------------------------------------
 */


function setBgColor(name, color) {
    obj = document.getElementById(name);
    // непосредственно смена при наведении не нужна
    //obj.style.background = color;
}

function setBugnoteColor(bugnote_id, bugnote_color){
	ShowHideDiv('bugnote_color_picker' + bugnote_id);
	var xmlHttp = new XMLHttpRequest();
	td = document.getElementById('td_' + bugnote_id);
	icon = document.getElementById('process_icon_' + bugnote_id);
	icon.innerHTML = '<img src="/i/process.gif"></img>';
	xmlHttp.open('get', '/bugnote_set_color.php?ajax=1&bugnote_id=' + bugnote_id + '&bugnote_color=' + bugnote_color);
	xmlHttp.send(null);
	xmlHttp.onreadystatechange=function(){
		if (xmlHttp.readyState != 4) return
		if(xmlHttp.responseText == 'ok'){
			var color = ls_bugnote_color_arr[bugnote_color] ;
			td.style.background = color;
			//если след. tr с классом "bugnote" - знач. это tr влож. файлов
			if ($('#td_' + bugnote_id).parent().next().attr('class') == 'bugnote')
				$('#td_' + bugnote_id).parent().next().children()[0].style.background = color;
		}else if(xmlHttp.responseText == 'read_only'){
			alert('Доступ только для чтения!');
		}else{
			alert('Доступ запрещен!');
		}
		icon.innerHTML = '';		
	}
}

function do_filter(color) {
    $('#bugnote_table').find('tr.bugnote').hide().next().hide();
    $('table.child_bugnote').hide();
    /*var tmp = $('#bugnote_table').find('tr.bugnote').hide().next().hide().next();
    if (tmp.attr('class') == 'child_bugnote') {
        tmp.hide();
    }*/
    $('#bugnote_table').find('td.bugnote_hdr').each(function(){
        rgbColor = $(this).css('backgroundColor');
        if (rgb2hex(rgbColor) == color) {
            $(this).parents('*').show();
            $(this).parents('.child_bugnote').prev().show().prev().show();
            $(this).parents('tr.bugnote').next('tr').show();
        }
    });
}

function rgb2hex(rgb) {
    var parts = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    // parts now should be ["rgb(0, 70, 255", "0", "70", "255"]
    if (!parts) {
        return rgb.toUpperCase();
    }
    parts[0] = '#';
    for (var i = 1; i <= 3; ++i) {
        parts[i] = parseInt(parts[i]).toString(16);
        if (parts[i].length == 1) parts[i] = '0' + parts[i];
    }
    return parts.join('').toUpperCase(); // "0070ff"
}

function setColorFilter(bugnote_color, button) {
    if (bugnote_color != 0) {
        do_filter(bugnote_color.toUpperCase());
    } else {
        $('.bugnote_hdr').parents('*').show();
        $('.bugnote_hdr').parents('.child_bugnote').prev().show().prev().show();
        $('.bugnote_hdr').parents('tr.bugnote').next('tr').show();
    }
    $('#bugnote_color_picker_filter').find('td').hide();
    $(button).show();
}

function showColorFilter() {
    $('#bugnote_color_picker_filter').find('td').show();
}

function moveBugnoteFrom(bugnote_id, action){
	OpenDiv( "bugnote_add", g_div_bugnote_add );
	document.getElementById('parent_bugnote_id').value = bugnote_id;
	var form = document.getElementById('bugnote_add_open');
	form.parentNode.removeChild(form);
	var comment_div = document.getElementById('bugnote_add_form_' + bugnote_id)
	comment_div.appendChild(form);
	if(action == 'remind'){
		var uname = document.getElementById(bugnote_id + '_uname').value;
		document.getElementById('and_remind').innerHTML = '<label><input type="checkbox" name="author_to" checked />' + uname + '</label>';
		document.getElementById('and_send_remind').value = '1';

        $('#add_bugnote_title, #reply_bugnote_title, #add_bugnote_button, #reply_bugnote_button').css('display', 'none');
        $('#remind_bugnote_title, #remind_bugnote_button, #remind_users').css('display', '');
        $('#tp_check').unbind('click', show_remind_users);
	}
    else if (action == 'reply'){
        document.getElementById('and_send_remind').value = '0';
		document.getElementById('and_remind').innerHTML = '';

        $('#remind_users, #add_bugnote_title, #remind_bugnote_title, #add_bugnote_button, #remind_bugnote_button').css('display', 'none');
        $('#reply_bugnote_title, #reply_bugnote_button').css('display', '');
        $('#tp_check').bind('click', show_remind_users);
    }
    else if (action == 'add') {
        document.getElementById('and_remind').innerHTML = '';
        document.getElementById('and_send_remind').value = '0';

        $('#remind_users, #reply_bugnote_title, #remind_bugnote_title, #reply_bugnote_button, #remind_bugnote_button').css('display', 'none');
        $('#add_bugnote_title, #add_bugnote_button').css('display', '');
        $('#tp_check').bind('click', show_remind_users);
    }
    if (action == 'add') {
        self.location = '#bugnonte_add';
    } else {
        self.location = '#' + bugnote_id;
    }
	var bugnote_text = document.getElementsByName('bugnote_text');
	bugnote_text = bugnote_text[0];
	bugnote_text.focus();
}

function show_remind_users() {
    if ($('#tp_check').is(':checked')) {
        $('#remind_users').show();
        $('#and_send_remind').val(1);
    } else {
        $('#remind_users').hide();
        $('#and_send_remind').val(0);
    }
}

/*
 * String manipulation
 */

function ShowHideDivState( p_div, p_state ) {
    oElement = document.getElementById(p_div);

    if (p_state) {
        oElement.style.display="block";
    }
    else {
        oElement.style.display="none";
    }
}



function ShowHideDiv( p_div ) {
    oElement = document.getElementById(p_div);
    
    if (oElement.style.display=="none") {
        oElement.style.display="block";
    }
    else {
        oElement.style.display="none";
    }

}



/*
 * String manipulation
 */

function Trim( p_string ) {
	if (typeof p_string != "string") {
		return p_string;
	}

	var t_string = p_string;
	var t_ch = '';

	// Trim beginning spaces

	t_ch = t_string.substring( 0, 1 );
	while ( t_ch == " " ) {
		t_string = t_string.substring( 1, t_string.length );
		t_ch = t_string.substring( 0, 1 );
	}

	// Trim trailing spaces

	t_ch = t_string.substring( t_string.length-1, t_string.length );
	while ( t_ch == " " ) {
		t_string = t_string.substring( 0, t_string.length-1 );
		t_ch = t_string.substring( t_string.length-1, t_string.length );
	}

	return t_string;
}


/*
 * Cookie functions
 */

function GetCookie( p_cookie ) {
	var t_cookie_name = "MANTIS_" + p_cookie;
	var t_cookies = document.cookie;

	t_cookies = t_cookies.split( ";" );

	var i = 0;
	while( i < t_cookies.length ) {
		var t_cookie = t_cookies[ i ];

		t_cookie = t_cookie.split( "=" );

		if ( Trim( t_cookie[ 0 ] ) == t_cookie_name ) {
			return( t_cookie[ 1 ] );
		}
		i++;
	}

	return -1;
}

function SetCookie( p_cookie, p_value ) {
	var t_cookie_name = "MANTIS_" + p_cookie;
	var t_expires = new Date();

	t_expires.setTime( t_expires.getTime() + (365 * 24 * 60 * 60 * 1000));

	document.cookie = t_cookie_name + "=" + p_value + "; expires=" + t_expires.toUTCString() + ";";
}


/*
 * Collapsible element functions
 */

var g_div_history		= 0x0001;
var g_div_bugnotes		= 0x0002;
var g_div_bugnote_add	= 0x0004;
var g_div_timestat		= 0x0008;
var g_div_upload_form	= 0x0010;
var g_div_monitoring	= 0x0020;
var g_div_sponsorship	= 0x0040;
var g_div_relationships	= 0x0080;
var g_div_filter        = 0x0100;
var g_div_iteration		= 0x0200;
var g_div_timeline		= 0x0400;

function GetViewSettings() {
	var t_cookie = GetCookie( "VIEW_SETTINGS" );

	if ( -1 == t_cookie ) {
		t_cookie = 0xffff;
	} else {
		t_cookie = parseInt( t_cookie );
	}

	return t_cookie;
}

function SetDiv( p_div, p_cookie_bit ) {
	var t_view_settings = GetViewSettings();

	if( t_view_settings & p_cookie_bit ) {
		document.getElementById( p_div + "_open" ).style.display = "";
		document.getElementById( p_div + "_closed" ).style.display = "none";
	} else {
		document.getElementById( p_div + "_open" ).style.display = "none";
		document.getElementById( p_div + "_closed" ).style.display = "";
	}
}

function ToggleDiv( p_div, p_cookie_bit ) {
	var t_view_settings = GetViewSettings();

	t_view_settings ^= p_cookie_bit;
	SetCookie( "VIEW_SETTINGS", t_view_settings );

	SetDiv( p_div, p_cookie_bit );
}

function CloseDiv( p_div, p_cookie_bit ){
	var t_view_settings = GetViewSettings();

	t_view_settings &= ~p_cookie_bit;
	SetCookie( "VIEW_SETTINGS", t_view_settings );

	SetDiv( p_div, p_cookie_bit );
}

function OpenDiv( p_div, p_cookie_bit ){
	var t_view_settings = GetViewSettings();

	t_view_settings |= p_cookie_bit;
	SetCookie( "VIEW_SETTINGS", t_view_settings );

	SetDiv( p_div, p_cookie_bit );
}

/* Check checkboxes */
function checkall( p_formname, p_state) {
	var t_elements = (eval("document." + p_formname + ".elements"));

	for (var i = 0; i < t_elements.length; i++) {
    	if(t_elements[i].type == 'checkbox') {
      		t_elements[i].checked = p_state;
   		}
  	}
}

/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */
function print_r(x, max, sep, l) {
	l = l || 0;
	max = max || 10;
	sep = sep || ' ';
	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}
	var
		i,r = '',t = typeof x,tab = '';
	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {
		l++;
		for (i = 0; i < l; i++) {
			tab += sep;
		}
		if (x && x.length) {
			t = 'array';
		}
		r += '(' + t + ") :\n";
		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch(e) {
				return "[ERROR: " + e + "]\n";
			}
		}
	} else {
		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}
		r += '(' + t + ') ' + x + "\n";
	}
	return r;
};
var var_dump = print_r;

function vd(elm, l){
	alert(var_dump(elm, l));
}

function defined(value){
	return (typeof value == "undefined") ? false : true;
}

function definedDefault(value, def){
	return defined(value) ? value : def;
}

//test obj is array
function isArray(obj) {
	if (obj.constructor.toString().indexOf("Array") == -1)
		return false;
	else
		return true;
}

