function addEvent(obj, evType, fn)
{ 
  if (obj.addEventListener)
  { 
    obj.addEventListener(evType, fn, false); 
    return true; 
  } 
  else if (obj.attachEvent)
  { 
    var r = obj.attachEvent("on"+evType, fn); 
    return r; 
  } 
  else { return false; } 
}

function mouseLeaves (element, evt) 
{
    if (typeof evt.toElement != 'undefined' && typeof element.contains !='undefined') 
    {
        return !element.contains(evt.toElement);
    }
    else if (typeof evt.relatedTarget != 'undefined' && evt.relatedTarget) 
    {
        return !contains(element, evt.relatedTarget);
    }
}

function contains(container, element) 
{
    while (element) 
    {
        if (container == element) 
        {
            return true;
        }
        element = element.parentNode;
    }
    return false;
}

function hideElement (element) 
{
    if (element.style) 
    {
        element.style.visibility = 'hidden';
    }
}

function showElement (element) 
{
    if (element.style) 
    {
        element.style.visibility = 'visible';
    }
}

function setFocusDelayed(element, delayedTime)
{
    setTimeout(function () { setFocus(element); }, delayedTime);
}

function setFocus(element)
{
    var elementObj = document.getElementById(element);  
    if (elementObj)
    {
        elementObj.setActive()
        try
        {
            elementObj.focus();
        }
        catch(er){ }
    }
}

var CursorPositioning_IsInitialized = false;
function CursorPositioning_InitCaretPositioning(ctrl)
{
    if (CursorPositioning_IsInitialized) return;

    var elementObj = document.getElementById(ctrl);      
    if (elementObj)
    {
        addEvent(elementObj, 'select', function(event) { CursorPositioning_StoreCaret(elementObj); });
        addEvent(elementObj, 'click', function(event) { CursorPositioning_StoreCaret(elementObj); });
        addEvent(elementObj, 'keyup', function(event) { CursorPositioning_StoreCaret(elementObj); });
    }
    
    CursorPositioning_IsInitialized = true;
}

function CursorPositioning_StoreCaret(textEl) 
{
    if (textEl.createTextRange) 
        textEl.caretPos = document.selection.createRange().duplicate();
}

function CursorPositioning_InsertAtCaret(textEl, text) 
{
    if (textEl.createTextRange && textEl.caretPos) 
    {
        var caretPos = textEl.caretPos;
        caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
    }
    else
        textEl.value  = text;
}


function GetCursorPositionForTextField (ctrl) {

	var CaretPos = 0;
	// IE Support
	if (document.selection) {

		setFocus(ctrl.id);
		var Sel = document.selection.createRange();

		Sel.moveStart ('character', -ctrl.value.length);

		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;

	return (CaretPos);

}

function SetCursorPositionForTextFieldToPosition(ctrl, pos)
{

	if(ctrl.setSelectionRange)
	{
		setFocus(ctrl.id);
		ctrl.setSelectionRange(pos,pos);
	}
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

//Note: Used to force postback on control that are ajaxfied
function ForceRealPostBack(eventTarget, eventArgument)
{
    __doPostBack(eventTarget, eventArgument);
}

//Note: If state isn't provided then textbox readonly is removed
function SetTextBoxReadonlyState(obj, state) 
{
    if (state) 
    {
        obj.setAttribute('readonly', state);
    } 
    else 
    {
        obj.removeAttribute('readonly');
    }
}

// external_script.js
function CreateControl(DivID, CLSID, CodeBase, ObjectID, WIDTH, HEIGHT, Style, URL, AUTOSTART, CustomParams)
{
  var d = document.getElementById(DivID);
  d.innerHTML = 
    "<object classid=" + CLSID + " CODEBASE='" + CodeBase + "' id=" + ObjectID + " width=" + WIDTH + " height=" + HEIGHT +" style='" + Style + "'><param name='URL' value=" + URL + "><param name='autoStart' value=" + AUTOSTART + " >" + CustomParams + "</object>";
}


function getIEVersionNumber() 
{
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) 
    {
        return 0;
    }
    else 
    {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}           

function HideCollapsiblePanelExtender(collapsiblePanelBehaviorID)
{
    if (!collapsiblePanelBehaviorID) return;

    var SoftCoCollapsiblePanelExtender = $find(collapsiblePanelBehaviorID);
    if (SoftCoCollapsiblePanelExtender)
    {
        var collapseElement = $get(SoftCoCollapsiblePanelExtender._collapseControlID);

        if (collapseElement)
            collapseElement.click();
    }
}

function ClearTextBoxValueAndStyling(obj)
{
    if (obj)
    {
        obj.value = '';
        obj.style.color = '';
    }
}

function GetRandomNumber()
{
    return Math.floor(Math.random() * 65000);
}



/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

function stopEventPropagation(e)
{
    if (e.stopPropagation)
        e.stopPropagation();
    if (e.preventDefault)
        e.preventDefault();
        
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}

function OpenDialogPopupWindow(url, title, callbackFunction, width, height, retry)
{
    retry = retry - 1;
    var currentWindow = window;
    var popUpWindow = null;
    var wndManager = null;
    do
    {
        var wndManager = null;
        if (currentWindow.GetRadWindowManager)
            wndManager = currentWindow.GetRadWindowManager();

        if (wndManager != null)
        {
            popUpWindow = wndManager.getWindowByName("DialogWindow");
        }
        
        if (currentWindow != window.parent)
            currentWindow = window.parent;
        else
            currentWindow = null;
    } while (popUpWindow == null && currentWindow != null)

    if (popUpWindow == null)
    {
        if (retry > 0)
            setTimeout(function () { OpenDialogPopupWindow(url, title, callbackFunction, width, height, retry); }, 100);
        return;
    }

    if (callbackFunction != null && callbackFunction != '')
        popUpWindow.add_close(callbackFunction);
    popUpWindow.set_title(title);
    popUpWindow.setSize(width, height);
    popUpWindow.setUrl(url);
    popUpWindow.show();
    popUpWindow.center();
    popUpWindow.setActive(true);
    
    setTimeout(function(){popUpWindow.setActive(true);}, 50);
    setTimeout(function(){popUpWindow.setActive(true);}, 150);    
    setTimeout(function(){popUpWindow.setActive(true);}, 2250);  
}

