lasturl = "";
sessionid = "";
email = "";
pagecontent = "";
prop = "";

function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
}
function showLogin(o){
  document.getElementById("loginline").innerHTML = '<span id=loginadvice>Property owner login</span>: email <input class=pale type=text id=email name=email> password <input class=pale onchange="submitLogin()" type=password name=passwd id=passwd> <input  type=submit value="OK" onfocus="submitLogin();" id=loginbutton>';
  document.getElementById("email").focus()
  o.onclick = ""  
}

function submitLogin(){
  //document.getElementById("loginbutton").onfocus = "";
  if(document.getElementById("loginline").style.visibility == 'hidden') return
  
  email = document.getElementById("email").value;
  var passwd = document.getElementById("passwd").value;
  if (email != '' && passwd != '') {

    AsynchUpdate("cgi-bin/g/gallery.py","mode=ologin"+"&email="+escape(email)+"&sessionid=''&passwd="+escape(passwd))
    document.getElementById("loginline").style.visibility="hidden"
  }
}

function getHTTPObject() { 
  if (typeof XMLHttpRequest != 'undefined') { 
    return new XMLHttpRequest(); 
  } 
  try { 
    return new ActiveXObject("Msxml2.XMLHTTP"); 
  } catch (e) { 
    try {
      return new ActiveXObject("Microsoft.XMLHTTP"); 
    } catch (e) {} 
  } return false; 
}
function logout(){
  location.reload()
}

function AsynchUpdate(myurl,param) {

  http = getHTTPObject();
  http.open("GET", myurl + "?" + param, true);
  http.onreadystatechange = useHttpResponse;
  lastparam = param
  lasturl = myurl
  http.send(null);
}
  
function ologin(words){
  // words[5] contains "ok", "failed" or "newuser" (temporary)
  var result = words[5];
  if (result == "ok"){
    // display OWNERVIEW page by replacing pagecontent
	ownerform(words);
  
  }
  if (result == "failed"){
  document.getElementById("loginline").style.visibility="visible"
  document.getElementById("loginadvice").innerHTML = "Login failed. Please re-try"
  document.getElementById("passwd").value = ""
  document.getElementById("email").focus()
    
  }
}
function useHttpResponse() {
  if (http.readyState == 4) {
    var textout = http.responseText;
    //var badnews = textout.indexOf("500 Internal") // on getting a 500 error, re-try the request, just once.
        // that solves (and hides) a nasty little problem of script appearing to complete OK but server returning a 500 error!
        // It also risks doubling a transaction!!!!!!
    //if (badnews > -1 && lasturl != ""){
    //   AsynchUpdate(lasturl, lastparam)
    //   lasturl = ""
    //   return
    //}
    if (textout && textout != "") {
      //alert("response: " + textout)
	  
      words = textout.split("~!")
	  sessionid = words[1];
	  if (words[3] != "") email = words[3];
      if (words[0] == "prompt"){

        prompt(words)
            
      } else if (words[0] == "ologin"){
        
        ologin(words)

      } else if (words[0] == "ulogin"){
        ulogin(words)

      } else if (words[0] == "newpropfailed"){
         newpropfailed(words)
      
      } else if (words[0] == "gotouploader"){

         gotouploader(words)
      
      } else if (words[0] == "loginfailed"){
         LoginFailed(words)
      
      } else if (words[0] == "newreg"){
         newreg(words)
      
      } else if (words[0] == "debug"){
         debug(words)
      
      } else if (words[0] == "GuestAddedOK"){
         guestaddedOK()

      } else if (words[0] == "newowner"){
         newowner()

      } else if (words[0] == "none"){
         // do nothing
      
      }  else alert("No valid mode word " +http.responseText + http.responseText.length);

    }
  }
}

