var xmlHttp ;
var xmlHttpOthers ;
var xmlHttpLogOut ;
var RoundScore= 0 ;
var points=-1;
var timerID = 0;
var tStart  = 180;
var chartXMLCache = null;

var modalBoxTimerID =0 ;
var tModalStart = null;

function StopTimer() {
   if(timerID) {
      clearTimeout(timerID);
      timerID  = null;
   }

   tStart = null;
}

function StartModalTimer()	{
	tModalStart = 15;
	var obj = 	document.getElementById('modalClock');
	if (obj != null)	obj.innerHTML = (tModalStart);
	modalBoxTimerID  = setTimeout("UpdateModalTimer()", 1000);
}

function UpdateModalTimer()	{	
   if(tModalStart ==0)  {
   		Modalbox.hide();
	 	return;
   }
   
   tModalStart =tModalStart -1;
   var obj = document.getElementById('modalClock');
   if (obj != null)	obj.innerHTML = (tModalStart );
   modalBoxTimerID  = setTimeout("UpdateModalTimer()", 1000);
}


function StartTimer() { 
   tStart = 180;
   var headerScore = 0+parseInt(document.getElementById('headerscore').innerHTML);
//   if (headerScore>=1000)	{
	   document.getElementById('downButton').href ="javascript:ValidateForm(3)";
	   document.getElementById('upButton').href="javascript:ValidateForm(2)";
   	   document.getElementById('downButton').className = "Vbutton";
	   document.getElementById('upButton').className = "Vbutton";
   	   document.getElementById('downButton').title = "Up 0% to +2%";
   	   document.getElementById('upButton').title = "Down 0% to -2%";

/*   }	else	{
	   document.getElementById('downButton').href="#";
	   document.getElementById('upButton').href="#";
	   document.getElementById('downButton').className = "VbuttonDisable";
	   document.getElementById('upButton').className = "VbuttonDisable";	   
   	   document.getElementById('downButton').title = "Only after reaching 1,000 points we allow 4 answer types";
   	   document.getElementById('upButton').title = "Only after reaching 1,000 points we allow 4 answer types";	   
   }		*/
   
   if (headerScore>=1000 && headerScore<5000)	tStart   = 120;
   if (headerScore>=5000 && headerScore<30000)	tStart   = 90;
   if (headerScore>=30000)						tStart   = 60;
   document.getElementById('clock').innerHTML = (tStart);
   timerID = setTimeout("UpdateTimer()", 1000);
}

function UpdateTimer()
{	
   if(tStart==0) {
      clearTimeout(timerID);
      ValidateForm(0);	

	  return;
   }
   
    var fontStyle="";
    var fontEnd = "";
	tStart=tStart-1;
	//if (tStart<=10)	{	fontStyle = "<font style=\"color:#9D2900\">";	 fontEnd = "</font>";	}

 	document.getElementById('clock').innerHTML = fontStyle + (tStart) + fontEnd;
	timerID = setTimeout("UpdateTimer()", 1000);

}

function enableFormSubmit()
{
document.getElementById('button').disabled=false;
}

function EndOfGame(){
	window.location='http://www.stocknewsgame.com/game_over.php';
}


