/**
 * Operation Description
 */
var operation = {
	/**
	 * Content might be empty, can contain text or an URL
	 */
	content: "Beispiel Text",
	
	/**
	 * Connector: all PDF-AS Connector values
	 */
	connector: "local", 
	
	/**
	 * DIV id where to place to UI
	 */
	uiId: "",
	
	/**
	 * Locale to use
	 */
	locale: "DE"
};

var pdfAsOrigin = "##REPLACE##DOMAIN##";

var pdfAsUrl = "##REPLACE##DOMAIN####REPLACE##CONTEXT##/Start";

var pdfAsVersionUrl = "##REPLACE##DOMAIN####REPLACE##CONTEXT##/version";


var pdfAs = {};

/**
 * create signed PDF Document containing
 * @param content The text content of the PDF Document
 * @returns
 */
pdfAs.signText = function(content, error, success) {
	this.createAsyncSignature(content.content, content.connector, content.uiId, pdfAsUrl, content.qrdata, content.locale, content.sig_pos_x, content.sig_pos_y, content.sig_pos_p, content.sig_pos_w, content.sig_pos_f, "TEXT", success, error);
};

pdfAs.signPdf = function(content, error, success) {
    this.createAsyncSignature(content.content, content.connector, content.uiId, pdfAsUrl, content.qrdata, content.locale, content.sig_pos_x, content.sig_pos_y, content.sig_pos_p, content.sig_pos_w, content.sig_pos_f, "PDF", success, error);
};

pdfAs.signPdfBase64 = function(content, error, success) {
    this.createAsyncSignature(content.content, content.connector, content.uiId, pdfAsUrl, content.qrdata, content.locale, content.sig_pos_x, content.sig_pos_y, content.sig_pos_p, content.sig_pos_w, content.sig_pos_f, "B64", success, error);
};

pdfAs.getVersion = function(cb, err) {
	var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if(xmlhttp.status == 200){
               var obj = JSON.parse(xmlhttp.responseText);
               cb(obj);
           }
           else if(xmlhttp.status == 400) {
        	   err('There was an error 400')
           }
           else {
        	   err('something else other than 200 was returned')
           }
        }
    }

    xmlhttp.open("GET", pdfAsVersionUrl, true);
    xmlhttp.send();
}


var postman = new NoJQueryPostMessageMixin('postMessage', 'receiveMessage');

var guid = (function() {
	  function s4() {
	    return Math.floor((1 + Math.random()) * 0x10000)
	               .toString(16)
	               .substring(1);
	  }
	  return function() {
	    return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
	           s4() + '-' + s4() + s4() + s4();
	  };
})();

function encodeQueryData(data)
{
   var ret = [];
   for (var d in data) {
	   if (typeof data[d] != "undefined") {
		   ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
	   }
   }
   return ret.join("&");
};

function addDataToForm(data, form) {
	var ret = [];
	   for (var d in data) {
		   if (typeof data[d] != "undefined") {
			   	var input = document.createElement('input');
			   	input.type = 'hidden';
			   	input.name = d;
			   	input.value = data[d];
			   	form.appendChild(input);
		   }
	   }
}


pdfAs.cbMap = {};

pdfAs.autoResize = function(eventId, height, width){
    var newheight = height;
    var newwidth = width;

    console.log("Resizing iframe " + width + "x" + height);

    newheight = newheight + 20;

    document.getElementById(eventId).height= (newheight) + "px";
    document.getElementById(eventId).width= (newwidth) + "px";
    eventId = eventId.substring(0, eventId.length - 7);
    var custDiv = eventId + "_div";
    var element = document.getElementById(custDiv);
    if ((typeof(element) !== 'undefined') && (element !== null)) {
    	element.style.margin = '-' + element.scrollHeight / 2 + 'px 0 0 -' + element.scrollWidth / 2 + 'px';
    }
};

