/* - Some commonly used javascript functions */

/* Global class for constants.
 * Is used statically like this var x = Constants.maxLength;
 */
function _Constants() {
    /* The attribute to use to define length limitation on e.g. textarea.
     */
    this.maxLength = 'maxlength';
}
var Constants = new _Constants();

/*
 * Return the object with id=name 
 */
function Doc_GetElm(name)
{
	return document.getElementById(name);
}

function OtherDoc_GetElm(doc, name)
{
	return doc.getElementById(name);
}

/* Return the window object of an iframe. */
/* Ulrik 20090427 */
function IFrame_GetWindow(iframe)
{
    return iframe.contentWindow;
}


/*
 * Return the 'document'-object of an iframe.
 */
function IFrame_GetDocument(iframe)
{
	if (Object_HasValue(iframe.contentDocument)) {
		// For NS6
		return iframe.contentDocument; 
	} 
	else if (Object_HasValue(iframe.contentWindow)) {
		// For IE5.5 and IE6
		return iframe.contentWindow.document;
		
	} 
	else if (Object_HasValue(iframe.document)) {
		// For IE5
		return iframe.document;
	} 
	else 
		alert("Couldn't access the document of an iframe!");
}

/*
 * Return the document belonging to an iframe by the name of "name"
 */
function Doc_GetFrameDocument(name)
{
	// Extract the frame itself..
	// This should eventually work a bit differently
	var frame = Doc_GetElm(name);
	
	// Make sure we actually got a frame.
	if (!Object_HasValue(frame))
		return null;
		
	// And return the document-reference
	return IFrame_GetDocument(frame);
}

/* Return the window belonging to an iframe by the id of ID. */
function Doc_GetFrameWindow(name)
{
    var frame = Doc_GetElm(name);
    if (!Object_HasValue(frame)) return null;
    return IFrame_GetWindow(frame);
}

/*
 * Return true if an object is defined and has a value
 */
function Object_HasValue(object)
{
	if (typeof(object) != "undefined" && object != null)
		return true;
	else
		return false;
}

/*
 * Trim a string by removing leading and trailing whitespaces.
 */
function String_Trim(str)
{
	// setup a variable to modify
	var returnStr = str;
	
	// Iterate through all leading and trailing whitespace.
	while (returnStr.substring(0, 1) == " ")
		returnStr = returnStr.substring(1, returnStr.length);
		
	while (returnStr.substring(returnStr.length - 1, returnStr.length) == " ")
		returnStr = returnStr.substring(0, returnStr.length-1);   
		
	// and return the result
	return returnStr;
}

/*
 * Return true if an object has a value as a string
 */
function String_HasValue(obj)
{
	// Make sure it's not a null-reference or an undefined
	// reference
	if (!Object_HasValue(obj))
		return false;
	
	// Extract the string from the object
	var str = String_Trim(obj.toString());

	// Make sure we have a > 0-length string
	if (str.length != 0 && str != "")
		return true;
	else 
		return false;
}


/* 
 *	Given a GET-request, add a query-parameter named param with value 
 *	and return the new request.
 */
function addQueryParam(url, param, value) {
    if (!String_HasValue(url))
        return null;
        
    if (url.indexOf("showDetails") >= 0)
        var x = 0;
    
    var tempUrl = url;
    var urlAnchor;
    
    if (url.indexOf("#") >= 0) {
        urlAnchor = url.split("#");
        tempUrl = urlAnchor[0];
    }

    //Strip trailing & if one exist.
    if (tempUrl.length > 1 && tempUrl.charAt(tempUrl.length - 1) == '&')
        tempUrl = tempUrl.substring(0, tempUrl.length - 1);
    
	if (url.indexOf("?") != -1)
		tempUrl += "&" + param + "=" + value;
	else
		tempUrl += "?" + param + "=" + value;
		
	if (isArray(urlAnchor) && urlAnchor.length >= 2)
	    tempUrl += "&#" + urlAnchor[1];
	
	return tempUrl;
}

/* Changes a parameter in the given url or adds the parameter if it does not exist.
 */
function setQueryParam(url, param, value) {
    if (!String_HasValue(url))
        return null;
        
    if (url.indexOf(param + "=") == -1) {
        return addQueryParam(url, param, value);
    }
    else if (!String_HasValue(value)) {
        return remQueryParam(url, param);
    }
    
    var anchor = "";
    
    if (url.indexOf("#") >= 0) {
        var urlAndAnchor = url.split("#");
        url = urlAndAnchor[0];
        anchor = "&#" + urlAndAnchor[1];
    }
    
    //Strip trailing & if one exist.
    if (url.length > 1 && url.charAt(url.length - 1) == '&')
        url = url.substring(0, url.length - 1);
    
    var urlAndQuery = url.split("?"); //Should we check that we only get an array with two elems here?
    var params = urlAndQuery[1].split("&"); //Splits the query part.

    for (var i = 0; i < params.length; i++) {
        if (params[i].indexOf(param + "=") != -1) {
            //Change the value and stop.
            params[i] = param + "=" + value;
            break;
        }
    }
    
    return urlAndQuery[0] + "?" + params.join("&") + anchor;
}

/* Gets the value of a parameter in the specified url.
 */
function getQueryParam(url, param) {
    if (!String_HasValue(url))
        return null;
    
    url = url.split("#")[0]; //Strip anchor (if any).
    
    if (url.indexOf(param + "=") == -1) {
        return null;
    }
    
    var params = url.split("?")[1].split("&");
    
    for (var i = 0; i < params.length; i++) {
        if (params[i].indexOf(param + "=") != -1) {
            return params[i].split("=")[1];
        }
    }
    
}

