//First things first, set up our array that we are going to use.
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + //all caps
"abcdefghijklmnopqrstuvwxyz" + //all lowercase
"0123456789+/=";

//Heres the encode function
function encode64(inp){

   var out = ""; //This is the output
   var chr1, chr2, chr3 = ""; //These are the 3 bytes to be encoded
   var enc1, enc2, enc3, enc4 = ""; //These are the 4 encoded bytes
   var i = 0; //Position counter

   do {

      //Set up the loop here
      chr1 = inp.charCodeAt(i++); //Grab the first byte
      chr2 = inp.charCodeAt(i++); //Grab the second byte
      chr3 = inp.charCodeAt(i++); //Grab the third byte

      //Here is the actual base64 encode part.
      //There really is only one way to do it.
      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
      enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
      enc4 = 64;
      }

      //Lets spit out the 4 encoded bytes
      out = out + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);

      // OK, now clean out the variables used.
      chr1 = chr2 = chr3 = "";
      enc1 = enc2 = enc3 = enc4 = "";

   } while (i < inp.length); //And finish off the loop

   //Now return the encoded values.
   return out;
}

//Heres the decode function
function decode64(inp) {
   var out = ""; //This is the output
   var chr1, chr2, chr3 = ""; //These are the 3 decoded bytes
   var enc1, enc2, enc3, enc4 = ""; //These are the 4 bytes to be decoded
   var i = 0; //Position counter

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   var base64test = /[^A-Za-z0-9\+\/\=]/g;

   if (base64test.exec(inp)) { //Do some error checking
   alert("There were invalid base64 characters in the input text.\n" +
   "Valid base64 characters are A-Z, a-z, 0-9, ´+´, ´/´, and ´=´\n" +
   "Expect errors in decoding.");
   }
   inp = inp.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do { //Here's the decode loop.

   //Grab 4 bytes of encoded content.
   enc1 = keyStr.indexOf(inp.charAt(i++));
   enc2 = keyStr.indexOf(inp.charAt(i++));
   enc3 = keyStr.indexOf(inp.charAt(i++));
   enc4 = keyStr.indexOf(inp.charAt(i++));

   //Heres the decode part. There's really only one way to do it.
   chr1 = (enc1 << 2) | (enc2 >> 4);
   chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
   chr3 = ((enc3 & 3) << 6) | enc4;

   //Start to output decoded content
   out = out + String.fromCharCode(chr1);

   if (enc3 != 64) {
   out = out + String.fromCharCode(chr2);
   }
   if (enc4 != 64) {
   out = out + String.fromCharCode(chr3);
   }

   //now clean out the variables used
   chr1 = chr2 = chr3 = "";
   enc1 = enc2 = enc3 = enc4 = "";

   } while (i < inp.length); //finish off the loop

   //Now return the decoded values.
   return out;
}
var SERVER_URL = "manage.php";
var loaded_xml;

var global_style;
var global_id;
var global_username;
var global_password;

var params = new Array();

var dURL=unescape(window.location);
var qStr='';
var haveDesign = false;

// If the encoded string is in the URL then use it. Otherwise, get it out of the cookie
if (dURL.indexOf('?') != -1) {
   var encodedStr = dURL.substr(dURL.indexOf('?')+1,dURL.length);
   qStr = decode64(encodedStr);
   haveDesign = true;
} else if (getCookie("store_querystr")) {
   qStr = decode64(getCookie("store_querystr"));
   haveDesign = true;
}

// If we have the query string from the URL or cookie, then process it
if (haveDesign) {
   var x = qStr.indexOf('?');
   if (x != -1) {
      var pairArray = qStr.substring(x+1, qStr.length).split('&');
      for (var i=0; i<pairArray.length; i++) {
         pair = pairArray[i].split('=');
         params[pair[0]] = pair[1];
      }
   }
}


global_style       = (typeof params["style"]    != "undefined")    ? params["style"] : 0;
global_ring_design = (typeof params["ring_design"] != "undefined") ? params["ring_design"] : 0;
global_username    = (typeof params["username"] != "undefined")    ? params["username"] : 'public@gilletts.com.au';
global_password    = (typeof params["password"] != "undefined")    ? params["password"] : '';

