var nav = userNavigator();

// ИСПОЛЬЗОВАТЬ ВМЕСТО getElementById() (может отдать массив элементов, если передать несколько id)
function js() 
{
	var elements = new Array();
	for(var i=0; i<arguments.length; i++) 
	{
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		
		if (arguments.length == 1)
			return element;
		
		elements.push(element);
	}
	return elements;
}
// ПЕРЕДАЕМ URL ВО ФРЕЙМ
function toajax(url)
{
	js('ajax').src = url;
}

// ОТКРЫВАЕТ СТРАНИЦУ В ОТДЕЛЬНОМ ОКНЕ
function openWindow(width,height,url,target)
{
	/*
	width	размер в пикселах	ширина нового окна
	height	размер в пикселах	высота нового окна
	left	размер в пикселах	абсцисса левого верхнего угла нового окна
	top	размер в пикселах	ордината левого верхнего угла нового окна
	toolbar	1 / 0 / yes / no	вывод панели инструменов
	location	1 / 0 / yes / no	вывод адресной строки
	directories	1 / 0 / yes / no	вывод панели ссылок
	menubar	1 / 0 / yes / no	вывод строки меню
	scrollbars	1 / 0 / yes / no	вывод полос прокрутки
	resizable	1 / 0 / yes / no	возможность изменения размеров окна
	status	1 / 0 / yes / no	вывод строки статуса
	fullscreen	1 / 0 / yes / no	вывод на полный экран
	*/ 
	if(!target) target = 'my';
	var left = Math.round((screen.width-width)/2);
	var top = Math.round((screen.height-height)/2)-40;
	var win = window.open(url, target, 'resizable=yes,width='+width+',height='+height+',scrollbars=1,top='+top+',left='+left);
	win.focus();
	// Пример:
	// <a href="page.htm" target="my" onClick="openWindow(570,700)">открыть</a>
}

// ПЕРЕЗАГРУЗИТЬ СТРАНИЦУ ПОСЛЕ РАБОТЫ ФРЕЙМА
function topReload()
{
	switch(userNavigator())
	{
		case "isOpera":
		case "isChrome":
			history.go(0);
			break;
		
		case "isGecko":
			history.back();
			setTimeout("top.location.reload(true)",500);
			break;
		
		default:
			history.back();
			history.go(0);
			break;
	}
}
// ВЫЗОВ ФУНКЦИИ history.back() ПОСЛЕ РАБОТЫ ФРЕЙМА
function topBack(post) // post - страница дергалась формой (иначе - ссылкой)
{
	showLoad(false);
	switch(userNavigator())
	{
		case "isChrome":
			if(post)
				history.back();
			break;
		
		default:
			history.back();
			break;
	}
}

function strpos( haystack, needle, offset)
{
	var i = haystack.indexOf( needle, offset ); // returns -1
	return i >= 0 ? i : false;
}


// ОПРЕДЕЛЕНИЕ ТИПА БРАУЗЕРА
function userNavigator()
{
	// Получим userAgent браузера и переведем его в нижний регистр 
	var ua = navigator.userAgent.toLowerCase(); 
	// Определим Internet Explorer 
	if( (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1) )
		return "isIE";
	// Opera 
	if( (ua.indexOf("opera") != -1) )
		return "isOpera";
	// Chrome
	if( (ua.indexOf("chrome") != -1) ) 
		return "isChrome";
	// Gecko = Mozilla + Firefox + Netscape 
	if( (ua.indexOf("gecko") != -1) ) 
		return "isGecko";
	// Safari, используется в MAC OS 
	if( (ua.indexOf("safari") != -1) ) 
		return "isSafari";
	// Konqueror, используется в UNIX-системах 
	if( (ua.indexOf("konqueror") != -1) ) 
		return "isKonqueror";

	return false;
}

// ПРЕДВАРИТЕЛЬНАЯ ЗАГРУЗКА КАРТИНОК
/*function preloadImg() // в аргументы передаются пути к картинкам
{
    arg = preloadImg.arguments;
    img = new Array();
    for(i=0; i<arg.length; i++)
    {
        img[i] = new Image;
        img[i].src = arg[i];
    }
}*/
$.preloadImg = function()
{
	for(var i=0; i<arguments.length; i++)
 	{
  		$("<img>").attr("src", arguments[i]);
 	}
};

// ФОРМАТИРУЕТ ВЫВОД ЧИСЛА, АНАЛОГ number_format() В PHP
function number_format(number, decimals, dec_point, thousands_sep) 
{
	var n = number, prec = decimals, dec = dec_point, sep = thousands_sep;
	n = !isFinite(+n) ? 0 : +n;
	prec = !isFinite(+prec) ? 0 : Math.abs(prec);
	sep = sep == undefined ? ',' : sep;
	
	var s = n.toFixed(prec), abs = Math.abs(n).toFixed(prec), _, i;
	if (abs > 1000) {
		_ = abs.split(/\D/);
		i = _[0].length % 3 || 3;
		_[0] = s.slice(0,i + (n < 0)) + _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
		s = _.join(dec || '.');
	}
	return s;
}

