/********************************************************************
 *  Bijgewerkt door:   		Hans Nauta
 *  Datum:			09-12-2012
 *  Versie:			2.5.2
 *  Domain:			NUON Retail
 *******************************************************************/


// Title of the page
var sc_page_title = "";
// init NUON_WA
var NUON_WA = sc_createNUON_WA();

function sc_createNUON_WA() {
	var obj = new Object();
	
	// init website account: for the Retail website the value is 'nuon.nl:'
	var str_Env = window.location.host.toString();
	if(str_Env.indexOf("dev.www.nuon.nl") > -1 || str_Env.indexOf("localhost") > -1) {
		obj.server="nuon.nl:development";
		
	} else if (str_Env.indexOf("test.www.nuon.nl") > -1 || str_Env.indexOf("acc.www.nuon.nl") > -1 || str_Env.indexOf("preview.www.nuon.nl") > -1) {
		obj.server="nuon.nl:acceptatie";
		
	} else {
		//make it a default, just in case!
		obj.server="nuon.nl:productie";
	} 
	
	// step id confirmation
	obj.STEP_CONFIRMATION = "bevestiging";
	// application types
	obj.APP_FORM = "formulier";
	obj.APP_MODULE = "module";
	// locations that should be logged in the click log
	obj.CLICK_LOCATIONS = "#mainnavigation, #subnavigation, #pagenavigation, #breadcrumb, #metanavigation, #metanavigation2, #contextual, #subcontent, #maincontent, #footer, #logobar, #contentnavigation";
	// site section 2
	obj.siteSection2 = "";
	
	obj.clear = function() {
		obj.formName = "";
		obj.formStep = "";
		obj.moduleName = "";
		obj.moduleStep = "";
		obj.errorValidation = "";
		
		for(prop in obj) {
			if (prop.match("^form")) {
				obj[prop] = "";
			}
		}
	};
	
	return obj;
}

/**
 * Log the evaluation of a FAQ.
 * 
 * @param question FAQ
 * @param from Query
 * @param evaluation Evaluation: y, n
 */
function sc_logFAQEvaluation(question, from, evaluation) {
	searchWaardering(evaluation,question,from);
}

/**
 * Log a view of an item/page in a search resultset.
 * 
 * @param from Query
 * @param itemcategory category PRD, FAQ or OVG
 * @param question Item or page
 * 
 * @return
 */
function sc_logSearchView(item, itemcategory, from) {
	searchClick(makeStringScProof(from), makeStringScProof(itemcategory), makeStringScProof(item));
}

/**
 * Log the hits of a search query.
 * 
 * @deprecated
 * 
 * @param question Query
 * @param numHits Number of hits
 */
function sc_logSearchNumHits(question, numHits) {
	if (numHits > 0) {
		NUON_WA.searchSucces = question;
		NUON_WA.searchResult = numHits;
	} else {
		NUON_WA.searchFailed = question;
		NUON_WA.searchResult = "0";
	}
}

/**
 * Log the hits of a search query by category. Valid categories are:
 * - "PRD";
 * - "FAQ";
 * - "OVG";
 * 
 * @param question Query
 * @param category category to register the number of hits for
 * @param numHits Number of hits
 */
function sc_logSearchNumHitsByCategory(question, category, numHits) {
	// Always log the search query
	NUON_WA.searchQuery = question;
	if (isNaN(numHits)) {
		numHits = 0;
	}
	if ("PRD" == category) {
		NUON_WA.searchResultPRD = numHits;
	}
	if ("FAQ" == category) {
		NUON_WA.searchResultFAQ = numHits;
	}
	if ("OVG" == category) {
		NUON_WA.searchResultOVG = numHits;
	}
}

function makeStringScProof(strInput){
	var forbiddenCharactersRegExp = "[\"\'<>+]";
	var re = new RegExp(forbiddenCharactersRegExp, "g");
	var newStrInput = strInput.replace(re, " ").replace(/^\s+|\s+$/g,"");
	//replace all "," comma charachters with "_" underscore charachters
	//Requested by SiteCatalyst
	return newStrInput.replace(/,/gi , "_");
}

/**
 * Initialize page variables.
 * 
 */
