// =============================================================================
// BestGamer.Ru (http://bestgamer.ru/)
// Powered by BestGamer
// Copyright by BestGamer.ru
// =============================================================================

var userAgent = navigator.userAgent.toLowerCase();
var is_opera  = ((userAgent.indexOf('opera') != -1) || (typeof(window.opera) != 'undefined'));
var is_saf    = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_webtv  = (userAgent.indexOf('webtv') != -1);
var is_ie     = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv));
var is_ie4    = ((is_ie) && (userAgent.indexOf('msie 4.') != -1));
var is_moz    = ((navigator.product == 'Gecko') && (!is_saf));
var is_kon    = (userAgent.indexOf('konqueror') != -1);
var is_ns     = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_saf));
var is_ns4    = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var is_mac    = (userAgent.indexOf('mac') != -1);

/**
* Function to emulate document.getElementsByTagName
*
* @param	object	Parent object (eg: document)
* @param	string	Tag type (eg: 'td')
*
* @return	array
*/
function fetch_tags(parentobj, tag)
{
	if (parentobj == null)
	{
		return new Array();
	}
	else if (typeof parentobj.getElementsByTagName != 'undefined')
	{
		return parentobj.getElementsByTagName(tag);
	}
	else if (parentobj.all && parentobj.all.tags)
	{
		return parentobj.all.tags(tag);
	}
	else
	{
		return new Array();
	}
}

/**
* Function to count the number of tags in an object
*
* @param	object	Parent object (eg: document)
* @param	string	Tag type (eg: 'td')
*
* @return	integer
*/
function fetch_tag_count(parentobj, tag)
{
	return fetch_tags(parentobj, tag).length;
}

// #############################################################################
// vB_PHP_Emulator class
// #############################################################################

/**
* PHP Function Emulator Class
*/
function vB_PHP_Emulator()
{
}

// =============================================================================
// vB_PHP_Emulator Methods

/**
* Find a string within a string (case insensitive)
*
* @param	string	Haystack
* @param	string	Needle
* @param	integer	Offset
*
* @return	mixed	Not found: false / Found: integer position
*/
vB_PHP_Emulator.prototype.stripos = function(haystack, needle, offset)
{
	if (typeof offset == 'undefined')
	{
		offset = 0;
	}

	index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

	return (index == -1 ? false : index);
}

/**
* Trims leading whitespace
*
* @param	string	String to trim
*
* @return	string
*/
vB_PHP_Emulator.prototype.ltrim = function(str)
{
	return str.replace(/^\s+/g, '');
}

/**
* Trims trailing whitespace
*
* @param	string	String to trim
*
* @return	string
*/
vB_PHP_Emulator.prototype.rtrim = function(str)
{
	return str.replace(/(\s+)$/g, '');
}

/**
* Trims leading and trailing whitespace
*
* @param	string	String to trim
*
* @return	string
*/
vB_PHP_Emulator.prototype.trim = function(str)
{
	return this.ltrim(this.rtrim(str));
}

/**
* Emulation of PHP's preg_quote()
*
* @param	string	String to process
*
* @return	string
*/
vB_PHP_Emulator.prototype.preg_quote = function(str)
{
	// replace + { } ( ) [ ] | / ? ^ $ \ . = ! < > : * with backslash+character
	return str.replace(/(\+|\{|\}|\(|\)|\[|\]|\||\/|\?|\^|\$|\\|\.|\=|\!|\<|\>|\:|\*)/g, "\\$1");
}

/**
* Emulates unhtmlspecialchars in vBulletin
*
* @param	string	String to process
*
* @return	string
*/
vB_PHP_Emulator.prototype.unhtmlspecialchars = function(str)
{
	f = new Array(/&lt;/g, /&gt;/g, /&quot;/g, /&amp;/g);
	r = new Array('<', '>', '"', '&');

	for (var i in f)
	{
		str = str.replace(f[i], r[i]);
	}

	return str;
}

/**
* Unescape CDATA from vB_AJAX_XML_Builder PHP class
*
* @param	string	Escaped CDATA
*
* @return	string
*/
vB_PHP_Emulator.prototype.unescape_cdata = function(str)
{
	var r1 = /<\=\!\=\[\=C\=D\=A\=T\=A\=\[/g;
	var r2 = /\]\=\]\=>/g;

	return str.replace(r1, '<![CDATA[').replace(r2, ']]>');
}

