function ShowFancyBox(strURL, windowName, width, height, title, onClosed)
{
    if (width == '')
        width = '75%';
    if (height == '')
        height = '75%';
    
    if (onClosed)
        $('#FancyBoxLink_id').fancybox({'width':width,'height':height, 'href': strURL, 'type': 'iframe', 'onClosed' : eval(onClosed)}); 
    else
        $('#FancyBoxLink_id').fancybox({'width':width,'height':height, 'href': strURL, 'type': 'iframe'}); 
        
    if (title)
        $('#FancyBoxLink_id').attr("title", title);; 

    $('#FancyBoxLink_id').trigger('click');
}

function ShowFancyBoxPicture(strURL, title)
{
    $('#FancyBoxLink_id').fancybox({'href': strURL}); 
        
    if (title)
        $('#FancyBoxLink_id').attr("title", title);; 

    $('#FancyBoxLink_id').trigger('click');
}

function Nethzah_CloseWindow()
{
    window.close();
}

function GlobalUtility_GetSelectedOption(ctlSelect)
{
    var strSelected = '|';
    for (i=0; i<ctlSelect.options.length; i++) 
    {
        if (ctlSelect.options[i].selected) 
        {
            strSelected = ctlSelect.options[i].value + "|" + ctlSelect.options[i].text;
        }
    }
    return strSelected.split("|");
}
function GlobalUtility_GetSelectedOptionValue(ctlSelect)
{
    var aSelectedOption = GlobalUtility_GetSelectedOption(ctlSelect);
    if (aSelectedOption.length > 0)
        return aSelectedOption[0];
    else
        return "";
}
function GlobalUtility_GetSelectedOptionText(ctlSelect)
{
    var aSelectedOption = GlobalUtility_GetSelectedOption(ctlSelect);
    if (aSelectedOption.length > 1)
        return aSelectedOption[1];
    else
        return "";
}

function GlobalUtility_AddSelectedOptionItem(ctlFrom, ctlTo)
{
    var intLastSelected = -1;
    for (var i = ctlFrom.length - 1; i>=0; i--)
    {
        if (ctlFrom.options[i].selected) 
        {
            GlobalUtility_AddOptionItem(ctlTo, ctlFrom.options[i].value, ctlFrom.options[i].text);
            ctlFrom.remove(i);
            
            intLastSelected = i;
        }
    }

    if ((ctlFrom.length > 0) && (intLastSelected != -1) && (ctlFrom.length > intLastSelected))
        ctlFrom.options[intLastSelected].selected = true;
}

function GlobalUtility_GetAllOptionValues(ctlSelect)
{
    var strItems = "";
    for (var i = ctlSelect.length - 1; i>=0; i--)
    {
        if (strItems == '')
            strItems = ctlSelect.options[i].value;
        else
            strItems += "," + ctlSelect.options[i].value;
    }
    return strItems;
}

function GlobalUtility_AddOptionItem(sel, value, text)
{
    var opt = document.createElement('option');
    opt.text = text;
    opt.value = value;
    sel.add(opt);
}

