/* -----------------------------------------------------------------
// One field to search them all.
//
// Generic Search for TNT Post
// Generic scripts with dependency on TNT Post framework/scripts
// Make sure the Page object has loaded first or this will fail.
//
// Build: 20071204
//
// Copyright 2007, TNT Post
----------------------------------------------------------------- */

// Initialize one field form
OneFieldKickStart = function() {
	if (window.page) {
		window.onefield = new OneField();
	}
	else {
		// try again in x milliseconds
		setTimeout("OneFieldKickStart()", 100); 
	}
}
OneFieldKickStart(); 

// Set event listeners
addEvent(window, "unload", function(){
	if (window.onefield) { window.onefield.destroy(); }
});

/* -----------------------------------------------------------------
// Main one field form object
----------------------------------------------------------------- */

OneField = function() {
	
	if (!window.page.hasSupport()) return;

	this.sForm = "frmOneField"; // The name of the form
	this.sField = "ofq"; // The name of the field

	this.sSearchUri = "/includes/controls/onefield/onefield.aspx";
	this.searchWidth = 920;
	
	this.warning.init(); // Init warning message
	this.validationInit(); // Init form validation
	this.fixInfoBoxes(); // Fix infoboxes on IE
	this.ofsearch.init(); // Prepare one field search	
	
	this.SearchHandler = null;

	new OFAutoSuggest(this.sField, {}); // hook up Autosuggest

}

// Helper function to clean up the onefield object
OneField.prototype.destroy = function() {
	
	if(!window.page.hasSupport()) return;
	
	// Kill objects to prevent memory leaks due to closures. - TODO!

}

/* -----------------------------------------------------------------
// OS form helpers/methods/properties/...
----------------------------------------------------------------- */

// Validation init
OneField.prototype.validationInit = function() {
	var myForm = document.getElementById(this.sForm);
	var myField = document.getElementById(this.sField);
	if (myForm) {
		var self = this;
		// Hook up field warning
		myField.onblur = function() {
			self.validateField(this);
		};
		// Hook up form submit
		myForm.onsubmit = function() {
			var bDoSubmit = self.validateField(myField);
			if (bDoSubmit) { self.doSearch(); };
			return false; 
		};
	};
};
OneField.prototype.validateField = function(obj) {
	if (obj.value.length < 1 || obj.value.match("Vul hier een vraag, uw plaatsnaam, track&trace, of postcode in.")) { 
		this.warning.show(obj, "Vul tenminste 1 zoekterm in.");
		return false;
	}
	else {
		this.warning.hide();
		return true;
	};
};

// Warning for validation
OneField.prototype.warning = {
	init : function() {
		// Construct messagenode
		var oBody = document.getElementsByTagName("body")[0];
		var oWarning = document.createElement("div");
		oWarning.id = "onefield-warning";
		var oWarningContainer = document.createElement("div");
		oWarningContainer.id = "onefield-warning-container";
		var oWarningArrow = document.createElement("span");
		oWarningArrow.id = "onefield-warning-arrow";
		var oWarningText = document.createTextNode("Let op: ");
		var oWarningMsg = document.createElement("span");
		oWarningMsg.id = "onefield-warning-msg";
		oWarningContainer.appendChild(oWarningArrow);
		oWarningContainer.appendChild(oWarningText);
		oWarningContainer.appendChild(oWarningMsg);
		oWarning.appendChild(oWarningContainer)
		oWarning._status = null;
		// IE only iframe
		if(document.all){ 
			var oWarningIFrame = document.createElement("iframe");
			oWarningIFrame.id = "onefield-warning-iframe";	
			oWarningIFrame.frameBorder = 0;
			oWarningIFrame.scrolling = "no";
			oWarningIFrame.src = "javascript:false;";
			oWarning.appendChild(oWarningIFrame);		
		}
		// Append to body
		oBody.appendChild(oWarning);
	},
	show : function(obj, msg) {
		var oWarning = document.getElementById("onefield-warning");
		if (oWarning && !oWarning._status) {
			var oWarningMsg = document.getElementById("onefield-warning-msg");
			var oWarningX   = calculateLeft(obj), oWarningY = calculateTop(obj) + 22;
			oWarning.style.left = oWarningX+"px";
			oWarning.style.top  = oWarningY+"px";
			oWarningMsg.innerHTML = msg;
			oWarning.style.display = "block";
			oWarning._status = "showing";
			setTimeout("window.onefield.warning.hide()", 5000); // Remove warning after x milliseconds
		};
	},
	hide : function() {
		var oWarning = document.getElementById("onefield-warning");
		if (oWarning) { 
			oWarning.style.display = "none"; 
			oWarning._status = null;
		};
	}
};

