// All the software in this file is proprietary and available only under a license agreement
// Please contact CubeWerx Australia Pty Ltd - info@cubewerx.com.au

//--------------------------------------------------------------------------------------------------//
// AJAX function to open up the XML file
function loadXMLDoc(url) 
{
	isIE = false;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) 
	{
        //alert("loadXMLDoc url no1 = " +url);
		req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
		//req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
        req.open("GET", url, false);
		//alert ("get completed")
        req.send(null);
		//alert("null set")
    // branch for IE/Windows ActiveX version
    } 
	else if (window.ActiveXObject) 
	{
		//alert("loadXMLDoc url no2 = " +url);
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) 
		{
            req.onreadystatechange = processReqChange;
			//req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
            req.open("GET", url, false);
            req.send();
        }
    }
}
// AJAX function to validate the XML file opens correctly
function processReqChange() 
{
//alert("readystate= " +req.readyState+ " status= " +req.status);
    // only if req shows "loaded"
    if (req.readyState == 4) 
	{
        // only if "OK"
        if (req.status == 200) 
		{
			// This is where you can place all the code to process the XML file
			//alert ("all OK");
			return;
		} 
		else 
		{
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
	}
}
//---------------------------------------------------------------------------------------------//
// Reads a MySQL DB and creates an XML file which then is read into DOM (Roaders Version)
function ajaxMySQL(url, query, file)
{
	var bnum=0;
	isIE=false;
	try
	{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
		} catch (e)	{
			// Internet Explorer Browsers
			try
			{	isIE =true;
				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try
					{
						ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e)	{
						// Something went wrong
						//alert("Your browser is too old to support AJAX applications!");
						return false;
					}
				}
		}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{	if(ajaxRequest.readyState == 4)  {return false;}}
	//alert ("AJAX Request = "+url+query)

	ajaxRequest.open("GET", url+query, false);
	if(isIE){ ajaxRequest.send(); }
	else { ajaxRequest.send(null); }

	// now go and get the XML file created
	var query="?timestamp="+new Date().getTime();
	if (ajaxFunction(file, query)){return true;}
	else {return false;}
}

//---------------------------------------------------------------------------------------------//
// Reads a MySQL DB and creates an XML file which then is read into DOM 
function ajaxGet(url, p1, p2, file)
{
	var bnum=0;
	isIE=false;
	try
	{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
		} catch (e)	{
			// Internet Explorer Browsers
			try
			{	isIE =true;
				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try
					{
						ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e)	{
						// Something went wrong
						//alert("Your browser is too old to support AJAX applications!");
						return false;
					}
				}
		}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{	if(ajaxRequest.readyState == 4)  {return false;}}
	alert ("AJAX Request = "+url+p1+p2)

	ajaxRequest.open("GET", url+p1+p2, false);
	if(isIE){ ajaxRequest.send(); }
	else { ajaxRequest.send(null); }
	alert ("done")

	// now go and get the XML file created
	var query="?timestamp="+new Date().getTime();
	if (ajaxFunction(file, query)){return true;}
	else {return false;}
}

//---------------------------------------------------------------------------------------------//
// This is a new version and I should replace the LoadXMLDoc vesrion above
function ajaxFunction(url, query)
{
	var bnum=0;
	isIE=false;
	try
	{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
		} catch (e)	{
			// Internet Explorer Browsers
			try
			{	isIE =true;
				ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try
					{
						ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
						} catch (e)	{
						// Something went wrong
						alert("Your browser is too old to support AJAX applications!");
						return false;
					}
				}
		}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{	if(ajaxRequest.readyState == 4)  {return;}}
	//alert ("AJAX Request = "+url+query)
	ajaxRequest.open("GET", url+query, false);
	if(isIE){ ajaxRequest.send(); }
	else { ajaxRequest.send(null); } 
}

//-------------------------------------------------------------------------------------------------------------
// function to read a SLD file (XML) and extract the title, each rule and build a Legend for screen display
function buildLegend (Url, leg, legTitle, legTable, legBox, legText, tdCell, firstTime, legName)

// Input variables for this function:
//	- Url = full sld Url of the SLD file
//	- leg = ID in application for whole of legend 
//	- legTitle = ID in application for legend Title 
//	- legTable = ID in application for legend Table
//	- legBox = Class definition for coloured box of legend item
//	- legText = Class definition for text of legend item
//	- tdCell = Class definition for Table cell holding coloured box of legend item
//	- firstTime = boolean flag to indicate elements already exist and needs to be removed/updated
//  - legName =  text string of the unique name of the legend
//
// Please note that all the positioning and style controls are underatken in the application
//------------------------------------------------------------------------------------------------------------
{
	// Open the XML file for the SLD and get data
	//alert("buildlegend")
	//alert (Url+", "+leg+", "+legTitle+", "+legTable+", "+legBox+", "+legText+", "+tdCell+", "+firstTime+", "+legName);
	loadXMLDoc(Url);
	var sldTitle = req.responseXML.getElementsByTagName("UserStyle");
	var title = sldTitle[0].getElementsByTagName("Title")[0].firstChild.nodeValue;
	var sldNamedLayer = req.responseXML.getElementsByTagName("NamedLayer");
	sldLayerName = sldNamedLayer[0].getElementsByTagName("Name")[0].firstChild.nodeValue;
	//alert ("SLD Name in Basics = "+sldLayerName);
		
	// Update the Legend Title with selected object
	var ltit = document.getElementById(legTitle);
	if (firstTime)
	{
		// if first time create the Legend Title Text node 
		var textNode = document.createTextNode(" ");
		ltit.appendChild(textNode);
		ltit.firstChild.nodeValue=title;
	}
	else
	{
		// update the existing LegendTitle Text node
		ltit.firstChild.nodeValue=title;
	}
				
	// Get the Table Object 
	var table=document.getElementById(legTable);
		
	// If this is not the first time kill off existing table body cell
	if (!firstTime)
	{
		
		var tbody=document.getElementById(legName);
		tbody.parentNode.removeChild(tbody);
		tbody.value=null;	// must null it out to completely kill it out of memory
	}

	// Ok now we can start afresh with a new Table Legend Body
	var tbody=document.createElement("tBody");
	tbody.setAttribute("id", legName);
		
	// Set up the FOR loop for all the Rules in the XML SLD file
	var sldRules = req.responseXML.getElementsByTagName("Rule");
	var num= sldRules.length;
	if (num>0)
	{	
		var strokeColr = ""; 
		var strokeWidth = "";
		var fillColr = ""; 
		var fillOpacity = opacityValue;
		//alert (opacityValue)
		// There are some rules in the SLD to control the symbology
		// Loop through all the rules in the SLD file and build legend rows for each
		for (i = 0; i < num ; i++)
		{	
		// Check for a polygon symboliser tag
		if (sldRules[i].getElementsByTagName("PolygonSymbolizer"))
		{	
			var sldPolygon = sldRules[i].getElementsByTagName("PolygonSymbolizer"); 
			var sldFill = sldRules[i].getElementsByTagName("Fill");
			if (sldFill.length > 0)
			{
				// find out how many CssParameter tags there are
				var sldFillCss = sldFill[0].getElementsByTagName("CssParameter");
				
				//alert ("sldFillCss = "+sldFillCss.length)
				if (sldFillCss.length > 0 )
				{
					var fillColr = ""; 
					var fillOpacity = opacityValue;
					// process each Fill CssParemeter attribute	
					for (j=0; j<sldFillCss.length ; j++)
					{
						var fillAtt = sldFillCss[j].getAttribute("name");
						if (fillAtt == "fill") 
						{
							fillColr = sldFill[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;		
						}
						if (fillAtt == "fill-opacity")
						{			
							fillOpacity = sldFill[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
						}
					}
				}
			}
			// find out how many Stroke Rule nodes
			var sldStroke = sldRules[i].getElementsByTagName("Stroke");
			if (sldStroke.length > 0)
			{
				var sldStrokeCss = sldStroke[0].getElementsByTagName("CssParameter");
				
				//alert ("sldStrokeCss = "+sldStrokeCss.length)
				if(sldStrokeCss.length > 0)
				{
					var strokeColr = ""; 
					var strokeWidth = "";
					// process each Stroke CssParemeter attribute				
					for (j=0; j<sldStrokeCss.length ; j++)
					{
						var strokeAtt = sldStrokeCss[j].getAttribute("name");
						if (strokeAtt == "stroke") 
						{
							strokeColr = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;		
						}
						if (strokeAtt == "stroke-width")
						{
							strokeWidth = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
						}
					}
				}
			}
		}
			//alert ("fillColr = "+fillColr+ " fillOpacity = "+fillOpacity);
			//alert ("strokeWidth = "+strokeWidth+ " strokeColr = "+strokeColr);

			// Ok now we have all the parameters from the SLD start to build the Legend
			var name = sldRules[i].getElementsByTagName("Name")[0].firstChild.nodeValue;			
				
			// set up the Table Body node and the TR node
			var tdIdbox="tdBox"+i;
			var tdIdtext="tdText"+i;
				
			// Set up the legend box TD node with appropriate color		
			var trNode = document.createElement("tr");
			var tdNode1 = document.createElement("td");
			tdNode1.className=tdCell;
			var divNode = document.createElement("div");
			divNode.className=legBox;
			divNode.setAttribute("id", tdIdbox);	
			divNode.style.backgroundColor=fillColr;
			var op=Number(fillOpacity);
			var fillNumber = Math.abs(op*100);
			setOpacity(divNode, fillNumber);
			/*if (isIE)
			{	// This is for IE's opacity control
				var op=Number(fillOpacity);
				var fillNumber = Math.abs(op*100);
				//divNode.style.filter="alpha(opacity="+fillNumber+");";
				divNode.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+ fillNumber +");"
			}
			else
			{	divNode.style.opacity=fillOpacity;
			}
			*/
			// set up borders
			if (strokeWidth == "")
			{	divNode.style.borderStyle="none";
			}
			else
			{	divNode.style.border=strokeWidth+"px solid "+strokeColr;
			}
			// append TD node with legend symbol box to TR node 
			tdNode1.appendChild(divNode);
			trNode.appendChild(tdNode1);
			
			// Now generate the Text node in the second column of the table row
			var tdNode2 = document.createElement("td"); 
			tdNode2.className=legText;
			var textNode = document.createTextNode(name);
			tdNode2.setAttribute("id", tdIdtext);	
			tdNode2.appendChild(textNode);
					
			// append TD node with legend text to TR node 
			trNode.appendChild(tdNode2);
			tbody.appendChild(trNode);	
		}
		// append the tbody note to the Table element
		table.appendChild(tbody);
	}
	else
	{	alert ("Sorry can't generate a legend");	}
}



function setOpacity(obj, opacity) 
{
// obj = object that is to have aopacity set for
// opacity =  integer between 0 & 100
	opacity = (opacity == 100)?99.999:opacity;

  // IE/Win
	obj.style.filter="alpha(opacity="+ opacity + ")";

  // Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;

  // Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;

  // Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}




//-------------------------------------------------------------------------------------


//function tggl(){
    	//tmp = map2.getCurrentMapType()
    	//map2.setMapType(map.getCurrentMapType());
    	//map.setMapType(tmp);
    //}
// function to interactively conmtrol the transparency of a map or layer
function transparency(tmap)
{
	var tmpX;
	var tmpY;
	var oElement=1;
	var vrp=document.getElementById("verp");
	var m2 = document.getElementById(tmap)

	// Function to handle mouse movements	
	function fn_Msmv(e)
	{
		if (!e) var e = window.event;
		if(oElement==2)
		{
			offX = (vrp.width);
			if(document.all){
				newX=window.event.clientX-offX;
			}else{
				newX=e.clientX-offX;
			}
			if((newX<601)&&(newX>0))
			{ // expects a slidare bar 600px wide
				if(document.all){
					vrp.style.left=newX
					m2.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+ parseInt(newX/6) +");"
				}
				else
				{
					vrp.style.left=(newX+"px")
					amt = (newX/6)
					if(amt>=10)
					{
						m2.style.opacity=eval("0."+ parseInt(amt))
					}
					else
					{
						m2.style.opacity=eval("0.0"+ parseInt(amt))
					}
				}
			}
		}
	}
	// Function to handle mouse down eventsa
	function fn_Msdn(e)
	{
		if (!e) {var e = window.event;}
		if(document.all)
		{
			if(e.srcElement.className=="mov"){oElement=2}
		}
		else
		{
			if(e.target.className=="mov"){oElement=2}
		}
	}
	// Function to handle mouseup events
	function fn_Msup(){	oElement=1;	}
	
	if(document.all)
	{
		document.onmousemove=fn_Msmv;
		document.onmousedown=fn_Msdn;
		document.onmouseup=fn_Msup;
	}
	else
	{
		window.onmousemove=fn_Msmv;
		window.onmousedown=fn_Msdn;
		window.onmouseup=fn_Msup;
	}
}
//---------------------generic wiondow utilities -----------------------------------------------//

// function to leap to a new pop-up window for big format maps
function leapToNew (link)
{
	var new_url=link;
	if (  (new_url != "")  &&  (new_url != null)  )
	window.open(new_url,999,'width=1000,height=780,toolbar=yes,location=no,directories=no,status=no,menubar=yes,scrollbars=yes');
}

// function to leap to new URL in same location for inline maps
function leapToSame (link)
{
	var new_url=link;
	if (  (new_url != "")  &&  (new_url != null)  )
	window.location=new_url;
}
	
// function to launch a sized window
function popUp(Url) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(Url, '" + id + "', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=900,height=1000,left = 10,top = 10');");	
}

// Generic function to launch a PopUp window
function makePopup(url, width, height, overflow) // overflow can be 'scroll', 'resize' or 'both'
{
	if (  (url != "")  &&  (url != null)  )
	{
		if (height > 800) {height = 800;}
		if (width > 800)  {width = 800;}
		if (overflow == '' || !/^(scroll|resize|both)$/.test(overflow))
		{ overflow = 'both';}
		// Now launch the window
		win = window.open (url, '', 'width='+width+', height='+height+', top=100, left=100'+
			', scrollbars='+(/^(scroll|both)$/.test(overflow) ? 'yes' : 'no')+
			', resizable=' +(/^(resize|both)$/.test(overflow) ? 'yes' : 'no')+
			', status=yes,toolbar=no,menubar=no,location=no');
		//return win;
	}
}


// function to get cookies
function getCookies(searchName)
{
	var cookies = document.cookie.split(";")
	for (var i=0; i < cookies.lenght; i++);
	{
		var cookieCrumbs = cookies[i].split("=");
		var cookieName = cookieCrumbs[0];
		var cookieValue = cookieCrumbs[1];
		if (cookieName == searchName)
		{
			return cookieValue;
		}
	}
	return false;
}

// function to get the date into standard format dd-mmm-yyyy
function formatDate()
{
	var months=new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
	var date= new Date()
	var month = date.getMonth()
	fullDate = date.getDate()+"-"+months[month]+"-"+date.getFullYear();
	return;
}

// --------------------Accounts and Login Management Utilities----------------------------------//

// Function to process the user entered Password
function Login (username, password, check)
{
	if (username && password ) 
	{
		result="notPresent";
		epword = hex_md4(password);			// encrypt the input password
		var query="?timestamp="+new Date().getTime();
		//alert ("pwUrl in Login = "+pwUrl)
		ajaxFunction(pwUrl, query);
		var loginXml = ajaxRequest.responseXML.getElementsByTagName("login");
		var loginNo = loginXml.length;
		//alert("logins = "+loginNo);
		if (loginNo == 0)	{ return;}
		else
		{
			for (i = 0; i<loginNo; i++)			// loop for each User Id in the XML file 
			{
				var loginName = loginXml[i].getAttribute("name");
				if (username == loginName)		// match the input User Id with whats in XML file
				{
					var pwd=loginXml[i].getElementsByTagName("password");
					var pwNo=pwd.length;
					//alert ("number of passwords for "+loginName+" = "+pwNo);
					for (ii = 0; ii<pwNo; ii++)	// loop for each password in the matched User Id
					{	
						var epasswd = pwd[ii].getAttribute("pw");
						//alert ("epasswd = "+epasswd+ " epword = "+epword);
						if (epasswd == epword)	// match the input Password with whats in the XML file for this User Id
						{
							// When used in 'check' mode advise that it is already in database
							if (check)
							{
								//alert ("duplicated");
								result="present";
								return;
							}								
							else
							{
								// jump to the destination URL protected by login/password
								//var htsite = "http://" + username + ":" + password + "@" + server;

								// log the successful login here
								formatDate();
								var loginType = "Login";
								query = "?uname="+username+"&tpassword="+password+"&datestamp="+fullDate+"&loginType="+loginType;
								var url = "logit.php"
								//alert ("about to update the log")
								ajaxFunction(url, query);
								//window.location = htsite;
								result = "loggedin";
								return ;
							}
						}
					}
				}
			}
		}
	}
	else
	{
		result="error";
		return;
	}
}
		
// Function to create the new account inside the server-side XML file
function createAccount (form)
{  
	// Get the email data from the form and validate it
	var uname = form.username.value;		// required
		
	// now validate the passwords
	var password01 = form.password01.value;	//required
	var password02 = form.password02.value;

	// check to see the two passwords match
	if ((password01 == password02) && (uname != password01))
	{	
		// check to see if the account/password already exists
		Login (uname, password01, true)
		//alert ("result = "+result);
		if (result=="present")
		{	
			// found one so return for new account/login
			alert ("Account/Passwords combination taken - Try Again"); 
			form.password01.value=''; 
			form.password02.value=''; 
			form.password01.focus;
			return;
		}
		if (result == "notPresent")
		{
			// write new account/login to XML file
			epassword = hex_md4(password01);	// required
			query = "?uname="+uname+"&epassword="+epassword+"&tpassword="+password01+"&accountUrl="+pwUrl;
			var url = "add.php";
			//alert(url+" : "+query)
			ajaxFunction(url, query);

			// log the successful login here
			formatDate();
			var loginType = "Register";
			query = "?uname="+uname+"&tpassword="+password01+"&datestamp="+fullDate+"&loginType="+loginType;
			var url = "logit.php"
			ajaxFunction(url, query);
			return;
		}
		if (result == "error")
		{
			alert ("Not enough information - Try Again");
			form.password01.value=''; 
			form.password02.value=''; 
			form.password01.focus;
			return;
		}
		return;
	}
	else 
	{
		// the two passwords are not the same so return for new entry
		alert ("Passwords do not match or same as username"); 
		form.password01.value=''; 
		form.password02.value='';
		form.username.value='';
		form.password01.focus; 
		return;
	}
}


// This function is used to drive the login form to enter login details
function loginForm()
{
	//alert("pwUrl = ("+pwUrl+") targetUrl = ("+targetUrl+")");
	place = document.getElementById('loginBox');
	place.className="mapon";
	form="<h4>Download Login:</h4>\n";
	form+="<form name='login' id='login' onsubmit='launchLogin(this.username.value, this.password.value, this.server.value, false);'>\n";
	form+="<input type='hidden' name='server' value='targetUrl' />\n";
	form+="Email:<br/>\n";
	form+="<input type='text' name='username'  size='20' />\n";
	form+="<br><br>Password:<br/>\n";
	form+="<input type='password' name='password'  size='20' /><br><br>\n";
	form+="<input type='submit' value='Login' name='button'  />\n";
	form+="<input type='button' value='Register' name='button' onclick='newAccount()'; />\n";
	form+="</form><br/>";
	//alert(form);
	place.innerHTML=form;
	var loginObj=document.getElementById('login');
	//loginObj.password.value=""; 
	//loginObj.username.value=""; 
	loginObj.username.focus;
}

// Function to launch the Login process and branch appropriately
function launchLogin( username, password, server, check)
{	
	// this is the main login checking function
	Login (username, password, check)
	if (result == "loggedin")
	{
		loggedIn=true;
		var surround=document.getElementById("surround");
		surround.parentNode.removeChild(surround);
		leapToSame(targetUrl);
	}
	else
	{
		alert ("Sorry Password not accepted - try again or Register a new one");
	}
}

// this is the new Account function for registration of new username/passwords
function newAccount()
{
	//alert ("pwUrl in new Account= "+pwUrl);
	form2="<h4>Free Login Registration:</h4>\n";
	form2+="<form name='newAccount' id='newAccount'  />\n";
	form2+="New Email:<br/>\n";
	form2+="<input type='text' name='username' id='username' size='20' />\n";
	form2+="<br /><br />New Password:<br/>\n";
	form2+="<input type='password' name='password01' size='20' />\n";
	form2+="<br><br>New Password Again:<br/>\n";
	form2+="<input type='password' name='password02' size='20' />\n";
	form2+="<input type='button' value='Register!' name='button' onClick='launchCreateAccount(this.form)';  />\n";
	form2+="</form><br/>";
	//alert (form2);
	place.innerHTML=form2;
	var newObj=document.getElementById('username');
	newObj.focus;
	
}

// Function to launch the Create Account process and branch appropriately
function launchCreateAccount (form)
{
	if(validateEmail(form))
	{
		// this actiually does the insert of the new account into passwords.xml
		createAccount (form);
		//alert ("Result = "+result);
		if (result == "notPresent")
		{
			//alert ("all is fine")
			loggedIn=true;
			var surround=document.getElementById("surround");
			surround.parentNode.removeChild(surround);
			leapToSame(targetUrl);
		}
	}
}

// function to validate an email address
//-------------------------------------------------------------------------------------------//
//			How to use....
//
//		<form name="formName" method="post" action="#" onSubmit="return ValidateForm(this.form)">
//          <p>Enter an Email Address : 
//          <input type="text" name="username">
//          </p>
//          <p> 
//          <input type="submit" name="Submit" value="Submit">
//          </p>
//      </form>
//------------------------------------------------------------------------------------------//

function validateEmail(form)
{
	var emailID = form.username
	
	if ((emailID.value==null)||(emailID.value==""))
	{
		alert("Please Enter your Email ID")
		emailID.focus()
		return false
	}
	if (echeck(emailID.value)==false)
	{
		emailID.value=""
		emailID.focus()
		return false
	}
	return true
 }

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		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					
	}



	
