var helpObject = new Object; //needed for the quick help
var g_ViewDevelopInfos = false; //Should development information be shown (like toolbars at pop ups?
var hideObjects = new Array();

var mouseX;
var mouseY;
var masterOffsetX = 0;
var masterOffsetY = 0;

//saves the mouse position
function RefreshMousePosition(e) {
    if (!e) {
        if (window.event)
            e = window.event;
        else if(window.Event)
            e = window.Event;
    }
    
    var scrollPosY;
    if (window.pageYOffset)
        scrollPosY = window.pageYOffset
    else if (document.documentElement && document.documentElement.scrollTop)
        scrollPosY = document.documentElement.scrollTop
    else if (document.body)
        scrollPosY = document.body.scrollTop

    var scrollPosX;
    if (window.pageXOffset) 
        scrollPosX = window.pageXOffset
    else if (document.documentElement && document.documentElement.scrollLeft)
        scrollPosX = document.documentElement.scrollLeft
    else if (document.body)
        scrollPosX = document.body.scrollLeft


    if(!IsIE()) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    } 
    else {
        mouseX = e.clientX + scrollPosX;       
        mouseY = e.clientY + scrollPosY;
    }
    
    DoHideOnOut();
}


//assign the mouse move handler, so whenever we move the mouse the latest position will be saved.
document.onmousemove = RefreshMousePosition;

function HideOnOut(obj) {
    hideObjects.push(obj);
}
function DoHideOnOut() {
    var i = 0;
    for (i = 0; i < hideObjects.length; i++) {
        if (hideObjects[i] != null) {
            var x = FindPosX(hideObjects[i]);
            var y = FindPosY(hideObjects[i]);
            
            if (hideObjects[i] != null && 
                (x > GetMouseX() || 
                x + GetWidth(hideObjects[i]) < GetMouseX() ||
                y > GetMouseY() ||
                y + GetHeight(hideObjects[i]) < GetMouseY())) {
                setTimeout("DoTimeOutHide(" + i + ")", 25);
            }
         }
    }
}
function DoTimeOutHide(i) {
    if (hideObjects[i] != null) {
        hideObjects[i].style.visibility = 'hidden';
        hideObjects[i] = null;
    }
}

//gets the x position of the cursor
function GetMouseX() {   
    return mouseX - masterOffsetX;
}


//gets the y position of the cursor
function GetMouseY() {      
    return mouseY - masterOffsetY;
}

//Sets the master offset
function SetMasterOffset(x, y){
    masterOffsetX = x;
    masterOffsetY = y;
}

//for the EworxTabControl
function Tab_Over() { 
    if (!IsIE()) {
        img = document.getElementById("divTabHoverIcon"); 
        img.style.display = "block"; 
        img.style.top = GetMouseY()  - 3 + "px"; 
        img.style.left = GetMouseX() - 20 + "px";
   }
   else {
        img = document.getElementById("divTabHoverIcon"); 
        img.style.display = "block";
        img.style.position = "absolute";
        img.style.top = GetMouseY()  - 3 + "px"; //window.event.y + "px";
        img.style.left = GetMouseX() - 20 + "px";//window.event.x - 20 + "px";        
    }
} 

//for the EworxTabControl
function Tab_Out() { 
    document.getElementById("divTabHoverIcon").style.display = "none"; 
}


//used for timeouts in Atlas calls
function Timeout(result) {
    if (result != null) {
        try {
            var msg= result.get_message();    
            alert("A unexpected timeout has occurred. Please retry: " + msg);
        }
        catch(e) {
        }
    }
}


//used for errors in Atlas calls
function Error(result) {
    if (result != null) {
        try {    
            alert("An unexpected error has occurred: " + result.get_message());
        }
        catch(e) {
        }
    }
}

//gets an element on the document
function GetElement(id) {
    if (!document.getElementById(id)) 
        alert("Object '" + id + "' does not exist on this document.");
    return document.getElementById(id);
}

