/*
 * The servicecenter.js is used for common javascript functions on the
 * Servicecenter/Online-Services/BKW-Partnersite plattform.
 */


jQuery.noConflict();

/** 
 * Execute global common js when document is ready 
 */
jQuery(function($) {

	// Init the quicklinks function
	if(jQuery('select[id|=quicklinks]').length > 0) {
		var $quicklinksDropdown = jQuery('select[id|=quicklinks]');
		$quicklinksDropdown.change(function(evt) {
			// code for trigger link
			var linkHref = jQuery(this).val();
			window.location = linkHref;
		});
		$quicklinksDropdown.width("auto");
	}
});


/**
 * Loads the customer user information
 * for the WSNavLoginUser component.
 */
function loadUserInfo(id, id2, url) {
	if(id != '' && url != '') {
		var ajax = new Ajax.Request(
		url,
		{
			method: 'get',
			onSuccess: function(transport){xmlPopulate(transport, id, id2);},
			onFailure:function(transport){alert('An error occured during the result set retrieval. HTTP Status: ' + transport.status)}
		}
		);
	}
	else if(id == '') {
		alert('No ID provided.');
	}
}

/*
 * Displays the customer information
 * in the WSNavLoginUser component.
 */
function xmlPopulate(transport, id, id2) {
	var xmlDoc = transport.responseXML;
	if(document.getElementById(id)) {
		var output = '<b>';
		if(xmlDoc.getElementsByTagName("customername1")[0].childNodes[0])
			output+=xmlDoc.getElementsByTagName("customername1")[0].childNodes[0].nodeValue;
		if(xmlDoc.getElementsByTagName("customername2")[0].childNodes[0])
			output+=" " + xmlDoc.getElementsByTagName("customername2")[0].childNodes[0].nodeValue;
		output+='</b>';
		document.getElementById(id).innerHTML = output;
	}

	if(document.getElementById(id2)) {
		document.getElementById(id2).innerHTML = xmlDoc.getElementsByTagName("customernumber")[0].childNodes[0].nodeValue;
	}
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(/; */);
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		if (c.substring(0, nameEQ.length) == nameEQ) {
			return c.substring(nameEQ.length);
		}
	}
	return null;
}

function deleteCookie(name, path) {
    document.cookie = name + "=" + (path ? "; path=" + path : "");
}

/**
 * Displays any errors in
 * the general WSErrors div element.
 *
 * @param type
 * @param message
 */
function showError(type, message){
	var errorDiv = document.createElement("div");
	var classAttribute = document.createAttribute("class");
	classAttribute.nodeValue = type;
	errorDiv.setAttributeNode(classAttribute);
	errorDiv.innerHTML = message;
	document.getElementById("WSErrors").appendChild(errorDiv);
}

/**
 * Checks wether the validation of the form
 * should be started or not.
 * If a user presses the 'back'-button, then
 * the form validation must not be executed.
 *
 * @param submitButtonId
 * @param formValidationObject
 * @return boolean True if the form shouldn't be validated or the form validation has passed correctly
 */
function doFormValidation(submitButtonId, formValidationObject) {
	if (submitButtonId == 0) {
		return true;
	} else if (submitButtonId == 1) {
		return formValidationObject.validate();
	} else {
		return false;
	}
}