// Function to fix the mouseover of the infoboxes in IE
OneField.prototype.fixInfoBoxes = function() {
	var i, aInfobox = getElementsByClassName("infobox", document);
	if (aInfobox) {
		this.infobox.init(); // Create a separate infobox
		var self = this;
		for (i=0; i<(aInfobox.length); i++) {
			aInfobox[i].onmouseover = function() {
				addClass(this, "infoboxhover");
				self.infobox.show(this);
				tickle();
			}
			aInfobox[i].onmouseout=function() {
				removeClass(this, "infoboxhover");
				self.infobox.hide();
				tickle();
			}
		}
	}
}
// Infobox div
OneField.prototype.infobox = {
	init : function() {
		var oBody = document.getElementsByTagName("body")[0];
		var oInfoBox = document.createElement("div");
		oInfoBox.id = "onefield-infobox";
		var oInfoBoxMsg = document.createElement("div");
		oInfoBoxMsg.id = "onefield-infobox-msg";
		oInfoBox.appendChild(oInfoBoxMsg);
		if(document.all){ // IE only iframe
			var oInfoBoxIFrame = document.createElement("iframe");
			oInfoBoxIFrame.id = "onefield-infobox-iframe";	
			oInfoBoxIFrame.frameBorder = 0;
			oInfoBoxIFrame.scrolling = "no";
			oInfoBoxIFrame.src = "about:blank";
			oInfoBox.appendChild(oInfoBoxIFrame);		
		}
		// Append to body
		oBody.appendChild(oInfoBox);
	},
	show : function(obj) {
		var oInfoBox = document.getElementById("onefield-infobox");
		if (oInfoBox) {
			var oInfoBoxMsg = document.getElementById("onefield-infobox-msg");
			var oObjDD = obj.getElementsByTagName("dd")[0];
			var oInfoBoxX = calculateLeft(oObjDD), oInfoBoxY = calculateTop(oObjDD);
			oInfoBox.style.left = oInfoBoxX+"px";
			oInfoBox.style.top  = oInfoBoxY+"px";
			oInfoBoxMsg.innerHTML = oObjDD.innerHTML;
			oInfoBox.style.display = "block";
			oObjDD.style.visibility = "hidden";
		}
	},
	hide : function() {
		var oInfoBox = document.getElementById("onefield-infobox");
		if (oInfoBox) {
			oInfoBox.style.display = "none";
		}
	}
};