// Support short form as well
global_style       = (typeof params["s"] != "undefined") ? params["s"] : global_style;
global_ring_design = (typeof params["r"] != "undefined") ? params["r"] : global_ring_design;
global_username    = (typeof params["u"] != "undefined") ? params["u"] : global_username;
global_password    = (typeof params["p"] != "undefined") ? params["p"] : global_password;

function autoLoadDesigns() {

	if (getCookie("store_username")) {
		document.getElementById('load_username').value = getCookie("store_username");
		loadDesigns();
	}
}

function stripIllegalXMLCharacters(stringtostrip) {
   var thestring = String(stringtostrip);
   thestring = thestring.replace(/&/g,"");
   thestring = thestring.replace(/</g,"");
   thestring = thestring.replace(/>/g,"");
   thestring = thestring.replace(/'/g,""); //'
   thestring = thestring.replace(/"/g,""); //"
   return thestring;
}

function loadDesigns() {

  global_username = document.getElementById('load_username').value;
  global_password = document.getElementById('load_password').value;

  if (validateAddress(global_username) == false) {
  	return;
  };

  req = new phpRequest();
  req.add('action','load');
  req.add('username',global_username);
  req.add('password',global_password);

  var response = req.execute();

  var message_node = response.documentElement.getElementsByTagName("message").item(0);
  var text = message_node.childNodes(0).childNodes(0).nodeValue;
  var status = message_node.childNodes(1).childNodes(0).nodeValue;

  if ((status == 1)){

		if (document.getElementById('remember_me').checked == 1) {
		   if (global_username != 'public@gilletts.com.au')  registerCookie("store_username",global_username);
		} else {
			deleteCookie("store_username","/");
		}

		loaded_xml = response;
		displayDesigns(response);

  }

  var pos = text.indexOf('password');
  if (pos > 1) {
     document.getElementById("load_password").value = "";
	  display("load_password");
  } else {
	  nodisplay("load_password");
  }

  document.getElementById("load_rings_message").innerHTML = '<span class="message_type_' + status + '">' + text + '</span>';
  display("load_rings_message");

}

function clearDesigns() {
	deleteCookie("store_username");
	display("load_rings_form");
	nodisplay("my_rings");
	nodisplay("load_password"); //Password was ingeriting the display
}

function displayDesigns(xml,nonotes) {

	var notes_td = (nonotes == 1) ? '' : '<td>Notes</td>';
	var myhtml = '<table width="100%" border="0" cellspacing="0" cellpadding="2"><tr class="my_designs_head"> <td nowrap>Ring Design Name</td>' + notes_td + '</tr>';

	var ring_designs = xml.getElementsByTagName("ring_design");
	var even = false;

   for (var i=0; i < ring_designs.length; i++) {

		var ring_design_node = ring_designs.item(i);
      var ring_design   = ring_design_node.attributes.getNamedItem("id").value;
 	   var name = ring_design_node.attributes.getNamedItem("name").value;
	   var comments = ring_design_node.attributes.getNamedItem("comments").value;
	   var style = ring_design_node.attributes.getNamedItem("style").value;
      var date_created = ring_design_node.attributes.getNamedItem("date_created").value;
      var stamp = ring_design_node.attributes.getNamedItem("stamp").value;
		var state = ring_design_node.attributes.getNamedItem("state").value;

		var myclass = even ? "my_designs_even" : "my_design_odd";

		var tooltip = state == "locked"
			? "This ring is locked, you can load it and view it, any changes to this design will be saved as a new design."
			: "Click on this ring to load it.";

		var notes_td = (nonotes == 1) ? '' : '<td class="' + myclass + '">' + comments + '</td>';

		var tooltipcode = 'onMouseover="toolTip(\'' + tooltip + '\');" onMouseout="deActivate()"';
	   myhtml +='<tr class="' + myclass + '"><td class="' + myclass + '"><span ' + tooltipcode + ' class="' + state + '_design"><a href="javascript:loadDesign(\'' + ring_design  + '\',\'' + style + '\');">' + name + '</a></span></td>' + notes_td + '</tr>';

      even =  ! even;

   }

   myhtml += '<td colspan="2" class="my_designs_footer">&nbsp; &raquo; <a href="javascript:clearDesigns();">These are not my ring designs - get my designs now</a></td></table>';
   document.getElementById("my_rings").innerHTML = myhtml;
	nodisplay("load_rings_form");
	display("my_rings");

}

// Load a single ring design given the ring_design ID and the style ID
function loadDesign(ring_design,style) {

   var debug = 0;

   if (style != global_style) {
      // We must do a redirect because the base style is different (or we are on the index page)
      var str = "?r=" + ring_design + "&s=" + style + "&u=" + global_username + "&p=" + global_password;
      registerCookie("store_querystr",encode64(str));

      // This check is needed to ensure that the cookie was set to the correct value
      if (getCookie("store_querystr") == encode64(str)) {
         window.location = "design.php";
      } else {
         window.location = "design.php?" + encode64(str);
      }

   } else {

      //Load the sent xml into the main XMLdesign xml
      debugMessage(debug,'Start',xmlDesign.xml);

      xmlDesign.loadXML(loaded_xml.xml);

      debugMessage(debug,'Before',xmlDesign.xml);

      var rootNode = xmlDesign.documentElement;
      var ringDesignsNode = rootNode.firstChild;

      //Strip out all of the ring_design nodes
      var i = 0;
      while(rootNode.childNodes[i]) {

         var id = rootNode.childNodes[i].getAttribute('id');
        // alert('ring_design ' + ring_design + ' Place ' + i + ' ID: ' + id + ' Length: ' + rootNode.childNodes.length);

         if (id != ring_design) {
            rootNode.removeChild(rootNode.childNodes[i]);
         } else {
            i++;
         }

      }

      debugMessage(debug,'During',xmlDesign.xml);

      debugMessage(debug,'After',xmlDesign.xml);

      setDesignXML();
      resetLayersAndDivs();
      redraw();
      sendChickHome();
      opentab(getFieldValue("UI_goForm","currentTab")); // We do this to set the GUI with the latest values

      // We need to reset this value because the figure in the loaded XML is wrong.
      // We need to use the max gemstones from the base style XML.
      setMaxGemstones();

      // Set this two to whatever the current ring_design ID and style ID are
      global_style       = style;
      global_ring_design = ring_design;

      setDesignFormFields(); // This sets all of the form fields to the newly loaded rings options

      // This sets the current design in a cookie
      var str = "?r=" + ring_design + "&s=" + style + "&u=" + global_username + "&p=" + global_password;
      registerCookie("store_querystr",encode64(str));

//		alert('Name: ' + fetchAttributeFromNode(ringDesignNode,'name') + ' State: ' + fetchAttributeFromNode(ringDesignNode,'state'));

   }
}

function validateAddress(incoming) {
	var emailstring = incoming;
	var ampIndex = emailstring.indexOf("@");
	var afterAmp = emailstring.substring((ampIndex + 1), emailstring.length);
		// find a dot in the portion of the string after the ampersand only
	var dotIndex = afterAmp.indexOf(".");
		// determine dot position in entire string (not just after amp portion)
	dotIndex = dotIndex + ampIndex + 1;
		// afterAmp will be portion of string from ampersand to dot
	afterAmp = emailstring.substring((ampIndex + 1), dotIndex);
		// afterDot will be portion of string from dot to end of string
	var afterDot = emailstring.substring((dotIndex + 1), emailstring.length);
	var beforeAmp = emailstring.substring(0,(ampIndex));
		//old regex did not allow subdomains and dots in names
		//var email_regex = /^[\w\d\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~]+(\.[\w\d\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~])*\@(((\w+[\w\d\-]*[\w\d]\.)+(\w+[\w\d\-]*[\w\d]))|((\d{1,3}\.){3}\d{1,3}))$/;
	var email_regex = /^\w(?:\w|-|\.(?!\.|@))*@\w(?:\w|-|\.(?!\.))*\.\w{2,3}/
		// index of -1 means "not found"
	if ((emailstring.indexOf("@") != "-1") &&
		(emailstring.length > 5) &&
		(afterAmp.length > 0) &&
		(beforeAmp.length > 1) &&
		(afterDot.length > 1) &&
		(email_regex.test(emailstring)) ) {
		  return true;
	} else {
			alert("Please check your email address. It does not appear to be valid.");
			return false;
	}
}

//Start phpRequest Object
function phpRequest() {
  //Set some default variables
  this.parms = new Array();
  this.parmsIndex = 0;

  //Set the server url
  this.server = SERVER_URL;

  //Add two methods
  this.execute = phpRequestExecute;
  this.add = phpRequestAdd;
}

function phpRequestAdd(name,value) {
  //Add a new pair object to the params
  value = encodeURIComponent(value);
  this.parms[this.parmsIndex] = new Pair(name,value);
  this.parmsIndex++;
}

function phpRequestExecute() {
  //Set the server to a local variable
  var targetURL = this.server;


   var httpRequest;
   if (typeof ActiveXObject != 'undefined') {
     httpRequest = new ActiveXObject('Microsoft.XMLHTTP');
   }
   else if (typeof XMLHttpRequest != 'undefined') {
     httpRequest = new XMLHttpRequest();
   } else {
     alert('Did not create a connection object');
     return 0;
   }

  //Make the connection and send our data
  try {

	 var queryString = "";
	 for (var i in this.parms) {
	 	if (i == 0) {
			queryString += this.parms[i].name + "=" + this.parms[i].value;
		} else {
			queryString += "&" + this.parms[i].name + "=" + this.parms[i].value;
		}
	 }
	 //debugMessage(1,"phpRequestExecute",queryString);
    //Two options here, only uncomment one of these
    httpRequest.open("POST", targetURL, false, null, null);
	 httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	 httpRequest.setRequestHeader("Content-Length", queryString.length);
    httpRequest.send(queryString);
  }catch (e){
    alert('An error has occured calling the external site: '+e);
    return false;
  }

  //Make sure we received a valid response
  switch(httpRequest.readyState) {
    case 1,2,3:
      alert('Bad Ready State: '+httpRequest.status);
      return false;
    break;
    case 4:
      if(httpRequest.status !=200) {
        alert('The server respond with a bad status code: '+httpRequest.status);
        return false;
      } else {
        var response = httpRequest.responseXML;
      }
    break;
  }
  return response;
}

var lastLoaded = -1;
var allImages = new Array();

function loadImages() {

   if (lastLoaded == imagesToLoad.length) {
      return;
   }

   if (lastLoaded == -1) {
      lastLoaded = 0;
      allImages[lastLoaded] = new Image();
      allImages[lastLoaded].src = image_server+"images/" + imagesToLoad[lastLoaded];
   }

	 if (lastLoaded == imagesToLoad.length) return;

   if (allImages[lastLoaded].complete) {
      lastLoaded = lastLoaded + 1;
	   if (lastLoaded == imagesToLoad.length) return;
      allImages[lastLoaded] = new Image();
      allImages[lastLoaded].src = image_server+"images/" + imagesToLoad[lastLoaded];
   }

   if (allImages[lastLoaded].complete) {
      lastLoaded = lastLoaded + 1;
	   if (lastLoaded == imagesToLoad.length) return;
      allImages[lastLoaded] = new Image();
      allImages[lastLoaded].src = image_server+"images/" + imagesToLoad[lastLoaded];
   }

   setTimeout("loadImages()",100);

}


//Utility Pair class
function Pair(name,value) {
  this.name = name;
  this.value = value;
}
//Only show the div when we need to
var initialize = 0;
function toolTip(message) {
   replaceContent('ToolTip',message);
   Activate();
}
function Activate(){
   initialize=1;
}
function deActivate(){
   initialize=0;
}
//Over here function
function overhere(e){
   var padding_left = 10;
   var padding_top = 10;
   var we = window.event;
   var db = document.body;


   // calculate x co-ordinates
   var x_coord = getNumber(we.pageX || we.clientX || 0) + getNumber(db.scrollLeft);
   var x_scr = getNumber(window.pageXOffset || db.scrollLeft || 0);
   if (x_coord < x_scr) x_coord = x_scr;

   // calculate y co-ordinates
   var y_coord = getNumber(we.pageY || we.clientY || 0) + getNumber(db.scrollTop);

   if(initialize){
     shiftTo('ToolTip',x_coord + padding_top, y_coord + padding_left);
     show('ToolTip');
   } else {
     shiftTo('ToolTip',0,0);
     hide('ToolTip');
   }
}

// convert a string to lowercase with 1st letter capitalised
function ucFirst(s)
{
	var c = s.charAt(0);

	if (parseInt(s.length)==1){
		return c.toUpperCase();
	}
	else
	{
		return c.toUpperCase() + s.slice(1).toLowerCase();
	}
}


//returns a zero instead of NaN
function getNumber(value) {

  var result;
  return isNaN(result = parseInt(value))? 0 : result;

}
