
/*
 Save and load user data (username and pwd for secure area, email message for contact page).
 Data is kept inside window.name variable as a serialized object.
*/


function GetUserData(){
	var savedobject = null;
	 if(window.top.name.length > 0)
	   try {
	    savedobject = JSON.parse(window.top.name);
	   }
	   catch(e){
		   savedobject = null;
	   }
	  return savedobject;
}


function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}


function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}


function SaveAuthInfo(username,passwordhash){
		function savedobjectcontructor(){}
	 var savedobject = GetUserData();
	 if(savedobject == null)		 
	  savedobject = new savedobjectcontructor();
	 if(username != null && passwordhash != null){
	  savedobject.username = username;
	  savedobject.passwordhash = passwordhash;   
	   // use cookies - no encryption for now
	  setCookie("user",savedobject.username,365);
	  setCookie("password",savedobject.passwordhash,365);
	 }
	 else {
	  setCookie("user","",1);
	  setCookie("password","",1);
	 }
	 window.top.name = JSON.stringify(savedobject);
}


function AuthInfoEmpty(){
	 var savedobject = GetUserData();
	 if(savedobject == null)		 
	  return true;
	 if(savedobject.username == undefined || savedobject.username == null)
	  return true;
	 if(savedobject.passwordhash == undefined || savedobject.passwordhash == null)
	  return true;
	 return false;
}


function SaveEmail(msg,title,from){
		function savedobjectcontructor(){}
	 var savedobject = GetUserData();
	 if(savedobject == null)		 
	  savedobject = new savedobjectcontructor();	
	 savedobject.emailmessage = msg.substr(0,Math.min(50000,msg.length));
	 savedobject.emailtitle = title.substr(0,Math.min(1000,title.length));
	 savedobject.emailsender = from.substr(0,Math.min(1000,from.length));
	 window.top.name = JSON.stringify(savedobject);
}



	 // save registration info temporarily, for preserving form data between page reloads
function SaveRegInfo(user,email){
		function savedobjectcontructor(){}
	 var savedobject = GetUserData();
	 if(savedobject == null)		 
	  savedobject = new savedobjectcontructor();	
	 savedobject.registrationemail = email.substr(0,Math.min(100,email.length));
	 savedobject.registrationusername = user.substr(0,Math.min(20,user.length));
	 window.top.name = JSON.stringify(savedobject);
}


	 // save login info temporarily, for preserving form data between page reloads
function SaveLoginFormInfo(username){
		function savedobjectcontructor(){}
	 var savedobject = GetUserData();
	 if(savedobject == null)		 
	  savedobject = new savedobjectcontructor();	
	 savedobject.loginformusername = username.substr(0,Math.min(20,username.length));
	 window.top.name = JSON.stringify(savedobject);
}




 // request an auth token, via ajax
function RequestToken_Ajax(){
 
  // get token
 var req = new XMLHttpRequest();
 
 req.open("GET","http://www.mywiicenter.com/requesttoken.php",false);
 req.setRequestHeader("If-Modified-Since","Sat, 1 Jan 2000 00:00:00 GMT");
 req.send(null);
 if(req.status != 200)
  return false;
  
 var tstart = req.responseText.indexOf("<t>");
 if(tstart < 0)
  return false;
 tstart += 3;
 var tend = req.responseText.indexOf("</t>");
 return req.responseText.substring(tstart,tend);
  
}


 // request a token , non-ajax version
function RequestToken_Iframe(){
 
 var ifr = document.createElement("iframe");
 ifr.id = "authiframe";
 ifr.style.width = ifr.style.height = "1px";
 ifr.style.zIndex = "150";
 ifr.style.position = "absolute";
 ifr.style.left = "-1000px";
 ifr.style.top = "0px";
 document.body.appendChild(ifr);
  // the iframe will call ReceiveToken_Iframe of this window, as soon as it loads
 ifr.src = "http://www.mywiicenter.com/requesttoken.php?UA=IE6";
 
}



  // the iframe will call ReceiveToken_Iframe of this window, as soon as it loads
