/* Очистка формы от текста, и возврат */
function clearText(field)
	{
	if (field.defaultValue == field.value)
		{
		field.value = '';
		}
	else if (field.value == '')
		{
		field.value = field.defaultValue;
		$(field).removeClass('completed');
		}
	else $(field).addClass('completed');
	}


/* Высота и ширины рабочей области */
function screenSize()
	{
    var w, h; // Объявляем переменные, w - длина, h - высота
    w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
    h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
    return {w:w,h:h};
	}

/* Высота и ширины рабочей области */
function totalSize()
	{
    var w, h; // Объявляем переменные, w - длина, h - высота
    w = document.body.clientWidth;
    h = document.body.clientHeight;
    return {w:w,h:h};
	}

function size()
	{
	alert("Длина = " + screenSize().w + "px<br />" + "Высота = " + screenSize().h + "px");
	}

function tSize()
	{
	alert("Длина = " + totalSize().w + "px<br />" + "Высота = " + totalSize().h + "px");
	}


/**
 *
 * @access public
 * @return void
 **/
function popupClose(id_element)
	{
	alert('#'+id_element);
	$('#'+id_element).hide();
	}

/**
 * Класс попап окошечка
 * @access public
 * @return void
 **/
function messageBox(id_element, name, content, buttons)
	{
	this.id_element = id_element;
	this.name = name;
	this.inner = content;
	this.buttons = buttons;

	this.submit = function(){};

	this.getHeader = function()
		{
		return '<h2><span>' + this.name + '</span></h2>';
		}

	this.getInner = function()
		{
		return '<div class="inner">' + this.inner  + '</div>';
		}

	this.getButtons = function()
		{
		var html = '';
		for	(var i in this.buttons)
			{
			html += '<div class="link"><div class="' + i +'" id="'
			  + this.id_element
			  + '_'
			  + i
			  + '">'
			  + this.buttons[i]['title']
			  + '</div></div>';
			}
		html = '<div class="popup_buttons">' + html + '<i class="floatbreaker"></i></div>';
		return html;
		}

	this.initButtons = function()
		{
		for	(var i in this.buttons)
			{
			if (typeof this.buttons[i]['onclick'] == 'function')// Вдруг не задан онклик
				{
				$('#' + this.id_element+ '_' + i).click(this.buttons[i]['onclick']);
				}
			else if(i == 'close')// Если кнопка закрыть
				{
				$('#' + this.id_element+ '_' + i).click(this.actionDestroy);
				}
			}
		}

	this.createBlock = function()
		{
		html = '<div id="' + this.id_element + '" class="popup" style="display:none;">'
		  + this.getHeader()
		  + this.getInner()
		  + this.getButtons()
		  + '</div>';
		$('#pageLayout').after(html);
		$('#' + this.id_element).fadeIn('fast');
		}

	this.createBackground = function()
		{
		$('#pageLayout').after('<div class="popup_transparent_bg" style="display:none;"></div>');
		$('.popup_transparent_bg').show();
		}

	this.actionCreate = function()
		{
		this.createBackground();
		this.createBlock();
		this.calculatePosition();
		this.initButtons();
		this.actionPrepare(); // Удаляем офервлоу с боди
		}

	// Поскольку функция биндится, параметры в неё передаются наследованием из initButtons
	this.actionDestroy = function()
		{
		$('#' + id_element).remove();
		$('.popup_transparent_bg').remove();
		this.actionUnprepare(); // Востанавливаем офервлоу с боди
		}

	this.calculatePosition = function()
		{
		// Высота прозрачного слоя
		$('.popup_transparent_bg').css('height',totalSize().h + 'px');
		var boxWidth = $('#' + this.id_element).width();
		var boxHeight = $('#' + this.id_element).height();
		var screenWidth = screenSize().w;
		var screenHeight = screenSize().h;
		var boxLeftMargin = ((screenWidth - boxWidth) / 2) - 75;
		var boxTopMargin = (screenHeight - boxHeight) / 2;
		$('#' + this.id_element).css('left',boxLeftMargin);
		$('#' + this.id_element).css('top',boxTopMargin);
		}

	this.actionPrepare = function()
		{
		if (typeof document.body.style.maxHeight === "undefined")//if IE 6
			{
			$("body","html").css(
				{
				height: "100%"
				});
			}
			$("html").css("overflow-y","hidden");
			$("html").css("overflow-x","hidden");
			$("body").css('padding-right','16px');
			}

	this.actionUnprepare = function()
		{
		if (typeof document.body.style.maxHeight === "undefined")//if IE 6
			{
	    	$("body","html").css(
	    		{
	    		height: "auto",
	    		width: "auto"
	    		});
			}
			$("html").css("overflow-y","scroll");
			$("html").css("overflow-x","hidden");
			$("body").css('padding-right','0px');
		}
	}