/**
* Emulates PHP's htmlspecialchars()
*
* @param	string	String to process
*
* @return	string
*/
vB_PHP_Emulator.prototype.htmlspecialchars = function(str)
{
	//var f = new Array(/&(?!#[0-9]+;)/g, /</g, />/g, /"/g);
	var f = new Array(
		(is_mac && is_ie ? new RegExp('&', 'g') : new RegExp('&(?!#[0-9]+;)', 'g')),
		new RegExp('<', 'g'),
		new RegExp('>', 'g'),
		new RegExp('"', 'g')
	);
	var r = new Array(
		'&amp;',
		'&lt;',
		'&gt;',
		'&quot;'
	);

	for (var i = 0; i < f.length; i++)
	{
		str = str.replace(f[i], r[i]);
	}

	return str;
}

/**
* Searches an array for a value
*
* @param	string	Needle
* @param	array	Haystack
* @param	boolean	Case insensitive
*
* @return	integer	Not found: -1 / Found: integer index
*/
vB_PHP_Emulator.prototype.in_array = function(ineedle, haystack, caseinsensitive)
{
	var needle = new String(ineedle);

	if (caseinsensitive)
	{
		needle = needle.toLowerCase();
		for (var i in haystack)
		{
			if (haystack[i].toLowerCase() == needle)
			{
				return i;
			}
		}
	}
	else
	{
		for (var i in haystack)
		{
			if (haystack[i] == needle)
			{
				return i;
			}
		}
	}
	return -1;
}

/**
* Emulates PHP's strpad()
*
* @param	string	Text to pad
* @param	integer	Length to pad
* @param	string	String with which to pad
*
* @return	string
*/
vB_PHP_Emulator.prototype.str_pad = function(text, length, padstring)
{
	text = new String(text);
	padstring = new String(padstring);

	if (text.length < length)
	{
		padtext = new String(padstring);

		while (padtext.length < (length - text.length))
		{
			padtext += padstring;
		}

		text = padtext.substr(0, (length - text.length)) + text;
	}

	return text;
}

/**
* A sort of emulation of PHP's urlencode - not 100% the same, but accomplishes the same thing
*
* @param	string	String to encode
*
* @return	string
*/
vB_PHP_Emulator.prototype.urlencode = function(text)
{
	text = escape(text.toString()).replace(/\+/g, "%2B");

	// this escapes 128 - 255, as JS uses the unicode code points for them.
	// This causes problems with submitting text via AJAX with the UTF-8 charset.
	var matches = text.match(/(%([0-9A-F]{2}))/gi);
	if (matches)
	{
		for (var matchid = 0; matchid < matches.length; matchid++)
		{
			var code = matches[matchid].substring(1,3);
			if (parseInt(code, 16) >= 128)
			{
				text = text.replace(matches[matchid], '%u00' + code);
			}
		}
	}

	// %25 gets translated to % by PHP, so if you have %25u1234,
	// we see it as %u1234 and it gets translated. So make it %u0025u1234,
	// which will print as %u1234!
	text = text.replace('%25', '%u0025');

	return text;
}

/**
* Works a bit like ucfirst, but with some extra options
*
* @param	string	String with which to work
* @param	string	Cut off string before first occurence of this string
*
* @return	string
*/
vB_PHP_Emulator.prototype.ucfirst = function(str, cutoff)
{
	if (typeof cutoff != 'undefined')
	{
		var cutpos = str.indexOf(cutoff);
		if (cutpos > 0)
		{
			str = str.substr(0, cutpos);
		}
	}

	str = str.split(' ');
	for (var i = 0; i < str.length; i++)
	{
		str[i] = str[i].substr(0, 1).toUpperCase() + str[i].substr(1);
	}
	return str.join(' ');
}

// initialize the PHP emulator
var PHP = new vB_PHP_Emulator();

// =============================================================================