function ValidateForm(Answer) {
	var form = document.getElementById('GameForm');
	var YourReaction;	
	/*if (Answer == 1)	{
		if ( document.getElementById('answers_1').checked) {Answer=1;	YourReaction = "<img src=\"images/up_arrow.gif\"/>$" + document.getElementById('delta1').innerHTML; 	}
		if ( document.getElementById('answers_2').checked) {Answer=2;	YourReaction = "<img src=\"images/neutral.png\"/>Neutral";											}
		if ( document.getElementById('answers_3').checked) {Answer=3;	YourReaction = "<img src=\"images/down_arrow.gif\"/>$" + document.getElementById('delta2').innerHTML;	}
	}*/
	if ( Answer==1)	{	YourReaction = "<img src=\"images/up_arrow.gif\"/>+2%"; 			}
	if ( Answer==2)	{	YourReaction = "<img src=\"images/up_arrow_med.gif\"/>0%-2%";		}
	if ( Answer==3)	{	YourReaction = "<img src=\"images/down_arrow_med.gif\"/>-2%-0%";	}	
	if ( Answer==4)	{	YourReaction = "<img src=\"images/down_arrow.gif\"/>-2%";			}

	if (document.getElementById('Pchange').value!=-1)	{
			var correct;
			var GeneralChange;
			var Pchange 	= parseFloat(document.getElementById('Pchange').value);
			var Stock_Price = parseFloat(document.getElementById('Stock_Price').value);

			var delta1 		= 1.02*Stock_Price;	//parseInt(document.getElementById('delta1').innerHTML);
			var delta2 		= 0.98*Stock_Price;	//parseInt(document.getElementById('delta2').innerHTML);

			if (Pchange >=delta1 ) 						{correct=1; GeneralChange= "<span><img src=\"images/up_arrow.gif\"/>";}	/*style=\"color:green\"*/
			if (Pchange>=Stock_Price && Pchange<delta1) {correct=2; GeneralChange= "<span><img src=\"images/up_arrow_med.gif\"/>";}	/*style=\"color:green\"*/
			if (Pchange<=Stock_Price && Pchange>delta2)	{correct=3; GeneralChange= "<span><img src=\"images/down_arrow_med.gif\"/>";}
			if (Pchange <=delta2 ) 						{correct=4; GeneralChange= "<span><img src=\"images/down_arrow.gif\"/>";}/*style=\"color:red\"*/
			
			var headerScore = parseInt(document.getElementById('headerscore').innerHTML);
			var roundScore  = parseInt(document.getElementById('RoundScore').innerHTML);
			var MarketReaction;		
			if (Answer > 0)	{ 
					if (correct==Answer || points==0) {	
						points = parseInt(100 * Math.abs(Pchange-Stock_Price));
						headerScore =headerScore +points; 
						RoundScore  =RoundScore +points;	
						document.getElementById('YourPoints').innerHTML = "<span style=\"color:green\">+"+points+"</span>";
					}	else 			 {	
						// wrong answer...
						if (Answer == 1) points = parseInt(100 * Math.abs(Pchange-delta1));
						if (Answer == 2) points = parseInt(100 * Math.abs(Pchange-delta1));
						if (Answer == 3) points = parseInt(100 * Math.abs(Stock_Price-Pchange));
						if (Answer == 4) points = parseInt(100 * Math.abs(Pchange-delta2));						
						headerScore =headerScore -points; RoundScore=RoundScore-points;	
						document.getElementById('YourPoints').innerHTML = "<span style=\"color:red\">-"  +points+"</span>"; 
						points = -points
					};
					document.getElementById('RoundScore').innerHTML = (RoundScore);
					document.getElementById('headerscore').innerHTML = parseInt(headerScore);
			}	else	{
				document.getElementById('YourPoints').innerHTML = '[?]';
				//document.getElementById('YourPointsText').style.display="none";							
			}
			var percChange = parseInt(100*Math.abs(Stock_Price-Pchange)/Stock_Price);
			if (Stock_Price>Pchange) percChange = -percChange;	else	percChange = "+"+percChange;
			MarketReaction	=  GeneralChange + percChange+ '% ($' + document.getElementById('Pchange').value + ")</span>" ;
	}	else	{
			points = -1;
			MarketReaction = '<font style="font-size:x-small; color:grey">[later today...]</font>';
			document.getElementById('YourPoints').innerHTML = '<font style="font-size:x-small; color:grey">[later today...]</font>'; 
	}
	document.getElementById("FeedbackDateRow").innerHTML=	document.getElementById("DateRow").innerHTML;	
	document.getElementById('prevTICKER').innerHTML = document.getElementById("ticker").innerHTML + " at closing bell";
	document.getElementById('OrigPrice').innerHTML = 	"$"+ document.getElementById('Stock_Price').value;
	if (Answer > 0)	 	document.getElementById('YourReaction').innerHTML = YourReaction;	
	document.getElementById('MarketReaction').innerHTML = MarketReaction;	

	//get next question
	if (Answer>0)	{
		Modalbox.show($('QuestionFeedback'), {title:"Feedback on your previous answer...", afterLoad: function() { StartModalTimer(); }});
		updatePrevQuestionChart(Answer);
	}

	FetchData(Answer);	
	document.getElementById('QuestionFeedback').style.display="";

/*	if (document.getElementById("QuestionType").value==2)	{
		document.getElementById('oldNewsFeedback1').style.display="none";
		document.getElementById('oldNewsFeedback2').style.display="none";
	}	else	{
		document.getElementById('oldNewsFeedback1').style.display="";	
		document.getElementById('oldNewsFeedback2').style.display="";	
	}
*/	
	//reset form
	//document.getElementById('GameForm').reset();
	//document.getElementById('button').disabled=true;	
}