function debug(words){
   alert(words);
}
function hidprofile(){
  var o = document.getElementById('profile');
  var b = document.getElementById('hidprofile');
  
  var v = o.style.display;
  
  if (v != 'inline' ) {
    o.style.display = 'inline'
	b.style.display = 'none';
  } else {
    o.style.display = 'none'
  }
}
function hidnewgal(){
  var o = document.getElementById('newgal');
  var b = document.getElementById('hidnewgal');
  
  var v = o.style.display;
  
  if (v != 'inline' ) {
    o.style.display = 'inline'
	b.style.display = 'none';
  } else {
    o.style.display = 'none'
  }
}

function delgallery(o){

    var propshort = o.id;
    prop = propshort

    yesno = confirm("Please confirm that you want to destroy the gallery: " + prop);
    if (yesno == false)	return
	
	window.location = "/cgi-bin/g/gallery.py?mode=delgallery&prop="+prop+"&session_id="+sessionid 


}	

function addpictures(o) {
    var prop = o.id;
    //alert("Debug: addpictures prop= " + prop + " email = " + email + " nick = " + "owner")
	window.location = "/cgi-bin/g/gallerylogin.py?prop="+prop+"&email=" + email + "&nick=owner"

}

function editgallery(o){

    var propshort = o.id;
    prop = propshort
    // save current content of pagecontent so that it can be reinstated. Then, within that
	// create an iframe and request a page for the iframe content.
	// or just load a new page?
	
	pagecontent = document.getElementById("pagecontent").innerHTML
	//pagecontent = document.body.innerHTML;

	document.getElementById("pagecontent").innerHTML = "<iframe id=editframe name=myframe width=100% height=600 src=cgi-bin/g/gallery.py?mode=edit&psn="+propshort+"&email=" + email+"&session_id="+sessionid + "></iframe>"


}	

function delgroup(o){
  var id = o.id
  AsynchUpdate("cgi-bin/g/gallery.py","mode=delgroup&prop="+escape(prop)+"&id="+escape(id)+"&sessionid="+escape(sessionid) )
  tr = document.getElementById("editframe").contentDocument.getElementById("r" + id)
  tr.style.visibility = "hidden"  
  tr = document.getElementById("editframe").contentDocument.getElementById("rh" + id)
  tr.style.visibility = "hidden"  
}

function delimage(o){
  var id = o.id
  AsynchUpdate("cgi-bin/g/gallery.py","mode=delimage&prop="+escape(prop)+"&id="+escape(id)+"&sessionid="+escape(sessionid) )
  // might well not work as these elements are in the iframe not in document.
  span = document.getElementById("editframe").contentDocument.getElementById("p" + id)
  span.innerHTML = ""
  
}

function descchanged(o){
  var id = o.id
  //alert("in descchanged " + prop)
  AsynchUpdate("/cgi-bin/g/gallery.py","mode=descchanged&prop="+escape(prop)+"&id="+escape(id)+"&sessionid="+escape(sessionid)+"&newdesc="+escape(encode_utf8(o.value)) )

}

function capchanged(o){
  var id = o.id

  AsynchUpdate("cgi-bin/g/gallery.py","mode=capchanged&prop="+escape(prop)+"&id="+escape(id)+"&sessionid="+escape(sessionid)+"&newcap="+escape(encode_utf8(o.value)) )

}

function parseTag(tag){
  // not really needed but keep in case on-screen update needed.
  // check/dispose of leading g
  result = new array
  
  if (tag[0] != "g"){
     alert("parseTag error 1")
  }
  tag = tag.substring(1)
  var parts = tag.split('p')
  
}
function myuploaders(o){

    var propshort = o.id;

    // save current content of pagecontent so that it can be reinstated. Then, within that
	// create an iframe and request a page for the iframe content.
	
	pagecontent = document.getElementById("pagecontent").innerHTML
	document.getElementById("pagecontent").innerHTML = "<iframe name=myframe width=100% height=600 src=cgi-bin/g/gallery.py?mode=uploaders&prop="+escape(propshort)+"&session_id="+sessionid+"></iframe>"
	
}	

