var encKey = "";
var aesReady = false;
var isSecurePage = false;

// these guys seem to want to be global

(function(){

	// the minimum version of jQuery we want
	var v = "1.4.1";

	// check prior inclusion and version
	if (window.jQuery === undefined || window.jQuery.fn.jquery < v) {
		var done = false;
		var script = document.createElement("script");
		
	
		script.src = location.protocol + "//ajax.googleapis.com/ajax/libs/jquery/" + v + "/jquery.min.js";
		
		
		if(location.protocol === "https:")
		{
			isSecurePage = true;
		}
	
		
		// alert(isSecurePage);
		
		script.onload = script.onreadystatechange = function(){
			if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
				done = true;
				initMyBookmarklet();
			}
		};
		document.getElementsByTagName("head")[0].appendChild(script);
	} else {
		initMyBookmarklet();
	}
	
	var qrUrl1;
	var qrUrl2;
	
	if(isSecurePage)
	{
			qrUrl1 = "https://secure.bluehost.com/~awakenin/pluribus1/js/qrcode.js";
			qrUrl2 = "https://secure.bluehost.com/~awakenin/pluribus1/js/jquery.qrcode.js";
	}
	else
	{
			qrUrl1 = "http://www.pluribus1.com/js/qrcode.js"
			qrUrl2 = "http://www.pluribus1.com/js/jquery.qrcode.js";
	}
	
	function initMyBookmarklet() {
		(window.myBookmarklet = function() {
		
	$.getScript(qrUrl1,
			function(data) {$.getScript(qrUrl2,
							function(data,a,b){
									// alert("loaded jquery.min.js!");
									
									// new stuff here
									var modalUrl;
									var jsCryptUrl;
									
									if(isSecurePage)
									{
						modalUrl 	= 	"https://secure.bluehost.com/~awakenin/pluribus1/js/jquery.simplemodal.1.4.3.min.js"
						jsCryptUrl 	= 	"https://secure.bluehost.com/~awakenin/pluribus1/js/javascrypt.min.js";
									}
									else
									{
										
										modalUrl = 		"http://www.pluribus1.com/js/jquery.simplemodal.1.4.3.min.js";
										jsCryptUrl = 	"http://www.pluribus1.com/js/javascrypt.min.js";
									}
										
									
									
									
									
									$.getScript(modalUrl,
							function(data,a,b){
									$.getScript(jsCryptUrl,
												function(data){
									doMyBookmarkletInit();  // nesting deepest!
												})
									
									})
									
									
									// end new stuff
									
									
									
									
									})}  // close grcode getscript function body, function param list, qrcode function body
				);
	

		})();
	}

})();

function submitCredentials(credInfo)
{	
	
	

	if(credInfo.credentialType != 'UNPW') alert("Unsupported Credential Type!");
	
	var credentialCipherStringAsBase64 = credInfo.credentialString;
	
	var ciphertext = CryptoJS.enc.Base64.parse(credentialCipherStringAsBase64);
	
	var key = CryptoJS.enc.Hex.parse(encKey);
	
	var iv = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
		
		
	var myParams = CryptoJS.lib.CipherParams.create({
                ciphertext: ciphertext, 
                iv: iv,
                key: key
            });
	


var  decrypted = CryptoJS.AES.decrypt(myParams,key,{iv: iv});

var credentialsAsJSON = decrypted.toString(CryptoJS.enc.Utf8);

	
	try
	{
	var credentials = jQuery.parseJSON(credentialsAsJSON);
	}
	catch(e)
	{
		alert("some kind of error: " + e);
	}
		

	
			// alert("got here username = " + credentials.username + " password = " + credentials.password);
			
	if((credInfo.pwdDomIdKeyType == "name") || (credInfo.pwdDomIdKeyType == "id"))
	{

	
		var usernameNode = $('input[' + credInfo.unameDomIdKeyType + '="' + credInfo.unameDomIdKey + '"]');
	
		// jQuery(usernameNode).focus();
		$(usernameNode).val(credentials.username);
		
		var usernameValue = $(usernameNode).attr("value");
		// alert('key is: ' + credInfo.unameDomIdKey + ' username is: ' + usernameValue);
			
	}
	// alert("type: " + credInfo.pwdDomIdKeyType);
	if((credInfo.pwdDomIdKeyType == "name") || (credInfo.pwdDomIdKeyType == "id"))
	{	
		var passwordNode = $('input[' + credInfo.pwdDomIdKeyType + '="' + credInfo.pwdDomIdKey + '"]');
		// jQuery(passwordNode).focus();
		$(passwordNode).val(credentials.password);
		
		var passwordValue = $(passwordNode).attr("value");
		// alert('key is: ' + credInfo.pwdDomIdKey + 'password is: ' + passwordValue);
	}


// alert("Form action: " + credInfo.formAction);

document.cookie = 'x-user-auth-helper=pluribus1.com-' + 'ZKK-ASDF-ASDF-1234-1234';

 var myForm = $('form[action="' + credInfo.formAction + '"]');
 
 // var formMethod = $(myForm).attr("method");
 // alert("Form Method " + formMethod);
 
 // alert('authenticating with ' + credInfo.uname + ',' + credInfo.pwd);
myForm.submit();

}