function sc_initPageVars() {
	// determine channel
	var path = document.location.pathname;
	var hierPrefix = path.substring(0,path.lastIndexOf('/') + 1);
	hier = sc_truncateHier(hierPrefix);

	NUON_WA.sitesection =  sc_truncateChannel(hierPrefix);
	
	if (typeof(sc_page_title)=="undefined" || (typeof(sc_page_title) != "undefined" && sc_page_title == "")) {
		// if undefined then title is filename of uri
		sc_page_title = path.substring(path.lastIndexOf('/') + 1);
	}

	NUON_WA.pagename = sc_truncatePageName(hier, sc_page_title, 100);
	NUON_WA.hier = sc_truncatePageName(hier, sc_page_title, 247); //255 minus length siteSection2


	// check if page is error page
	if (!(NUON_WA.errorPage == null || typeof(NUON_WA.errorPage) == "undefined")) {
		NUON_WA.errorURL = document.location.pathname;
	}
	
	// check from variable for search logging
	var query = document.location.search;
	var from = getParameter(query, "from");
	var itemcategory = getParameter(query, "itemcategory");

	if (typeof(from) != "undefined" && from != "") {
		sc_logSearchView(sc_page_title, itemcategory, from);
	}
}

/**
 * Get a parameter from the given query string.
 * 
 * @param queryString query string to search in for the parameter name
 * @param parameterName parameter name to search for in the queryString
 * @return parameter value or empty value if none is found
 */
function getParameter(queryString, parameterName) {
	// Add "=" to the parameter name (i.e. parameterName=value)
	var parameterName = parameterName + "=";

	if (queryString.length > 0) {
		// Find the beginning of the string
		begin = queryString.indexOf(parameterName);
		// If the parameter name is not found, skip it, otherwise return the
		// value
		if (begin != -1) {
			// Add the length (integer) to the beginning
			begin += parameterName.length;
			// Multiple parameters are separated by the "&" sign
			end = queryString.indexOf("&", begin);
			if (end == -1) {
				end = queryString.length
			}
			// Return the string
			return queryString.substring(begin, end);
		}
		
		// Return empty string if no parameter has been found
		return "";
	}
}

/**
 * Truncate the pagename, as this cannot exceed 100 characters.
 * 
 * @param hier
 *            hierarchy of the url (everything before the last '/')
 * @param pageTitle
 *            page title
 * @return
 */
function sc_truncatePageName(hier, pageTitle, size) {

	var lenHier = hier.length;
	var lenPageTitle = pageTitle.length;
	var truncatedPageName;
	
	if (lenHier + lenPageTitle > size) {
		// truncate to max. size characters
		truncatedHierLen = size - lenPageTitle;
		truncatedPageName = hier.substring(0, truncatedHierLen - 5) + ".../" + pageTitle;
	} else {
		truncatedPageName = hier + pageTitle;
	}
	
	return truncatedPageName;
}

/**
 * Truncate hierarchy. 'zakelijk' is removed.
 * 
 * @param hierPrefix hierarchy prefix
 * @return
 */
function sc_truncateHier(hierPrefix) {
	hierPrefix = hierPrefix.replace(/^\/zakelijk/, "");
	
	return hierPrefix.substring(1);
}

/**
 * Truncate channel. The context will be skipped.
 * 
 * @param hierPrefix hierarchy prefix
 */
function sc_truncateChannel(hierPrefix) {
	var context = "";	//for retail, this guy stays empty
	channel = hierPrefix;
	
	if (context != "") {
		var regexp = new RegExp("^" + context);
		channel = hierPrefix.replace(regexp, ""); 
	}
	
	return channel.split("/")[1];
}

/**
 * Click on a tab.
 * 
 * @param tabReference tab id
 */
function sc_clickTab(tabReference) {
	sc_clickTab(tabReference, null);
}

/**
 * Click on a tab.
 * 
 * @param tabReference tab id
 * @param settings Other custom settings
 */
function sc_clickTab(tabReference, settings) {
	
	var saved_page_title = sc_page_title;
	
	// determine pageName, channel
	if (settings != null) {
		for (var key in settings) {
			eval(key + " = \"" + settings[key] + "\"");
		}
	}
	if (sc_page_title != "") {
		sc_page_title = sc_page_title + "/" + tabReference;
	} else {
		sc_page_title = tabReference;
	}
	sc_initPageVars();
	sc_page_title = saved_page_title;

	NUON_WA.track();
}

/**
 * Log an AJAX step. An array of custom key-value
 * settings can be passed as argument. This
 * will be evaluated as Javascript variable values. 
 * 
 * @deprecated, use sc_clickAjax
 * @param appId application id
 * @param stepId step id
 * @param settings custom settings
 */