pdfAs.createAsyncSignature = function(pdfUrl, connector, divID, pdfAsURL, qrcode, locale, sigPosX, sigPosY, sigPosP, sigPosW, sigPosF, type, success, error) {
	// generate EventID
	var eventId = guid();
	
	var parameters = {
			PDFURL: pdfUrl,
			CONNECTOR: connector,
			EVENTID: eventId,
			TYPE: type,
			TARGETURL: document.URL,
			NEW: "1",
			QRCODE: qrcode,
			LOCALE: locale,
			SIG_POS_X: sigPosX,
			SIG_POS_Y: sigPosY,
			SIG_POS_P: sigPosP,
			SIG_POS_W: sigPosW,
			SIG_POS_F: sigPosF
	};
	
	/*var querystring = encodeQueryData(parameters);
	
	console.log("Querystring: " + querystring);
	
	var url = pdfAsURL;
	
	if(pdfAsURL.indexOf('?') === -1) {
		url = url + "?" + querystring;
	} else {
		url = url + "&" + querystring;
	}
	
	console.log("URL: " + url);*/
	var iframeid = eventId + "_iframe";
	var iframe = document.createElement('iframe');
	iframe.width = '100%';
	iframe.height = '100%';
	iframe.frameBorder = '0';
    //iframe.src = url;
    iframe.id = iframeid;
    iframe.name = iframeid;
    iframe.style.overflow="auto";
    iframe.scrolling="no";
	
	if (typeof divID === "undefined") {
		// Create a div
		var custDiv = eventId + "_div";
		var docHeight = window.innerHeight; //grab the height of the page
        var scrollTop = window.screenTop; //grab the px value from the top of the page to where you're scrolling
		var div = document.createElement('div');
		document.body.appendChild(div);
		div.id = custDiv;
		div.style.display = 'block';
		div.style.zIndex = 32770;
		div.style.background = '#FFF';
		div.style.position = 'absolute';
		//div.style.width = '45em';
		//div.style.height = '300px';
		div.style.top = '50%';
		div.style.left = '50%';
		div.style.margin = '-150px 0 0 -22.5em';
		div.style.textAlign = 'center';
		div.style.boxShadow = '0 0 5px #E0E4CC';
		div.style.borderStyle= 'groove';
		div.style.borderRadius= '8px';
		div.style.borderColor= '#E0E4CC';
		
		var innerdiv = document.createElement('div');
		innerdiv.style.display = 'block';
		div.appendChild(innerdiv);
		var innerdivbottom = document.createElement('div');
		innerdivbottom.style.display = 'block';
		div.appendChild(innerdivbottom);
		var btnText = 'Abbrechen';
		if(locale == "EN") {
			btnText = 'Cancel';
		}
		innerdivbottom.innerHTML = "<center><button type='button' style='margin: 8px;' onclick='pdfAs.closeInstance(\"" + eventId + "\")'>" + btnText + "</button></center>"
		
		//innerdiv.innerHTML = "<a href='#' onclick='pdfAs.checkOverlay(\"" + eventId + "\")'>close</a>";
		innerdiv.appendChild(iframe);
	} else {
		var element = document.getElementById(divID);
		
		var innerdiv = document.createElement('div');
		innerdiv.setAttribute('class', 'pdfas_innerdiv');
		innerdiv.style.display = 'block';
		element.appendChild(innerdiv);
		var innerdivbottom = document.createElement('div');
		innerdivbottom.style.display = 'block';
		element.appendChild(innerdivbottom);
		
		var btnText = 'Abbrechen';
		if(locale == "EN") {
			btnText = 'Cancel';
		}
		
		innerdivbottom.innerHTML = "<center><button type='button' style='margin: 8px;' onclick='pdfAs.closeInstance(\"" + eventId + "\")'>" + btnText + "</button></center>"
		
		innerdiv.appendChild(iframe);
	}
	
	var form = document.createElement('form');
	form.method = "POST";
	form.action = pdfAsURL;
	form.target = iframeid;
	form.enctype = "application/x-www-form-urlencoded";
	
	addDataToForm(parameters, form);
	
	this.addCallback(eventId, custDiv, error, success);
	document.body.appendChild(form);
	form.submit();
};


pdfAs.addCallback = function(eventId, custDiv, error, success) {
	pdfAs.cbMap.eventId = {suc: success, err: error, div: custDiv};
};

pdfAs.closeInstance = function(eventId) {
	pdfAs.checkOverlay(eventId);
	pdfAs.doErrorCB(eventId, "Abort", "Aborted by the user.");
}

pdfAs.checkOverlay = function(eventId) {
	if(pdfAs.cbMap.eventId) {
		if(typeof pdfAs.cbMap.eventId.div != "undefined") {
			var element = document.getElementById(pdfAs.cbMap.eventId.div);
			element.style.display = 'none';
			element.parentNode.removeChild(element);
		}
	}
};

pdfAs.doSuccessCB = function(eventId, pdfurl) {
	if(pdfAs.cbMap.eventId) {
		pdfAs.cbMap.eventId.suc(decodeURIComponent(pdfurl));
	}
};

pdfAs.doErrorCB = function(eventId, error, cause) {
	if(pdfAs.cbMap.eventId) {
		pdfAs.cbMap.eventId.err(decodeURIComponent(error), decodeURIComponent(cause));
	}
};

pdfAs.messageHandler = function(event) {
	if(event.origin !== pdfAsOrigin) return;
	data = JSON.parse(event.data);
	console.log('message received:  ' + data, event);
	if(data.suc || data.err) {
		pdfAs.checkOverlay(data.eventId);
		if(data.suc) {
			console.log('Success Message: ' + data.suc.pdfUrl);
			pdfAs.doSuccessCB(data.eventId, data.suc.pdfUrl);
		} else if(data.err) {
			console.log('Error Message: ' + data.err.msg);
			pdfAs.doErrorCB(data.eventId, data.err.error, data.err.cause);
		} 
	} else if(data.resize) {
		pdfAs.autoResize(data.resize, data.height, data.width);
	}
};

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

var jqueryRegistration = function() {
	postman.receiveMessage(pdfAs.messageHandler, pdfAsOrigin);
	//window.addEventListener("message", pdfAs.messageHandler, false);
};

/**
 * Protect window.console method calls, e.g. console is not defined on IE
 * unless dev tools are open, and IE doesn't define console.debug
 */
(function() {
  if (!window.console) {
    window.console = {};
  }
  // union of Chrome, FF, IE, and Safari console methods
  var m = [
    "log", "info", "warn", "error", "debug", "trace", "dir", "group",
    "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",
    "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"
  ];
  // define undefined methods as noops to prevent errors
  for (var i = 0; i < m.length; i++) {
    if (!window.console[m[i]]) {
      window.console[m[i]] = function() {};
    }    
  } 
})();

jqueryRegistration();