function flagPw(){
var r = Math.round(Math.random() * 65000);
return r.toString("16");
}


function getEncKey()
{
		var k = Generate_key();
		// alert("generated key: " + k);
		return k;
// return "testPassword";
}

function doMyBookmarkletInit () {

encKey = getEncKey();  // globally defined at top

// creat div for QRCode

// creat div for QRCode

var myQRNode = $("body").prepend('' + 
								'<div id="qrDisplayModal" style="border-style: solid; border-width: 5px; height: 380px; width: 600px; background-color: #FFFFFF"; position: fixed; top: 12em; margin-left: auto; margin-right: auto">' +
								'<div id="pleaseWait" style="width: 256px; height: 256; position: absolute; top: 4em; display: block; margin-left: 4em;   z-index: 768">' +
								'<span>Generating QR code, please wait ...</span>' +
								'</div>' +
								'<div id="pb1QRcode" style="position: absolute; background-color: white; top: 4em;  display: block; margin-left: 4em;  z-index: 1024">' +
								'</div></div>' +			
								'');


var pb1SessionId;
jQuery('#qrDisplayModal').modal();

// this (sequence) wants to be returned in the js load I think

var sequenceUrl;
if(isSecurePage)
{
	sequenceUrl = "https://secure.bluehost.com/~awakenin/pluribus1/sequence.php?fd=" + location.href + "&getSequence=?";
}
else
{
	sequenceUrl = "http://www.pluribus1.com/sequence.php?fd=" + location.href + "&getSequence=?";
}

$.getJSON(sequenceUrl,
function(data) {
		
	pb1SessionId = data.extSequence;
	// var pb1KeyFlagPassword = flagPw();
	
	/*  original url based scheme
	var pb1Url = 'http://www.pluribus1.com/i.php?s=' + pb1SessionId + "&k=" + 
		encKey + "&u=" + window.location.hostname + 
		"&p=" + pb1KeyFlagPassword;
*/
// not sure if pb1KeyFlagPassword stays and probably should add full path here instead
var scheme = 0;
if(isSecurePage) {scheme = 1};


var pb1Url;
pb1Url = 'pb1:';
pb1Url = pb1Url + scheme + ':';
pb1Url = pb1Url + encKey + ':' + pb1SessionId + ':' + window.location.hostname + ':' + window.location.pathname;

		

	
	jQuery('#pb1QRcode').qrcode({
		render	: "canvas",
		text	: pb1Url
		});
	
	
	jQuery("#pb1QRcode").after('<div id="scanMe" style="text-align: center; position: absolute; margin-left: 330px; margin-right: 100; top: 120px">' +
				'<img src="http://www.pluribus1.com/phonyLogo.png" />' +
								  '<br />To authenticate to <br /><span style="font-weight: bold" id="domainString"></span>,</br>scan QR code with the<br /> pluribus mobile app' +
								  '<div/>');
	jQuery("#domainString").html(window.location.hostname);

	jQuery.ajaxSetup(
	{
		timeout: "360000"
	});
	
// time to asynchronously load the decrypt js

aesReady = false;
if(isSecurePage)
{
	aesUrl = "https://secure.bluehost.com/~awakenin/pluribus1/js/aes.js";
}
else
{
	aesUrl = "http://www.pluribus1.com/js/aes.js";
}
jQuery.getScript(aesUrl,function(data,a,b){$aesReady = true;})

if(isSecurePage)
{
	var getSiteAuthDataUrl = "https://secure.bluehost.com/~awakenin/pluribus1/getSiteAuthData.php";
}
else
{
	var getSiteAuthDataUrl = "http://www.pluribus1.com/getSiteAuthData.php";
}

	jQuery.getJSON(getSiteAuthDataUrl + "?s=" + pb1SessionId  + "&d=" + window.location.hostname + "&cb=?", function (data) {
	
	jQuery('#pb1QRcode').hide();
	//jQuery().modal.close();
	
	// alert(data);
	submitCredentials(data)});

});

}