function goback(){
	document.getElementById("pagecontent").innerHTML = pagecontent
	
}

function editgoback(){ // like goback, except the gallery has to be re-built after edits
    //alert(prop)
	document.getElementById("pagecontent").innerHTML = pagecontent
    AsynchUpdate("cgi-bin/g/gallery.py","mode=rebuild&prop="+escape(prop)+"&sessionid="+escape(sessionid) )
	
}

// there is no psnchanged function because short name can't be changed as other things reference it.
function pnchanged(o){
   origpsn = o.name
   pn = o.value
   AsynchUpdate("cgi-bin/g/gallery.py","mode=pnchanged&origpsn="+escape(origpsn)+"&newpn="+escape(pn)+"&sessionid="+escape(sessionid) )
   alert("Property name change saved")
}

function purlchanged(o){
   origpsn = o.name
   purl = o.value
   AsynchUpdate("cgi-bin/g/gallery.py","mode=purlchanged&origpsn="+escape(origpsn)+"&newpurl="+escape(purl)+"&sessionid="+escape(sessionid) )

   alert("Property URL change saved")

}

function plocchanged(o){
   origpsn = o.name
   ploc = o.value
   AsynchUpdate("cgi-bin/g/gallery.py","mode=plocchanged&origpsn="+escape(origpsn)+"&newploc="+escape(ploc)+"&sessionid="+escape(sessionid) )

   alert("Property location change saved")

}


function addguest(){
  var name=value("newgname")
  var email = value("newgemail")
  var nick = value("newgnick")
  
  var prop = value("prop")
  
  AsynchUpdate("cgi-bin/g/gallery.py","mode=adduploader&email="+escape(encode_utf8(email))+"&sessionid="+sessionid+"&prop="+escape(prop)+"&name="+escape(encode_utf8(name))+"&nick="+escape(nick) )
  
}
function frameref(o){
  return window.frames["myframe"].document.getElementById(o);
}
function guestaddedOK(){
  

  // make the added line visible on screen

  var gl = frameref("guestlist").innerHTML
  
  gl += "<div id=" + frameref('newgemail').value + "><table><tr><td width=230>"+ frameref("newgname").value +"</td><td width=350>"+ frameref('newgemail').value + "</td><td width=200>" + frameref('newgnick').value + "</td><td><button onclick=top.delguest('" +  frameref('newgemail').value + "')>Remove</button></td></tr></table></div>"

  frameref("guestlist").innerHTML = gl
  
  frameref("newgname").value = ""
  frameref("newgemail").value = ""
  frameref("newgnick").value = ""

  frameref("newgname").focus()  
  
}

function delguest(guestmail){

  var prop = value("prop")

  AsynchUpdate("cgi-bin/g/gallery.py","mode=delguest&guestmail="+escape(guestmail)+"&sessionid="+sessionid+"&prop="+prop)
  //alert( "about to hide ID:" + guestmail)
  frameref(guestmail).style.display = 'none';
  frameref(guestmail).innerHTML = ""

}


function newowner(){

  var reguser = value("newuser");
  var regemail = value("newemail")
  var regpass = value("newpassword")
  var propname = value("npropname");
  var propshortname = value("npropshortname");
  var propurl = value("npropurl");
  var proploc = value("nproploc");

  
  AsynchUpdate("cgi-bin/g/gallery.py","mode=newowner&newuser="+escape(reguser)+"&newemail="+escape(regemail)+"&sessionid="+sessionid+"&newpassword="+escape(regpass)+"&propname="+escape(propname)+"&propshortname="+escape(propshortname)+"&propurl="+escape(propurl)+"&proploc="+escape(proploc) )
  alert("New owner added.")
  empty("newuser")
  empty("newemail")
  empty("newpassword")
  empty("npropname")
  empty("npropshortname")
  empty("npropurl")
  empty("nproploc")
  
}