function updatePrevQuestionChart(Answer)	{
	var chartXML = chartXMLCache ;
	if (Answer ==0)	return;
	/* || chartXML=="")	{
		document.getElementById("whatsOthers").style.display="none";	
		return;
	}*/
	document.getElementById("prevQuestionChart").style.display="none";	
	document.getElementById("OthersProgress").style.display="";		

	var NewsID = document.getElementById("NewsID").value;
	var querystr = ("chartbreakdown2.php?id="+NewsID);

	xmlHttpOthers=GetXmlHttpObject()
	if (xmlHttpOthers==null)	 {
		 alert ("Browser does not support HTTP Request")
		 return;
	}
	xmlHttpOthers.onreadystatechange=otherThinkCallback; 
	xmlHttpOthers.open("GET",querystr,true)
	xmlHttpOthers.send(null)
}

function otherThinkCallback()	{
	if (xmlHttpOthers.readyState==4 || xmlHttpOthers.readyState=="complete")	 { 
		var obj = document.getElementById("OthersProgress");
		if (obj != null)	obj.style.display="none";	
		var obj2 = document.getElementById("prevQuestionChart");
		if (obj2 !=null)	{
			obj2.style.display="";	
			obj2.innerHTML = xmlHttpOthers.responseText;
		}
	}
}	



function Loaded_Chart ( id ){
   if ( id=="my_chart" ){
      document.my_chart.SetVariable('update_xml', chartXMLCache);	//'<chart><chart_type>bar</chart_type></chart>');
   }
}

function FetchData(Answer)	{

	var url;
	StopTimer();
	//document.getElementById("leftbar").style.display="none";
	document.getElementById("questionheader").style.display="none";
	document.getElementById("questiontext").style.display="none";
	document.getElementById("questiontext2").style.display="none";	

	document.getElementById("Data").style.display="none";
	document.getElementById("progress").style.display="";
	document.getElementById("questionEmpty").style.display="";	
	
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)	 {
		 alert ("Browser does not support HTTP Request")
		 return;
	}

	var date = new Date();
	var timestamp = date.getTime();
	var NewsID = document.getElementById("NewsID").value;
	var	QuestionType = document.getElementById("QuestionType").value;
	var Stock_Price = parseFloat(document.getElementById('Stock_Price').value);

	var delta1 		= 1.02*Stock_Price;	//	parseInt(document.getElementById('delta1').innerHTML);
	var delta2 		= 0.98*Stock_Price;	//parseInt(document.getElementById('delta2').innerHTML);
		
	if (Answer==0)	{
		url = "question.php?t="+timestamp;
	}	else { 
		url = "question.php?t="+timestamp+"&Answer="+Answer+"&d1="+delta1+"&d2="+delta2+"&NewsID="+NewsID+"&RS="+RoundScore+"&P="+points+"&QuestionType="+QuestionType +"&RoundID="+RoundID;
	}

	xmlHttp.onreadystatechange=stateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);

}