function end(array) 
{	
	// Set the internal pointer of an array to its last element
	// 
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   bugfixed by: Legaev Andrey

	var last_elm, key;

	if (array.constructor === Array){
		last_elm = array[(array.length-1)];
	} else {
		for (key in array){
			last_elm = array[key];
		}
	}

	return last_elm;
}


function remove_input_value(obj,text,color)
{
	if(obj.value==text)
	{
		obj.style.color=color;
		obj.value='';
	}
}
function add_input_value(obj,text,color)
{
	if(obj.value=='')
	{
		obj.style.color=color;
		obj.value=text;
	}
}

function mousePageXY(e)
{
	var x = 0, y = 0;
	if (!e) e = window.event;
	if (e.pageX || e.pageY)
	{
		x = e.pageX;
		y = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
		y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
	}
	
	return {"x":x, "y":y};
}

// ОПРЕДЕЛЕНИЕ КООРДИНАТ ЭЛЕМЕНТА
function absPosition(obj) 
{ 
	var x = y = 0;
	while(obj) 
	{
		x += obj.offsetLeft;
		y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return {x:x, y:y};
	// Пример:
	// "x = " + absPosition(obj).x;
	// "y = " + absPosition(obj).y;
}

function getElementPosition(obj)
{
    var w = obj.offsetWidth;
    var h = obj.offsetHeight;
	
    var l = 0;
    var t = 0;
	
    while (obj)
    {
        l += obj.offsetLeft;
        t += obj.offsetTop;
        obj = obj.offsetParent;
    }

    return {"left":l, "top":t, "width": w, "height":h};
}

function BodySize()
{
	var width = document.body.clientWidth; // ширина  
	var height = document.body.clientHeight; // высота

	return {"width":width, "height":height};
}
// Размеры клиентской части окна браузера
function screenSize() 
{
	var w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
	var h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
	return {w:w, h:h};
}

function add_photo()
{
	var sch = js('sch_photo').value*1 + 1;
	var tab = js('tab_add_photo');
	
	var _tr = tab.insertRow(-1);
	_tr.id = 'tr_photo'+sch;
	
    var cell_1 = top.document.createElement('TD');
	var cell_2 = top.document.createElement('TH');
	
	// убираем + - у предыдущей строки
	var pred_tr = js('tr_photo'+(sch-1));
	if(pred_tr)
	{
		_th = pred_tr.getElementsByTagName('TH');
		_th[0].innerHTML = '';
	}	
	
	// поле файл 
	_tr.appendChild(cell_1);
    cell_1.innerHTML = '<input type="file" name="user_photo['+sch+']" />';
	// + -	
	_tr.appendChild(cell_2);
	cell_2.innerHTML = '<a href="" target="ajax" class="link2" onclick="add_photo();return false;">ещё</a>';
	
	// увеличиваем счетчик
	js('sch_photo').value = sch;
	
	// убираем + у 5-й строки
	if(sch+1==4) 
	{
		var cur_tr = js('tr_photo'+sch);
		if(cur_tr)
		{
			_th = cur_tr.getElementsByTagName('TH');
			_th[0].innerHTML = '';
		}
	}
}

function clear_select(obj,flag)
{
	while(obj.options.length) 
		obj.options[0] = null;
	
	if(flag)
		obj.options[0] = new Option('', '');
}

function show_hide_block(obj_id)
{
	if(js(obj_id).style.display == 'none')
		js(obj_id).style.display = 'block';
	else
		js(obj_id).style.display = 'none';
}

function show_hide_tr(obj_id)
{
	display = (nav=='isIE' ? "block" : "table-row");
		
	if(js(obj_id).style.display == 'none')
		js(obj_id).style.display = display;
	else
		js(obj_id).style.display = 'none';
}

function rgb2hex(r, g, b) 
{
	return (((r & 255) << 16) + ((g & 255) << 8) + b).toString(16);
}

function hex2rgb(hex) 
{
	return (function (v) {
		return [v >> 16 & 255, v >> 8 & 255, v & 255];
	})(parseInt(hex, 16));
}

jQuery.fn.blackout = function(settings){
	
	// Settings
	settings = $.extend({
		color : '#000',
		opacity : 80,
		z : 50
	}, settings);
	
	settings.opacity = parseInt(settings.opacity)*0.01;

	var $blackout = $('<div id="blackout"></div>');
	$blackout.css({
		'width' : $.browser.msie ? $('body').width() : $(document).width(),
		'height' : $(document).height(),
		'position' : 'absolute',
		'left' : '0',
		'top' : '0',
		'background-color' : settings.color,
		'padding' : '0',
		'z-index' : settings.z,
		'display' : 'none'
	});
	$blackout.animate({opacity:settings.opacity},0);
	
	$(window).resize(function(){
		$blackout.css({
			'width' : $.browser.msie ? $('body').width() : $(document).width(),
			'height' : $(document).height()
		});
	});
	
	$('body').prepend($blackout);
}