function ownerform(words){
  // words contains "ologin", sessionID, username, email, owner_id, resultcode=ok, payload
  var sal = "Welcome back "
  if (words[3] == "ben@learntotype.com") sal = "System Administration page for "
  newhtml = '<br><h2>' + sal + words[2] + '</h2><br><br><button id=hidprofile onclick=hidprofile();>Edit my profile</button><span id=profile class=hidspan>Here, you can change your email address, password or name: <br><div id=enclosure><table>  <tr><td>Your name</td><td><input id=reguser name=reguser value="' + words[2] + '"></td><td></td></tr>   <tr><td>Your email address</td><td><input id=regemail name=regemail value="' + words[3]+ '"></td><td></td></tr>  <tr><td>Password</td><td><input type=password id=regpassword name=regpassword><input type=hidden id=owner value="'+ words[4] +'"<input type=hidden id=sessionid value= "'+sessionid+'" ></td><td><button id=owneredit onclick="owneredit()">Save</button></td></tr>  </table></div><hr></span><br><br>Manage my existing galleries: '+ words[6]+'<hr><button id=hidnewgal onclick=hidnewgal();>Add a new gallery</button><span id=newgal class=hidspan><br><div id=enclosure><table><tr><td>Property short name</td><td><input id=newpropshortname name=propshortname size=30></td><td class=info>The short name becomes <br>part of your galleries URL. <br>You cannot change it later.</td></tr><tr><td>Property name</td><td><input size=40 id=newpropname name=propname></td><td class=info>This is the name of the property that <br>will be shown in several places.</td></tr><tr><td>Property web address</td><td><input size=40 id=newpropurl name=propurl></td></tr><tr><td>Property location</td><td><input size=40 id=newproploc name=proploc></td><td><button id=newprop onclick="newprop()"><div id=reason></div>Add</button></td></tr></table></div></span><button id=logout onclick="logout()">Log Out</button>'
  // reguser , propname, propurl, regemail, regpassword
  
  document.getElementById("pagecontent").innerHTML = newhtml;
}

function owneredit(){
   // owner has changed name, email or password
   var name = value('reguser');
   var email = value('regemail');
   var password = value('regpassword');
   AsynchUpdate("cgi-bin/g/gallery.py","mode=owneredit&regemail="+escape(email)+"&sessionid="+escape(sessionid)+"&regname="+escape(name)+"&regpassword="+escape(password) )
   alert("Information saved")
   hidprofile()
   
}

