var allowWindowLeave = false

/*
NAVIGATE HELPERS
Origin: GolfBox
*/
function onbeforepostback() { return true } // event
function onbeforeredirect() { return true } // event

function _validatePostBack(strCommand) {
	if (arguments[2]) { // a browser comp. hack
		var theValidatorObject = eval(arguments[2])
	} else {
		if (typeof (cv) == 'object') {
			var theValidatorObject = cv
		} else {
			var theValidatorObject = eval('cv')
		}
	}
	theValidatorObject.validate()

	if (!theValidatorObject.isValid) {
		theValidatorObject.render()
	} else {
		// use the .net framework postback functions
		//(arguments[1]) ? __doPostBack(strCommand,arguments[1]) : __doPostBack(strCommand);
		if (onbeforepostback(strCommand, arguments[1])) {
			(arguments[1]) ? _postBack(strCommand, arguments[1]) : _postBack(strCommand);
		}
	}
}

function _validateDoPostBack(PostBackCommand) {
	if (arguments[2]) { // a browser comp. hack
		var theValidatorObject = eval(arguments[2])
	} else {
		if (typeof (cv) == 'object') {
			var theValidatorObject = cv
		} else {
			var theValidatorObject = eval('cv')
		}
	}
	theValidatorObject.validate()

	if (!theValidatorObject.isValid) {
		theValidatorObject.render()
	} else {
		// use the .net framework postback functions
		if (onbeforepostback(PostBackCommand, arguments[1])) {
			(arguments[1]) ? __doPostBack(PostBackCommand, arguments[1]) : __doPostBack(PostBackCommand, '');
		}
	}
}

function _redirect(strUrl) {
	_allowLeave();
	if (onbeforeredirect(strUrl)) {
		self.location.href = strUrl
	}
}

function _confirmRedirect(strConfirm, strUrl) {
	_allowLeave();
	if (confirm(strConfirm)) {
		_redirect(strUrl);
	}
}

function _confirmPostBack(strConfirm, strCommand) {
	if (confirm(strConfirm)) {
		if (onbeforepostback(strCommand, arguments[1])) {
			(arguments[1]) ? _postBack(strCommand, arguments[2]) : _postBack(strCommand);
		}
	}
}

function _allowLeave() {
	allowWindowLeave = true
	if (getObj('allowWindowLeave')) getObj('allowWindowLeave').value = 1
}

function _postBack(strCommand) {
	_allowLeave();
	document.forms['aspnetForm'].__EVENTTARGET.value = strCommand;
	if (arguments[1] != 'undefined') {
		document.forms['aspnetForm'].__EVENTARGUMENT.value = arguments[1]
	}
	if (onbeforepostback(strCommand, arguments[1])) {
		document.forms['aspnetForm'].submit();
	}
}

function _forcePostBack(strCommand) {
	_allowLeave();
	document.forms['aspnetForm'].__EVENTTARGET.value = strCommand;
	if (arguments[1]) {
		document.forms['aspnetForm'].__EVENTARGUMENT.value = arguments[1]
	}

	document.forms['aspnetForm'].submit();
}

var myWin = null;
function openWindow(url, name, width, height, scroll, status) {
	status = (arguments[5]) ? arguments[5] : 'no';
	var winl = (screen.width - width) / 2;
	var wint = (screen.height - height) / 2;
	settings = 'height=' + height + ',width=' + width + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',toolbar=no,location=no,status=' + status + ',menubar=no,resizable=no,dependent=no'
	myWin = window.open(url, name, settings, myWin)
	if (parseInt(navigator.appVersion) >= 4) { myWin.window.focus(); }
}

function openHCPCert() {
	openWindow('/site/score/hcp.aspx', 'hcpWin', 660, 280, 'yes', '');
}

function openHCPCalcTable() {
	openWindow('/site/score/hcp_calctable.aspx', 'hcp_calctable', 660, 280, 'yes', '');
}


/*
OBJECT EXTENSIONS
Origin: GolfBox
*/
Array.prototype.exists = function(value, objectProperty_1, objectProperty_2) { // kaldes theArray.exists(value)
	for (var intLoop = 0; intLoop < this.length; intLoop++) {

		var compareVal_1
		var compareVal_2

		if (typeof (this[intLoop]) == 'object') {
			compareVal_1 = (objectProperty_1) ? eval('this[intLoop].' + objectProperty_1) : this[intLoop]
		} else {
			compareVal_1 = this[intLoop]
		}

		if (typeof (value) == 'object') {
			compareVal_2 = (objectProperty_2) ? eval('value.' + objectProperty_2) : value
		} else {
			compareVal_2 = value
		}

		if (compareVal_1 == compareVal_2) {
			this.onExist(intLoop);
			return true;
		}
	}
	return false;
}

