var srcComp = 0;
var g_searchoption = '';
function showContent(){
	document.getElementById("hidden_if_js_disabled").style.display = "block";
}
function ClearDoc()	{
	var doc = document.forms[0];
	doc.Open
}
			
function buildKeyWQuery(keyWSelected, keyWFldName)
{
	var nbrSel = 0;
	var keyWString = "";
		
		if (keyWSelected.selectedIndex == 0) {
			//All keywords have been selected
			keyWString = "";
		}
		else {
			for (i = 1; i < keyWSelected.length; i++) {
				if (keyWSelected.options[i].selected) {
					keyWString = keyWString + '(IN "' + keyWFldName + '""' + keyWSelected.options[i].value + '")';
					nbrSel = nbrSel + 1;
				}
			}
			if (nbrSel > 1) {
				keyWString = "(OR " + keyWString + ")";
			}
		// update the global counter
		srcComp++;
		};
		return keyWString;
}
function buildStrQuery(stringValue) {
// Builds the string query
	var doc = document.forms[0];
	var strTmp = "";
	var strPart = "";
	var strOperator = "";
	var i = 0;
	var quoteRemoved = "";
	var strString = "";
			
	function removeQuote(stringToClean) {
		var remQTmp = "";
		var remQPart = "";
		var remQString = "";
		var j = 0;
		
		// delimiter
		remQTmp = stringToClean + '"~~';
		remQPart = remQTmp.split('"');
		j = 0;
		while (remQPart[j] != "~~") {
			remQString = remQString + remQPart[j];
			j++;
		}
		return remQString;
	}
			
	quoteRemoved = removeQuote(stringValue);
	function findSelectedRB(fldName) {
		var searchVal = "";
		searchVal = fldName[fldName.selectedIndex].value;
		return searchVal;
	}
			
	// delimiter
	strTmp = quoteRemoved + " ~~";
			
	// Find which type of search is selected
	strOperator = findSelectedRB(doc.searchType);
	
	if (strOperator != "PHRASE") {
		strPart = strTmp.split(" ");
		i = 0;
		while (strPart[i] != "~~") {
			strString = strString + '"' + strPart[i] + '"';
			i++;
		};
		if (strString.indexOf('""') > 0) {
			strString = "(" + strOperator + " " + strString + ")";
		};
	}
	else {
		// If the search type is a phrase, than return the string without the string if any
		strString = '"' + quoteRemoved + '"';
	};
	if (strString == '""') {
		strString = "";
	}
	else {
		// additional search component
		srcComp++;
	};
	return strString;
}
	
function checkQuery(iLang)
    {
		var doc = document.forms[0];
		var srcPrefix = "";
		var srcSuffix = "";
		var tmpSrcString = "";
		// This is to avoid searching projects that have not yet been approved for the web (cida68)
		var projForTheWeb = '(IN "projRevStatus""3")';
		
		srcComp = 0;
		doc.FormStatus.value = "Ok";
			
		if (iLang == "fra") {
			countryFld = "countryWebFr";
		} else {
			countryFld = "countryWebEn";
		}
		tmpScrString = buildStrQuery(doc.projKeyword.value) + buildKeyWQuery(doc.projCountry, countryFld);
		// Replace the "¸" with a valid coma for LES.
		tmpScrString = tmpScrString.replace( "¸", "," );
		// If there are more than one search component, and the proper string prefix and suffix
		if (srcComp > 0) {
			if (srcComp > 1) {
			srcPrefix = "(AND ";
			srcSuffix = ")";
			};
			doc.DESQueryString.value = "(AND " + srcPrefix + tmpScrString + srcSuffix + projForTheWeb + ")";
			return true;
		}
		else {
			doc.FormStatus.value = "QueryBlank";
			if (iLang == "fra") {
				doc.desTemplateFile.value = "cpoSearchFr.htm";
			} else {
				doc.desTemplateFile.value = "cpoSearchEn.htm";
			}
			return false;
		}
	}