function rankSelect()	{
	document.getElementById("imageGlobe").style.display = "none";
	document.getElementById("imageCountry").style.display = "none";
	document.getElementById("regionRank").style.display = "none";
	document.getElementById("regionAll").style.display = "none";		
	document.getElementById("cityRank").style.display = "none";
	document.getElementById("cityAll").style.display = "none";		
	document.getElementById("countryRank").style.display = "none";
	document.getElementById("countryAll").style.display = "none";		
	document.getElementById("worldRank").style.display = "none";
	document.getElementById("worldAll").style.display = "none";		
	
	var sele = document.getElementById("RankStats").value;
	if (sele == 1)	{
		document.getElementById("imageGlobe").style.display = "";
		document.getElementById("worldRank").style.display = "";
		document.getElementById("worldAll").style.display = "";			
	}
	if (sele == 2)	{
		document.getElementById("imageCountry").style.display = "";
		document.getElementById("countryRank").style.display = "";
		document.getElementById("countryAll").style.display = "";		
	}
	if (sele == 3)	{
		document.getElementById("imageCountry").style.display = "";
		document.getElementById("regionRank").style.display = "";
		document.getElementById("regionAll").style.display = "";		
	}
	if (sele == 4)	{
		document.getElementById("imageCountry").style.display = "";
		document.getElementById("cityRank").style.display = "";
		document.getElementById("cityAll").style.display = "";		
	}
}