//opens a popup window
function Popup(url, id, width, height, resizeable) {
    resizeable ? resizeable = "yes" : resizeable = "no";
    var screenLeft = ((screen.width - width) / 2);
    var screenTop = (screen.height - height) / 2;  
    if (g_ViewDevelopInfos)
        var w = window.open(url, id, "toolbar=yes,scrollbars=yes,location=no,status=yes,menubar=yes,resizable=" + resizeable + ",width=" + width + ",height=" + height + ",top=" + screenTop + ",left=" + screenLeft);
    else
        var w = window.open(url, id, "toolbar=no,scrollbars=yes,location=no,status=yes,menubar=no,resizable=" + resizeable + ",width=" + width + ",height=" + height + ",top=" + screenTop + ",left=" + screenLeft);
    if (w)
        w.focus();
    else
        alert("Popup blockiert.");
    return w;
}

//displays the 'please wait' window
function Wait(WaitId) {
    var div = GetElement(WaitId);
    if (IsIE()) { 
        div.style.left = ((document.body.offsetWidth - 300) / 2) + "px";
        div.style.top = ((document.body.offsetHeight - 75) / 2) + "px";
    }
    else { 
        div.style.left = ((window.innerWidth - 250) / 2) + "px";
        div.style.top = ((window.innerHeight - 75) / 2) + "px";
    }
    div.style.display = "inline";
    setTimeout("document.getElementById('imgWait').src = document.getElementById('imgWait').src", 10);
    if (IsIE6()) {
        var selects = document.getElementsByTagName("select");
        var i;
        for (i = 0; i < selects.length; i++) 
            if (Hits(div, selects[i]))
                selects[i].style.display = "none";
    }
}

//hides the 'please wait' window
function HideWait(WaitId) {
    var div = document.getElementById(WaitId);
    if (IsIE6()) {
        selects = document.getElementsByTagName("select");
        var i;
        for (i = 0; i < selects.length; i++) 
            if (Hits(div, selects[i]))
                selects[i].style.display = "inline";
    }
    if (div)
        div.style.display = "none";
}

//hides or displays a div
function ToggleOne(div) {
    div = document.getElementById(div);  
      
    if (div.style.display == "none")
        div.style.display = "block";
    else
        div.style.display = "none";  
}

//waits some time before displaying the quick help
function HelpOver(id, x, y) {
    if (helpObject[id] != 1)
        helpObject[id] = 1;
    setTimeout("DisplayHelp('" + id + "'," + x + ", " + y +")", 500);
}

//displays the quick help
function DisplayHelp(id, x, y) {
    if (helpObject[id] == 1) {
        div = GetElement(id);
        if (div.style.display == "none") {
            img = document.getElementById("img" + id);
            
            GetElement(id).style.display = "block";
            
            if (IsIE6()) {
                selects = document.getElementsByTagName("select");
                helpObject[id + "selects"] = selects;
                var i;
                for (i = 0; i < selects.length; i++) 
                    if (Hits(div, selects[i]))
                        selects[i].style.display = "none";
            }
        }
    }
}

//hides the quick help
function HelpOut(id) {
    helpObject[id] = 0;
   
    var div = GetElement(id);
    if (div.style.display != "none") {
        var mouseX = GetMouseX();
        var mouseY = GetMouseY();

        var divX = FindPosX(div);
        var divY = FindPosY(div);

        if (mouseX - 2 < divX || mouseX > parseInt(divX + GetWidth(div)) || mouseY - 2 < divY || mouseY > parseInt(divY + GetHeight(div))) {
            GetElement(id).style.display = "none";
            selects = helpObject[id + "selects"];
            if (selects != null && IsIE6()) {
                var i;
                for (i = 0; i < selects.length; i++) 
                    selects[i].style.display = "inline";
            }
        }
    }
}