function ReceiveToken_Iframe(t){
		
	var ifr = document.getElementById("authiframe");
	// destroy iframe, it's no use anymore
	document.body.removeChild(ifr);
	
	
   // get requested url from user data, stored from ChangeLocation, and redirect window
	 var savedobject = GetUserData();
	 if(savedobject == null)
	  return false;
	  
	 var windowelement = savedobject.windowtoredirect; 
	 var url = savedobject.requestedurl;
	 var user = savedobject.username;
	 var shapwd = savedobject.passwordhash;
	 
	 savedobject.windowtoredirect = null;
	 savedobject.requestedurl = null;
	
	 if(windowelement == null || url == null)
	  return false;
	 
	   // send SHA256( t + SHA256(password) + t )
	  shapwd = sha256_digest(t + shapwd + t);
	  
	  var scrollinfo = "";
	  var scrollindex = url.indexOf("#i");
	  if(scrollindex >= 0){
		var ind = parseInt(url.substr(scrollindex + 2));
		if(ind > 0)
	     scrollinfo = "#i" + ind;
	   url = url.substring(0,scrollindex);
	  }
	  
	  // parse windowelement
	  if(windowelement == "window")
	   window.location.href = ((url.indexOf("?") < 0) ? (url + "?") : url) + ((user != undefined) ? ("&user=" + user + "&t=" + t + "&ph=" + shapwd) : "") + scrollinfo;
	  else if(windowelement == "top")
	   window.top.location.href = ((url.indexOf("?") < 0) ? (url + "?") : url) + ((user != undefined) ? ("&user=" + user + "&t=" + t + "&ph=" + shapwd) : "") + scrollinfo;
	  else if(windowelement.indexOf("popup:") == 0){ // popup window expressed as the string "popup:<popup name>"
	   eval("windowelement=" + windowelement.substring(6) + ";");
       windowelement.location.href = ((url.indexOf("?") < 0) ? (url + "?") : url) + ((user != undefined) ? ("&user=" + user + "&t=" + t + "&ph=" + shapwd) : "") + scrollinfo;
	  }
	  else { // iframe expressed as the string "iframe:<iframe id>"
	   windowelement = document.getElementById(windowelement.substring(7)); 
	   if(windowelement && windowelement.contentWindow)
        windowelement.contentWindow.location.href = ((url.indexOf("?") < 0) ? (url + "?") : url) + ((user != undefined) ? ("&user=" + user + "&t=" + t + "&ph=" + shapwd) : "") + scrollinfo;
	  }
	 
	 changinglocation = false;	
	 return true;
}


 // change this eventually
var using_ajax = false;
 // if there is a ChangeLocation pending for this window or window.top, ChangeLocation does nothing
var changinglocation = false;

function ChangeLocation(windowelement,url){
	
	  // use cookies - no encryption for now
	  
	  
	  // parse windowelement
	  if(windowelement == "window")
	   window.location.href = url;
	  else if(windowelement == "top")
	   window.top.location.href = url;
	  else if(windowelement.indexOf("popup:") == 0){ // popup window expressed as the string "popup:<popup name>"
	   eval("windowelement=" + windowelement.substring(6) + ";");
       windowelement.location.href = url;
	  }
	  else { // iframe expressed as the string "iframe:<iframe id>"
	   windowelement = document.getElementById(windowelement.substring(7)); 
	   if(windowelement && windowelement.contentWindow)
		windowelement.contentWindow.location.href = url;	   
	  }
	  
	  return;
	  
	  
	  
	  // old code, never reach this point for now
	  
		
	if(changinglocation)
	 return;
	else if(windowelement == "window" || windowelement == "top")
	 changinglocation = true;	
	 
           // get user data
		function savedobjectcontructor(){}
	 var savedobject = GetUserData();
	 if(savedobject == null)		 
	  savedobject = new savedobjectcontructor();
	  
	  
 if(!using_ajax){
	 
	 savedobject.requestedurl = url; 
	 savedobject.windowtoredirect = windowelement;
	 window.top.name = JSON.stringify(savedobject);
   RequestToken_Iframe();
	 
 }
 else {
	 
	 // TODO, not needed as of now
  
 }	     
 
}