function stateChanged() 	{ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")	 { 
		var stf = xmlHttp.responseXML.documentElement.getElementsByTagName('ERROR');
		if (stf == null)	{
			document.getElementById("loadingtext").innerHTML = xmlHttp.responseText+"<br>Hold on while we continue to search for a relevant question...";
			//FetchData(0);
			return;
		}
		stf = xmlHttp.responseXML.documentElement.getElementsByTagName('ERROR')[0];
		var errCode = stf.childNodes[0].nodeValue;
		if ( errCode == "1")	{
			document.getElementById("loadingtext").innerHTML = "Please wait while we continue to search for a relevant question...";
			//FetchData(0);
			return;
		}
		if (errCode  == "2")	{
			document.getElementById("loadingtext").innerHTML = "Sorry.  No more relevant questions apply to your setting.  Please consider changing your profile's sector";
			return;
		}
		if (errCode  == "3")	{
			document.getElementById("loadingtext").innerHTML = "Sorry.  Missing relevant questions per your setting.  Please consider changing your profile's sector";
			return;
		}

		if (errCode  == "15")	{
			document.getElementById("loadingtext").innerHTML = "Sorry.  System error has occured.  Please click <a href=\"play_game.php\"> to reload.</a>";
			return;
		}

		document.getElementById("loadingtext").innerHTML = "Please wait.  Loading next question...";
		document.getElementById("worldRank").innerHTML	 = xmlHttp.responseXML.documentElement.getElementsByTagName('worldRank')[0].childNodes[0].nodeValue;
		document.getElementById("worldAll").innerHTML = xmlHttp.responseXML.documentElement.getElementsByTagName('worldAll')[0].childNodes[0].nodeValue;
		document.getElementById("countryRank").innerHTML	 = xmlHttp.responseXML.documentElement.getElementsByTagName('countryRank')[0].childNodes[0].nodeValue;
		document.getElementById("countryAll").innerHTML = xmlHttp.responseXML.documentElement.getElementsByTagName('countryAll')[0].childNodes[0].nodeValue;
		document.getElementById("regionRank").innerHTML	 = xmlHttp.responseXML.documentElement.getElementsByTagName('regionRank')[0].childNodes[0].nodeValue;
		document.getElementById("regionAll").innerHTML = xmlHttp.responseXML.documentElement.getElementsByTagName('regionAll')[0].childNodes[0].nodeValue;
		document.getElementById("cityRank").innerHTML	 = xmlHttp.responseXML.documentElement.getElementsByTagName('cityRank')[0].childNodes[0].nodeValue;
		document.getElementById("cityAll").innerHTML = xmlHttp.responseXML.documentElement.getElementsByTagName('cityAll')[0].childNodes[0].nodeValue;
	
var imgw = xmlHttp.responseXML.documentElement.getElementsByTagName('StockGraphImg');

if (imgw != null)	  	document.getElementById("StockGraphImg").src=xmlHttp.responseXML.documentElement.getElementsByTagName('StockGraphImg')[0].childNodes[0].nodeValue; 
var titily = xmlHttp.responseXML.documentElement.getElementsByTagName('Title');

if (titily !=null)		document.getElementById("Title").innerHTML		=xmlHttp.responseXML.documentElement.getElementsByTagName('Title')[0].childNodes[0].nodeValue; 

	var obju = xmlHttp.responseXML.documentElement.getElementsByTagName('FullStory');

	if (obju != null)	{
		obju = xmlHttp.responseXML.documentElement.getElementsByTagName('FullStory')[0].childNodes[0];
		if (obju != null)		document.getElementById("FullStory").innerHTML		=xmlHttp.responseXML.documentElement.getElementsByTagName('FullStory')[0].childNodes[0].nodeValue; 
	}

	var obju2 = xmlHttp.responseXML.documentElement.getElementsByTagName('FullStoryStart');
	if (obju2 !=null)		document.getElementById("FullStoryStart").innerHTML		=xmlHttp.responseXML.documentElement.getElementsByTagName('FullStoryStart')[0].childNodes[0].nodeValue; 

	 	document.getElementById("ticker").innerHTML		=(xmlHttp.responseXML.documentElement.getElementsByTagName('Ticker')[0].childNodes[0].nodeValue).toUpperCase(); 
	 	document.getElementById("ticker2").innerHTML		=(xmlHttp.responseXML.documentElement.getElementsByTagName('Ticker')[0].childNodes[0].nodeValue).toUpperCase(); 	 	
	    document.getElementById("industry").innerHTML	=xmlHttp.responseXML.documentElement.getElementsByTagName('Industry')[0].childNodes[0].nodeValue; 
	    document.getElementById("companyName").innerHTML	=xmlHttp.responseXML.documentElement.getElementsByTagName('Company')[0].childNodes[0].nodeValue; 	    
		var russel = xmlHttp.responseXML.documentElement.getElementsByTagName('Russel')[0].childNodes[0].nodeValue; 
	    document.getElementById("russel").innerHTML		=russel + "%"; 
		var Pdelta =  parseFloat(russel)/100;
		var StockPrice = xmlHttp.responseXML.documentElement.getElementsByTagName('Stock_Price')[0].childNodes[0].nodeValue;

/*		var up   = Math.ceil( (1.02+Pdelta)*StockPrice);	if (up<StockPrice)		up   = Math.round(StockPrice);
		var down = Math.floor( (0.98+Pdelta)*StockPrice);	if (down>StockPrice)	down = Math.round(StockPrice);	*/
		var up   = 1.02*StockPrice;	up = up.toFixed(2);
		var down = 0.98*StockPrice;	if (down<0)	down = StockPrice;	down = down.toFixed(2);
		/*document.getElementById("delta1").innerHTML='+2% up';
		document.getElementById("deltaMid").innerHTML= '-2% to +2%';
		document.getElementById("delta2").innerHTML='-2% down';*/

		var QuesTyp = xmlHttp.responseXML.documentElement.getElementsByTagName('QuestionType')[0].childNodes[0].nodeValue;
	    var quesDate = xmlHttp.responseXML.documentElement.getElementsByTagName('Date')[0].childNodes[0].nodeValue; 
   	    
	    if (QuesTyp  == 1)  {
	    	document.getElementById("ImpactTange").innerHTML= /*quesDate+*/ "closing bell";
	    	document.getElementById("DateRow").innerHTML=quesDate;
	    }
	    if (QuesTyp  == 2) 	{
	    	document.getElementById("ImpactTange").innerHTML= 'closing bell <span class="red">TODAY</span>';
	    	document.getElementById("DateRow").innerHTML=quesDate + " (Today)";	    
	    }

 	 	document.getElementById("StockPrice").innerHTML="$"+StockPrice; 
	    document.getElementById("Stock_Price").value=StockPrice ; 
	    document.getElementById("Pchange").value=xmlHttp.responseXML.documentElement.getElementsByTagName('PriceChange')[0].childNodes[0].nodeValue; 

   	    document.getElementById("Date").value= quesDate;
 
   	    
	    document.getElementById("NewsID").value=xmlHttp.responseXML.documentElement.getElementsByTagName('NewsID')[0].childNodes[0].nodeValue; 	 
	    document.getElementById("QuestionType").value=xmlHttp.responseXML.documentElement.getElementsByTagName('QuestionType')[0].childNodes[0].nodeValue; 	

        document.getElementById("progress").style.display="none";
		document.getElementById("questionEmpty").style.display="none";	        
	    document.getElementById("leftbar").style.display="";
		document.getElementById("questionheader").style.display="";
		document.getElementById("questiontext").style.display="";
		document.getElementById("questiontext2").style.display="";	    
	    document.getElementById("Data").style.display="";
		
		//DoFade(7, ["leftbar"], false)
		/*xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null)	 {
			 alert ("Browser does not support HTTP Request")
			 return;
		}

		var NewsID = document.getElementById("NewsID").value;
		var url = "chartbreakdown.php?w=400&id="+NewsID;
		xmlHttp.onreadystatechange=chartResultsPopulate;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);*/

		StartTimer();
	 } 
}
var divNews=1;
function showNews(div, index)	{
	var obj = document.getElementById('fullStory'+div);
	if (obj == null)	return;
	document.getElementById('fullStory'+divNews).style.display="none";	
	divNews= div;
	if (obj.innerHTML != "" )		{	obj.style.display= "";		return;	}
	
	
	obj.style.display="none";
	document.getElementById('fullStoryLoader'+div).style.display="";
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)	 {
		 alert ("Browser does not support HTTP Request")
		 return;
	}

	url = "getNews.php?id="+index;

	xmlHttp.onreadystatechange=showNewsCallback; 
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function showNewsCallback()	{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")	 { 
			document.getElementById('fullStoryLoader'+divNews).style.display="none";
			document.getElementById('fullStory'+divNews).innerHTML= xmlHttp.responseText;
			document.getElementById('fullStory'+divNews).style.display="";

	}
}	


