﻿/*
	GolfBox.Web.UI.Commmon
	Version: 1.0
	
	All rights reserved GolfBox(r)
*/

var allowWindowLeave = false


// OVERWRITE OF GetObject()
function getObject(id) {
	return getObj(id);
}
function GetObject(id) {
	return getObj(id);
}

/* 
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();
}


/* OBJECT EXTENSIONS */
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
		}

		//alert(compareVal_1 +'=='+ compareVal_2)
		if (compareVal_1 == compareVal_2) {
			this.onExist(intLoop);
			return true;
		}
	}
	return false;
}

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
		}
	}
}

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': // days
			iOut = parseInt(number / 86400000);
			if (rounding) iOut += parseInt((number % 86400000) / 43200001);
			break;
		case 'h': case 'H': //hours
			iOut = parseInt(number / 3600000);
			if (rounding) iOut += parseInt((number % 3600000) / 1800001);
			break;
		case 'n': case 'N': // minutes
			iOut = parseInt(number / 60000);
			if (rounding) iOut += parseInt((number % 60000) / 30001);
			break;
		case 's': case 'S': // seconds
			iOut = parseInt(number / 1000);
			if (rounding) iOut += parseInt((number % 1000) / 501);
			break;
		default:

			return null;
	}

	return iOut;
}

Date.prototype.dateAdd = function(datepart, value) {

	_year = this.getFullYear();
	_month = this.getMonth();
	_date = this.getDate();
	_hour = this.getHours();
	_minute = this.getMinutes();
	_seconds = this.getSeconds();

	switch (datepart) {
		case 'y':
			_year = _year + value;
			break;
		case 'm':
			_month = _month + value;
			break
		case 'd':
			_date = _date + value;
			break;
		case 'h':
			_hour = _hour + value;
		case 'n':
			_minute = _minute + value;
			break;
		case 's':
			_seconds = _seconds + value;
			break;
	}

	this.setFullYear(_year);
	this.setMonth(_month);
	this.setDate(_date);
	this.setHours(_hour);
	this.setMinutes(_minute);
	this.setSeconds(_seconds);
}


Date.prototype.toIsoDateTimeString = function () {
	return this.format('yyyymmddThhnnss');
}

Date.prototype.toIsoDateString = function () {
	return this.format('yyyymmdd');
}

Date.prototype.toIsoTimeString = function () {
	return this.format('hhnnss');
}

Date.prototype.format = function(sformat) {
	value = this;
	yy = value.getFullYear();
	yyyy = String.Right('0000' + yy, 4);

	m = value.getMonth();
	m = m + 1
	mm = String.Right('00' + m, 2);

	d = value.getDate();
	dd = String.Right('00' + d, 2);

	h = value.getHours();
	hh = String.Right('00' + h, 2);

	n = value.getMinutes();
	nn = String.Right('00' + n, 2);

	s = value.getSeconds();
	ss = String.Right('00' + s, 2);

	var _tvalue = '';
	_tvalue = sformat;
	_tvalue = _tvalue.replace('yyyy', yyyy);
	_tvalue = _tvalue.replace('mm', mm);
	_tvalue = _tvalue.replace('dd', dd);
	_tvalue = _tvalue.replace('hh', hh);
	_tvalue = _tvalue.replace('nn', nn);
	_tvalue = _tvalue.replace('ss', ss);
	_tvalue = _tvalue.replace('yy', yy);
	_tvalue = _tvalue.replace('m', m);
	_tvalue = _tvalue.replace('d', d);
	_tvalue = _tvalue.replace('h', h);
	_tvalue = _tvalue.replace('n', n);
	_tvalue = _tvalue.replace('s', s);

	return _tvalue;
}


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;
}


String.prototype.trim = function() {
	// Use a regular expression to replace leading and trailing
	// spaces with the empty string
	return this.replace(/(^\s*)|(\s*$)/g, '');
}

String.prototype.format = function() {
	var str = this;
	for (var i = 0; i < arguments.length; i++) {
		var re = new RegExp('\\{' + (i) + '\\}', 'gm');
		str = str.replace(re, arguments[i]);
	}
	return str;
}

String.format = function() {
	if (arguments.length == 0)
		return null;
	var str = arguments[0];
	for (var i = 1; i < arguments.length; i++) {
		var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
		str = str.replace(re, arguments[i]);
	}
	return str;
}