function debugIt() {
		$('#msgDiv').html("DEBUGGING: All DES fields:").show();
		$.each($('[name^=DES]'), function(i) { 
			if (this.type=='radio' || this.type=='checkbox') {
				$('#msgDiv').append("<br />"+this.type + "<strong>"+ "~" +this.name+":</strong> "+this.value + "~checked:" +this.checked);
			} else {
				$('#msgDiv').append("<br />"+this.type + "<strong>"+ "~" +this.name+":</strong> "+this.value);
			}
		});
}	
	
function newBuildKeyWQuery(keyWFldID, keyWFldName, queryExpression) {
	var nbrSel = 0;
	var keyWString = "";
	var valAry = new Array();
	var valEle = '';
	
	if ($("#" + keyWFldID)[0].type=='select-multiple') {
		$("#" + keyWFldID + " option:selected").each(function() {
			//alert($(this).val());
			valEle = $(this).val().split(",");
			for (i=0; i<valEle.length; i++) {
				if (valEle[i] != '') valAry.push( '(' + queryExpression + ' "' + keyWFldName + '" "' + valEle[i] + '")' );
			}
		});
	} else {
		// we can expand the method to get field's value based on field type
	}
	
	if (valAry.length > 1) {
		keyWString = "(OR " + valAry.join(" ")+ ")";
		// update the global counter
		srcComp++;
	} else if (valAry.length == 1) {
		keyWString = valAry[0];
		// update the global counter
		srcComp++;
	}
	//alert(keyWString);
	return keyWString;
}	
	
function copySelectedOption(keyWFldID, hiddenFldID) {
	var valAry = new Array();
	if ($("#" + keyWFldID)[0].type=='select-multiple') {
		$("#" + keyWFldID + " option:selected").each(function() {
			valAry.push( $(this).text() );
		});
	} else {
		// we can expand the method to get field's value based on field type
	}
	$("#" + hiddenFldID).val(valAry.join(","));
}
	
