
function GetLastUrlPart() {
    var urlStrings = document.location.toString().split('/');

    return urlStrings[urlStrings.length - 1];
}

function get_cookie(cookie_name)
{
  var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

  if (results)
    return (unescape(results[2]));
  else
    return null;
}

function queryStringRetrieve(paramName) {
    var queryOnly = window.location.search.substring(1);
    var arrayOfelements = queryOnly.split("&");

    paramName = paramName.toLowerCase();

    for (var cnt = 0; cnt < arrayOfelements.length; cnt++) {
        var valuePair = arrayOfelements[cnt].split("=");
        if (valuePair[0].toLowerCase() == paramName) {
            return valuePair[1];
        }
    }

    return null;
}

function RedirectToSelf() {
    window.location.href = window.location.href;
}

function LoadJsfile(filename, filetype) {
    if (filetype == "js") {
        var fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("src", filename);
    }
    else if (filetype == "css") {
        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    if (typeof fileref != "undefined") {
        document.getElementsByTagName("head")[0].appendChild(fileref);        
    }
}

function ToBoolean(obj) {
    if (obj == 'false' || obj == '0') {
        return false;
    } else {
        return true;
    }
}

function copyText(idHoldText, pageURL) {
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        var copyText = document.getElementById(idHoldText);
        copyText.innerText = pageURL;
        Copied = copyText.createTextRange();
        Copied.execCommand("Copy");
    } else {
        alert('Unable to copy to clipboard');
    }
}

function GetMyParentNode(selectedNode, parentDepth) {
    var currentNode = selectedNode;
    for (var i = 0; i < parentDepth; i++) {
        currentNode = currentNode.parentNode;
    }

    return currentNode;
}
    
/*-----------------------------------------------------------------------------------------------------
Class Detail: 
    To save any keys/values pair in window.top.name, so it persist between redirect within the same page
    
Usage Restriction:
    1.Ensure that [window.top.name] property is not re-set anywhere else in target page [reserve field].
    2.Ensure that <asp:scriptManager> is added in target page.
    ---------------------------------------------------------------------------------------------------
*/
function PersistedPropertyPair() {
    this.pValue = '';
    this.pKey = '';
}
function PersistedPropertyInCurrentWindow() {
    this.setValue = Set_Value;
    this.getValue = Get_Value;
    this.dispose = Dispose_Obj;
    this.keyArray = new Array();
}

function Set_Value(key, value) {
    var foundKey = false;
    if (window.top.name.length > 0 && window.top.name != 'blank') {
        this.keyArray = Sys.Serialization.JavaScriptSerializer.deserialize(window.top.name);
    }
    for (var i = 0; i < this.keyArray.length; i++) {
        if (this.keyArray[i].pKey == key) {
            this.keyArray[i].pValue = value;

            foundKey = true;
            break;
        }
    }

    if (foundKey == false) {
        var item = new PersistedPropertyPair();
        item.pKey = key;
        item.pValue = value;

        try {
            this.keyArray.push(item);
        } catch (e) {
            //just in case, there is some existed garbage strings in window.top.name, so we clear them first
            this.keyArray = new Array();
            this.keyArray.push(item);
        }
    }
    window.top.name = Sys.Serialization.JavaScriptSerializer.serialize(this.keyArray);
}

function Get_Value(key) {
    if (this.keyArray.length == 0 && window.top.name.length > 0 && window.top.name != 'blank') {
        this.keyArray = Sys.Serialization.JavaScriptSerializer.deserialize(window.top.name);
    }
    for (var i = 0; i < this.keyArray.length; i++) {
        if (this.keyArray[i].pKey == key) {
            return this.keyArray[i].pValue 
        }
    }
    
    return 'not found';
}

function Dispose_Obj() {
    this.keyArray = null;
    window.top.name = '';
}
//-------------------------end persist class implementation----------------------------------

function URLEncode(plaintext) {
    var SAFECHARS = "0123456789" + 				// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()"; 				// RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";
    var encoded = "";

    for (var i = 0; i < plaintext.length; i++) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+"; 			// x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode > 255) {
                alert("Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted.");
                encoded += "+";
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    } // for

    return encoded;
}