function chartResultsPopulate()	{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")	 { 
		chartXMLCache 	 = xmlHttp.responseText;
		document.my_chart.SetVariable('Is_Loaded_Chart', 'true');
	}
}	


function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}



var FadeInterval = 600;
var StartFadeAt = 7;
var FadeSteps = new Array();
	FadeSteps[1] = "ff";
	FadeSteps[2] = "ee";
	FadeSteps[3] = "dd";
	FadeSteps[4] = "cc";
	FadeSteps[5] = "bb";
	FadeSteps[6] = "aa";
	FadeSteps[7] = "99";
	FadeSteps[8] = "88";
	FadeSteps[9] = "77";
	FadeSteps[10] = "66";
	FadeSteps[11] = "55";
	FadeSteps[12] = "44";
	FadeSteps[13] = "33";
	FadeSteps[14] = "22";

function DoFade(colorId, targetId, disappear) {
	return;
    if (colorId >= 1) {
		document.getElementById(targetId).style.backgroundColor = "#ffff" + FadeSteps[colorId];
        if (colorId==1) {
			clearTimeout (FadeTO);
            document.getElementById(targetId).style.backgroundColor = "transparent"
            if (disappear==true) {alert (document.getElementById(targetId).style.display = "none");};
		}
        colorId--;
	//	alert(colorId);
        FadeTO = 
		setTimeout("DoFade("+colorId+",'"+targetId+"')", FadeInterval, disappear);
	}
}

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 


	function submitenterSearch(myfield,e) {
			var keycode;
			if (window.event) keycode = window.event.keyCode;
			else if (e) keycode = e.which;
			else return true;
			
			if (keycode == 13)	   {
			   
		   		LogIn();
		   		return false;
			   }
			else
			   return true;
		}
		
		
		
		
		
		