// Function to do search
OneField.prototype.doSearch = function(){
	this.ofsearch.show();
	var sQuery = '';
	if (arguments.length > 0) {
		sQuery = arguments[0];
	}
	else {
		sQuery = document.getElementById(this.sField).value;
	};
	this.getSearchResults(escape(sQuery));
};
OneField.prototype.getSearchResults = function(sQuery) {
	var xmlhttp = null;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp == null) { 
		this.ofsearch.hide();
		return;
	}
	// Build link to Search URI.
	var url = this.sSearchUri
		+ "?output=html&rnd=" + (new Date().getTime())
		+ "&ofq=" + this.clean(sQuery);
	var self = this;
	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange=function() {
	 if (xmlhttp.readyState == 4) { // We've got a result back
		if (xmlhttp.status == 200) { // And it's valid
			var oSearch = document.getElementById("onefield-search");
			var oSearchContent = document.getElementById("ofs-content");
			var oLoader = document.getElementById("onefield-loader");
			oSearchContent.innerHTML = xmlhttp.responseText;
			// show the results...
			oSearch.style.display = "block";
			oLoader.style.display = "none";
			oSearch.style.marginLeft = "-" + parseInt((self.searchWidth / 2),10) + "px";
			oSearch.style.width = self.searchWidth + "px";
			var winHeight = (window.innerHeight || self.innerHeight || (document.documentElement&&document.documentElement.clientHeight) || document.body.clientHeight) - 40;
			oSearch.style.height = (winHeight) + "px";
			oSearchContent.style.height = (winHeight-87) + "px";
			if (!(navigator.userAgent.indexOf("MSIE 6.0") != -1)) {
				oSearch.style.marginTop = "-" + parseInt((winHeight / 2),10) + "px";
			};
			self.SearchHandler = new Search();
			tickle();
		}
		else {
			// Something went wrong (not found|forbidden|?)
			self.ofsearch.hide();
		};
		xmlhttp = null;
	 }
	}
	xmlhttp.send(null);
};
// Search divs (rework of jQuery's Thickbox)
OneField.prototype.ofsearch = {
	init : function() {
		// preload stuff...
		this.loadimg = new Image();// preload image
		this.loadimg.src = "/img/onefield/loadingAnimation.gif";
	},
	show : function() {
		var oBody = document.getElementsByTagName("body")[0];
		// create overlay
		var oOverlay = document.createElement("div");
		oOverlay.id = "onefield-overlay";
		oOverlay.className = "onefield-overlayBG";
		oOverlay.onclick = this.hide;
		if(document.all){ // IE only iframe
			var oOverlayIFrame = document.createElement("iframe");
			oOverlayIFrame.id = "onefield-hideSelects";	
			oOverlayIFrame.frameBorder = 0;
			oOverlayIFrame.scrolling = "no";
			oOverlayIFrame.src = "about:blank";
			oBody.appendChild(oOverlayIFrame);
			oOverlayIFrame = null;
		}
		// create search
		var oSearch = document.createElement("div");
		oSearch.id = "onefield-search";
		oSearch.innerHTML = "<div id=\"ofs-head\"><div id=\"ofs-close\"><a href='#' onclick=\"onefield.ofsearch.hide();\">Sluit venster</a></div></div><div id=\"ofs-content\"></div><div id=\"ofs-foot\"></div>";
		// create loader
		var oLoader = document.createElement("div");
		oLoader.id = "onefield-loader";
		oLoader.innerHTML = "<img src=\""+this.loadimg.src+"\" />";
		// Append to body
		oBody.appendChild(oOverlay);
		oBody.appendChild(oSearch);
		oBody.appendChild(oLoader);
		oOverlay = null;
		oSearch = null;
		oLoader = null;
	},
	hide : function() {
		// remove one field layers
		var oBody = document.getElementsByTagName("body")[0];
		var oOverlay = document.getElementById("onefield-overlay");
		oOverlay.onclick = null;
		var oOverlayIFrame = document.getElementById("onefield-hideSelects");
		var oSearch = document.getElementById("onefield-search");
		var oLoader = document.getElementById("onefield-loader");
		oBody.removeChild(oSearch);
		oBody.removeChild(oLoader);
		if (oOverlayIFrame) { oBody.removeChild(oOverlayIFrame); };
		oBody.removeChild(oOverlay);
	}
};

OneField.prototype.clean = function(sQuery){
	sQuery = sQuery.replace("<", "");
	sQuery = sQuery.replace(">", "");
	sQuery = sQuery.replace("?", "");
	sQuery = sQuery.replace("&", "");
	return sQuery;
};