//checks if one object hits another one at any place
function Hits(obj1, obj2) {
    var obj1X = FindPosX(obj1);
    var obj1Y = FindPosY(obj1);
    var obj1Width = GetWidth(obj1);
    var obj1Height = GetHeight(obj1);
    var obj2X = FindPosX(obj2);
    var obj2Y = FindPosY(obj2);
    var obj2Width = GetWidth(obj2);
    var obj2Height = GetHeight(obj2);
    var x;
    var y;
    
    for (x = obj2X; x <= obj2X + obj2Width; x += 2)
        if (x >= obj1X && x <= obj1X + obj1Width)
            //we hit it on the X axis
            for (y = obj2Y; y <= obj2Y + obj2Width; y += 2)
                if (y >= obj1Y && y <= obj1Y + obj1Height)
                    return true;

    return false;
}

//hides or displays a div and writes the value whether or not it's displayed to a hidden field
function ToggleOneAndSet(div, hiddenField) {
    div = document.getElementById(div);  
    hiddenField = document.getElementById(hiddenField);
      
    if (div.style.display == "none") {
        div.style.display = "block";
        hiddenField.value = "ON";
    }
    else {
        div.style.display = "none"; 
        hiddenField.value = "OFF";
    }
}

//hides or displays a div and toggles an image
function ToggleOneAndImage(div, image, onImage, offImage) {
    div = GetElement(div);  
    image = GetElement(image);
      
    if (div.style.display == "none") {
        div.style.display = "block";
        image.src = onImage;
    }
    else {
        div.style.display = "none"; 
        image.src = offImage;
    }
}

//hides or displays a div and toggles two images
function ToggleOneAndTwoImages(div, image1, image2, onImage1, onImage2, offImage1, offImage2) {
    if (GetElement(div).style.display == "none")
        GetElement(image2).src = onImage2;
    else
        GetElement(image2).src = offImage2;

    ToggleOneAndImage(div, image1, onImage1, offImage1);
}

//hides and shows two divs
function Toggle(div1, div2) {
    div1 = document.getElementById(div1);  
    div2 = document.getElementById(div2);  
          
    if (div1.style.display == "none") {
        div1.style.display = "block";
        div2.style.display = "none";  
    }
    else {
        div1.style.display = "none";  
        div2.style.display = "block";
    }
}

//hides and shows two divs
function ToggleByValue(div1, div2, value) {
    div1 = document.getElementById(div1);  
    div2 = document.getElementById(div2);  
          
    if (value) {
        div1.style.display = "block";
        div2.style.display = "none";  
    }
    else {
        div1.style.display = "none";  
        div2.style.display = "block";
    }
}

//hides and shows two divs, and sets a hidden field whether or not the first div is displayed
function ToggleAndSet(div1, div2, hiddenField) {
    div1 = document.getElementById(div1);  
    div2 = document.getElementById(div2);      
    hiddenField = document.getElementById(hiddenField);
      
       
    if (div1.style.display == "none") {
        div1.style.display = "block";
        div2.style.display = "none";        
        hiddenField.value = "OFF";
    }
    else {
        div1.style.display = "none"; 
        div2.style.display = "block";        
        hiddenField.value = "ON";
    }
}

//adds a new item to a listbox
function AddToList(list, text, value) {
    list.length ++;
    list.options[list.length - 1].value = value;
    list.options[list.length - 1].text = text;
}

//removes the currently selected item from a listbox
function RemoveSelectedFromList(list) {
    var selected = list.selectedIndex;
    if (selected >= 0) {
        var replaceTextArray = new Array(list.length - 1);
        var replaceValueArray = new Array(list.length - 1);

        for (var i = 0; i < list.length; i++) {
            if ( i < selected) { replaceTextArray[i] = list.options[i].text; }
            if ( i > selected ) { replaceTextArray[i-1] = list.options[i].text; }
            if ( i < selected) { replaceValueArray[i] = list.options[i].value; }
            if ( i > selected ) { replaceValueArray[i-1] = list.options[i].value; }
        }
        list.length = replaceTextArray.length;  
        for (i = 0; i < replaceTextArray.length; i++) { 
            list.options[i].value = replaceValueArray[i];
            list.options[i].text = replaceTextArray[i];
        }
    }
}