function URLDecode(encoded) {
    var HEXCHARS = "0123456789ABCDEFabcdef";
    var plaintext = "";
    var i = 0;
    while (i < encoded.length) {
        var ch = encoded.charAt(i);
        if (ch == "+") {
            plaintext += " ";
            i++;
        } else if (ch == "%") {
            if (i < (encoded.length - 2)
					&& HEXCHARS.indexOf(encoded.charAt(i + 1)) != -1
					&& HEXCHARS.indexOf(encoded.charAt(i + 2)) != -1) {
                plaintext += unescape(encoded.substr(i, 3));
                i += 3;
            } else {
                alert('Bad escape combination near ...' + encoded.substr(i));
                plaintext += "%[ERROR]";
                i++;
            }
        } else {
            plaintext += ch;
            i++;
        }
    } // while

    return plaintext;
}

function replaceAllString(str, from, to) {
    var idx = str.indexOf(from);

    while (idx > -1) {
        str = str.replace(from, to);
        idx = str.indexOf(from);
    }

    return str;
}

function ClearMemory() { 
    var allDoms = $('html *');       
    var obj;
    for(var i=allDoms.length-1; i>=0; i--)
    {
        obj = allDoms[i];
        
        if (obj != null && typeof obj != "undefined") {
            try
            {
                $(obj).unbind();
                //$(obj).remove();
                //$(obj).empty();      
            }catch(e)
            {
                //alert(e.toString());
            }
        }
    }   
    
    $(window).unbind();
}

function EndRequestHandler(sender, args) {
    var jsCtrl = JsFindControl('txtScriptToRun');
    var vals = jsCtrl.value;
    if (vals.length > 0) {
        vals = vals.replace('<div>', '');
        vals = vals.replace('</div>', '');
        eval(vals);
        jsCtrl.value = '';
    }
}