function checkAdvQuery(iLang) {
	var doc = document.forms[0];
	var srcPrefix = "";
	var srcSuffix = "";
	var tmpSrcString = "";
	// This is to avoid searching projects that have not yet been approved for the web (cida68)
	var projForTheWeb = '(IN "projRevStatus""3")';
	
	srcComp = 0;
	doc.FormStatus.value = "Ok";
	if (iLang == "fra") {
		countryFld = "countryWebFr";
		sofFld = "SECTOROFFOCUS";
		dacFld ="SECTORL1";
		sectorFld = "sector_code";
		wbsFld = "wbs_statusFr";
	} else {
		countryFld = "countryWebEn";
		sofFld = "SECTOROFFOCUS";
		dacFld ="SECTORL1";
		sectorFld = "sector_code";
		wbsFld = "wbs_statusEn";
	}
	
	if (g_searchoption=='SoF') {
	tmpScrString = buildStrQuery(doc.projKeyword.value) + 
		buildKeyWQuery(doc.projCountry, countryFld) + 
		buildKeyWQuery(doc.projSoF, sofFld) + 
		buildKeyWQuery(doc.projSector, sectorFld) +
		buildKeyWQuery(doc.projStatus, wbsFld);
	} else {
	tmpScrString = buildStrQuery(doc.projKeyword.value) + 
		buildKeyWQuery(doc.projCountry, countryFld) + 
		buildKeyWQuery(doc.projSctrBlck, dacFld) + 
		buildKeyWQuery(doc.projSector, sectorFld) +
		buildKeyWQuery(doc.projStatus, wbsFld);	
	}
	if ($('#projPartner').length != 0) {		// if the projPartner field is available
		tmpScrString += newBuildKeyWQuery("projPartner", "vendor_number", "EQ " );
		copySelectedOption('projPartner', 'selectedProjPartner');
	}
	
	// Replace the "¸" with a valid coma for LES.
	tmpScrString = tmpScrString.replace( "¸", "," );
	// If there are more than one search compononent, and the proper string prefix and suffix
	if (srcComp > 0) {
		if (srcComp > 1) {
		srcPrefix = "(AND ";
		srcSuffix = ")";
		};
		doc.DESQueryString.value = "(AND " + srcPrefix + tmpScrString + srcSuffix + projForTheWeb + ")";
		// for debugging
		//debugIt();		
		//$('#msgDiv').append("<br />"+ $("#selectedProjPartner").val());
		return true;
	}
	else {
		doc.FormStatus.value = "QueryBlank";
			if (iLang == "fra") {
				doc.desTemplateFile.value = "cpoAdvSearchFr.htm";
			} else {
				doc.desTemplateFile.value = "cpoAdvSearchEn.htm";
			}
		return false;
	}
}
function checkStatus(statusvar, iLang){
	if (statusvar == 'QueryBlank') {
		if(iLang == 'eng'){
			document.writeln('<fieldset class="dsselect"><strong>Sorry, we are unable to address your request as formulated. Please select at least one item or enter keywords.<p>For a complete list of project profiles published on the Project Browser, use the list by <a href="http://www.acdi-cida.gc.ca/cidaweb/cpo.nsf/vWebProjByNumEn?OpenView"> Number.</a></strong></fieldset>');
		} else {
			document.writeln('<fieldset class="dsselect"><strong>Désolé, la recherche ainsi formulée ne peut être traitée. Veuillez sélectionner au moins un élément de recherche ou inscrire un ou plusieurs mots clés.<p>Pour obtenir une liste complète des profils de projets publiés dans la Banque de projets, utilisez la liste par <a href=\"http://www.acdi-cida.gc.ca/cidaweb/cpo.nsf/vWebProjByNumFr?OpenView\">numéro.</a></strong></fieldset>');
		}
	}
}
function genNameValuePair(NameValuePair) {
	var i = NameValuePair.indexOf("=");
	var NameOnly = NameValuePair.substring(0,i);
	var ValueOnly = NameValuePair.substring(i+1,NameValuePair.length);
	if (NameOnly.indexOf("DESCategory") >= 0 || NameOnly.indexOf("DESConstraint") >= 0) {
		document.writeln('<input type="hidden" name="' + NameOnly + '" value="' + ValueOnly + '" />');
	}
}
var accent = "àÀâÂçÇéÉèÈêÊëËîÎïÏôÔùÙûÛüÜ";
var escape = new Array("&agrave","&Agrave","&acirc","&Acirc","&ccedil","&Ccedil","&eacute","&Eacute","&egrave","&Egrave","&ecirc","&Ecirc","&euml","&Euml","&icirc","&Icirc","&iuml","&Iuml","&ocirc","&Ocirc","&ugrave","&Ugrave","&ucirc","&Ucirc","&uuml","&Uuml");
function escapeFrenchChars(itext){
	var xtmp = "";
				
	for(x=0;x < itext.length;x++){
		for(b=0;b<accent.length;b++){
			if(itext.charAt(x) == accent.charAt(b)){
				itext = itext.substring(0,x) + escape[b] + ";" + itext.substring(x+1);
				xtmp = escape[b];
				x = x + xtmp.length + 1;
			}
		}
	}
	return itext;
}
function gotoPage(num) {
	document.forms[0].DESGetPage.value = num;
	document.forms[0].submit();
}
			