/* Custom form validators */
Validation.addAllThese([
	['validate-date-ch', 'Please provide a valid date, format: dd.mm.yyyy', function(v) {
		var isEmpty = !Validation.get('IsEmpty').test(v);
		var dateValidator = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/.test(v);
		var formatValidator = /^[0-9]{2}\.[0-9]{2}\.[0-9]{4}$/.test(v);
		return  isEmpty &&  dateValidator && formatValidator;
	}],
	['validate-datechooser-range', 'Please provide a date within the range shown in the date chooser', function(v, el) {
		// Checks if a date is between the ranges defined by the element's datechooser classes
		// (class="... dc-earliestdate='dd.mm.yyyy' dc-latestdate='dd.mm.yyyy' ...")

		var dates = new Object();
		$w(el.className).each(function (classItem) {
			var match;
			if ((match = classItem.match(/^dc-(\w+)date='(\d{2}).(\d{2}).(\d{4})'$/))) {		
				//Mantis 24779: For the parseInt always pass the second parameter () otherwise a
				//string starting with "0" is considered to be in octal base...
				var day = parseInt(match[2], 10);
				var month = parseInt(match[3], 10) - 1;
				var year = parseInt(match[4], 10);
				
				currentDate = new Date(year, month, day, 0, 0, 0);
				dates[match[1]] = currentDate;
			}
		});

		var minDate = dates["earliest"];
		var maxDate = dates["latest"];

		// Parse supplied date string dd.MM.yyyy
		var suppliedDateArray = v.split(".");
		var suppliedDate = new Date(suppliedDateArray[2], suppliedDateArray[1] - 1, suppliedDateArray[0], 0, 0, 0);

		return (!minDate || suppliedDate >= minDate) && (!maxDate || suppliedDate <= maxDate);
	}],
	['validate-phone', 'Please provide a phone number, format: 0ddddddddd or ddddddddd', function(v, el) {
		var countryCodeID = el.name+'CountryCode';
		var countryCode = $(countryCodeID).value;
		if (countryCode.toLowerCase() == "ch") {
			var replaced = v.replace(/ /g, "");
			return Validation.get('IsEmpty').test(replaced) || /^(0\d{9})$|^([1-9]\d{8})$/.test(replaced);
		} else {
			var replaced = v.replace(/ /g, "");
			return Validation.get('IsEmpty').test(replaced) || /^\d+$/.test(replaced);
		}
	}],
	['validate-dependscheckbox', 'Please fill out this field', function(v, el) {
		// The additional attribute 'depends_on' holds an id of the
		// checkbox element
		var checkboxElementId = $(el.id).readAttribute('depends_on');
		var dependingCheckboxElement = $(checkboxElementId);

		if(dependingCheckboxElement.checked == false) {
			if(Validation.get('IsEmpty').test(v))
				return false;
		}

			return true;
	}],
	['validate-communication-inputs', 'Please fill out at least one phone field', function(v, el) {
		var phoneInputElement = $('phone');
		var mobileInputElement = $('mobile');

		if(Validation.get('IsEmpty').test(phoneInputElement.value) && Validation.get('IsEmpty').test(mobileInputElement.value)) {
			return false;
		}

		return true;
	}],
	['validate-apartmentlabels', 'Please give a correct apartment label', function(v, el) {
		var radioApartmentLabel = $('apartmentLabel');
		var radioApartmentLabelUnknown = $('apartmentLabelUnknown');
		var selectKnownApartmentLabel = $('knownLabel');

		if(radioApartmentLabel.checked == false && radioApartmentLabelUnknown.checked == false) {
			return false;
		}
		
		return true;
	}],
	['validate-email-custom', 'Please enter a valid email address. For example fred@domain.com .', function (v) {
		return /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v);
	}],
	['validate-password-guidelines', 'Your password doesn\'t fullfill the password guidelines', function (v) {
		// Check password for password guidelines
		// 1. At least 6 chars
		// 2. At least one letter (deactivated)
		// 3. At least one number (deactivated)
		// 4. At least one special character (deactivated)
		// return /^(?=.{6,})(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$/.test(v);
		return /^(?=.{6,}).*$/.test(v);
	}]
]);

/**
* Retrieves the 'wtParams' hidden input value
* and sets a Webtrends request.
* At the moment only following wt parameters
* are recognized by the script:
* - wtScenarioName
* - wtScenarioStepName
* - url
*/
function startGetWebtrendsParams(useCaseName) {
	var wtParams = $('wtParams_' + useCaseName);

	if(cqConfig.isPublish == true && wtParams != undefined) {
		wtParams = wtParams.value.toQueryParams();
		wtTrackRequest(wtParams.url, wtParams.wtScenarioName + "_" + wtParams.wtScenarioStepName, wtParams.wtScenarioName, wtParams.wtScenarioStepName);
	}
}