function newprop(){
  // self-service addition of new property by existing owner.

   var psn = value('newpropshortname')
   var pn = value('newpropname')
   var purl = value('newpropurl')
   var ploc = value('newproploc')
   var moan = "";
   if (psn.length > 15) moan += "Sorry - Property short name cannot be more than 15 characters.\n";
   if (pn.length > 25) moan += "Sorry - Property name cannot be more than 25 characters.\n";
   if (ploc.length > 35) moan += "Sorry - Location cannot be more than 35 characters.\n";

   if (moan != ""){
      alert(moan + "Please abbreviate and re-try.")
      return
   }
   if (psn.length < 2) moan += "Please enter a Short Name for your property.\n";
   if (pn.length < 2) moan += "Please enter a Name for your property (e.g. The Oast House).\n";
   if (ploc.length < 2) moan += "Please enter a Location (e.g. Kent, UK) for your property.\n";
   if (moan != ""){
      alert(moan + "Please complete fields and re-try.")
      return
   }
   
   
   AsynchUpdate("cgi-bin/g/gallery.py","mode=newprop&email="+escape(email)+"&sessionid="+escape(sessionid)+"&propshortname="+escape(psn)+"&propname="+escape(pn)+"&propurl="+escape(purl)+"&proploc="+escape(ploc) )
}
function requestform(){
  
  var text = '<div class=whiteline><center>Your previous guests take the pictures - Your future guests view them</center></div><div id=about style="margin-left: 150px ; margin-top: 0px;"><center>First, a few words about Holisnaps.com</center><br><p class=contact>Holisnaps is free to use and always will be. The site does carry advertising which may appear on any page. Having a gallery here increases the visibility of your own web pages as we carry a link back to your site.<br><br>Holisnaps.com and DiscEarning Ltd provide this service for hosting photos taken at and around privately owned and run holiday accommodation. The photos remain the property of the uploader.<br><br>The criteria for acceptable properties are that they must be uniquely identifyable, must be advertised for rent somewhere on the web and must be owned or operated by a person who owns fewer than 10 holiday properties.<br><br>Once you have submitted the form, your request is reviewed by a human and you should get an email response, normally within 24 hours. The email will contain your login information and full instructions for maintaining your properties gallery.</p><h2>New property owner registration</h2><table class=info><tr><th></th><th></th></tr>  <tr><td class=info>Your name</td><td><input id=reguser name=reguser></td><td class=note></td></tr>  <tr><td class=info>Name of your property</td><td><input size=40 id=propname name=propname></td><td class=note>This is the name of the property<br>as it will show on the gallery page.</td></tr>  <tr><td class=info>URL of your main page</td><td><input size=50 id=propurl name=propurl></td><td class=note>Enter the http:// address of your own page<br>or reference to your property on a listing site.</td></tr>  <tr><td class=info>Location of your property</td><td><input size=50 id=regloc name=regloc></td><td class=note>(e.g. Cyprus - west coast)</td></tr>  <tr><td class=info>Your email address</td><td><input size=50 id=regemail name=regemail></td><td class=note></td></tr>  <tr><td class=info>Choose a password</td><td><input type=password id=regpassword name=regpassword></td><td class=note>Do not use the same password that <br>you use for high security web sites.</td></tr><tr><td class=info> '
  //text  += '<img src=cat.gif height=30px width=38px>This animal is a </td><td><input type=text id=identify size=20>'
  text += '<button id=newreg onclick="newreg()">Send</button></td></tr></table></div>'
  // reguser , propname, regloc, propurl, regemail, regpassword
  document.getElementById("pagecontent").innerHTML = text
  document.getElementById("reguser").focus()
  
}

function newpropfailed(words){
  document.getElementById("").innerHTML = words[6];
}

function gotouploader(words){
    // simulate the request that the form in uploader.html would make if the owner were to 
	// log in manually
	//alert("gotouploader: " + words[5] + " : " + words[3])
	
	window.location = "/cgi-bin/g/gallerylogin.py?prop="+words[5]+"&email=" + words[3] + "&nick="
}


function newreg(){
  propname = value("propname")
  reguser = value("reguser")
  propurl= value("propurl")
  regemail = value("regemail")
  regpassword = value("regpassword")
  regloc = value("regloc")
  //identify = value("identify")
  
  //validation
  var invalid = "";
  if (propname == "") invalid = "Property Name";
  if (reguser == "") invalid = "Your Name";
  if (propurl == "") invalid = "URL";
  if (regemail.indexOf("@")<0 ) invalid = "Email address";
  if (regpassword == "") invalid = "Password";
  if (regloc == "") invalid = "Location";
  //if (identify.toLowerCase() != "cat") invalid = "ROBOT-shield";
  
  if (invalid != "") {
     alert("Sorry, the form is incomplete or incorrect. Please correct the field: " + invalid)
     return
  }
  
  AsynchUpdate("/cgi-bin/g/gallery.py","mode=register&reguser="+escape(reguser)+"&propname="+escape(propname)+"&propurl="+escape(propurl)+"&regloc="+escape(regloc)+"&regemail="+escape(regemail)+"&regpassword="+escape(regpassword))
  
  location.reload()
  alert("Thanks - we will get back to you shortly. ")

}
function empty(s){
    document.getElementById(s).value = ""
  

}
function value(s){
  if (document.getElementById(s) == null ){
       return window.frames["myframe"].document.getElementById(s).value
  } else {
    return document.getElementById(s).value
  }

}

