/**
 *  kieskeurig-questfield.js
 * 
 *  NOTE: Must be loaded after mo-common.js and the third-party swfobject.js file!
 *
 *  Adds ProductFinder search to the Kieskeurig page
 *
 *  Created for Kieskeurig QuestField demo page
 *	(c) 2009 MasterObjects, Inc.
 *
 *	Revision 7
 */

var testConfig = {questletVersion: 200, technology: 'auto', useStyles: true};
var useQuestFields = QO.allowField(testConfig);
var useAjaxPrototype = testConfig.QO.technology == "dhtml";
if (!useQuestFields) {
	alert('DEMO MESSAGE' + MO.N + MO.N + 'This page is showing the "old" Kieskeurig search interface, because the QuestField demo has not yet been tested with your web browser.');
}

var kieskeurigMetaAvailable = false;
var showingKieskeurigPopUp = false;
var kieskeurigQualifier = null;
var kieskeurigId;
var metaLeft;
var metaWidth;
var kieskeurigQuestFieldId = "kieskeurigQuestField";
var kieskeurigInput = "keuze";
var kieskeurigForm = "searchform";

// OVERRIDE KIESKEURIG FUNCTION TO SUPPORT CORRECT URL
function popupimage(id, prod) {  
   window.name = 'kk_bigimage';
   var popup = window.open("http://www.kieskeurig.nl/nl/product.nsf/webimagebig?readform&id="+id+"&prod="+prod,"popup","width=300,height=300,top=50,left=200,toolbar=no,location=no,directories=no,menubar=no,resizable=yes,scrollbars=1"); 
   if (popup.focus) { 
   	popup.focus(); 
   } 
}

function kieskeurigLink(a) {
	var theTarget = MO.env.iphone ? "_self" : "_blank";
	var theUrl = typeof a == "string" ? a : a.href || null;
	if (theUrl) {
		if (confirm("This link leads to the Kieskeurig website.")) {
			QO.util.gotoUrl ('info', theUrl, theTarget);
		}
	}
	return false;
}

if (useQuestFields) {
	this.DoSearch = function(theTarget) {
		if (kieskeurigId) {
			// a Kieskeurig product was selected
			return kieskeurigLink("http://www.kieskeurig.nl/product/" + kieskeurigId + ".htm");
		}
		else {
			alert("In this demo page, the traditional search was disabled." + MO.N + MO.N + "It could remain enabled if Kieskeurig chooses so.");
			return false;
		}
	};
}

// Helper functions for wrapping the right Kieskeurig HTML in the page

function startKieskeurigNestedTable() {
	document.write('<table width="640" border="0" cellspacing="0" cellpadding="0"><tr>');
}

function endKieskeurigNestedTable() {
	document.write('</tr></table>');
}

function startKieskeurigConditionalDiv(visible) {
	document.write('<div' + (visible ? '' : ' style="display:none"')  + '>');
}

function endKieskeurigConditionalDiv() {
	document.write('</div>');
}

function writeKieskeurigCategoriesHTML(width,contentChannel) {
	if (contentChannel == "freedb-demo" && useQuestFields) {
		document.write(
			'<select onchange="setKieskeurigFreedbQualifier(this);' +
							'" style="height:19px;font:11px helvetica, arial, sans-serif;width:' + width + 'px">' +
				'<option value="0">* Alle Genres</option>' +
				'<option value="blues">Blues</option>' +
				'<option value="country">Country</option>' +
				'<option value="data">Data-CD</option>' +
				'<option value="misc">Diversen</option>' +
				'<option value="soundtrack">Soundtracks</option>' +
				'<option value="folk">Folk</option>' +
				'<option value="jazz">Jazz</option>' +
				'<option value="classical">Klassiek</option>' +
				'<option value="newage">New Age</option>' +
				'<option value="pop">Pop</option>' +
				'<option value="reggae">Reggae</option>' +
				'<option value="rock">Rock</option>' +
			'</select>' +
			/* hide the traditional categories: */
			'<select name="code" style="display:none"></select>'
		);
	}
	else {
		document.write(
			'<select name="code" onchange="' +
							(useQuestFields ? 'setKieskeurigProductQualifier(this);' : 'updateBox(\'refresh\')') +
							'" style="' + (useQuestFields ? 'height:19px;font:11px helvetica, arial, sans-serif;' : '') +
																		'width:' + width + 'px">' +
				'<option value="0">' +
					' * alles ' +
				'</option>' +
			'</select>'
		);
	}
}