String.Left = function(str, n) {
	if (n <= 0)
		return "";
	else if (n > String(str).length)
		return str;
	else
		return String(str).substring(0, n);
}

String.Right = function(str, n) {
	if (n <= 0)
		return "";
	else if (n > String(str).length)
		return str;
	else {
		var iLen = String(str).length;
		return String(str).substring(iLen, iLen - n);
	}
}



// #######################################
function StringBuilder() {
	this._string = [];
}

StringBuilder.prototype.append = function(value) {

	if (value == null)
		value = '';

	this._string.add(value);
}

StringBuilder.prototype.toString = function() {
	return this._string.join('');
}


function Page() {
};

Page.Lcid = 1030;
Page.Locale = 'da';
Page.CountryIsoCode = 'DK';

Page.GetPageXY = function(elm) {
	var point = { x: 0, y: 0 };

	while (elm) {
		point.x += elm.offsetLeft;
		point.y += elm.offsetTop;
		elm = elm.offsetParent;
	}
	return point;
}

Page.SetPageXY = function(elm, x, y) {

	var parentXY = { x: 0, y: 0 };

	if (elm.offsetParent) {
		parentXY = Page.GetPageXY(elm.offsetParent);
	}

	elm.style.left = (x - parentXY.x) + 'px';
	elm.style.top = (y - parentXY.y) + 'px';
}

Page.GetDateDelimiter = function() {
	switch (Page.Lcid) {
		case 1031: return '.'; break;
		case 1030: return '-'; break;
		case 1044: return '.'; break;
		case 1053: return '-'; break;
		case 1035: return '.'; break;
		case 1061: return '.'; break;
		case 2052: return '-'; break;
		default: return '/'; break;
	}
}

Page.GetLcid = function() {
	return Page.Lcid;
}

/* COOKIES */
Page.SetCookie = function(sName, sValue) {
	var date = new Date();
	date.setDate(date.getDate() + 30);
	document.cookie = sName + '=' + escape(sValue) + '; expires=' + date.toGMTString() + '; path=/;';
}

Page.GetCookie = function(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(new String(aCrumb[1]));
	}
	// a cookie with the requested name does not exist
	return null;
}

Page.GetCookieArray = function(sName, sDel) {
	// cookies are separated by semicolons
	var aCookie = Page.GetCookie(sName);
	if (aCookie != null) {
		return aCookie.split(sDel);
	}

	// a cookie with the requested name does not exist
	return null;
}

Page.DeleteCookie = function(sName) {
	document.cookie = sName + "=''; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}




// #######################################
// MISC

function getObject(strClientId) {
	if (document.getElementById) {
		return (document.getElementById(strClientId)) ? document.getElementById(strClientId) : null;
	} else {
		return (document.all(strClientId)) ? document.all(strClientId) : null;
	}
}

function getObj(strClientId) {
	return getObject(strClientId);
}

function GBParseInt(val) {
	return parseInt(val, 10)
}

/* SET CLIENT FOCUS */
var clientFocus = ''
var clientFocusMode = ''
function setFocus(strClientId, focusMode) {
	clientFocus = strClientId;
	clientFocusMode = (arguments[1]) ? arguments[1] : 'first';
	_runSetFocus();
}

function setFocusOnLoad(strClientId, focusMode) {
	clientFocus = strClientId
	clientFocusMode = (arguments[1]) ? arguments[1] : 'first';
	GBAttachEvent('onload', _runSetFocus);
}

function _runSetFocus() {
	if (!document.getElementById(clientFocus)) {
		return;
	}
	
	if (clientFocus != '') {
		try {
			document.getElementById(clientFocus).focus();
			if (clientFocusMode == 'select') {
				document.getElementById(clientFocus).select();
			}
			if (clientFocusMode == 'first') {
				document.getElementById(clientFocus).focus();
			}
			if (clientFocusMode == 'end') {
				var range = document.getElementById(clientFocus).createTextRange(); // Lav textrange
				range.move('sentence', 1);
				range.select(); // Flyt cursor
			}
		} catch (e) {}
	}
}

/* EVENT HANDLER */
var cmdButton = ""
var cmdButtonDisabled = false
function setCMDButton(btn) {
	cmdButton = btn
}

function doButtonCmd(e) {

	var _event = null;

	if (e) {
		_event = e;
	} else {
	_event = event;
	}

	if (_event.keyCode == 116) { allowWindowLeave = true };
	if (cmdButtonDisabled) { return true }
	if (cmdButton == 'NONE') { return true }

	if ((_event.keyCode == 13 || (_event.keyCode == 78 && _event.altKey)) && event.srcElement.tagName != "TEXTAREA" && event.srcElement.tagName != "SELECT") { //ENTER eller ctrl+højrepil
		if (cmdButton == "") {
			if (document.getElementById("cmdSubmit")) {
				cmdButton = "cmdSubmit"
			}
		}

		if (document.getElementById(cmdButton)) {
			document.getElementById(cmdButton).click()
			cmdButton = ""
		} else { }
	} else if (_event.keyCode == 66 && _event.altKey) { //ctrl+venstrepil
		window.event.returnValue = false
		window.event.cancelBubble = true

		if (cmdButton == "") {
			if (document.getElementById("cmdCancel")) {
				cmdButton = "cmdCancel"
			}
		}

		if (document.getElementById(cmdButton)) {
			document.getElementById(cmdButton).click()
			cmdButton = ""
		} else { }
	}
}

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 (arguments[2]) {
		objToAddEventListnerTo = arguments[2];
	}

	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		eval(objToAddEventListnerTo + '.addEventListener(\''+moz_event+'\','+sPointer+',false);');
	} else { // IE
		eval(objToAddEventListnerTo + '.attachEvent(\''+sEvent+'\','+sPointer+')');
	}
}