////////////////////////////////////////////////////
// Registration stuff							////
////////////////////////////////////////////////////
function echeck(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str=="")	{
			alert("Missing E-mail");
			return false;
		}
		if (str.indexOf(at)==-1){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    alert("Invalid E-mail ID")
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    alert("Invalid E-mail ID")
		    return false
		 }

 		 return true					
	}
function validateRegFormOnSubmit(update) {
	 var reason = "";
	 var emailID	=document.getElementById("email");
	 var username 	= document.getElementById("user");
	 var pass 		= document.getElementById("pass");
	 var pass2		= document.getElementById("pass2");
	
     reason += validateUsername(username);
     if (!update)	reason += validatePassword(pass,pass2);
     reason += validateEmail(emailID);
      
     if (reason != "") {
       alert("Some fields need correction:\n" + reason);
       return false;
     }
 	return true;
}


function validateUsername(fld) {
    var error = "";
    var illegalChars = /\W/; // allow letters, numbers, and underscores
 
    if (fld.value == "") {
        fld.style.background = '#ffffcc'; 
        error = "You didn't enter a username.\n";
    } else if (fld.value.length < 5) {
        fld.style.background = '#ffffcc'; 
        error = "The username is too short.\n";
    } else if (illegalChars.test(fld.value)) {
        fld.style.background = '#ffffcc'; 
        error = "The username contains illegal characters.\n";
    } else {
        fld.style.background = '#ffffff';
    }
    return error;
}

function validatePassword(fld,fld2) {
    var error = "";
    var illegalChars = /[\W_]/; // allow only letters and numbers 
 
    if (fld.value == "") {
        fld.style.background = '#ffffcc';
        error = "You didn't enter a password.\n";
    } else if ((fld.value.length < 7) || (fld.value.length > 15)) {
        error = "The password needs to be at least 7 characters. \n";
        fld.style.background = '#ffffcc';
    } else if (illegalChars.test(fld.value)) {
        error = "The password contains illegal characters.\n";
        fld.style.background = '#ffffcc';
    } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
        error = "The password must contain at least one numeral.\n";
        fld.style.background = '#ffffcc';
    } else if (fld.value != fld2.value) {
        error = "The passwords do not match.\n";
        fld.style.background = '#ffffcc';	        fld2.style.background = '#ffffcc';
    } else {
        fld.style.background = '#ffffff';			fld2.style.background = '#ffffff';
    }
   return error;
}  


function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validateEmail(fld) {
    var error="";
    var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (fld.value == "") {
        fld.style.background = '#ffffcc';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
        fld.style.background = '#ffffcc';
        error = "Please enter a valid email address.\n";
    } else if (fld.value.match(illegalChars)) {
        fld.style.background = '#ffffcc';
        error = "The email address contains illegal characters.\n";
    } else {
        fld.style.background = '#ffffff';
    }
    return error;
}