function sc_clickStepApp(appId, stepId, settings) {
	
	// determine pageName, channel
	if (settings != null) {
		for (var key in settings) {
			eval(key + " = \"" + settings[key] + "\"");
		}
	}
    
    sc_page_title = "formulier/" + appId + "/" + "Stap "+ stepId; 
	sc_initPageVars();

	NUON_WA.track();
}

/**
 * Log an AJAX step. An array of custom key-value
 * settings can be passed as argument. This
 * will be evaluated as Javascript variable values. 
 * 
 * @param settings custom settings
 */
function sc_clickAjax(settings) {
	
	// evaluate map of settings (key, value pairs)
	if (settings != null) {
		for (var key in settings) {
			eval(key + " = \"" + settings[key] + "\"");
		}
	}

	// set sc_page_title with form/module properties
	if (typeof(NUON_WA.moduleStep) != "undefined" && NUON_WA.moduleStep != "") {
		sc_page_title = NUON_WA.moduleName + "/" + NUON_WA.moduleStep;
	}
	if (typeof(NUON_WA.formStep) != "undefined" && NUON_WA.formStep != "") {
		sc_page_title = NUON_WA.formName + "/" + NUON_WA.formStep;
	}
	
	sc_initPageVars();
	
	NUON_WA.track();
	NUON_WA.clear();
}

/**
 * Linkclick implementation.
 */
jQuery(document).ready(function() {
	// add onclick event to track links 
	jQuery("a, button, input[type=submit]").click(function() { 
		var anchor = jQuery(this);
		jQuery(this).parents(NUON_WA.CLICK_LOCATIONS).eq(0).each(function() { 
			var area = jQuery(this).attr("id");
			var clickinfo = anchor.attr("nuonwa:clickinfo");
			if (typeof(clickinfo) == "undefined" || clickinfo == null) {
				// if cickinfo is not at anchor,
				// then check clickinfo in ul, if anchor is in a list
				anchor.parent("li").parent("ul").each(
					function() {
						clickinfo = jQuery(this).attr("nuonwa:clickinfo");
					}
				);
				if (typeof(clickinfo) == "undefined" || clickinfo == null) {
					clickinfo = "";
				}
			}
			
			var anchorText = anchor.text();
			anchorText = anchorText?anchorText: anchor.innerText?anchor.innerText:"";
			anchorText = anchorText?anchorText: (anchor.find("img").length == 1 ? anchor.find("img").attr("src") : "");
			anchorText = anchorText?anchorText: (anchor.get(0).tagName.toUpperCase() == "INPUT"  ? anchor.val() : "");
			linkClick(anchorText,area, NUON_WA.pagename, clickinfo);
		}); 
	});
});

/**
 * Log the language of the website.
 * Only used in Coporate website.
 * 
 */
function sc_language() {
	var path = document.location.pathname;
	
	if (path.match("^/nl")) {
		NUON_WA.language="Nederlands"
	} else {
		NUON_WA.language="English"
	}
}

/**
 * Log a click on a dropdown selectbox when choosing
 * options.
 * 
 */
function sc_logDropdownClick(selectElm, optionSpanElm) {
	var optionText = jQuery(optionSpanElm).text();
	var selectObj = jQuery(selectElm);

	// get label text
	var labelText = selectObj.attr("nuonwa:clickinfo");
  	
  	// get location
	var location = selectObj.parents(NUON_WA.CLICK_LOCATIONS).eq(0).attr("id");

	linkClick(labelText, location, NUON_WA.pagename, optionText);

}

/**
 * Log form fields. Div elements with the class nuonwa are selected.
 * The content of div is the value of the form field.
 * The form field name is specified by the class starting with 
 * 'nuonform'.
 * 
 */
function sc_logFormFields() {
	var nuonwaFields = jQuery("*.nuonwa").each(
			function() {
				var classnames = jQuery(this).attr("class").split(" ");
				for(var i = 0; classnames.length > i; i++) {
					var classname = classnames[i].replace(/^\s+|\s+$/g,"");
					if (classname != "" && classname.match(/^nuonform/)) {
						var fieldname = classname.substring(4);
						var fieldvalue = jQuery(this).text().replace(/\s{2,}/g, " ").replace(/^\s+|\s+$/g,"");						
						eval("NUON_WA." + fieldname + "='" + fieldvalue + "'");
						break;
					}
				}
			}
	);
	
}
