/*
* The "common.js" file is used for centralizing
* common javascript functions.
*
*/

/* 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='MMddyyyy' dc-latestdate='MMddyyyy' ...")

		var dates = new Object();
		$w(el.className).each(function (classItem) {
			var match;
			if ((match = classItem.match(/^dc-(\w+)date='(\d{8})'$/))) {		
				//Mantis 24779: For the parseInt always pass the second parameter () otherwise a
				//string starting with "0" is considered to be in octal base...
				var year = parseInt(match[2].substring(4), 10);
				var month = parseInt(match[2].substring(0, 2), 10) - 1;
				var day = parseInt(match[2].substring(2, 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");
}

/* enlarge/reduce font sizes. Sebastian Lisken. Tested for IE and gecko. */
function changeFontSizeById (targetID, increment)
{
  if (! document.getElementById) return;
  var rootNode = document.getElementById(targetID);
  if (rootNode != null) {
    changeFontSize(rootNode, increment);
  }
}

function changeFontSizesByTagName (tagName, increment)
{
  if (! document.getElementById) return;
  var rootNodes = document.getElementsByTagName(tagName);
  if (rootNodes != null) {
    for (var i = 0; i < rootNodes.length; ++i) {
      changeFontSize(rootNodes[i], increment);
    }
  }
}

function changeDocumentFontSize (increment)
{
	changeFontSize(document.getElementById('col1_content'), increment);
	changeFontSize(document.getElementById('col2_content'), increment);
  	changeFontSize(document.getElementById('col3_content'), increment);
}

function changeFontSize (element, increment)
{
  var factor = Math.pow(2, increment);
  var oldSize = getFontSize(element), newSize;
  if (oldSize == null) {
    newSize = round(factor * 100, 0.01) + "%";
  } else {
    newSize = round(oldSize.value * factor, 0.01) + '' + oldSize.unit;
  }
  element.style.fontSize = newSize;
}

function getStyle (element, cssProperty)
{
  var value;
  if (document.defaultView && document.defaultView.getComputedStyle) {
    cssProperty = cssProperty.replace(/[A-Z]/g, function (match)
      {
        return "-" + match.toLowerCase();
      }
    );
    value = document.defaultView.getComputedStyle(element, '').getPropertyValue(cssProperty);
  } else if (element.currentStyle) {
    value = element.currentStyle[cssProperty];
  } else {
    value = null;
  }
  return value;
}

/*
  named font sizes and their approximate translation into percentages.
  http://www.w3.org/TR/REC-CSS2/fonts.html#font-size-props
*/
var absoluteSizeNames = new Array('xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large');
var relativeSizeNames = new Array('smaller', 'larger');
var namedSizes = { };
var normalSize = "100%", normalSizeIndex = 3, sizeFactor = 1.2;
for (i in absoluteSizeNames)
{
  namedSizes[absoluteSizeNames[i]] = Math.pow(sizeFactor, i - normalSizeIndex) * 100 + "%";
}
namedSizes[relativeSizeNames[0]] = 1 / sizeFactor;
namedSizes[relativeSizeNames[1]] = sizeFactor;
namedSizes[undefined] = namedSizes[null] = namedSizes[''] = normalSize;

function getFontSize (element)
{
  var fontSize = getStyle(element, "fontSize");
  if (fontSize in namedSizes) {
    fontSize = namedSizes[fontSize];
  }
  var tailIndex = fontSize.match(/[^0-9]*$/).index;
  var number = parseFloat(fontSize.substring(0, tailIndex));
  if (isNaN(number)) {
    return null;
  } else {
    return { unit: fontSize.substring(tailIndex), value: number };
  }
}

function round (number, granularity)
{
  return Math.round(number / granularity) * granularity;
}

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);
}