/**
* Adds onclick event to the save search prefs buttons
*
* @param	string	The ID of the button that fires the search prefs
*/
function vB_AJAX_ImageReg_Init()
{
	if ((typeof vb_disable_ajax == 'undefined' || vb_disable_ajax < 2) && $('refresh_imagereg'))
	{
		$('refresh_imagereg').onclick = vB_AJAX_ImageReg.prototype.image_click;
		//$('refresh_imagereg').style.cursor = pointer_cursor;
		$('refresh_imagereg').style.display = '';

		if ($('imagereg'))
		{
			//$('imagereg').style.cursor = pointer_cursor;
			$('imagereg').onclick = vB_AJAX_ImageReg.prototype.image_click;
		}
	}
};

/**
* Class to handle saveing search prefs
*
* @param	object	The form object containing the search options
*/
function vB_AJAX_ImageReg()
{
	// AJAX handler
	this.xml_sender = null;

	// Imagehach
	this.imagehash = '';

	// Closure
	var me = this;

	/**
	* OnReadyStateChange callback. Uses a closure to keep state.
	* Remember to use me instead of this inside this function!
	*/
	this.handle_ajax_response = function(obj)
	{
		$('progress_imagereg').style.display = 'none';
		if (obj.responseXML)
		{
				
			var objimagehash = fetch_tags(obj.responseXML, 'imagehash')[0];
			var imagehash = PHP.unescape_cdata(objimagehash.firstChild.nodeValue);
			if (imagehash)
			{
				$('imagehash').value = imagehash;
				$('imagereg').src = '/image.php?type=regcheck&imagehash=' + imagehash;
			}
		}
	}
};

/**
* Submits the form via Ajax
*/
vB_AJAX_ImageReg.prototype.fetch_image = function()
{
	$('progress_imagereg').style.display = '';
	
	var form_action = '/ajax.php?do=imagereg&imagehash=' + this.imagehash;
	var param = new Hash({'do' : 'imagereg', 'imagehash' : this.imagehash});
	
	new Ajax.Request(form_action, {
	asynchronous : false,
	method: 'post',
	parameters: param,
	onSuccess: this.handle_ajax_response,
	evalScripts : true});
};

/**
* Handles the form 'submit' action
*/
vB_AJAX_ImageReg.prototype.image_click = function()
{
	var AJAX_ImageReg = new vB_AJAX_ImageReg();
	AJAX_ImageReg.imagehash = $('imagehash').value;
	AJAX_ImageReg.fetch_image();
	return false;
};

// =============================================================================

function comments_quote_name(name, firm_id)
{
	$('comments_message').value += name+', ';
	ProcessScrollTo('comments_form');
	return false;
}

function comments_page(page)
{
	if (!comments_id || !page)
	{
		return false;
	}
	else
	{
		url = '/comments/'+comments_id+'/'+page+'/';
		
		/*new Ajax.Updater("comments_block",url, {
		method: 'get',
		onFailure: function(){alert("Не удалось загрузить комментарии."); return false;},
		onSuccess: ProcessScrollTo('comments_block'),
		evalScripts : false});*/
		
		new Ajax.Request(url, {
		asynchronous : false,
		method: 'get',
		onFailure: function(){alert("Не удалось добавить комментарий."); return false;},
		onSuccess: comments_update,
		evalScripts : true});
	}
	
	return false;
}

function comments_update(obj)
{
	if (obj.responseText != false)
	{
		$("comments_block").innerHTML = obj.responseText;
		ProcessScrollTo('comments_block');
	}
	
	return false;	
}

function add_ts(param) {
	var ts = new Date();

	if ( param ) {
		param=param.merge({ t : ts.getTime() });
	} else {
		param = new Hash({ t : ts.getTime() });
	}
	return param;
}


function comments_new(param, thread)
{
	if(loggedinuser == false)
	{
		user_login();
		return false;	
	}
	
	var form_action = '/newreply.php?do=postreply&t=' + thread;
	
	param = param.merge({ 'loggedinuser' : loggedinuser, 'ajax' : '1'});
	
	new Ajax.Request(form_action, {
	asynchronous : false,
	method: 'post',
	parameters: param,
	onFailure: function(){alert("Не удалось добавить комментарий."); return false;},
	onSuccess: comments_do_ajax_post,
	evalScripts : true});
			
	return false;
}