function JS_GetObjectTop(refobj) 
{
	var y = 0;
	if (refobj)
	{
		if (refobj.offsetTop)
			y = refobj.offsetTop;
		var obj = refobj.offsetParent;
		while (obj != null) {
			y += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	return y;
}

function JS_GetObjectLeft(refobj) 
{
	var x = 0;
	if (refobj)
	{		
		if (refobj.offsetLeft)
			x = refobj.offsetLeft;
		if (refobj && typeof(refobj.parentElement) != 'undefined' && refobj.offsetParent)
		{
		    var obj = refobj.offsetParent;
		    while (obj) 
		    {
			    x += obj.offsetLeft;
			    obj = obj.offsetParent;
		    }
		}
	}
	return x;
}

function InstantASP_Bookmark(url, title)
{
    if (window.sidebar) // firefox
	    window.sidebar.addPanel(title, url, "");
    else if(window.opera && window.print){ // opera
	    var elem = document.createElement('a');
	    elem.setAttribute('href',url);
	    elem.setAttribute('title',title);
	    elem.setAttribute('rel','sidebar');
	    elem.click();
    } 
    else if(document.all)// ie
	    window.external.AddFavorite(url, title);


//    if(window.sidebar) 
//        window.sidebar.addPanel(title, url,""); 
//    else if( document.all ) 
//        window.external.AddFavorite( url, title);
//    else if( window.opera && window.print ) 
//        alert("Sorry! Your browser doesn't support this function."); 
}

function Motif_GetServerUrl()
{
	return window.location.protocol + "//" + window.location.hostname 
}

function MLX_TimeoutManager(myID, functionName)
{
    //public fields
    this.id = myID;
    this.functionName = functionName;
    this.timeoutRetried = 0;
    this.maxTimeoutTries = 20;                
    this.requiredElements = new Array();    //Will test for the existence of these elements before calling the function
    
    //public functions
    this.setTimeout = function(delay, isNotFirst)
    {
        this.functionName = this.functionName.replace("()", "");
        if (isNotFirst)
            this.timeoutRetried++
        else
            this.timeoutRetried = 0;
   
        if (this.timeoutRetried > this.maxTimeoutTries)
            return;
   
        //Trace info
        if (MLX_TraceInstanceExists())
        {
            _MLX_TraceInstance.addFunc(this.id + ".setTimeout");
            _MLX_TraceInstance.addArg("isNotFirst", isNotFirst);
            _MLX_TraceInstance.addInfo("timeoutRetried = " + this.timeoutRetried);
        }
               
        delay += (this.timeoutRetried) * 100;
        if (this.isReady())
        {
            setTimeout(this.functionName + '()', delay)
        }
        else
            setTimeout(this.id + ".setTimeout(" + delay + ", true)", delay);
    }
    
    this.isReady = function()
    {
        //debugger;
        var func = null, el = null;
        try {func = eval(this.functionName)}
        catch(e){}
   
        if (func
            &&
            (
                typeof(func) == 'function' 
                || 
                (this.functionName.indexOf(".") != -1 && typeof(func) == 'object')
            ))
        {
            // Check if the required elements exist also
            for (var i = 0; i < this.requiredElements.length; i++)
            {
                try {el = eval(this.requiredElements[i])}
                catch(e){}
                
                if (typeof(el) == 'undefined' || !el)
                    return false;
            }
            
            //Trace info
            if (MLX_TraceInstanceExists())
            {
                _MLX_TraceInstance.addFunc(this.id + ".setTimeout");
                _MLX_TraceInstance.addInfo("<i>" + this.functionName + "</i> is ready");
                _MLX_TraceInstance.addInfo("typeof(func) = " + typeof(func));
            }
            
            return true;
        }
        
        return false;
    }
}
function MLX_TraceInstanceExists()
{
    return typeof(_MLX_TraceInstance) == "object";
}

function Motif_URLEncode(plaintext)
{
	return encodeURIComponent(plaintext);
}

function Motif_GetArgs(s)
{
	//returns name/value objects from a querystring
	var args = new Object()
	if(s.indexOf("?") == -1)
		var query = s;
	else
		var query = s.substring(s.indexOf("?")+1);
	var pairs = query.split("&");

	for(var i=0;i<pairs.length;i++)
	{
		var pos = pairs[i].indexOf("=");
		if (pos == -1) continue;
		var argname = pairs[i].substring(0,pos).toLowerCase();
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}
	args.count = pairs.length;
	return args;
}

$(function(){
	//all hover and click logic for buttons
	$(".fg-button:not(.ui-state-disabled)")
	.hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
		}
	)
	.mousedown(function(){
			$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
			if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
			else { $(this).addClass("ui-state-active"); }	
	})
	.mouseup(function(){
		if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
			$(this).removeClass("ui-state-active");
		}
	});
});