//gets the value how much the user has scrolled to the left
function GetScrollLeft() {
    if (self.pageXOffset) // all except Explorer 
	    return self.pageXOffset;
    else if (document.documentElement && document.documentElement.scrollLeft) // Explorer 6 Strict
	    return document.documentElement.scrollLeft;
    else if (document.body) // all other Explorers
	    return document.body.scrollLeft;
}


//gets the value how much the user has scrolled down
function GetScrollTop() {
    if (self.pageYOffset) // all except Explorer 
	    return self.pageYOffset;
    else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
	    return document.documentElement.scrollTop;
    else if (document.body) // all other Explorers
	    return document.body.scrollTop;
}


//gets the actual width of an object
function GetWidth(obj) {
    if (obj != null)
        return obj.offsetWidth;
    else
        return 0;
}


//gets the actual height of an object
function GetHeight(obj) {
    if (obj != null)
        return obj.offsetHeight;
    else
        return 0;
}

//returns the x-offset of an object
function FindPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
		
	return curleft;
}

//returns the y-offset of an object
function FindPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
		
	return curtop;
}

//drag & drop
var g_elementId = "";
var g_isDragging = false;
var g_hasDragMoved = false;
var g_dragAndDropArgument = ""; //[type]@[elementId]@[index]
var g_dropArgument = "";        //[type]@[elementId]@[index]
var g_dropFunctions = new Array();

//returns if somenthing is dragging at the moment.
function IsDragging() {
    return (g_isDragging && g_hasDragMoved);
}

//starts dragging
function Drag(argument, e) {
    var button;
    if (!e)
        e = window.event;
    if (e && e.which)
        button = e.which;
    else if (e)
        button = e.button;

    if (IsIE() && button != 1)
        return; //we only allow left clicks to start the drag/drop operation.

    g_isDragging = true;
    g_dragAndDropArgument = argument;
    Move();
    document.onselectstart = new Function ("return false;")
    document.onmousemove = function() { Move(); return false; };
    document.onmouseup = function() { ResetDrag(); Move(); return false; }
}

//stops dragging -> Drop
function Drop(onto) {
    if (onto != g_dragAndDropArgument) {
        g_dropArgument = onto;
        document.onselectstart = new Function ("return true;")
        CallDropFunctions(onto)
    }
    ResetDrag();
    return true;
}

//the Drag-Start-Argument. Which element has been dragged.
function GetDragDropArgument() {
    return g_dragAndDropArgument;
}

//resets the drag & Drop mechanism
function ResetDrag() {
    g_isDragging = false;
    g_HasDragMoved = false;
}

//checks if it is a drag or if it is a click
function CheckDragging() {
    g_hasDragMoved = g_isDragging;
    Move();
}

//shows a div while dragging something
function Move() {
    var div = GetElement("divDragAndDrop");
    if (IsDragging()) {
        if (IsIE()) { //Gecko won't display the dragging div, but at least we won't get javascript errors.
            div.style.visibility = "visible";
            div.style.left = window.event.x + document.documentElement.scrollLeft + 1;
            div.style.top = window.event.y + document.documentElement.scrollTop - 11;
        }
    }
    else {
        div.style.visibility = "hidden";
        document.onmousedown = null;
        document.onmouseup = null;
    }
}

function GetDragDropArgumentIndex() {
    return GetDragDropArgumentValue(g_dragAndDropArgument, 2);
}

function GetDragDropArgumentType() {
    return GetDragDropArgumentValue(g_dragAndDropArgument, 0);
}

function GetDragDropArgumentId() {
    return GetDragDropArgumentValue(g_dragAndDropArgument, 1);
}