function comments_do_ajax_post(obj)
{
	if (fetch_tag_count(obj.responseXML, 'commentsnew'))
	{
		$('comments_message').value='';
		comments_page("new");
		return false;
	}
	
	if (fetch_tag_count(obj.responseXML, 'loggedout'))
	{
		loggedinuser = '0';
		user_login();
		return false;	
	}
	
	if (fetch_tag_count(obj.responseXML, 'error'))
	{
		var errors = fetch_tags(obj.responseXML, 'error')[0];
		var error_text = PHP.unescape_cdata(errors.firstChild.nodeValue);
		
		alert(error_text);
		return false;	
	}
		
	//alert(obj.responseText);
	return false;	
}

function user_login()
{
	//alert('123');
	new Ajax.Request("/login/form/", {
		asynchronous : false,
		method: 'get',
		onSuccess: user_login_dialog,
		evalScripts : true
	});
	return false;
}

function user_login_dialog(obj)
{
	//alert(obj.responseText);
	var dialoginfo = fetch_tags(obj.responseXML, 'body')[0];
	
	$('dialog_global_body').innerHTML = PHP.unescape_cdata(dialoginfo.firstChild.nodeValue);
	$('dialog_global_title').innerHTML = dialoginfo.getAttribute('title');
	$('dialog_global_footer').innerHTML = dialoginfo.getAttribute('footer');
	
	var dialog = $('dialog_global');
	
	dialog.style.width = '350px';
	dialog.style.zIndex = 1000;
	
	dialog_display_center(dialog);
	
	dialog.style.display = '';
}

function user_login_process(param)
{
	//alert('123');
	param = param.merge({'ajax' : '1'});
	
	new Ajax.Request('/login/?do=login', {
	asynchronous : false,
	method: 'post',
	parameters: param,
	onFailure: function(){alert("Не удалось авторизироватся, попробуйте еще раз или обновите страницу."); return false;},
	onSuccess: user_login_result,
	evalScripts : false
	});
	
	return false;
}

function user_login_result(obj)
{
	//alert(obj.responseText);
	if (fetch_tag_count(obj.responseXML, 'userid'))
	{
		var userid = fetch_tags(obj.responseXML, 'userid')[0];
		
		loggedinuser = PHP.unescape_cdata(userid.firstChild.nodeValue);
		
		$('login_error').style.display = 'none';
		$('login_error').innerHTML = '';
		
		dialog_global_close();
	}
	else if (fetch_tag_count(obj.responseXML, 'error'))
	{
		var error = fetch_tags(obj.responseXML, 'error')[0];
		var text = PHP.unescape_cdata(error.firstChild.nodeValue);
		
		$('login_error').style.display = 'block';
		$('login_error').innerHTML = '<p style="margin: 10px;">' + text + '</p>';
	}
	
	return false;
}

function user_register()
{
	//alert('123');
	new Ajax.Request("/register/ajax/", {
		asynchronous : false,
		method: 'get',
		onFailure: function(){alert("Не удалось загрузить интерфейс регистрации, обновите страницу."); return false;},
		onSuccess: user_register_dialog,
		evalScripts : true
	});
	return false;
}

function user_register_dialog(obj)
{
	//alert(obj.responseText);
	var dialoginfo = fetch_tags(obj.responseXML, 'body')[0];
	
	$('dialog_global_body').innerHTML = PHP.unescape_cdata(dialoginfo.firstChild.nodeValue);
	$('dialog_global_title').innerHTML = dialoginfo.getAttribute('title');
	$('dialog_global_footer').innerHTML = dialoginfo.getAttribute('footer');
	
	var dialog = $('dialog_global');
	
	dialog.style.width = '500px';
	dialog.style.zIndex = 1000;
	
	dialog_display_center(dialog);
	
	dialog.style.display = '';
}