function searchInfoDisplay(iPageSize, iTotalHits, iLang) {
	var iPageNum = document.forms[0].DESGetPage.value;
	var iPagesReturned = Math.ceil(iTotalHits / iPageSize);
	document.writeln("<div>");
					
	if(iPagesReturned > 0){
   		if(iLang == "eng"){
			document.writeln("<br/>Page: ");
		} else {
			document.writeln("<br/>Page : ");
		}
	}
	
	if(iPagesReturned > 1 && iPageNum > 1){
   		var iPreviousPage = Number(iPageNum) - 1;
		if(iLang == "eng"){
   			document.writeln("<a href='javascript:gotoPage(" + iPreviousPage + ");'>Previous</a>&nbsp;&nbsp");
		} else {
			document.writeln("<a href='javascript:gotoPage(" + iPreviousPage + ");'>Pr&eacute;c&eacute;dente</a>&nbsp;&nbsp");
		}
	}
	for(i=1;i<=iPagesReturned;i++){
 		if(i == iPageNum){
      			document.writeln(i);
   		} else {
      			document.writeln("<a href='javascript:gotoPage(" + i + ");' onclick='javascript:gotoPage(" + i + ");'>" + i + "</a>");
   		}
   		if(i<iPagesReturned){document.writeln(",");}
	}
	if(iPagesReturned > 1 && iPageNum < iPagesReturned){
  		var iNextPage = Number(iPageNum) + 1;
		if(iLang == "eng"){
	   		document.writeln("&nbsp;&nbsp<a href='javascript:gotoPage(" + iNextPage + ");'>Next</a><br /><br /></div>");
		} else {
			document.writeln("&nbsp;&nbsp<a href='javascript:gotoPage(" + iNextPage + ");'>Suivante</a><br /><br /></div>");
		}
	} else {
		document.writeln("<br /><br /></div>");
	}
}
function genNameValuePair(NameValuePair) {
	var i = NameValuePair.indexOf("=");
	var NameOnly = NameValuePair.substring(0,i);
	var ValueOnly = NameValuePair.substring(i+1,NameValuePair.length);
	if (NameOnly.indexOf("DESCategory") >= 0 || NameOnly.indexOf("DESConstraint") >= 0) {
		document.writeln('<input type="hidden" name="' + NameOnly + '" value="' + ValueOnly + '" />');
	}
}
function printTableHeaderEng(){
	document.writeln('<table class="size100"><caption>Search Results</caption><tr><th class="lightgreyBG">Project Title</th><th class="lightgreyBG">Project Status</th><th class="lightgreyBG">Project Duration</th></tr>');
}
function printTableHeaderFra(){
	document.writeln('<table class="size100"><caption>Résultats de la recherche</caption><tr><th class="lightgreyBG">Titre du projet</th><th class="lightgreyBG">État du projet</th><th class="lightgreyBG">Durée du projet</th></tr>');
}
function printTableFooter(){
	document.writeln('</table><br />');
}
function generateResults(iItemUrl, docTitle, docWbs_status, docProjStartDate, docProjEndDate, iLang) {
	// If the docTitle is still empty then we will set the 
	// title to the document id.
	if (docTitle == "" && iLang == 'eng') {
		docTitle = "No title";
	} else if (docTitle == "" && iLang == 'fra'){
		docTitle = "Aucun titre";
	}
	
	if (docWbs_status == "En planification") {
		docWbs_status = "Planification";
	} else if (docWbs_status == "En finalisation") {
		docWbs_status = "Finalisation";
	}
	document.writeln("<tr>");
	document.writeln("<td class=\"small\" valign=\"top\"><a href=\""+iItemUrl+"\" target=\"new\">"+docTitle+"</a></td>");
	document.writeln("<td class=\"small\" align=\"center\" valign=\"top\">"+docWbs_status+"</td>");
	document.writeln("<td class=\"small\" width=\"80\" align=\"center\" valign=\"top\">"+docProjStartDate.substring(0,4)+"-"+docProjEndDate.substring(0,4)+"</td>");
	document.writeln("</tr>");
}
var defaultSelectOption_eng = '<option value="All" selected="selected">All</option>';
var defaultSelectOption_fra = '<option value="Tous" selected="selected">Tous</option>';
var showDACSector = function(iLang, searchoption) { 
	var codes = [];
	var tempCodes; 
	var url = '';
	
	// get user selected options
	$('#proj' + searchoption + ' option:selected').each(function () {
		codes.push($(this).val());
	}); 
	if ( codes.length == 1 && ($.inArray( 'All', codes) > -1 || $.inArray( 'Tous', codes) > -1) ) {
		// if user selects only the 'All' option
		url = '*'; 
	} else if ( codes.length > 1 && ($.inArray( 'All', codes) > -1 || $.inArray( 'Tous', codes) > -1) ) {
		if ($.inArray( 'All', codes) > -1) {
			// if user selects 'All' option and other options, remove 'All' option from the search list
			tempCodes = $.grep(codes, function(val) { return val != 'All'; });
			// and then unselects 'All' option
			$('#proj' + searchoption + ' option[value=All]').removeAttr('selected');
		} else {
			tempCodes = $.grep(codes, function(val) { return val != 'Tous'; });
			$('#proj' + searchoption + ' option[value=Tous]').removeAttr('selected');			
		}
	} else { 
		// copy sof to temp value holder
		tempCodes = $.grep(codes, function(val) { return val != ''; });
	}
	
	if (url=='*') {
		url = "http://www.acdi-cida.gc.ca/cidaweb/cpo.nsf/lookupSector?openagent&lang=" + iLang + "&searchoption=" + searchoption + "&codes=*&callback=?"; 
	} else {
		url = "http://www.acdi-cida.gc.ca/cidaweb/cpo.nsf/lookupSector?openagent&lang=" + iLang + "&searchoption=" + searchoption + "&codes=" + tempCodes.join('~') + "&callback=?"; 
	}
	// for debugging
	//$('#msgDiv').text(url); $('#msgDiv').show();
	
	var options = '';
	// lookup the DAC sectors related to the selected search options
	$.getJSON(url, function(data){	
		//check to see if we have any data returned
		if (data.sectors) {
			//loop through the returned data
			$.each(data.sectors, function(i,item){ 
				if ( iLang=='eng') 
					options += '<option value="' + item.sectorcode + '">' + item.sectorcode + ' ' + item.descriptionEn + '</option>';
				else
					options += '<option value="' + item.sectorcode + '">' + item.sectorcode + ' ' + item.descriptionFr + '</option>';	
				// for debugging
				//$('#msgDiv').text(options); $('#msgDiv').show();
			});
			if ( iLang=='eng') {
				$('#projSector').html(defaultSelectOption_eng + options).show();
			} else {
				$('#projSector').html(defaultSelectOption_fra + options).show();
			}
		} else {
			$('#projSector').hide();
			$('#msgDiv').text(data.error)
			$('#msgDiv').show();
		}
	});	
};	
function loadSearchOption(iLang, searchoption, altSearchoption, altHref) { 
	var msgeng = {	"SoF" : 
					{
						"searchHelp" : "sector(s)",
						"altSearchOption" : "<a href='" + altHref + "'>Advanced search using DAC Sector Blocks</a>"
					},
					"SctrBlck" : 
					{
						"searchHelp" : "DAC sector blocks", 
						"searchOption1" : "Using DAC Sector Blocks",
						"searchOption2" : "Using DAC Sector Blocks",
						"altSearchOption" : "Standard <a href='" + altHref + "'>Advanced Search</a>"
					}
				};
	var msgfra = {	"SoF" : 
					{
						"searchHelp" : "secteurs",
						"searchOption" : "",
						"altSearchOption" : "<a href='" + altHref + "'>Recherche avancée en fonction des groupes de secteurs du CAD</a>"
					},
					"SctrBlck" : 
					{
						"searchHelp" : "groupes de secteurs du CAD", 
						"searchOption1" : "en fonction des groupes de secteurs du CAD",
						"searchOption2" : "en fonction des groupes de secteurs du CAD",
						"altSearchOption" : "<a href='" + altHref + "'>Recherche avancée</a> standard"
					}
				};
	var obj = eval('msg'+iLang+'.'+searchoption);
	for(var o in obj) {
		$('#'+o).html( obj[o] );	
	}
	$('#' + searchoption + 'Div').show();
	$('#' + altSearchoption + 'Div').hide();
	
	var options = '';
	// 'sof' and 'dac' two arrays are stored in a notes keyword document
	if ((searchoption == 'SoF') && !(typeof sof == 'undefined')) {
		options = generateSearchOptions(iLang, sof);
	} else if ((searchoption == 'SctrBlck') && !(typeof dac == 'undefined')) { 
		options = generateSearchOptions(iLang, dac);
	} 
	$('#proj'+searchoption).html(options);
	// for debugging
	//$('#msgDiv').text(options).show();
	
	// remove all previously loaded sectors when user changes the search option selection
	$('#proj'+searchoption).change( function () {
		$('#projSector').html( (iLang=='eng') ? defaultSelectOption_eng : defaultSelectOption_fra);
	})
}
function generateSearchOptions(iLang, arr) {
	var temp = '';
	$.each(arr, function(i,item){ 
		if (iLang=='eng') {
			temp += '<option value="' + i + '">' + item.descriptionEn + '</option>';
		} else {
			temp += '<option value="' + i + '">' + item.descriptionFr + '</option>';
		}	
	});		
	return (iLang == 'eng') ? defaultSelectOption_eng + temp : defaultSelectOption_fra + temp; 
}
	