Array.prototype.find = function(value, objectProperty_1, objectProperty_2) { // kaldes theArray.exists(value)
	for (var intLoop = 0; intLoop < this.length; intLoop++) {

		var compareVal_1
		var compareVal_2

		if (typeof (this[intLoop]) == 'object') {
			compareVal_1 = (objectProperty_1) ? eval('this[intLoop].' + objectProperty_1) : this[intLoop]
		} else {
			compareVal_1 = this[intLoop]
		}

		if (typeof (value) == 'object') {
			compareVal_2 = (objectProperty_2) ? eval('value.' + objectProperty_2) : value
		} else {
			compareVal_2 = value
		}

		if (compareVal_1 == compareVal_2) {
			return this[intLoop];
		}
	}
	return null;
}

Array.prototype.onExist = function() { }

Array.prototype.add = function(value) {
	this[this.length] = value; return this[this.length - 1]
}

Array.prototype.addKey = function(key, value) {
	this[key] = value; return this[key]
}

Array.prototype.remove = function(value) {
	for (var ii = 0; ii < this.length; ii++) {
		if (this[ii] == value) {
			val = this[ii]
			this.splice(ii, 1);
			return val
		}
	}
}

Array.prototype.init = function() {
	for (var i = 0; i < arguments.length; i++) {
		this[i] = arguments[i]
	}
}

Date.prototype.clone = function() {
	var tdate = new Date(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds())
	return tdate
}

Date.prototype.dateDiff = function(start, end, interval, rounding) {

	var iOut = 0;

	var bufferA = Date.parse(start);
	var bufferB = Date.parse(end);

	// check that the start parameter is a valid Date.
	if (isNaN(bufferA) || isNaN(bufferB)) {
		return null;
	}

	// check that an interval parameter was not numeric.
	if (interval.charAt == 'undefined') {
		// the user specified an incorrect interval, handle the error.
		return null;
	}

	var number = bufferB - bufferA;

	// what kind of add to do?
	switch (interval.charAt(0)) {
		case 'd': case 'D':
			iOut = parseInt(number / 86400000);
			if (rounding) iOut += parseInt((number % 86400000) / 43200001);
			break;
		case 'h': case 'H':
			iOut = parseInt(number / 3600000);
			if (rounding) iOut += parseInt((number % 3600000) / 1800001);
			break;
		case 'n': case 'N':
			iOut = parseInt(number / 60000);
			if (rounding) iOut += parseInt((number % 60000) / 30001);
			break;
		case 's': case 'S':
			iOut = parseInt(number / 1000);
			if (rounding) iOut += parseInt((number % 1000) / 501);
			break;
		default:

			return null;
	}

	return iOut;
}

String.prototype.isOneOf = function() {

	/*
	example:
	myVal = 'teststring'
	alert(myVal.isOneOf('teststring1','teststring2')) // returns false
	alert(myVal.isOneOf('teststring1','teststring2','teststring')) // returns true
	*/

	// check base type
	base_type = typeof (this).toString()
	if (base_type != 'string') {
		alert('Invalid base type for string.isOneOf() - Only strings are allowed as base types.');
		return false;
	}

	// check to if this eaquels one of the provided argument values.
	for (var iArguments = 0; iArguments < arguments.length; iArguments++) {
		arg = arguments[iArguments]
		arg_type = typeof (arg)
		if (arg_type == 'string') { // test string
			if (this.toLowerCase() == arg.toLowerCase()) {
				return true;
			}
		}
		if (arg_type == 'number') { // test numeric
			if (this == arg) {
				return true;
			}
		}
	}; return false;
}

/*
Static/shared format method on the String Object
Use: String.format(stringToFormat, arguments[n]...)
Example 1: String.format('The result is {0}', 'good')
Returns: "The restult is good"
Example 2: String.format('The result is {0} and your age is: {1}', 'good',27)
Returns: "The restult is good and your age is 27"
*/
String.format = function(StringToFormat) {
	var returnString = StringToFormat
	for (var i = 1; i < arguments.length; i++) {
		returnString = returnString.replace('{' + (i - 1) + '}', arguments[i])
	}
	return returnString
}