function AutoRemoveInvalidUrlCharater(obj) {  
    //obj.value = obj.value.replace(/[\s\*\?\$\%\\|/:<>#&\'\",;]+/g, '').substr(0, 100);    
   obj.value = obj.value.replace(/[\s\*\$\\|<>\'\",;]+/g, '').substr(0, 100); 
}

function AllowNumberOnly(evt)
{
    var e = event || evt; 
    var charCode = e.which || e.keyCode;
     
    if (charCode > 31 && (charCode < 48 || charCode > 57)) { 
        return false; 
    } 
    return true;    
}

var _prefixclientIds = null;
function AddClientId(cid) {
    if (_prefixclientIds == null)
        _prefixclientIds = new Array;

    if (!Array.contains(_prefixclientIds, cid))
        Array.add(_prefixclientIds, cid);
}

function JsFindControl(controlId) {
    var foundControl = null;
    
    if (_prefixclientIds == null) {
        return foundControl;
    }

    if (_prefixclientIds.length > 0) {
        for (var i = 0; i < _prefixclientIds.length; i++) {
            foundControl = $get(_prefixclientIds[i] + "_" + controlId);
            if (foundControl != null)
                break;
        }
    } else {
        foundControl = $get(controlId);
    }

    return foundControl;
}

function FlashIeFirefox() {
    if (FlashDetect.installed) {
        return "FLASH";
    }
    else {
        var userAgentString = navigator.userAgent;
        
        if (userAgentString.indexOf("MSIE") > 0) {
            return "IE";
        }
        else if (userAgentString.indexOf("Firefox") > 0) {
            return "FIREFOX";
        }
        else {
            return "UNKNOWN";
        }
    }
}

function GetFileRevisionIDFromURL(fileURL) {
    var urlParts = fileURL.split('/');

    if (urlParts.length > 1) {
        var filRevisionAndHash = urlParts[urlParts.length - 2].split('_');

        if (filRevisionAndHash.length == 4) {
            return filRevisionAndHash[1];
        }
    }

    return -1;
}

/*function ReleaseMemory(domObj)
{
    if(domObj != null)
    {                
        //$(domObj).unbind('onmouseout');  
        //$(domObj).unbind('onclick');  
        //$(domObj).unbind('onmouseup');  
        //$(domObj).unbind('onmouseenter');  
        //$(domObj).unbind('onmouseleave');  
        //$(domObj).unbind('onmousedown');
        //$(domObj).unbind('onmouseover');                
        $(domObj).remove();
    }
    var domWithEvents = $("div[onmouseout], span[onmouseout], td[onmouseout], tr[onmouseout], div[onclick], span[onclick], td[onclick], tr[onclick], div[onmouseup], span[onmouseup], td[onmouseup], tr[onmouseup], div[onmouseenter], span[onmouseenter], td[onmouseenter], tr[onmouseenter], div[onmouseleave], span[onmouseleave], td[onmouseleave], tr[onmouseleave], div[onmousedown], span[onmousedown], td[onmousedown], tr[onmousedown], div[onmouseover], span[onmouseover], td[onmouseover], tr[onmouseover]");
    for(var i=0; i<domWithEvents.length;  i++)
    {
        //$(domWithEvents[i]).empty();
        $(domWithEvents[i]).unbind('onmouseout');  
        $(domWithEvents[i]).unbind('onclick');  
        $(domWithEvents[i]).unbind('onmouseup');  
        $(domWithEvents[i]).unbind('onmouseenter');  
        $(domWithEvents[i]).unbind('onmouseleave');  
        $(domWithEvents[i]).unbind('onmousedown');  
        $(domWithEvents[i]).unbind('onmouseover');  
    }
}*/

function removeObject(obj) {
    if (obj != null && typeof obj != "undefined") {
        var leakDoms = $(obj).find('*');
        for (var i = leakDoms.length - 1; i >= 0; i--) { 
            $(leakDoms[i]).unbind();
            $(leakDoms[i]).remove();
            $(leakDoms[i]).empty();
        }
        $(obj).unbind();
        $(obj).remove();
        $(obj).empty();
    }
}


/*---Memory Leaking Area Class---*/
function MemoryLeakCleanUp() {
    this._leakDoms = new Array();
}

MemoryLeakCleanUp.prototype = {

    addLeakDom: function (domId) {
        if (!Array.contains(this._leakDoms, domId))
        {
            Array.add(this._leakDoms, domId);
        }
    },

    clearMemory: function () {
        if(this._leakDoms != null)
        {
            var obj;
            
            for(var i=this._leakDoms.length - 1; i>=0; i--)
            {
                obj = $(this._leakDoms[i]);
                if (obj != null && typeof obj != "undefined") {                
                    var leakDoms = $(obj).find('*');
                    for (var i = leakDoms.length - 1; i >= 0; i--) {
                        $(leakDoms[i]).unbind();
                        //$(leakDoms[i]).remove();
                        //$(leakDoms[i]).empty();
                    }
                    
                    $(obj).unbind();
                    //$(obj).remove();
                    //$(obj).empty();
                }
            }
        }
    }
}
/*---Memory Leaking Area---*/


function addEventScript(elm, evType, fn, useCapture) {
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.attachEvent) {
        var r = elm.attachEvent("on" + evType, fn);
        return r;
    }
    else {
        elm["on" + evType] = fn;
    }
}

function removeEventScript(obj, type, fn) {
    try
    {
        if (obj.removeEventListener) {
            obj.removeEventListener(type, fn, false);
        }
        else if (obj.detachEvent) {
            obj.detachEvent("on" + type, fn);
            obj[type + fn] = null;
            obj["e" + type + fn] = null;
        }
    }catch(e)
    {
        alert(e);
    }
}

function checkAllBoxes(obj, isChecked) {
    var elm = obj.getElementsByTagName("input");
    for (var i = 0; i < elm.length; i++) {
        if ((elm[i].type == "checkbox") && elm[i].disabled == false) {
            elm[i].checked = isChecked;
        }
    }
}

function KeepAlive(interval, handler)
{
    this._interval = interval;
    this._isActive = false;    
    this._handler = handler;     
    this._timer = null;     
    
    document.onmousemove = function(){if(_keepAlive != null) _keepAlive.ValidateInterval(true);}        
}

KeepAlive.prototype = {

    Tick: function () {
        if(this._isActive)
        {
            if(this._handler != null)
            {
                this._handler();    
                this.StartTicking();                                                     
            }
        }else
        {
            this.StartTicking();       
        }
    },
    
    StartTicking: function(){                   
        this.ValidateInterval(false);        
        this._timer = setTimeout(KeepAliveReTick, this._interval);        
    },
    
    ValidateInterval: function(isActive) {
        this._isActive = isActive;
    },
    
    StopTick: function()
    {
        clearTimeout(this._timer);
    }
}

function KeepAliveReTick()
{
    if(_keepAlive != null) _keepAlive.Tick();    
}

function OpenPage(linktype,link,jsproperties)
{	
	if(linktype == 'BL') {
	    window.open(link, 'BL', '')
	}
	else if(linktype == 'MF') {
		window.location.href= link;
	}
	else if(linktype == 'JS') {
		window.open(link, "QL",  "'" + jsproperties+ "'");
	}
	else if(linktype == 'TP') {
		window.top.location.href=link;
	}
}

function RedirectClick(buttonFullName,dropDownName,buttonName,isExternal)
{
	var dropDownID = buttonFullName.replace('_' + buttonName, '_' + dropDownName);
	var dropDown = document.getElementById(dropDownID);
	var selection = dropDown.options[dropDown.selectedIndex].value;
	
	if (selection != 0)
	{
		var optionsArray = selection.split('|');
		var linkType = optionsArray[1];
		var link = optionsArray[2];
		
		if (linkType == 'BL')
		{
            window.open(link);
        }
        else if (linkType == 'MF')
        {
            window.location.href = link;
        }
        else if (linkType == 'JS')
        {
        var jsproperties = optionsArray[3]
        		window.open(link, "QL",  "'" + jsproperties+ "'");
			//window.open(link);
        }            
        else if (linkType == 'TP')
        {
			if (isExternal == 1)
			{
				window.parent.location.href = link;
			}
			else
			{
				window.top.location.href = link;
			}
        }
	}
}

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent)
        while (1) {
        curleft += obj.offsetLeft;
        if (!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent)
        while (1) {
        curtop += obj.offsetTop;
        if (!obj.offsetParent)
            break;
        obj = obj.offsetParent;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;

}

function SilverLightInstalled() 
{
	var browser = navigator.appName;
	var silverlightInstalled = false;

	if (browser == 'Microsoft Internet Explorer')
	{
		try 
		{
			var slControl = new ActiveXObject('AgControl.AgControl');
			silverlightInstalled = true;
		}
		catch (e) 
		{
			// Error. Silverlight not installed.
		}
	}
	else 
	{
		try 
		{
			if (navigator.plugins["Silverlight Plug-In"]) 
			{
				silverlightInstalled = true;
			}
		}
		catch (e) 
		{
			// Error. Silverlight not installed.
		}
	}
	
	return silverlightInstalled;
}

function resetFlashToDisplayOntop() {
    var loc = new String(window.parent.document.location);
    if(loc.indexOf("https://") != -1) {
        $("object").each(function() {
            this.style.visibility = "visible";
        });
    }
    $("embed").each(function() {
        if (this.name.indexOf("adMovieGo") != -1) {
            $(this).attr("wmode", "window");
        }
    });       
}
function setFlashToDisplayUnderneath() {
    $("embed").each(function() {
        this.style.zIndex = 1;
        this.style.display = "block";
        $(this).attr("wmode", "opaque");
    });
    var loc = new String(window.parent.document.location);
    if (loc.indexOf("https://") != -1) {
        $("object").each(function() {
            this.style.visibility = "hidden";
        });
    }
}

function closeDialog(closeAll, updatePopups) {
    if (updatePopups == true) {
        var currentDialog = $(".ui-dialog-content");
        currentDialog.attr("name", (currentDialog.attr("name") + "_closed"));
        currentDialog.attr("id", (currentDialog.attr("id") + "_closed"));
    }

    if (closeAll == true) {
        $(".ui-dialog-content").dialog("close", function() {
            $(this).dialog("destroy").remove();
        });
    }
    else
    {
        $(".ui-dialog-content:last").dialog("close", function() {
            $(this).dialog("destroy").remove();
        });
    }
}

function isSilverlightInstalled() {
    var isSilverlightInstalled = false;
    
    try
    {
        //check on IE
        try
        {
            var slControl = new ActiveXObject('AgControl.AgControl');
            isSilverlightInstalled = true;
        }
        catch (e)
        {
            //either not installed or not IE. Check Firefox
            if ( navigator.plugins["Silverlight Plug-In"] )
            {
                isSilverlightInstalled = true;
            }
        }
    }
    catch (e)
    {
        //we don't want to leak exceptions. However, you may want
        //to add exception tracking code here.
    }
    return isSilverlightInstalled;
}

function isChrome() {
    return Boolean(window.chrome);
}

function jQueryToggleFlashVisibility(arguments) {
    if(toggleFlashVisibility != null) {
        if(arguments[0].modal == true) {
            toggleFlashVisibility.hide();
        } else if (arguments[0] == 'close') {
             var getOverlay = $('div.ui-widget-overlay');
        
            if (getOverlay.length < 2 && $(".ImageEditingComponent").length == 0) {
                toggleFlashVisibility.show();
                setTimeout(function() { $("input.button-reload-content").click(); }, 350); 
            }
        }
    }
}

var toggleFlashVisibility = {
    hide: function() {
        if($('.ui-dialog:visible').length > 0) {
            if($('.ui-dialog-content object').css('visibility') === 'visible') {document.body.className = "hideAllFlash";}
            else {document.body.className = "hideFlash";}
        } else {document.body.className = "hideFlash";}
    }, show: function() {
        document.body.className = "";
    }
}

function resizeImageFromUrl(obj) {
	var imgHeight = $(obj).height();
	var imgWidth = $(obj).width();
    var numValue = "100";

	if (imgHeight > imgWidth) {
		$(obj).height(numValue);
	}
	else {
		$(obj).width(numValue);
	}
}

var currentObj = null;

$.fn.limitChars = function(limit) {
    if (this.length > 0) {
	    this[0].onpaste = function() {currentObj = this; setTimeout(function() {currentObj.value = currentObj.value.substr(0,limit);}, 100);};
    }

	this.keydown(function(e){
		if(this.value.length > limit) {
			this.value = this.value.substr(0,limit);
			return false;
		}
		
		return true;
    });    
}

function AlertDialog(alertTitle, alertMessage) {
    if ($("#dialogAlertBox").length == 0) {
        $("body").append('<div id="dialogAlertBox" class="ModalBackground" style="display: none;"><div class="modalInfoIcon"></div><div class="rightMessage"><div id="dialogAlertBoxMessage"></div></div><br clear="all" /></div>');
    }
    
    $("#dialogAlertBoxMessage").text(alertMessage);
    $("#dialogAlertBox").dialog({
        modal: true,
        title: alertTitle,
        width: 500,
        resizable: false,
        show: "clip",
        hide: "clip",
        zIndex: 9999,
        buttons: {                
            "OK": function(e) {
                $("#dialogAlertBox").dialog("close");
                e.preventDefault();
            }
        }
    });
}

$.fn.limitChars = function(limit) {
	 $(this).keydown(function(e){
		if(this.value.length > limit) {
			this.value = this.value.substr(0,limit);
			return false;
		}
		
		return true;
    });    
}

function resizeImageFromUrl(obj) {
	var imgHeight = $(obj).height();
	var imgWidth = $(obj).width();
    var numValue = "100";

	if (imgHeight > imgWidth) {
		$(obj).height(numValue);
	} else {
		$(obj).width(numValue);
	}
}

//-------------------------search functions----------------------------------

function htmlEncode(value) { return $('<div/>').text(value).html(); }
function htmlDecode(value) { return $('<div/>').html(value).text(); }
    
function EncodeSearchQuery(controlId) {
   var parentControl = controlId.substring(0, controlId.lastIndexOf("_"));
   document.getElementById(parentControl + '_encodedSearchQuery').value = htmlEncode($("#" + parentControl + '_searchQuery').val());
   document.getElementById(parentControl + '_searchQuery').setAttribute("innerText", $("#" + parentControl + '_searchQuery').val());
   document.getElementById(parentControl + '_searchQuery').disabled = true;
   $("input[id$=_searchQuery]").attr("disabled","true");
   return true;
}