function alertMessage(header, body)
	{
	var oAlert = new messageBox('alert',header,body,
		{
		close:
			{
			title: 'OK',
			onclick: function()
				{
				oAlert.actionDestroy();
				}
			}
		});
	oAlert.actionCreate();
	}

/* Выводит сообщение в стиле alert(), только через нашу собственную апи */
function alertMessage(header, body)
	{
	var oAlert = new messageBox('alert',header,body,
		{
		close:
			{
			title: 'OK',
			onclick: function()
				{
				oAlert.actionDestroy();
				}
			}
		});
	oAlert.actionCreate();
	}

/*Encodes data to Base64 format*/
function base64Encode(data)
	{
	if (typeof(btoa) == 'function')
		{
		return btoa(data);
		} //use internal base64 functions if available (gecko only)
	var b64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	var byte1, byte2, byte3;
	var ch1, ch2, ch3, ch4;
	var result = new Array(); //array is used instead of string because in most of browsers working with large arrays is faster than working with large strings
	var j=0;
	for (var i=0; i<data.length; i+=3)
		{
		byte1 = data.charCodeAt(i);
		byte2 = data.charCodeAt(i+1);
		byte3 = data.charCodeAt(i+2);
		ch1 = byte1 >> 2;
		ch2 = ((byte1 & 3) << 4) | (byte2 >> 4);
		ch3 = ((byte2 & 15) << 2) | (byte3 >> 6);
		ch4 = byte3 & 63;
		if (isNaN(byte2))
			{
			ch3 = ch4 = 64;
			}
		else if (isNaN(byte3))
			{
			ch4 = 64;
			}
		result[j++] = b64_map.charAt(ch1)+b64_map.charAt(ch2)+b64_map.charAt(ch3)+b64_map.charAt(ch4);
		}
	return result.join('');
	}

/*Decodes Base64 formated data*/
function base64Decode(data)
	{
	data = data.replace(/[^a-z0-9\+\/=]/ig, '');// strip none base64 characters
	if (typeof(atob) == 'function') return atob(data);//use internal base64 functions if available (gecko only)
	var b64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	var byte1, byte2, byte3;
	var ch1, ch2, ch3, ch4;
	var result = new Array(); //array is used instead of string because in most of browsers working with large arrays is faster than working with large strings
	var j=0;
	while ((data.length%4) != 0)
		{
		data += '=';
		}
	for (var i=0; i<data.length; i+=4)
		{
		ch1 = b64_map.indexOf(data.charAt(i));
		ch2 = b64_map.indexOf(data.charAt(i+1));
		ch3 = b64_map.indexOf(data.charAt(i+2));
		ch4 = b64_map.indexOf(data.charAt(i+3));
		byte1 = (ch1 << 2) | (ch2 >> 4);
		byte2 = ((ch2 & 15) << 4) | (ch3 >> 2);
		byte3 = ((ch3 & 3) << 6) | ch4;
		result[j++] = String.fromCharCode(byte1);
		if (ch3 != 64) result[j++] = String.fromCharCode(byte2);
		if (ch4 != 64) result[j++] = String.fromCharCode(byte3);
		}
	return result.join('');
	}

/* отправка формы */
function submitForm(e)
	{
	form = getForm(e);
	form.submit();
	}

/* получение формы, в которую обёрнут передаваемый элемент */
function getForm(element)
	{
	while(true)
		{
		if (element.tagName.toLowerCase() == 'form')
			{
			return element;
			}
		element = element.parentNode;
		if (!element)
			{
			break;
			}
		} // while
	return null;
	}


/* Получаем в ответ версию флеш */
function flash_version()
	{
	var d, n = navigator, m, f = 'Shockwave Flash';
	if((m = n.mimeTypes) && (m = m["application/x-shockwave-flash"]) && m.enabledPlugin && (n = n.plugins) && n[f]) {d = n[f].description}
	else if (window.ActiveXObject) { try { d = (new ActiveXObject((f+'.'+f).replace(/ /g,''))).GetVariable('$version');} catch (e) {}}
	return d ? d.replace(/\D+/,'').split(/\D+/) : [0,0];
	};

/* Переходим по url */
function getUrl(url)
	{
	document.location = url;
	}

function formFocus(element)
	{
	var text = $(element).val();
	$(element).val(text);
	$(element).focus();
}