/**
* Executes a dcsMultiTrack() call
* for UseCases request.
* Executes only if its the Publish instance.
*/
function wtTrackRequest(url, title, scenarioname, stepname) {
	if(cqConfig.isPublish == true) {
		dcsMultiTrack('DCS.dcsuri', url, 'WT.ti', title, 'WT.si_n', scenarioname, 'WT.si_p', stepname);
	}
}

/**
* Executes a dcsMultiTrack() call for
* tracking error messages.
* Executes only if its the Publish instance.
*/
function wtTrackError(url, scenarioname, stepname, basecode) {
	if(cqConfig.isPublish == true) {
		dcsMultiTrack('DCS.dcsuri', url, 'WT.ti', scenarioname + '_' + stepname, 'DCSext.wt_si_n', scenarioname, 'DCSext.wt_si_p', stepname, 'DCSext.wt_base', basecode);
	}
}

//<!-- provides Functionality needed for opening a Popup-Window -->
function openGroupComposition() {
	window.open("","groupComposition","width=500,height=340,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,hscroll=no, resizable=no,copyhistory=no");
}

function openShowMeteringCode() {
	window.open("","showMeteringCode","width=500,height=180,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,hscroll=no, resizable=no,copyhistory=no");
}

function openPictureWindow_Fever(imageName,imageWidth,imageHeight,title,alt) {
	newWindow = window.open("","newWindow","width="+imageWidth+",height="+imageHeight);
	newWindow.document.open();
	newWindow.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
	newWindow.document.write('<html><title>'+title+'</title><body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginheight="0" marginwidth="0" onBlur="self.close()">');
	newWindow.document.write('<img src='+imageName+' width='+imageWidth+' height='+imageHeight+' alt=\"'+alt+'\" title=\"'+alt+'\">');
	newWindow.document.write('</body></html>');
	newWindow.document.close();
	newWindow.focus();
}

function AutoTrimmer (form) {
	Event.observe($(form), 'submit', function() {
		AutoTrimmer.execute(form);
	});
}

AutoTrimmer.execute = function (form) {
	var trimInput = function (input) {
		input.value = input.value.strip();
	};
	form = $(form);
	form.getInputs('text').each(trimInput);
	form.select('textarea').each(trimInput);
	return true;
}

function limitInputLength (input, maxLength) {
	var limiter = function (event) {
		var input = event.element();
		if (input.value.length > maxLength) {
			input.value = input.value.substring(0, maxLength);
		}
	};
	$(input).observe("keyup", limiter);
	$(input).observe("change", limiter);
}

/**
 * Set up the jQuery autocompetion function for
 * the WSClientMove, etc. use cases. To prevent that two autocomplete menu
 * opens, we have added custom search: and open: functions where we check
 * if the current input has the focus(css class 'focused'). If the current input
 * has the focus then the autocomplete menu will be displayed otherwise we close it and
 * don't send a search request.
 * 
 * @param sourceUrl The Webservice url for retrieving the autocompletion datas
 */
function setupAutoCompletion(sourceUrl) {
	
	var focusClass = "focused";
	
	jQuery("#street").autocomplete({
		source: getAutoCompletionSourceFunction("getStreets", sourceUrl),
		minLength: 3,
		delay: 0,
		search: getIsFocusedFunction(),
		open: autocompleteOpenAction()
	});
	
	jQuery("#houseNumber").autocomplete({
		source: getAutoCompletionSourceFunction("getHouseNumbers", sourceUrl),
		minLength: 1,
		delay: 0,
		search: getIsFocusedFunction(),
		open: autocompleteOpenAction()
	});
	
	jQuery("#zip").autocomplete({
		source: getAutoCompletionSourceFunction("getZips", sourceUrl),
		minLength: 2,
		delay: 0,
		search: getIsFocusedFunction(),
		open: autocompleteOpenAction()
	});
	
	jQuery("#city").autocomplete({
		source: getAutoCompletionSourceFunction("getCities", sourceUrl),
		minLength: 3,
		delay: 0,
		search: getIsFocusedFunction(),
		open: autocompleteOpenAction()
	});
	
	// Toggle focus status
	jQuery("#street, #houseNumber, #zip, #city").blur(function() {
		jQuery(this).removeClass(focusClass);
	});
	jQuery("#street, #houseNumber, #zip, #city").focus(function() {
		jQuery(this).addClass(focusClass);
	});
}