function PageObject(lcid, iso) {
	this.LCID = lcid;
	this.countryISOCode = iso;
}

PageObject.prototype.getDateDelimiter = function() {
	switch (this.LCID) {
		case 1031: return '.'; break;
		case 1030: return '-'; break;
		case 1044: return '.'; break;
		case 1053: return '-'; break;
		default: return '/'; break;
	}
}

function IIF(Statement, ValueIfTrue, ValueIfFalse) {
	if (Statement) {
		return ValueIfTrue;
	} return ValueIfFalse;
}

/*
#########

XMLObject()

#########
*/
function XMLObject() {
	this.progId;
	this.error;
	this.xmlhttp;
	this.xmldom;
}

XMLObject.prototype.getHTTPObject = function() {
	try { // Mozilla Browsers
		this.xmlhttp = new XMLHttpRequest();
		this.progId = 'XMLHttpRequest()';
	} catch (ex) {
		// IE Browsers
		var progIds = ["MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Msxml2.XMLHTTP.6.0", "Msxml2.ServerXMLHTTP.5.0", "Microsoft.XMLHttp"];

		for (var currentProgID = 0; currentProgID < progIds.length; currentProgID++) {
			try {
				this.xmlhttp = new ActiveXObject(progIds[currentProgID]);
				this.progId = progIds[currentProgID];
				break; // get the newest from the list
			}
			catch (ex) {
				this.error = ex;
			}
		}
	}
	return this.xmlhttp;
}

XMLObject.prototype.send = function(file, postData) {
	this.getHTTPObject();

	this.xmlhttp.open("POST", file, false);
	this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	this.xmlhttp.send(postData);
}


XMLObject.prototype.getDOMDocumentObject = function() {
	try { // Mozilla Browsers
		this.xmldom = new DOMParser();
		this.progId = 'DOMParser()';
	} catch (ex) {
		// IE Browsers
		var progIds = ["MSXML2.DomDocument.4.0", "MSXML2.DomDocument.3.0", "MSXML2.DomDocument", "Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Microsoft.DomDocument"];

		for (var currentProgID = 0; currentProgID < progIds.length; currentProgID++) {
			try {
				this.xmldom = new ActiveXObject(progIds[currentProgID]);
				this.progId = progIds[currentProgID];
				break; // get the newest from the list
			}
			catch (ex) {
				this.error = ex;
			}
		}
	}
	return this.xmldom;
}



/* EVENT HANDLER */
var cmdButton = ""
var cmdButtonDisabled = false
function setCMDButton(btn) {
	cmdButton = btn
}

function doButtonCmd() {
	try {
		if (event.keyCode == 116) { allowWindowLeave = true };
		if (cmdButtonDisabled) { return true }
		if (cmdButton == 'NONE') { return true }

		if (event.keyCode == 13) {
			if (document.getElementById(cmdButton)) {
				document.getElementById(cmdButton).click()
				return true
			}

			if (cmdButton != '') {
				if (!document.getElementById(cmdButton)) {
					return false
				}
			}
		}
	} catch (e) { }
}
document.onkeydown = doButtonCmd;

/* COOKIES */
function setCookie(sName, sValue) {
	date = new Date();
	date.setDate(date.getDate() + 30)
	//alert('set:'+sValue)
	document.cookie = sName + "=" + escape(sValue) + "; expires=" + date.toGMTString() + '; path=/;';
}

function getCookie(sName) {
	// cookies are separated by semicolons
	var aCookie = document.cookie.split("; ");

	for (var i = 0; i < aCookie.length; i++) {
		// a name/value pair (a crumb) is separated by an equal sign
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0])
			return unescape(aCrumb[1]);
	}

	// a cookie with the requested name does not exist
	return null;
}