//Get one value of a drag argument
function GetDragDropArgumentValue(argument, index) {
    var ret;
    var startIndex = 0;
    var endIndex = 0;
    
    for (var i = 0; i < index; i++) {
        startIndex = argument.indexOf("@") + 1;
        argument = argument.substr(startIndex, argument.length - startIndex);        
    }
    
    if (argument.indexOf("@") != argument.lastIndexOf("@")) { //determine the id of the gridview
            g_elementId = argument.substr(argument.indexOf("@") + 1, argument.length - argument.indexOf("@") - 1 - (argument.length - argument.lastIndexOf("@")));
    }
    
    endIndex = argument.substr(startIndex, argument.length - startIndex).indexOf("@") + startIndex;

    if (endIndex <= 0)
        endIndex = argument.length - startIndex;
    
    ret = argument.substring(0, endIndex);
    return ret;
}

//Get the index of the drop argument
function GetDropArgumentValue() {
    return GetDragDropArgumentValue(g_dropArgument, 2);
}

//Get the html type on which is dropped to
function GetDropArgumentType() {
    return GetDragDropArgumentValue(g_dropArgument, 0);
}

//Get the name of the element on which is dropped to
function GetDropArgumentName() {
    return GetDragDropArgumentValue(g_dropArgument, 1);
}

//Register a function, which should be called after dropping
function RegisterDrop(func) {
    g_dropFunctions.push(func);
}

//Calls the drop functions
function CallDropFunctions(argument) {
    for (var i = 0; i < g_dropFunctions.length; i++) {
        var func = g_dropFunctions[i];
        f = new Function(func);
        f();
    }
}

function DragDragDropDiv() {
    document.write("<div id='divDragAndDrop' style='position: absolute; visibility: hidden; background-color:#aaaaaa; width:200px; height:22px;'></div>");
}
DragDragDropDiv();

//Master Functions
var masterResizeFunctions = new Array();

function MasterResize(fncs) {
    var fncs = "";
    for (var i = 0; i < masterResizeFunctions.length; i++) {
        fncs += masterResizeFunctions[i] + ';';
    }
    if (fncs != "") 
        RegisterEvent(window, "onresize", new Function(fncs));
}


function OnLoadResize() {
    var fncs = "";
    for (var i = 0; i < masterResizeFunctions.length; i++) {
        fncs += masterResizeFunctions[i] + ';';
    }
    f = new Function(fncs);
    f();
    return true;
}

function MasterRegisterResizeFunction(functionName) {
    masterResizeFunctions.push(functionName);
}

function MasterUnRegisterResizeFunction(functionName) {
    masterResizeFunctions.pop(functionName);
}

function MasterGetHeight(withScroll) {
    var height = document.documentElement.clientHeight;
    if (withScroll)
        height = document.documentElement.scrollHeight;
    return height;
}

//browser
function IsIE() {
    return (document.all);
}
function IsIE6() {
  var browserVersion = navigator.appVersion;
  var appVer = parseFloat( browserVersion );
  return (IsIE() && appVer >= 6 && appVer < 7);
}

function IsOpera() {
    return (navigator.userAgent.indexOf("Opera") != -1 && document.getElementById);
}

function IsNS() {
    return (document.layers);
}

function IsMozilla() {
    return (!document.all && document.getElementById);
}

function RegisterEvent(obj, method, functionPointer) {
    if (IsIE())
        obj.attachEvent(method, functionPointer);
    else 
        obj.addEventListener(GetEventMethodForGecko(method), functionPointer, false);
}

function UnregisterEvent(obj, method, functionPointer) {
    if (IsIE())
        obj.detachEvent(method, functionPointer);
    else
        obj.removeEventListener(GetEventMethodForGecko(method), functionPointer, false);
}

function GetEventMethodForGecko(method) {
    method = method.toLowerCase();
    if (method == "onmousedown")
        method = "mousedown";
    else if (method == "onmouseup")
        method = "mouseup";    
    else if (method == "onclick")
        method = "click";   
    else if (method == "onmousemove")
        method = "mousemove";   
    else if (method == "onmouseover")
        method = "mouseover";   
    else if (method == "onmouseout")
        method = "mouseout";                                           
    else if (method == "onresize")
        method = "resize"; 
    return method;   
}

//gets a value from the querystring
function GetQuerystring(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable)
            return pair[1];
    } 
    alert('Querystring variable ' + variable + ' not found.');
}