/**
 * Returns an anonymous function with the return of the 
 * isFocused function. This is used for the autocomplete.
 */
function getIsFocusedFunction() {
	return function(event, ui) {
		return isFocused(jQuery(this));
	}
}

/**
 * Returns true if the current jQuery object has set 
 * the 'focused' css class, else false,
 */
function isFocused(jqObj) {
	if(jqObj.hasClass("focused")) {
		return true;
	} else {
		return false;
	}
}

/**
 * If the jQuery object has not the focus it
 * closes the autocomplete menu. This is only used for the 
 * autocomplete.
 */
function autocompleteOpenAction() {
	return function(event, ui) {
		if(!isFocused(jQuery(this))) {
			jQuery(this).autocomplete("close");
		}
	}
}

/**
 * Builds the AutoCompletion source request with element ids:
 * - street
 * - houseNumber
 * - zip
 * - city
 *
 * Request for getting autocompletions choices looks like this:
 * http://SERVER:PORT/base2/completion?function=FUNC&street=xx&houseNumber=xx&zip=xx&city=xx
 * 
 * FUNC can be: getStreets, getHouseNumbers, getZips, getCities
 *
 * We have to use the escape() function to correctly encode the url parameters because
 * of the BKW Completion webservice. This webservice is running on a Oracle server and seems
 * only to be able handling iso encoded url parameters. Otherwise we should use encodeURI.
 */
function getAutoCompletionSourceFunction(functionName, sourceUrl) {
	
	// Set the function param for the service
	sourceUrl = sourceUrl + "?function=" + functionName; 
	
	// Return the source request function
	return function(request, response) {
		
		// Build the param string with correct 
		// url encoding(escape) for old Oracle server
		var paramString = "street=" + escape(jQuery("#street").val()) + "&houseNumber=" + jQuery("#houseNumber").val()
		+ "&zip=" + jQuery("#zip").val() + "&city=" + escape(jQuery("#city").val());
			
		jQuery.ajax({
			url: sourceUrl,
			dataType: 'text',
			data: paramString,
			success: function(data) { 
				// Make sure the incoming data is actual JSON
				// Logic borrowed from http://json.org/json2.js
				// Or: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
				var cleandata = data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                .replace(/(?:^|:|,)(?:\s*\[)+/g, '');
				
				// Remove the options key for correct regex check
				cleandata = cleandata.replace(/options/, '');
				
	            if (/^[\],:{}\s]*$/.test(cleandata)) {
	            	// Fix data to correct json format
	            	// Replace options to "options"
	            	data = data.replace("options", "\"options\"");
	            	
	            	// Parse the json string
					var jsonObj = jQuery.parseJSON(data);
					if(jsonObj.options) {
						response(jsonObj.options);
					}
				}
			} 
		});
	};
}

/**
 * Init datepickers with css class 'datepicker' 
 * and with regional settings "de".
 * 
 * @param minDate A date string or date object with the minimum date
 * @param maxDate A date string or date object with the max date
 * @param buttonTxt The text which is set as alt/title-attribute
 * @param buttonImg The path to the calendar icon image
 */
function initDatepicker(minDate, maxDate, buttonTxt, buttonIcon) {
	// Init the datepickers
	jQuery(".datepicker").datepicker(
			{
				minDate: minDate, 
				maxDate: maxDate,
				showOn: "button",
				buttonText: buttonTxt,
				buttonImage: buttonIcon,
				buttonImageOnly: true
				}, jQuery.datepicker.regional['de']);
}