function MotifSoft_OpenNewWindow(strURL, windowName, width, height)
{
    if (windowName == '')
        windowName = 'NewWindow';
        
    if (width == '')
        width = 800;
    if (height == '')
        height = 600;

    window.open(strURL, windowName, 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=' + width + ',height=' + height + ',top=200,left=200');
}

function Motif_OpenWindow(strURL, windowName, widthPec, heightPec)
{
    if (windowName == '')
        windowName = 'NewWindow';
        
    if (widthPec == '')
        widthPec = .8;
    else
        widthPec = widthPec / 100;
    if (heightPec == '')
        heightPec = .6;
    else
        heightPec = heightPec / 100;

 	var width	= parseInt(screen.width * widthPec);
 	var height = parseInt(screen.height* heightPec);
 	var WindowTop	= parseInt((screen.height-height)/2);
 	var WindowLeft= parseInt((screen.width-width)/2);

    window.open(strURL, windowName, 'fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,addressbar=no,location=no,width=' + width + ',height=' + height + ',top=' + WindowTop + ',left=' + WindowLeft);
}

function KMSViewArticle(intArticleId)
{
    var url = 'ViewArticle.aspx?Id=' + intArticleId;
    Motif_OpenWindow(url, 'KMSViewArticle', '60', '70');
}

// Open Common Windows
function GlobalUtility_KMS_EmailArticle(strURL)
{
    Motif_OpenWindow(strURL, 'EmailArticle', 65, 70);
}
function GlobalUtility_KMS_OpenArticle(strURL)
{
    Motif_OpenWindow(strURL, 'KMSViewArticle', 65, 70);
}
function GlobalUtility_KMS_PrintArticle(strURL)
{
    Motif_OpenWindow(strURL + "&Print=yes", 'KMSPrint', 65, 70);
}
function GlobalUtility_Email_EmailView(strURL)
{
    Motif_OpenWindow(strURL, 'EmailView', 65, 70);
}
function GlobalUtility_EmailQueue_Edit(strURL)
{
    Motif_OpenWindow(strURL, 'EmailQueue_Edit', 65, 70);
}
function GlobalUtility_OpenTemplate(id, ParentTableId, ParentId)
{
    var url = '/Setup/TemplateFolder/TemplateDetailPopup.aspx';
    if (id != '')
        url += '?Id=' + id;
    
    if ((ParentTableId) && (ParentTableId != ''))
        url += '?ParentTableId=' + ParentTableId;
    if ((ParentId) && (ParentId != ''))
        url += '&ParentId=' + ParentId;
        
    Motif_OpenWindow(url, 'EmailTemplate', 65, 70);
}
function GlobalUtility_OpenSelectTemplate()
{
    var strURL = '/Setup/TemplateFolder/SelectTemplate.aspx';
    Motif_OpenWindow(strURL, 'SelectTemplate', 65, 70);
}

function Global_ShowNotification(msg)
{
    $.jGrowl(msg);
}

function createCookie(name, value, days)
{
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return null;
}

function eraseCookie(name)
{
  createCookie(name, "", -1);
}

function GetDateDiff(date1,date2,interval) { 
    var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7; 
    date1 = new Date(date1); 
    date2 = new Date(date2); 
    var timediff = date2 - date1; 
    if (isNaN(timediff)) return NaN; 
    switch (interval) { 
        case "years": return date2.getFullYear() - date1.getFullYear(); 
        case "months": return ( 
            ( date2.getFullYear() * 12 + date2.getMonth() ) 
            - 
            ( date1.getFullYear() * 12 + date1.getMonth() ) 
        ); 
        case "weeks"  : return Math.floor(timediff / week); 
        case "days"   : return Math.floor(timediff / day);  
        case "hours"  : return Math.floor(timediff / hour);  
        case "minutes": return Math.floor(timediff / minute); 
        case "seconds": return Math.floor(timediff / second); 
        default: return undefined; 
    } 
} 

$.ctrl = function(key, callback, args) {
    var isCtrl = false;
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null

        if(e.ctrlKey) isCtrl = true;
        if(e.keyCode == key.charCodeAt(0) && isCtrl) {
            callback.apply(this, args);
            return false;
        }
    }).keyup(function(e) {
        if(e.ctrlKey) isCtrl = false;
    });
};