/*
 *	Given a GET-request, remove any existing query-parameters named param
 *	from teh request.
 */
function remQueryParam(url, param) {
    if (!String_HasValue(url))
        return null;
	
	// - 1 includes '&' or '?'
	var paramStart = url.indexOf(param + "=") - 1;
	
	if (paramStart == -1)
		return url;
		
	/* Okay, so the parameter is there. But is it at the end? */ 
	var paramEnd = url.indexOf("&", paramStart + 1);
	
	// Just remove everything after paramStart
	if (paramEnd == -1)
		return url.substring(0, paramStart);
	else
	{
		// only remove parts.
		return url.substring(0, paramStart) + url.substring(paramEnd);
	}
}

/* Finds the default selection of a select html element.
 *
 * Copyright 2007 ScanRate Financial Systems A/S
 * Henning C. Nielsen 20071004
 */		
function findDefaultSelection(select)
{
	if (select == undefined || select.nodeName != 'SELECT')
	{
		return null;
	}
	
	for (var i = 0; i < select.options.length; i++)
	{
		if (select.options[i].defaultSelected)
		{
			return select.options[i];
		}
	}
	
	return null;
}

/* Makes textareas support the maxlength attribute. Uses the checkMaxLength() function.
 *
 * Copyright 2007 ScanRate Financial Systems A/S
 * Henning C. Nielsen 20071009
 */
function setMaxLength(tagName) {
	var x = document.getElementsByTagName(tagName);
	
	if (x == null) {
	    return;
	}

	for (var i = 0; i < x.length; i++) {
	    /* The onChange attribute is only modified if it's empty!
	     * Otherwise do it yourself in your source!
	     */
		if (x[i].onkeypress == null && x[i].onchange == null && x[i].getAttribute(Constants.maxLength)) {
			x[i].onkeypress = x[i].onchange = checkMaxLength;
			x[i].onkeypress();
		}
	}
}

/* Is used from setMaxLength()
 *
 * Copyright 2007 ScanRate Financial Systems A/S
 * Henning C. Nielsen 20071009
 */
function checkMaxLength() {
	var maxLength = this.getAttribute(Constants.maxLength);
	var currentLength = this.value.length;

	if (currentLength > maxLength) {
        /* Cut extra text.
         */
        this.value = this.value.substring(0, maxLength);
	}
	
	return true;
}

/* Hides a block.
 * 
 * Copyright 2008 ScanRate Financial Systems A/S
 * Henning C. Nielsen 20080813
 */
function hideBlock(elem, sender) {
    if (!this.Object_HasValue(elem)) {
        return false;
    }
    
    elem.style.display = "none";
    
    /* Change anchor to the sender if the sender was specfied.
     */
    if (sender && sender.id) {
        this.document.location = "#" + sender.id;
    }
    
    return true;
}

/* Shows a block and scrolls down to it or to the specified anchor element.
 * 
 * Copyright 2008 ScanRate Financial Systems A/S
 * Henning C. Nielsen 20080813
 */
function showBlock(elem, anchorElem) {
    if (!this.Object_HasValue(elem)) {
        return false
    }
    
    elem.style.display = "inline-block";
    
    if (anchorElem && anchorElem.id) {
        this.document.location = "#" + anchorElem.id;
    }
    
    return true;
}

/* Tries to determine if a block is hidden or not and then hides it if it is visible and shows it
 * if it is hidden.
 *
 * Copyright 2008 ScanRate Financial Systems A/S
 * Henning C. Nielsen 20080813
 */
function toggleBlock(elem, anchorElem, sender) {
    if (!Object_HasValue(elem)) {
        return false;
    }
    
    if (elem.style.display == "none" || elem.style.display == "") {
        this.showBlock(elem, anchorElem);
    }
    else {
        this.hideBlock(elem, sender);
    }
}

/* Add events in IE5+, NS6 and Mozilla(firefox)
 *
 * Copyright 2008 ScanRate Financial Systems A/S
 * Henning C. Nielsen 20080813
 */
function addEvent(elm, evType, fn, useCapture) {

    /* Add the event to the current window by default.
     */
    if (!elm && window) {
        elm = window;
    }

	if (elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		return elm.attachEvent("on"+evType, fn);
	}

	return false;
}

/* Cross-browser function to make the given function run on load.
 *
 * Copyright 2008 ScanRate Financial Systems A/S
 * Henning C. Nielsen 20080813
 */
function addOnLoadEvent(func) {
    if (window.addEventListener)
    {
        window.addEventListener("load", func, false);
    }
    else if (window.attachEvent)
    {
        window.attachEvent("onload", func);
    }
    else if (document.getElementById)
    {
        window.onload = func;
    }
}

/* URLEncode a clear-string. */
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

function isArray(x) {
    if (!x)
        return false;
        
    return x.constructor.toString().indexOf("Array") >= 0;
}

function defaultButton(btn, e)
{
    var cbtn = $("#" + btn);

    // Process on enter key:
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
    {
        // Cancel the default submit:
        e.returnValue = false;
        e.cancel = true;
     
        // Try to get the navigation url.
        var href = $(cbtn).attr("href");
        
        if (typeof(href) == typeof(undefined))
        {
            // If not found, then just click on the button.
            $(cbtn).click();
        }
        else if (href.indexOf("__doPostBack") > 0)
        {
            // This is strange! Firefox (only) trigger the first control 
            // onclick event instead of the post back control event.
            // Reset all onclick events for input controls:
            $("input").each(function (){ this.onclick = ""; });
            
            // If the url is a post back
            // event, then raise the event:
            __doPostBack(btn,'');
        }
        else
        {
            // Default: Redirect to navigation url:
            document.location.href = href;
        }
    }
}