var langAffixes= ['En','Fr'];
var locales = ['enUS', 'frFR'];
function initializeProcess(iLang, langAffix) {
	$('#msgDiv').hide();
	$('#projPartnerDiv').hide();
		
	var searchtypes = ['SoF','SctrBlck'];
	var searchoption = ''; 
	var arr = new Array();
	// find out the alternate language
	var altLangAffix = $.grep(langAffixes, function(val) { return val != langAffix; });
	
	var locale = ''; 
	var args = window.location.href.split('&'); 
	for(var i=0; i<args.length; i++){
		arg = args[i].split('=');
		if(arg[0].toLowerCase() == "searchoption") {
			searchoption = arg[1];
		} else if(arg[0].toLowerCase() == "desclientlocale") {
			locale =  arg[1];
			arr.push(args[i]);
		} else {
			arr.push(args[i]);
		}
	}
		
	// find out what is the alternate search type
	var altSearchtype = $.grep(searchtypes, function(val) { return val != searchoption; });
		
	if ( altSearchtype.length != 1) {
		//if alternate search type cannot be identified, use the default advanced search option (search by CIDA Sector of Focus)
		searchoption = 'SoF'; 
		altSearchtype = 'SctrBlck';
	}
	arr.push("searchoption=" + altSearchtype);
		
	//register the onclick event for the "Display DAC Sector" button
	$('#btnShowSector').click( function () {
		showDACSector(iLang, searchoption);
	})
	loadSearchOption(iLang, searchoption, altSearchtype, arr.join("&"));
	loadPartnerOption( iLang );
	
	g_searchoption = searchoption;
	
	// find out the alternate locale
	var altLocale = $.grep(locales, function(val) { return val != locale; });
	//alert(langAffix+"\t"+altLangAffix+"\n"+locale+"\t"+altLocale);
	if ( altLocale.length == 1) {
		//if alternate locale can be identified, replace the "Français" link with the proper href
		$('#altLangSearchLink').attr('href', window.location.href.replace(locale, altLocale).replace(eval('/'+ langAffix+ '/g'), altLangAffix ));
	}
}
function setLinks(langAffix, locale) {
	// find out the alternate language
	var altLangAffix = $.grep(langAffixes, function(val) { return val != langAffix; });
	// find out the alternate locale
	var altLocale = $.grep(locales, function(val) { return val != locale; });
	var altSearchLink = '';
	if (document.referrer.indexOf('searchoption')!= -1) {
		$('#altLangSearchLink').attr('href', document.referrer.replace(locale, altLocale).replace(eval('/'+ langAffix+ '/g'), altLangAffix ));
	}
}	
function loadPartnerOption(iLang) { 
	var options = "";
	if (typeof(partner)=='undefined') {
		$('#projPartnerDiv').hide();
	} else {
		var defaultOption_eng = '<option value="" selected="selected">Select</option>';
		var defaultOption_fra = '<option value="" selected="selected">Choisir</option>';
		var defaultSelectOption = eval('defaultOption_' + iLang); 
		for (p in partner) { 
			if (p!="") options += '<option title="' +p+ '" value="' + partner[p] + '">' + p + '</option>';
		}
		if(options!=''){
			$('#projPartner').html(defaultSelectOption + options);
			$('#projPartnerDiv').show();
		} else {
			$('#projPartnerDiv').hide();
		}
	}
}