//checks or unchecks all checkboxes
function CheckAllCheckboxes(checked, id){
    var i = 0;
    var checkBox = document.getElementById(id + "_" + i);
    while (checkBox) {
        if (!checkBox.disabled)
            checkBox.checked = checked;
        i++;
        checkBox = document.getElementById(id + "_" + i);
    }
}

//for the navigation
function ToggleNavigation(divName) {
    var div = GetElement("div" + divName);
    if (div.style.display == "none") {
        div.style.display = "block";
        GetElement("img" + divName).src = icon_opened;
    }
    else {
        div.style.display = "none";
        GetElement("img" + divName).src = icon_closed;      
    }
}

//fires a postback when the user presses the enter key
//usage: onkeypress = PostbackOnEnter(event.keyCode, event.which, 'control');
function PostbackOnEnter(ieChar, geckoChar, control) {
    if ((geckoChar && geckoChar == 13) || ieChar == 13)
        __doPostBack(control, "");
    return true;
}

//sets a cookie
function Set_Cookie( name, value, expires, path, domain, secure ) {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
        ( (expires) ? ";expires=" + expires_date.toGMTString() : "" ) + 
        ( (path) ? ";path=" + path : "" ) + 
        ( (domain) ? ";domain=" + domain : "" ) +
        ( (secure) ? ";secure" : "" );
}
// try to get the cookie
function Get_Cookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ ) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split('=');
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if (cookie_name == check_name) {
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 ) {
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if (!b_cookie_found) {
		return null;
	}
}				
// this deletes the cookie when called
function Delete_Cookie(name, path, domain) {
    if (Get_Cookie(name))
        document.cookie = name + "=" +
                            ((path) ? ";path=" + path : "") +
                            ((domain) ? ";domain=" + domain : "" ) +
                            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}	

//hides the given element
function HideElement(elementId) {
    var div = GetElement(elementId);
    
    if(div) {
        div.style.visibility = "hidden";
    }
}
//displays the given element in the middle of the screen
function DisplayElement(elementId) {
    var div = GetElement(elementId);
    
    if(div) {
        var left;
        var top;
        
        if (IsIE()) { 
            left = ((document.body.offsetWidth - div.offsetWidth) / 2);
            top = ((document.body.offsetHeight - div.offsetHeight) / 2);
        }
        else { 
            left = ((window.innerWidth - div.width) / 2);
            top = ((window.innerHeight - div.height) / 2);
        }
        
        if (top < 0)
            top = 50;
            
        div.style.left = left + "px";
        div.style.top = top + "px";
        div.style.display = "inline";
        div.style.visibility = "visible";
    }
}

function GetUrlParamValue(url, paramName) {
    //Returns a parameter value of an url
    if (url == null || url == "" || url == "undefined")
        url = window.location.href;
        
    var retVal = "";
    if (url.indexOf("?") > -1) {
        var qs = url.substr(url.indexOf("?"));
        var params = qs.split("&");
        for (var i = 0; i < params.length; i++) {
            if (params[i].toLowerCase().indexOf(paramName.toLowerCase() + "=") > -1) {
                retVal = params[i].split("=")[1];
                break;
            }
        }
    }
    return retVal;
}

function AddOrReplaceUrlParamValue(url, paramName, newVal) {
    if (url == null || url == "" || url == "undefined")
        url = window.location.href;

    var retVal = "";
    if (url.indexOf("?") > -1) {
        var qs = url.substr(url.indexOf("?"));
        var params = qs.split("&");
        for (var i = 0; i < params.length; i++) {
            if (params[i].toLowerCase().indexOf(paramName.toLowerCase() + "=") > -1) {
                var paramVal = params[i].split("=")[1];
                retVal = url.replace(params[i], paramName + "=" + newVal);
                break;
            }
        }
        //Param not found yet
        if (retVal == "")
            retVal = url + "&" + paramName + "=" + newVal;
    }
    
    //No params available yet
    if (retVal == "")
        retVal = url + "?" + paramName + "=" + newVal;
    return retVal;
}