function writeKieskeurigQuestField(width,contentChannel) {
	metaLeft = document.getElementById("productMetaDrawer").style.left.split('px')[0];
	metaWidth = document.getElementById("metaTable").width.split('px')[0];

	var o = {};
	o.id				= kieskeurigQuestFieldId;
	o.license			= "0000001";
	o.defaultDomain		= "questobjects.com";
	o.questletVersion	= 200;
	o.useStyles			= true;
	o.skinName			= "qo-generic-red";
	o.footerColor		= "#E6E6E6";
	o.footerHeight		= 18;
	o.technology		= "auto";
	o.listLayout		= "SimpleScroll";
	o.language			= "nl";
	o.autoSelect		= "match";
	o.showResultArrows	= false;
	o.hoverSelect		= true;
	o.autoComplete		= "off";
	o.questFieldWidth	= width;
	o.questFieldHeight	= 19;
	o.popUpWidth		= width-1;
	o.popUpToLeft		= false;
	o.contentChannel	= contentChannel;
	o.popUpHandler		= "kieskeurigPopUpHandler";
	o.errorHandler		= "demoErrorHandler";
	
	if (contentChannel == "freedb-demo") {
		//o.connectString		= "/questobjects-temporary-dev/server";
		o.connectString		= "/questobjects-temporary/server";
		o.popUpRows			= 20;
		o.metadataHandler	= "kieskeurigMusicHandler";
		o.queryLength		= 2;
		o.keepLatin			= true;
		o.placeholder		= "find music...";
		o.footerHTML		= '<p style="padding:4px;margin:0">Demo for Kieskeurig BV by <a href="http://www.masterobjects.com">MasterObjects, Inc.</a></p>';
	}
	else {
		o.connectString		= "/questobjects/server";
		o.popUpRows			= 29;
		o.metadataHandler	= "kieskeurigProductHandler";
		o.valueInput		= kieskeurigInput;
		o.valueForm			= kieskeurigForm;
		o.placeholder		= "find products...";
		o.footerHTML		= '<p style="padding:4;margin:0">ProductFinder Demo created for Kieskeurig BV by <a href="http://www.masterobjects.com">MasterObjects, Inc.</a></p>';
	}
	QO.field.insert(o);
	QO.field.addContainer(o.id,"productMetaDrawer");

	if (useAjaxPrototype) {
		document.write('<font color="#FF0000">(The field above is a beta version of the AJAX QuestField. Minor issues may occur.)&nbsp;</font>');
	}
}

function kieskeurigHighlight(theInput,theString,color,prefix,suffix) {
	prefix = prefix + '<font color="' + color + '">';
	suffix = '</font>' + suffix;
	var theInputValues = theInput.split(" ");
	for (var i = 0; i<theInputValues.length; i++) {
		var theWord = theInputValues[i];
		var theStopWords = ",for,to,the,at,and,of,in,y,&,en,de,het,een,op,a,li,an";
		if (theWord.length > 2 && (theStopWords.indexOf(',' + theWord.toLowerCase()) == -1)) {
			theString = MO.util.replaceAll(theString,theWord,prefix + theWord + suffix);
			theWord = theWord.substr(0,1).toUpperCase() + theWord.substr(1);
			theString = MO.util.replaceAll(theString,theWord,prefix + theWord + suffix);
			theWord = theWord.toUpperCase();
			theString = MO.util.replaceAll(theString,theWord,prefix + theWord + suffix);
			theWord = theWord.toLowerCase();
			theString = MO.util.replaceAll(theString,theWord,prefix + theWord + suffix);
			theWord = theWord.substr(0,1).toUpperCase() + theWord.substr(1);
			theString = MO.util.replaceAll(theString,theWord,prefix + theWord + suffix);
		}
	}
	return theString;
}

