var global_timerid=null;

jQuery.noConflict();
jQuery(document).ready(function($){
	/*
	$.each($('.text_02, .text_02_b, .head_01, .devlogin, .text_02_head, .text_02_head_license'), function(){
		$('<span class="shadow">' + this.innerHTML + '</span>').appendTo(this);
	});
	*/

	$.each(['awards_menu', 'downloads_menu'], function(){
		var div = $('div.' + this),
			ul = $('ul.' + this),
			ulPadding = 0;
	
		var divWidth = div.width();
	
		div.css({overflow: 'hidden'});
		
		var lastLi = ul.find('li:last-child');
		
		div.mousemove(function(e){

			var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;	
			var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
			div.scrollLeft(left);
		});		
	});
});

function ce3_rpcRequest(target, service, login, password) {
	
	new Ajax.Request(target,{
		parameters  : {'service':service, 'procedure':'checkAuth', 'username':login, 'action':service, 'login': login, 'password':password},			
		onSuccess: function(transport){
			//console.log(transport.responseJSON.loginerror);
			//return false;
			//if(transport.responseText=='false')
			if(transport.responseJSON.loginerror && transport.responseJSON.loginerror!='othersession' && transport.responseJSON.loginerror!='termsandconditions')
			{
				document.getElementById('incorrectlogin').style.display='block';
				document.getElementById('incorrectlogin').innerHTML=transport.responseJSON.loginerror;
				if(document.getElementById('flashcontent') && document.getElementById('flashcontent').style.display=='none')
					document.getElementById('flashcontent').style.display='block';
				
				if(document.getElementById('messageboxlogin'))
				{
					document.getElementById('messageboxlogin').style.display='none';
				}
				return false;
			}
			
			if(transport.responseJSON.loginerror=='othersession')
			{
				if(!document.getElementById('messageboxsessions'))
				{
					document.getElementById('messageboxlogin').style.display='none';
					document.body.innerHTML=document.body.innerHTML+'<div id="messageboxsessions" style="z-index:9999; position:fixed; top:0px; left:0px; width:100%; height:1000px; border:0px solid white; background-image: url(/img/transparent.png); display:block; vartical-align:middle;"><center><div class="warnmessage_container" id="warnmessage_container" style="text-align:left; top:200px;"><div class="warnmessage"><img src="/img/warnmessage_ico.png" /><div class="warnmessage_text">Your user alias is already logged in on another machine. If you continue with this session, all other sessions will be terminated.</div><a class="form_button" style="margin-left:10px;" id="cancel_button" href="#" onclick="return cancel_login();">Cancel</a><a class="form_button" style="position:relative; top:-30px;" id="warnmessage_close_button" href="#" onclick="document.getElementById(\'messageboxsessions\').style.display=\'none\'; return ce3_Auth(document.getElementById(\'CryEngine3AuthForm\'), \'1\');">Continue</a></div></div></div></center></div>';
					document.getElementById('warnmessage_close_button').focus();
				}
				else
					document.getElementById('messageboxsessions').style.display='block';
				
				$('username').value=login;
				$('password').value=password;
				
				return false;
			}
			
			if(service=='login'){
				if(transport.responseJSON.loginerror=='termsandconditions')
				{
					alert(document.getElementById('CryEngine3AuthForm').action);
					document.getElementById('CryEngine3AuthForm').action='/termsandconditions';
					document.getElementById('CryEngine3AuthForm').submit();
					return false;
				}
				global_timerid = window.setTimeout("redirect_login()", 2000);
			} else if(service=='termsandconditions'){
				global_timerid = window.setTimeout("redirect_login()", 2000);
			}

		 	return false;
		}
	});
	return false;		
}

function redirect_login()
{

	if(document.getElementById('CryEngine3AuthForm'))
	{
		document.getElementById('CryEngine3AuthForm').submit();
	}
	
	window.clearTimeout(global_timerid);
}

function ce3_Auth(CryEngine3AuthForm) {
	var login = $('username').value;
	var password = $('password').value;

	if(document.getElementById('incorrectlogin').style.display=='block')
		document.getElementById('incorrectlogin').style.display='none';

	if(!document.getElementById('messageboxlogin'))
		document.body.innerHTML=document.body.innerHTML+'<div id="messageboxlogin" style="z-index:9999; position:fixed; top:0px; left:0px; width:100%; height:1000px; border:0px solid white; background-image: url(/img/transparent.png); display:block; text-align:center; padding-top:20%;"><img src="/img/loading.gif"></div>';
	else
		document.getElementById('messageboxlogin').style.display='block';
	
	ce3_rpcRequest('/core/UserAction.php', 'login', login, password);
	
	return false;
}