/* don't handle refresh for now

 // check if this page has been refreshed, and re-load it with a new auth token, because refreshing it the old, and expired,
 // token would be sent again, causing a login failure even if the user was logged in
function HandleRefresh(iframe){
		
           // get user data
		function savedobjectcontructor(){}
	 var savedobject = GetUserData();
	 if(savedobject == null)		 
	  savedobject = new savedobjectcontructor();
	 
	 var page = location.href.substring(location.href.lastIndexOf("/") + 1);
	 var questionindex = page.indexOf("?");
	 if(questionindex >= 0)
	  page = page.substring(0,questionindex);
	  
	   // check the last page visited
	 if(!iframe){
	 
	  if(savedobject.lastpage == page && savedobject.lastpagereload == false){
		 // either the user has refreshed the page, or the login or registration page is about to reload
		 // after submitting the form
		 
		  // check if the page is not the login or registration page.
		  // in that case, it simply will ask again to enter login or registration info
		 if(location.href.indexOf("login.php") < 0 && location.href.indexOf("register.php") < 0){
			 
			 // preserve parameters
		  var paramindex = location.href.indexOf("?");
		  var params = "";		  
		  
		  while(paramindex >= 0){
		   var paramendindex = location.href.indexOf("&",paramindex + 1);
		   if(paramendindex < 0)
		    paramendindex = location.href.length;
		   var param = location.href.substring(paramindex + 1,paramendindex);
		   if(param.indexOf("t=") != 0 && param.indexOf("user=") != 0 && param.indexOf("ph=") != 0 && param.length > 0)
		    params = params + "&" + param;
		   paramindex = location.href.indexOf("&",paramindex + 1);
		  }
		   // update location
		  ChangeLocation("window",location.href.substring(0,location.href.lastIndexOf("/") + 1) + page + "?" + params);
		 }
		  		  
		 savedobject.lastpagereload = true;
	 }	
	 else
		 savedobject.lastpagereload = false;
	 
	  // keep track of the last page visited
	  
	 var savedobject1 = GetUserData();
	 if(savedobject1 == null)		 
	  savedobject1 = new savedobjectcontructor();
		 savedobject1.lastpage = page;	
		 savedobject1.lastpagereload = savedobject.lastpagereload;
	 window.top.name = JSON.stringify(savedobject1);	
	 
	}
	else {
		
		// this windows is an iframe which has been refreshed, the code is the same except but uses different global variables
	 
	  if(savedobject.lastiframepage == page && savedobject.lastiframepagereload == false){
		 // either the user has refreshed the page, or the login or registration page is about to reload
		 // after submitting the form
		 
		  // check if the page is not the login or registration page.
		  // in that case, it simply will ask again to enter login or registration info
		 if(location.href.indexOf("login.php") < 0 && location.href.indexOf("register.php") < 0){
			 
			 // preserve parameters
		  var url = location.href;
			 
		  var scrollinfoindex = url.indexOf("#i");
		  var scrollinfo = "";
		  if(scrollinfoindex > 0){
		   scrollinfo = "#i" + parseInt(url.substring(scrollinfoindex + 2));
		   url = url.substring(0,scrollinfoindex);
		  }
		  
		  alert("iframe, url="+url);
		   
		  var paramindex = url.indexOf("?");
		  var params = "";		  
		  
		  while(paramindex >= 0){
		   var paramendindex = url.indexOf("&",paramindex + 1);
		   if(paramendindex < 0)
		    paramendindex = url.length;
		   var param = url.substring(paramindex + 1,paramendindex);
		   if(param.indexOf("t=") != 0 && param.indexOf("user=") != 0 && param.indexOf("ph=") != 0 && param.length > 0)
		    params = params + "&" + param;
		   paramindex = url.indexOf("&",paramindex + 1);
		  }
		   // update location
		  ChangeLocation("window",url.substring(0,url.lastIndexOf("/") + 1) + page + "?" + params + scrollinfo);
		 }
		  		  
		 savedobject.lastiframepagereload = true;
	 }	
	 else
		 savedobject.lastiframepagereload = false;
	 
	  // keep track of the last page visited
	  
	 var savedobject1 = GetUserData();
	 if(savedobject1 == null)		 
	  savedobject1 = new savedobjectcontructor();
		 savedobject1.lastiframepage = page;	
		 savedobject1.lastiframepagereload = savedobject.lastiframepagereload;
	 window.top.name = JSON.stringify(savedobject1);	
		
	}
	
}



 // if this window is a popup, copy the opener's global vars
 if(window.opener && !window.opener.closed)
  window.top.name = window.opener.top.name;
 else if(!parent || (parent == window)){
  // check if this page has been refreshed, and re-load it with a new auth token, because the old, and expired,
  // token would be sent again, causing a login failure even if the user was logged in
  HandleRefresh(false);
 }
 else if(parent && parent != window && location.href.indexOf("requesttoken.php") < 0){
  HandleRefresh(true);
 }
  
*/