function kieskeurigIdHandler(fieldName, m) {
	m = m || {};
	kieskeurigId = m["meta0"] || null;
	return true;
}

function kieskeurigProductHandler(fieldName, m) {
	m = m || {};
	var theId = m.meta0, thePrice = m.meta1, thePartNumber = m.meta2, theBrand = m.meta3,
		theType = m.meta4, theCategory = m.meta5, theImage = m.meta6,  theWidth = m.meta7,
		theDepth = m.meta8, theHeight = m.meta9, maxPrice = m.meta10, prices = m.meta11,
		theOtherFields = m.meta12;
	MO.$('metaImage').src = "/images/spinner.gif";
	if (theId) {
		kieskeurigMetaAvailable = true;
		kieskeurigId = theId;
		var theName = unescape(theBrand) + " " + unescape(theType);
		MO.$('metaTitle').innerHTML = theName;
		MO.$('metaKopen').innerHTML = "Prijsvergelijk " + theName;
		MO.$('metaWinkelprijzen').innerHTML = prices ? (prices + " winkelprijzen van &euro; " + unescape(thePrice) + " tot &euro; " + unescape(maxPrice)) : "";
		
		MO.$('metaProductLabel').innerHTML = thePartNumber ? "Partnumber" : "";
		MO.$('metaProduct').innerHTML = QO.util.unescape(thePartNumber,'');

		MO.$('metaTypeLabel').innerHTML = theType ? "Type " + unescape(theCategory) : "";
		MO.$('metaType').innerHTML = QO.util.unescape(theType,'');
		
		MO.$('metaSizeLabel').innerHTML = theHeight ? "Afmetingen (H x B x D)" : "";
		MO.$('metaSize').innerHTML = theHeight ? (unescape(theHeight) + " x " + unescape(theWidth) + " x " + unescape(theDepth) + " cm") : "";

		MO.$('metaExtraLabel').innerHTML = theOtherFields ? "Het demo-QuestField vindt dit product ook door te zoeken op:" : "";
		var theInput = QO.field.getValue(kieskeurigQuestFieldId,true);
		MO.$('metaExtra').innerHTML = theOtherFields ? kieskeurigHighlight(theInput,MO.util.replaceAll(unescape(theOtherFields),"onbekend",""),'#24549C','<b>','</b>') : "";
		
		MO.$('metaInformatie').href = 
				MO.$('metaImageJump').href = 
			"http://www.kieskeurig.nl/product/" + theId + ".htm";
		MO.$('metaReviews').href =
			"http://www.kieskeurig.nl/review/" + theId + ".htm";
		MO.$('metaPrijzen').href = 
				MO.$('metaKopen').href = 
						MO.$('metaWinkelprijzen').href =
			"http://www.kieskeurig.nl/kopen/" + theId + ".htm";
		MO.$('metaImage').src = theImage || 
			("http://images.kieskeurig.nl/images/product/" + theId + ".jpg");
		MO.$('metaImageLarge').href =
			"javascript:popupimage('" + theId + "','" + theName + "');";
	} else {
		kieskeurigMetaAvailable = false;
	}
	showKieskeurigMeta();
}