function ce3_Auth_termsandconditions(CryEngine3AuthForm) {
	var login = $('username').value;
	var password = $('password').value;

	if(document.getElementById('incorrectlogin').style.display=='block')
		document.getElementById('incorrectlogin').style.display='none';

	if(!document.getElementById('messageboxlogin'))
		document.body.innerHTML=document.body.innerHTML+'<div id="messageboxlogin" style="z-index:9999; position:fixed; top:0px; left:0px; width:100%; height:1000px; border:0px solid white; background-image: url(/img/transparent.png); display:block; text-align:center; padding-top:20%;"><img src="/img/loading.gif"></div>';
	else
		document.getElementById('messageboxlogin').style.display='block';
	
	ce3_rpcRequest('/core/UserAction.php', 'termsandconditions', login, password);
	return false;
}

function ce3_logoutRequest(target, service) {
	
	if(document.getElementById('flashcontent') && document.getElementById('flashcontent').style.display=='block')
		document.getElementById('flashcontent').style.display='none';
	
	new Ajax.Request(target,{
		parameters  : {'service':service, 'action':service},			
		onSuccess: function(transport){
			
			// No errors, service is accacible with those login/password
			if(service=='phpbblogout'){
								
				global_timerid = window.setTimeout("redirect_logout()", 1000);
				
			}

		 	return false;
		}
	});
	return false;		
}

function logout(CryEngine3AuthForm, sid) {
	
	if(!document.getElementById('messageboxlogin'))
		document.body.innerHTML=document.body.innerHTML+'<div id="messageboxlogin" style="z-index:9999; position:fixed; top:0px; left:0px; width:100%; height:1000px; border:0px solid white; background-image: url(/img/transparent.png); display:block; text-align:center; padding-top:20%;"><img src="/img/loading.gif"></div>';
	else
		document.getElementById('messageboxlogin').style.display='block';
	
	//ce3_logoutRequest('/forums/ucp.php?mode=logout&sid='+sid, 'phpbblogout');
	location.href='/core/UserAction.php?action=logout';
	
	return false;
}

function DeleteFieldContent(field)
{
	if(field.value=='Username' || field.value=='Password')
		field.value="";
	
	field.select();
}



function redirect_logout()
{
	
	
	if(document.getElementById('CryEngine3LogoutForm'))
	{
		document.getElementById('CryEngine3LogoutForm').submit();
	}
	
	window.clearTimeout(global_timerid);
}

var videoinner=null;

function show_image(imageurl)
{
	/*if(document.getElementById('div_video'))
	{
		videoinner=document.getElementById('div_video').innerHTML;
		document.getElementById('div_video').innerHTML=' ';
//		document.getElementById('div_video').style.width='448px';
		document.getElementById('div_video').style,display='none';
	}*/
	document.getElementById('div_image_slideshow').innerHTML='<div style="position:relative; top:10%; vertical-align:middle; text-align:center;"><img id="image_slideshow_image" src="'+imageurl+'?id='+Math.random()+'" style="cursor: pointer;"></div>';
	document.getElementById('div_image_slideshow').style.display='block';
	
} 

function ChangePositionTextBoxState()
{
	var value = document.userform.Position.value.toUpperCase();	
	
	if (value == "[OTHER]")
		document.userform.PositionText.disabled = false;
	else
	{
		document.userform.PositionText.disabled = true;
		document.userform.PositionText.value = "";
		
	}
}
/****************************************************************************/
var http=null;
var id=null;