//GBAttachEvent('onkeydown', 'doButtonCmd');


var ShortcutMan = {};

ShortcutMan.getEventCode = function(evt) {
	//IE browsers don't pass the event object as an argument, so get them from the window object
	if (!evt)
		var evt = window.event;

	if (evt.keyCode) //on IE use keycode
		var code = evt.keyCode;
	else if (evt.which) //on mozilla use wich
		var code = evt.which;

	// removed by KB, not really sure this does any good...
	/*if (code >= 65 && code <= 90) //let's just use lower case codes
		code = code + 32;*/


	var ctrl = evt.ctrlKey ? 'c' : ''; //is ctrl pressed
	var alt = evt.altKey ? 'a' : ''; //is alt pressed
	var shift = evt.shiftKey ? 's' : '';  //is shift pressed
	return ctrl + alt + shift + code;        //put all the pieces together and return the string
}

//a hash to store the actions in code / action pairs
ShortcutMan.keyShortcuts = {};

ShortcutMan.registerShortcut = function(code, action) {
	//if the code is not in the correct form, do nothing
	if (!/^c?a?s?\d{1,3}$/.test(code))
		return;

	//store the action in the keyshortcut hash
	ShortcutMan.keyShortcuts[code] = action;
}

ShortcutMan.readShortcut = function(evt) {
	//convert the event object in a keyboard shortcut code
	var code = ShortcutMan.getEventCode(evt);

	//if there is an action associated with that keystroke
	if (typeof (ShortcutMan.keyShortcuts[code]) == 'function') {
		//execute it
		ShortcutMan.keyShortcuts[code]();
		//and override the browser default behaviour
		document.defaultAction = false;
	} else //otherwise just tell the browser to keep on what hes doing
		document.defaultAction = true;

	return document.defaultAction;
}

var DBAction = {
    Insert: 1,
    Update: 2,
    Delete: 4,
    Ignore: 8
}

var DBMode = {
    New: 1,
    Updated: 2,
    Deleted: 4,
    DB: 8,
    Unchanged: 16
}

var DBResult = {
    Inserted: 1,
    Updated: 2,
    Deleted: 4,
    NoChange: 8
}

var GolfUnion = {
	Denmark: 1,
	Sweden: 2,
	Norway: 4,
	Finland: 8,
	Estonia: 16,
	Other: 1024
}

var TimeUnit = {
	Minute: 1,
	Hour: 2,
	Day: 4,
	GetUnit: function(interval) {
		switch (interval) {
			case TimeUnit.Minute:
				return 'n';
				break;
			case TimeUnit.Hour:
				return 'h';
				break;
			case TimeUnit.Day:
				return 'd';
				break;
		}
	}
}

var Guid = {
	equals: function(guid1, guid2) {
		var tguid1, tguid2
		tguid1 = guid1.toLowerCase();
		tguid1 = tguid1.replace('{', '');
		tguid1 = tguid1.replace('}', '');

		tguid2 = guid2.toLowerCase();
		tguid2 = tguid2.replace('{', '');
		tguid2 = tguid2.replace('}', '');

		return (tguid1 == tguid2);
	}
}