function deleteCookie(sName) {
	document.cookie = sName + "=''; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}


/* MISC HELPER FUNCTIONS */
function getObj(id) {
	return document.getElementById(id)
}

function showObj(obj) {
	obj.style.display = '';
	obj.style.visibility = 'visible';
}

function hideObj(obj) {
	obj.style.display = 'none';
	obj.style.visibility = 'hidden';
}

function buttonDisable(clientId, disable) {
	obj = getObj(clientId)
	if (!obj) return;

	if (disable) {
		obj.disabled = true
		obj.style.color = 'silver'
	} else {
		obj.style.color = 'white'
		obj.disabled = false
	}
}


/* DATAGRID FUNCTIONS */
function rowHover(obj, cmd) {
	var row = obj.parentNode

	for (var i = 0; i < row.childNodes.length; i++) {
		td = row.childNodes[i]
		if (td.tagName == 'TD') {
			if (td.getAttribute("hover")) {
				switch (td.getAttribute("hover")) {
					case 'link':
						td.childNodes[0].style.textDecoration = 'underline';
						if (cmd) td.title = getObj(cmd).title
						break;
					case 'image':
						imgHover(td.childNodes[0]);
						break;
				}
			}
		}
	}
}

function rowDehover(obj, cmd) {
	var row = obj.parentNode

	for (var i = 0; i < row.childNodes.length; i++) {
		td = row.childNodes[i]
		if (td.tagName == 'TD') {
			if (td.getAttribute("hover")) {
				switch (td.getAttribute("hover")) {
					case 'link':
						td.childNodes[0].style.textDecoration = '';
						break;
					case 'image':
						imgDehover(td.childNodes[0]);
						break;
				}
			}
		}
	}
}

function imgHover(obj, img) { // used to swap image buttons
	newSrc = obj.src.replace('_off.gif', '_on.gif')
	obj.src = newSrc
}

function imgDehover(obj, img) { // used to swap image buttons
	newSrc = obj.src.replace('_on.gif', '_off.gif')
	obj.src = newSrc
}

/* CUROSR MOVER */
_GolfId_allowCursorMove = true
function GolfId_moveCursor(objTxt1, objTxt2, stringLength) {

	objUrs1 = getObj(objTxt1)
	objUrs2 = getObj(objTxt2)

	if (objUrs1.value.length == stringLength) {
		if (_GolfId_allowCursorMove) {
			try {
				objUrs2.focus();
			} catch (e) { }
		}
	}

	if (objUrs1.value.length == 1) {
		_GolfId_allowCursorMove = true
	}
}

function GolfId_allowFocus() {
	_GolfId_allowCursorMove = false
}

function GBParseInt(value) {
	return parseInt(value, 10)
}



/* CUSTOM CONTROLS */
function GBDropDown(ControlId, OptionId, OptionText, OptionValue) {
	this.ControlId = ControlId;
	this.OptionId = OptionId;
	this.OptionText = OptionText;
	this.OptionValue = OptionValue;
}

GBDropDown.prototype.debug = function() {
	x = ''
	x += 'ControlId: ' + this.ControlId + '\n';
	x += 'OptionId: ' + this.OptionId + '\n';
	x += 'OptionText: ' + this.OptionText + '\n';
	x += 'OptionValue: ' + this.OptionValue + '\n';

	alert(x)
}

function GBDropDown_SetSelection(ControlId, OptionId, OptionText, OptionValue) {

	// is it a change - else quit
	if (getObj('GBDropDown_SelectedOption_' + ControlId).value == OptionValue) return;

	getObj('GBDropDown_TextLabel_' + ControlId).innerHTML = OptionText;
	getObj('GBDropDown_SelectedOption_' + ControlId).value = OptionValue;

	// reset selection
	_itemCount = getObj('GBDropDown_DropPanel_' + ControlId).getAttribute('numberOfItems')
	for (var _optionCounter = 0; _optionCounter < _itemCount; _optionCounter++) {
		getObj('GBDropDown_Option' + _optionCounter + '_' + ControlId).className = 'ContextMenuItem';
	}

	getObj('GBDropDown_Option' + OptionId + '_' + ControlId).className = 'ContextMenuItem ContextMenuItem-Selected';

	GBDropDown_OnSelectionChange(new GBDropDown(ControlId, OptionId, OptionText, OptionValue))
}

function GBDropDown_OnSelectionChange(/*GBDropDown*/sender) { };


function bookingWin(url, isCompany) {
	var _h = 400
	if (screen && !isCompany) {
		if (screen.height > 600) {
			_h = 600
		}
	}

	openWindow(url + '&time=' + cc.dateTimeToText(new Date()) + '&height=' + _h, 'bookingWin', 750, _h, 'yes', '');
}

function toggleDisplay(strClientId) {
	var coll = document.getElementsByName(strClientId);
	if (coll.length == 0) { alert('Object (' + strClientId + ') was not found on the page!'); return false };

	for (i = 0; i < coll.length; i++) {
		theObj = coll[i];
		if (theObj.style.display == 'none') {
			theObj.style.display = '';
			theObj.style.visibility = 'visible';
		}
		else {
			theObj.style.display = 'none';
			theObj.style.visibility = 'hidden';
		}
	}
}

function showTerms(Mode) {
	switch (Mode) {
		case 'teetime':
			window.open('http://help.golf.se/default.aspx?pageId=556');
			break;
		case 'membercard':
			window.open('http://help.golf.se/default.aspx?pageId=557');
			break;
	}
}


function RegisterClientChange() {
	this.RegisterChanges = true;

	this._hasChanges = false;
	this._monitorFields = [];
}

RegisterClientChange.prototype.Register = function(obj) {
	if (!this.RegisterChanges) return;

	this._hasChanges = false; // reset the flag

	//var _monitorFields = [];

	if (!this._monitorFields.exists(obj.Name, 'Name')) this._monitorFields.add(obj);

	for (var iField = 0; iField < this._monitorFields.length; iField++) {
		_mf = this._monitorFields[iField];
		x = String.format('getObj(\'{0}\').{1}', _mf.Name, _mf.PropertyToCheck);
		_newValue = eval(x)
		if (_mf.OrgValue != _newValue) {
			this._hasChanges = true;
		}
	}

	this.OnChange();
}

RegisterClientChange.prototype.HasChanges = function() {
	return this._hasChanges
}

RegisterClientChange.prototype.OnChange = function() { }

function fieldOjb(name, orgvalue, newvalue, propertyToCheck) {
	this.Name = name;
	this.OrgValue = orgvalue;
	this.NewValue = (newvalue != 'undefined') ? newvalue : null;
	this.PropertyToCheck = (propertyToCheck == 'undefined' || propertyToCheck == null) ? 'value' : propertyToCheck;
}

function myWindow(width, height) {
	this.width = width;
	this.height = height;
}
function GetWindowSize() {
	var myWidth = 0, myHeight = 0;
	if (typeof (window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return new myWindow(myWidth, myHeight);
}


/* .net hacks */
function ASPNET_SetUniqueRadioButton(nameregex, current) {
	re = new RegExp(nameregex);
	frm = document.forms['aspnetForm']
	for (i = 0; i < frm.elements.length; i++) {

		elm = frm.elements[i]

		if (elm.type == 'radio') {
			if (re.test(elm.name)) {
				elm.checked = false;
			}
		}
	}
	current.checked = true;
}

function GBAttachEvent(sEvent, sPointer) {
	moz_event = ''
	switch (sEvent) {
		case 'onload': moz_event = 'load'; break;
		default: moz_event = sEvent.replace('on', '')
	}
	objToAddEventListnerTo = 'window';
	if (sEvent == 'onkeydown') objToAddEventListnerTo = 'document';

	if (window.addEventListener) { // Mozilla, Netscape, Firefox
		eval(objToAddEventListnerTo + '.addEventListener(\'' + moz_event + '\',' + sPointer + ',false);');
	} else { // IE
		eval(objToAddEventListnerTo + '.attachEvent(\'' + sEvent + '\',' + sPointer + ')');
	}
}

function GolfSEPasswordValidator(strClientId, strErrorText) {
	this.clientId = strClientId
	this.errorText = strErrorText
}

GolfSEPasswordValidator.prototype.validate = function() {

	/*
	---------------------------------
	validate the password
	valid format: 4 digits
	valid format: min. 6 characters, letters a-z, upper and lower case + 0-9.
	must contain at least two digits
	Example: aBc03F
	*/
	var _pwdValue = getFormField(this.clientId)
	if (this.testValue == _pwdValue) return true

	var _integerCount = 0

	if (_regExp(this, /^\d{4}$/)) {
		return true
	}

	if (_regExp(this, /^[a-zA-Z0-9]{6,}$/)) {
		// The RegExp format was valid now test if the password
		// contains at least two digits
		for (var i = 0; i < _pwdValue.length; i++) {
			if (!isNaN(_pwdValue.substring(i, i + 1))) {
				_integerCount++
			}
		}
		if (_integerCount >= 2) return true
	}

	return false
}

function GolfSEPasswordValidator_Facade(source, arguments) {

	var val = new GolfSEPasswordValidator(source.controltovalidate, source.errormessage)
	cv.add(val)
	if (!cv.validate()) {
		cv.render()
		arguments.IsValid = false
	} else {
		arguments.IsValid = true
	}

	getObj(source.id).style.display = 'none'
}