function connect_to_ajax_script(ajax_file)
{
	if (window.XMLHttpRequest) {
   		http = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
   		http = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (http != null) {
		http.open("POST", ajax_file, true);
		//http.onreadystatechange = ausgeben;
		http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		id = window.setTimeout("cancel()", 5500);
	}
	
	return http;
}

function cancel() {
	http.abort();
}

function getpagecontent(contentid, divid, anker)
{
	if(!anker)
		anker=0;
	/*
	if(!document.getElementById('loadcontent'))
		document.body.innerHTML=document.body.innerHTML+'<div id="loadcontent" style="z-index:9999; position:fixed; top:0px; left:0px; width:100%; height:1000px; border:0px solid white; background-image: url(/img/transparent.png); display:block; text-align:center; padding-top:20%;"><img src="/img/loading.gif"></div>';
	else
		document.getElementById('loadcontent').style.display='block';
	*/
	http=connect_to_ajax_script("/custom_ajax_functions.php");
	http.onreadystatechange = function() {
		setpagecontent(http, contentid, divid, anker);
	};
	
	http.send("step=getcontent&conid="+contentid);
	
	return false;
}

function setpagecontent(http, contentid, divid, anker) {
	if (http.readyState == 4) {
		
		cont=http.responseText;
		//alert("DIVID:"+divid);
		if(cont=='false' || cont.length==0)
		{
			location.href='/index.php?accesserror=1';
			window.clearTimeout(id);
			return false;
		}
		
		document.getElementById(divid).innerHTML="";

		if(evalScript(cont))
		{
			document.getElementById(divid).innerHTML=evalScript(cont);
		}
		else
		{
			document.getElementById(divid).innerHTML=cont;
		}
		
		if(anker!=0)
			self.location.href="#"+anker;
		
		/*if(contentid==1)
		{
		 var so = new SWFObject("/videoplayer/video_400x224.swf", "sotester", "400", "224", "9", "#000000"); so.addVariable("videoPath", "/images/home/CryEngine3_T1_v4.flv"); so.addVariable("autoPlay", "no"); so.addVariable("videoPreview", "/images/home/mce.jpg"); so.addParam("wmode", "opaque"); so.addParam("allowFullScreen", "true"); so.addVariable("loopVideo", "yes"); so.write("flashcontent");
		}*/

		//document.getElementById('contenteditdiv').style.left='0px';
		//document.getElementById('contenteditdiv').style.width='100%';
		
		
		window.clearTimeout(id);
		
		http=connect_to_ajax_script("/custom_ajax_functions.php");
		http.onreadystatechange = function() {
			setnavigation(http, contentid);document.getElementById("ajfooter").innerHTML="";
		};
		http.send("step=getnavigation&conid="+contentid);
	}
}

function setnavigation(http, contentid) {
	if (http.readyState == 4) {
		
		if(evalScript(http.responseText))
			document.getElementById('navigation').innerHTML=evalScript(http.responseText);
		else
			document.getElementById('navigation').innerHTML=http.responseText;
		
		window.clearTimeout(id);
		
		if($('textcontainer'))
			CSBfleXcroll('textcontainer');
		
		if($('textcontainer_tabs'))
			CSBfleXcroll('textcontainer_tabs');
		
		if($('textcontainer_tabs_devcenter'))
			CSBfleXcroll('textcontainer_tabs_devcenter');
		
		jQuery.noConflict();
		
		jQuery(document).ready(function($){
		
		$.each(['awards_menu', 'downloads_menu'], function(){
			var div = $('div.' + this),
				ul = $('ul.' + this),
				ulPadding = 0;
		
			var divWidth = div.width();
		
			div.css({overflow: 'hidden'});
			
			var lastLi = ul.find('li:last-child');
			
			div.mousemove(function(e){

				var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + ulPadding;	
				var left = (e.pageX - div.offset().left) * (ulWidth-divWidth) / divWidth;
				div.scrollLeft(left);
			});
		});
		});
		
		http=connect_to_ajax_script("/custom_ajax_functions.php");
		http.onreadystatechange = function() {
			setfooter(http);
		};
		http.send("step=getfooter&conid="+contentid);
		
	}
}

function setfooter(http)
{
	document.getElementById("ajfooter").innerHTML="";
	if (http.readyState == 4) {
		document.getElementById("ajfooter").innerHTML=http.responseText;
		window.clearTimeout(id);
	}
}

//document.getElementById('menu_title_'+contentid).className='selected';

function evalScript(scripts)
{	try
	{	
		
		if(scripts != '')	
		{	var script = "";
		
			scripts = scripts.replace(/<script[^>]*><!(?:--)([\s\S]*?)(\/\/\s--\s*)?><\/script>/gi, function(){
				
			if (scripts !== null) script += arguments[1] + '\n';
				return '';});
			//alert(window.setTimeout(script, 0));
			if(script)
			{
				/*if(window.execScript)
					window.execScript(script) 
				else*/
					window.setTimeout(script, 0);
			}
			
			
		}
		return false;
	}
	catch(e)
	{	
		alert(e)
	}
}

/**

*           Validates the IPs on the Company Form page primarily.

**/
function validateIP (FromIP, ToIP, form) 

{

            errorString = "";

            theName = "IPaddress";

            

            var ipPattern = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;

            var ipArray = FromIP.match(ipPattern);

            

            if (FromIP == "0.0.0.0")

            errorString = errorString + theName + ': '+FromIP+' is a special IP address and cannot be used here.';

            else if (FromIP == "255.255.255.255")

            errorString = errorString + theName + ': '+FromIP+' is a special IP address and cannot be used here.';

            if (ipArray == null)

            errorString = errorString + theName + ': '+FromIP+' is not a valid IP address.';

            else 

            {

                        for (i = 1; i < 5; i++) 

                        {

                                    thisSegment = ipArray[i];

                                    if (thisSegment > 255) 

                                    {

                                                errorString = errorString + theName + ': '+FromIP+' is not a valid IP address.';

                                                break;

                                    }

                                    if ((i == 0) && (thisSegment > 255)) 

                                    {

                                                errorString = errorString + theName + ': '+FromIP+' is a special IP address and cannot be used here.';

                                                break;

                            }

                        }

            }

            extensionLength = 3;

            if (errorString == "")

            {

                        if (ToIP == "")

                        {

                                    form.submit();

                                    return;

                        }

                        var ipArray = ToIP.match(ipPattern);

                        

                        if (ToIP == "0.0.0.0")

                        errorString = errorString + theName + ': '+ToIP+' is a special IP address and cannot be used here.';

                        else if (ToIP == "255.255.255.255")

                        errorString = errorString + theName + ': '+ToIP+' is a special IP address and cannot be used here.';

                        if (ipArray == null)

                        errorString = errorString + theName + ': '+ToIP+' is not a valid IP address.';

                        else 

                        {

                                    for (i = 1; i < 5; i++) 

                                    {

                                                thisSegment = ipArray[i];

                                                if (thisSegment > 255) 

                                                {

                                                            errorString = errorString + theName + ': '+ToIP+' is not a valid IP address.';

                                                            break;

                                                }

                                                if ((i == 0) && (thisSegment > 255)) 

                                                {

                                                            errorString = errorString + theName + ': '+ToIP+' is a special IP address and cannot be used here.';

                                                            break;

                                        }

                                    }

                        }

                        extensionLength = 3;

                        if (errorString == "")

                        {

                                    var FirstIP = FromIP.split(".");

                                    var SecondIP = ToIP.split(".");

                                    if(FirstIP[0] != SecondIP[0] ||

                                       FirstIP[1] != SecondIP[1] ||

                                       FirstIP[2] != SecondIP[2] ||

                                       FirstIP[3] >=  SecondIP[3])

                                    {

                                                errorString = errorString + theName + ': ' + FromIP + ' and ' + ToIP + ' are not a proper range.'

                                                alert(errorString);

                                    }

                                    else

                                                form.submit();

                        }

                        else

                                    alert (errorString);

            }

            else
            	alert (errorString);

}

function customSetFocus(id)
{
	if(document.getElementById(id))
		document.getElementById(id).focus();
	
	return true;
}

function cancel_login()
{
	location.href='/core/UserAction.php?action=logout';
}

function sendcontact(theForm)
{
	http=connect_to_ajax_script("/custom_ajax_functions.php");
	
	http.onreadystatechange = function() {
		
		setcontactmessage(http);
	};
	
	http.send("step=sendcontact&FirstName="+theForm.FirstName.value+"&LastName="+theForm.LastName.value+"&Position="+theForm.Position.value+"&Company="+theForm.Company.value+"&Email="+theForm.Email.value+"&Notes="+theForm.Notes.value+"&Website="+theForm.Website.value);
	
	return false;
}

function sendcontactE3(theForm)
{
	http=connect_to_ajax_script("/custom_ajax_functions.php");

	http.onreadystatechange = function() {

		setcontactmessage(http);
	};

	http.send("step=sendcontactE3&FirstName="+theForm.FirstName.value+"&LastName="+theForm.LastName.value+"&Position="+theForm.Position.value+"&Company="+theForm.Company.value+"&Email="+theForm.Email.value+"&Notes="+theForm.Notes.value+"&Website="+theForm.Website.value);

	return false;
}

function sendcontactCGDC(theForm)
{
	http=connect_to_ajax_script("/custom_ajax_functions.php");

	http.onreadystatechange = function() {

		setcontactmessage(http);
	};

	http.send("step=sendcontactCGDC&FirstName="+theForm.FirstName.value+"&LastName="+theForm.LastName.value+"&Position="+theForm.Position.value+"&Company="+theForm.Company.value+"&Email="+theForm.Email.value+"&Notes="+theForm.Notes.value+"&Website="+theForm.Website.value);

	return false;
}

function setcontactmessage(http) {
	
	if (http.readyState == 4) {
		
		cont=http.responseText;
		
		document.getElementById("contactform").innerHTML=cont;
		if($('textcontainer'))
			CSBfleXcroll('textcontainer');
		
		window.clearTimeout(id);
		
	}
	
	return false;
}