function ValidateRegForm(){
	
	
	if (username.value =="" || username.value.length<4)	{
		alert("Username must be at least 4 characters long");
		username.style.backgroundColor='#ffffcc'; 		
		username.focus();
		return false;
	}			
	
	if (pass.value=="" || pass2.value=="")	{
		alert("Password are missing");
		pass.style.backgroundColor='#ffffcc'; 		
		pass2.style.backgroundColor='#ffffcc'; 			
		pass.focus();
		return false;
	}	

	if (pass.value!=pass2.value)	{
		alert("Passwords do not match");
		pass.style.backgroundColor='#ffffcc'; 		
		pass.style.backgroundColor='#ffffcc'; 			
		pass.focus();
		return false;
	}	

	
	if (pass.value.length<6)	{
		alert("Passwords must be at least 6 characters long");
		pass.style.backgroundColor='#ffffcc'; 		
		pass.focus();
		return false;
	}	

	if (echeck(emailID.value)==false){
		emailID.value="";		
		emailID.style.backgroundColor='#ffffcc'; 
		emailID.focus();
		return false;
	}			

	document.regForm.submit();
}

function toggleSectors()	{
	var tog = document.getElementById("sectorsDiv").style.display;
	if (tog =="none")	{
		msg = "click to collapse";
		tog = "";
	}		else	{
		tog = "none";
		msg = "click to expand";
	}
	document.getElementById("sectorsDiv").style.display = tog;
	document.getElementById("sectorsExpand").innerHTML = msg;
	
}





////////////////////////////////////////////////////////////////////////////////////
//  LOgin stuff
////////////////////////////////////////////////////////////////////////////////////

function logout(){

	try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttpLogOut=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttpLogOut=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttpLogOut=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
	if (xmlHttpLogOut==null)
	 {
	 alert ("Browser does not support HTTP Request")
	 return
	 }
	 
	var url="logout.php" 
	
	xmlHttpLogOut.open("GET",url,true)
	xmlHttpLogOut.send(null)
	xmlHttpLogOut.onreadystatechange=function()
	{
		if (xmlHttpLogOut.readyState==4 || xmlHttpLogOut.readyState=="complete")
		 { 
		    if(navigator.appName.indexOf('Microsoft')!=-1)	
				top.window.navigate("http://www.stocknewsgame.com");
			else 
				top.window.location.href="http://www.stocknewsgame.com";

		    //document.getElementById("login").innerHTML=xmlHttpLogOut.responseText;
		 } 
	}
}

function LogIn(){
	var username = document.getElementById("user").value;
	var password = document.getElementById("pass").value;
	
	return doLogIn(username, password);
}

function doLogIn(username,password){
		document.getElementById("loader").style.display = "";
		var remember = document.getElementById("rememberMe").checked;
		var url = "check-login.php?user=" + username + "&pass=" +password + "&remember=" +remember;
		
		try		 {		 // Firefox, Opera 8.0+, Safari
			xmlHttpLogin=new XMLHttpRequest();
		}	catch (e)	 {		 //Internet Explorer
			try	{
			  xmlHttpLogin=new ActiveXObject("Msxml2.XMLHTTP");
		    } catch (e)	  {
		  	  xmlHttpLogin=new ActiveXObject("Microsoft.XMLHTTP");
		    }
		}
		
		if (xmlHttpLogin==null)	 {
			 alert ("Browser does not support HTTP Request")
			 return;
		}
		
		xmlHttpLogin.open("POST",url,true)
		xmlHttpLogin.send(null)
		xmlHttpLogin.onreadystatechange=loginCallback;
}

function loginCallback()	{
	if (xmlHttpLogin.readyState==4 || xmlHttpLogin.readyState=="complete")	 { 
			     document.getElementById("loader").style.display = "none";
			     var resp = xmlHttpLogin.responseText;
			     if (resp.indexOf('Welcome')==-1)	{
			     	 //alert (resp);
				     document.getElementById("login").innerHTML=resp;
				    
				 }	else	{
					if(navigator.appName.indexOf('Microsoft')!=-1)	window.navigate("http://www.stocknewsgame.com");
						else window.location.href="http://www.stocknewsgame.com";				 
				 }
			     
			     
			} 

}

	

function popUp(URL) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=430,height=160,left = 312,top = 284');");
}