function user_register_process(param)
{
	//alert('123');
	param = param.merge({'ajax' : '1', 
	'username' : $('register_username').value, 'referrername' : $('referrerfield_txt').value, 
	'password' : $('register_password').value, 'passwordconfirm' : $('register_password').value, 
	'email' : $('register_email').value, 'emailconfirm' : $('register_email').value, 
	'imagestamp' : $('imagestamp').value, 'imagehash' : $('imagehash').value,  
	'timezoneoffset' : $('sel_timezoneoffset').value, 'dst' : '2'});/*, 
	'options[adminemail]' : $('cb_adminemail').value, 'options[showemail]' : $('cb_showemail').value, 
	'rules_bestgamer' : $('rules_bestgamer').value, 'rules_forum_bestgamer' : $('rules_forum_bestgamer').value});*/
	
	/*if($('rules_bestgamer').checked == true)
	{
		param = param.merge({'rules_bestgamer' : $('rules_bestgamer').value});	
	}
	
	if($('rules_forum_bestgamer').checked == true)
	{
		param = param.merge({'rules_forum_bestgamer' : $('rules_forum_bestgamer').value});	
	}*/
	
	if($('cb_adminemail').checked == true)
	{
		param = param.merge({'options[adminemail]' : $('cb_adminemail').value});	
	}
	
	if($('cb_showemail').checked == true)
	{
		param = param.merge({'options[showemail]' : $('cb_showemail').value});	
	}
	//alert($('rules_bestgamer').checked);
	new Ajax.Request('/register/?do=addmember', {
	asynchronous : false,
	method: 'post',
	parameters: param,
	onFailure: function(){alert("Не удалось зарегистрироваться, попробуйте еще раз или обновите страницу."); return false;},
	onSuccess: user_register_result,
	evalScripts : true
	});
	
	return false;
}

function user_register_result(obj)
{
	//alert(obj.responseText);
	if (fetch_tag_count(obj.responseXML, 'registerinfo'))
	{
		var registerinfo = fetch_tags(obj.responseXML, 'registerinfo')[0];
		var text = PHP.unescape_cdata(registerinfo.firstChild.nodeValue);
		
		/*var userid = fetch_tags(obj.responseXML, 'userid')[0];
		loggedinuser = PHP.unescape_cdata(userid.firstChild.nodeValue);*/
		
		loggedinuser = registerinfo.getAttribute('userid');
		
		$('register_error').style.display = 'none';
		$('register_errorlist').innerHTML = '';
		
		$('dialog_global_body').innerHTML = '<p style="margin: 10px;">' + text + '</p>';
		$('dialog_global_footer').innerHTML = '<input type="submit" class="button" value="Закрыть" onclick="return dialog_global_close();">';
		
		ProcessScrollTo('dialog_registr');
		
		//dialog_close('user_login');
	}
	else if (fetch_tag_count(obj.responseXML, 'error'))
	{
		var error = fetch_tags(obj.responseXML, 'error')[0];
		var text = PHP.unescape_cdata(error.firstChild.nodeValue);
		
		$('register_error').style.display = 'block';
		$('register_errorlist').innerHTML = text;
		ProcessScrollTo('dialog_registr');
	}
	
	return false;
}

function dialog_global_close()
{
	$('dialog_global').style.display = 'none';
	$('dialog_global_title').innerHTML = '';
	$('dialog_global_body').innerHTML = '';
	$('dialog_global_footer').innerHTML = '';
}

function dialog_display_center(dialog)
{
	/*var scrolls = document.viewport.getScrollOffsets();
	dialog.style.left = document.viewport.getWidth() / 2 - 200 + scrolls.left + 'px';
	dialog.style.top = document.viewport.getHeight() / 2 - 150 + scrolls.top + 'px';*/
	
	var measurer = (is_saf ? 'body' : 'documentElement');
	dialog.style.left = (is_ie ? document.documentElement.clientWidth : self.innerWidth) / 2 - 200 + document[measurer].scrollLeft + 'px';
	dialog.style.top = (is_ie ? document.documentElement.clientHeight : self.innerHeight) / 2 - 150 + document[measurer].scrollTop + 'px';
}

function ProcessScrollTo(obj)
{
	if (!$(obj)) return;
	offset=0;
	for (tmp=$(obj);tmp;tmp=tmp.offsetParent) offset+=tmp.offsetTop;
	for (tmp=$(obj).parentNode;tmp&&tmp!=document.body;tmp=tmp.parentNode) if (tmp.scroolTop) offset-=tmp.scroolTop;
	window.scrollTo(0,offset);
}