function kieskeurigMusicHandler(fieldName, m) {
	m = m || {};
	var theGenre = m.meta0, theTracks = m.meta1;
	function splitFreedbTitle(theValue) {
		var theTitle = theValue;
		var thePos = theValue.indexOf(" /");
		if (thePos > -1) {
			theTitle = theValue.substr(0,thePos) + "<br>";
			theValue = theValue.substr(thePos + 3);
			thePos = theValue.lastIndexOf(", ");
			if (thePos > -1) {
				theTitle = theValue.substr(thePos + 1) + " " + theTitle;
				theValue = theValue.substr(0, thePos);
			} else {
				thePos = theTitle.lastIndexOf(", ");
				if (thePos > -1) {
					var temp = theValue;
					theValue = theTitle.substr(thePos + 1);
					theTitle = temp + " " + theTitle.substr(0, thePos) + "<br>";
				}
			}
			theTitle = theTitle + theValue;
		}
		return theTitle;
	}

	if (theGenre || theTracks) {
		kieskeurigMetaAvailable = true;
		var theInput = QO.field.getValue(kieskeurigQuestFieldId,true);
		MO.$('metaTitle').innerHTML = 
			kieskeurigHighlight(theInput,splitFreedbTitle(QO.field.getValue(kieskeurigQuestFieldId)),'#99CCFF','','');
		MO.$('metaGenre').innerHTML = theGenre ? 
			("<b>Genre: " + unescape(theGenre)) + "</b>" : "";
		MO.$('metaTracks').innerHTML = theTracks ? 
			("<b>Tracks:</b><br><ol>"+ kieskeurigHighlight(theInput,MO.util.replaceAll(unescape(theTracks),"&apos;","'"),'#24549C','<b>','</b>') + "</ol>") : "";		
	} else {
		kieskeurigMetaAvailable = false;
	}
	showKieskeurigMeta();
}

function kieskeurigPopUpHandler(fieldId, willOpen, coordinates, pane) {
	showingKieskeurigPopUp = (pane != "close");
	showKieskeurigMeta();
}

function showKieskeurigMeta() {
	var toShow = (kieskeurigMetaAvailable && showingKieskeurigPopUp);
	var theDisplay = toShow ? "block" : "none";
	var theStyle = document.getElementById("productMetaDrawer").style;
	if (theStyle.display == theDisplay) {
		return;
	}
	if (toShow) {
		theStyle.left = metaLeft - metaWidth + "px";
	}
	theStyle.display = theDisplay;
	if (!toShow) {
		return;
	}

	/* slide into view */
	var slideSpeed = 10;
	var slideInterval = 20;
    var percent = 100;
    slide();
    var timer = setInterval(slide, slideInterval);

    function slide() {
        percent -= slideSpeed;
        if (percent <= 0) {
            percent = 0;
            clearInterval(timer);
        }
        theStyle.left = (metaLeft - Math.round((metaWidth * percent) / 100)) + "px";
    }

}


function setKieskeurigFreedbQualifier(selection) {
	kieskeurigQualifier = (selection.selectedIndex == 0) ? null : selection.options[selection.selectedIndex].value;
	QO.field.query(kieskeurigQuestFieldId,kieskeurigQualifier,null,true);
}

function setKieskeurigProductQualifier(selection) {
	var value = QO.field.getValue(kieskeurigQuestFieldId,true);
	if (kieskeurigQualifier) {
		value = MO.util.replaceAll(value,kieskeurigQualifier,"");
	}
	kieskeurigQualifier = (selection.selectedIndex == 0) ? null : selection.options[selection.selectedIndex].text;
	// see the QuestField admin guide
	if (value == "") {
		//MO.$(kieskeurigInput).value = kieskeurigQualifier;
		value = kieskeurigQualifier;
	}
	QO.field.query(kieskeurigQuestFieldId,kieskeurigQualifier,value,true);
}


function kieskeurigFocus() {
	if (useQuestFields) {
		MO.$(kieskeurigQuestFieldId).focus();
	}
}

function demoErrorHandler(id,number,text,recoverable) {
	var errorText =
		"Oops! It seems that an unexpected error occurred in this demo page." + MO.N + MO.N +
		"Either the DSL connection to the demo server is down, or we are updating the server. In either case, thank you for calling us so that we can rectify the situation!" + MO.N + MO.N + "U.S./Canada: +1-800-518-6001 (toll-free)" + MO.N + "Rest of world: +31-346-285-144";
	if (recoverable) {
		errorText += MO.N + MO.N + '(You can try your query again by clicking on the "triangle" on the right side of the QuestField.)';
	}
	alert(errorText);
}

// END of kieskeurig-questfield.js