﻿/**
 * jQuery.query - Query String Modification and Creation for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/8/13
 *
 * @author Blair Mitchelmore
 * @version 2.1.6
 *
 **/
new function(settings) { 
  // Various Settings
  var $separator = settings.separator || '&';
  var $spaces = settings.spaces === false ? false : true;
  var $suffix = settings.suffix === false ? '' : '[]';
  var $prefix = settings.prefix === false ? false : true;
  var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
  var $numbers = settings.numbers === false ? false : true;
  
  jQuery.query = new function() {
    var is = function(o, t) {
      return o != undefined && o !== null && (!!t ? o.constructor == t : true);
    };
    var parse = function(path) {
      var m, rx = /\[([^[]*)\]/g, match = /^([^[]+?)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
      while (m = rx.exec(match[2])) tokens.push(m[1]);
      return [base, tokens];
    };
    var set = function(target, tokens, value) {
      var o, token = tokens.shift();
      if (typeof target != 'object') target = null;
      if (token === "") {
        if (!target) target = [];
        if (is(target, Array)) {
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        } else if (is(target, Object)) {
          var i = 0;
          while (target[i++] != null);
          target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
        } else {
          target = [];
          target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
        }
      } else if (token && token.match(/^\s*[0-9]+\s*$/)) {
        var index = parseInt(token, 10);
        if (!target) target = [];
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else if (token) {
        var index = token.replace(/^\s*|\s*$/g, "");
        if (!target) target = {};
        if (is(target, Array)) {
          var temp = {};
          for (var i = 0; i < target.length; ++i) {
            temp[i] = target[i];
          }
          target = temp;
        }
        target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
      } else {
        return value;
      }
      return target;
    };
    
    var queryObject = function(a) {
      var self = this;
      self.keys = {};
      
      if (a.queryObject) {
        jQuery.each(a.get(), function(key, val) {
          self.SET(key, val);
        });
      } else {
        jQuery.each(arguments, function() {
          var q = "" + this;
          q = q.replace(/^[?#]/,''); // remove any leading ? || #
          q = q.replace(/[;&]$/,''); // remove any trailing & || ;
          if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
          
          jQuery.each(q.split(/[&;]/), function(){
            var key = decodeURIComponent(this.split('=')[0] || "");
            var val = decodeURIComponent(this.split('=')[1] || "");
            
            if (!key) return;
            
            if ($numbers) {
              if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
                val = parseFloat(val);
              else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
                val = parseInt(val, 10);
            }
            
            val = (!val && val !== 0) ? true : val;
            
            if (val !== false && val !== true && typeof val != 'number')
              val = val;
            
            self.SET(key, val);
          });
        });
      }
      return self;
    };
    
    queryObject.prototype = {
      queryObject: true,
      has: function(key, type) {
        var value = this.get(key);
        return is(value, type);
      },
      GET: function(key) {
        if (!is(key)) return this.keys;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        while (target != null && tokens.length != 0) {
          target = target[tokens.shift()];
        }
        return typeof target == 'number' ? target : target || "";
      },
      get: function(key) {
        var target = this.GET(key);
        if (is(target, Object))
          return jQuery.extend(true, {}, target);
        else if (is(target, Array))
          return target.slice(0);
        return target;
      },
      SET: function(key, val) {
        var value = !is(val) ? null : val;
        var parsed = parse(key), base = parsed[0], tokens = parsed[1];
        var target = this.keys[base];
        this.keys[base] = set(target, tokens.slice(0), value);
        return this;
      },
      set: function(key, val) {
        return this.copy().SET(key, val);
      },
      REMOVE: function(key) {
        return this.SET(key, null).COMPACT();
      },
      remove: function(key) {
        return this.copy().REMOVE(key);
      },
      EMPTY: function() {
        var self = this;
        jQuery.each(self.keys, function(key, value) {
          delete self.keys[key];
        });
        return self;
      },
      load: function(url) {
        var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
        var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
        return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
      },
      empty: function() {
        return this.copy().EMPTY();
      },
      copy: function() {
        return new queryObject(this);
      },
      COMPACT: function() {
        function build(orig) {
          var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
          if (typeof orig == 'object') {
            function add(o, key, value) {
              if (is(o, Array))
                o.push(value);
              else
                o[key] = value;
            }
            jQuery.each(orig, function(key, value) {
              if (!is(value)) return true;
              add(obj, key, build(value));
            });
          }
          return obj;
        }
        this.keys = build(this.keys);
        return this;
      },
      compact: function() {
        return this.copy().COMPACT();
      },
      toString: function() {
        var i = 0, queryString = [], chunks = [], self = this;
        var encode = function(str) {
          str = str + "";
          if ($spaces) str = str.replace(/ /g, "+");
          return encodeURIComponent(str);
        };
        var addFields = function(arr, key, value) {
          if (!is(value) || value === false) return;
          var o = [encode(key)];
          if (value !== true) {
            o.push("=");
            o.push(encode(value));
          }
          arr.push(o.join(""));
        };
        var build = function(obj, base) {
          var newKey = function(key) {
            return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
          };
          jQuery.each(obj, function(key, value) {
            if (typeof value == 'object') 
              build(value, newKey(key));
            else
              addFields(chunks, newKey(key), value);
          });
        };
        
        build(this.keys);
        
        if (chunks.length > 0) queryString.push($hash);
        queryString.push(chunks.join($separator));
        
        return queryString.join("");
      }
    };
    
    return new queryObject(location.search, location.hash);
  };
}(jQuery.query || {}); // Pass in jQuery.query as settings object
/*************************************************************************/


/*  
===============================================================================
WResize is the jQuery plugin for fixing the IE window resize bug
...............................................................................
Copyright 2007 / Andrea Ercolino
-------------------------------------------------------------------------------
LICENSE: http://www.opensource.org/licenses/mit-license.php
WEBSITE: http://noteslog.com/
===============================================================================
*/
(function($) {
    $.fn.wresize = function(f) {
        version = '1.1';
        wresize = { fired: false, width: 0 };

        function resizeOnce() {
            if ($.browser.msie) {
                if (!wresize.fired) {
                    wresize.fired = true;
                }
                else {
                    var version = parseInt($.browser.version, 10);
                    wresize.fired = false;
                    if (version < 7) {
                        return false;
                    }
                    else if (version == 7) {
                        //a vertical resize is fired once, an horizontal resize twice
                        var width = $(window).width();
                        if (width != wresize.width) {
                            wresize.width = width;
                            return false;
                        }
                    }
                }
            }

            return true;
        }

        function handleWResize(e) {
            if (resizeOnce()) {
                return f.apply(this, [e]);
            }
        }

        this.each(function() {
            if (this == window) {
                $(this).resize(handleWResize);
            }
            else {
                $(this).resize(f);
            }
        });

        return this;
    };

})(jQuery);

/*************************************************************************/

function getMaxZ(){
    var maxZ = Math.max.apply(null, $.map($('body > *'), function(e, n) {
        if ($(e).css('position') == 'absolute')
            return parseInt($(e).css('z-index')) || 1;
    }));

    return maxZ;
}

jQuery.fn.currentMousePosition = function(mousePosition) {
    var jsonContainerDivs = $("#[isjsonrendercontainer]");
    
    if (mousePosition !== null && mousePosition !== undefined) {
        $(jsonContainerDivs).data("currentMousePosition", mousePosition);
    }
    else {
        if ($(jsonContainerDivs).data("currentMousePosition") == null || 
            $(jsonContainerDivs).data("currentMousePosition") == undefined) {
            $(jsonContainerDivs).data("currentMousePosition", { X: 0, Y: 0 });
        }
        return $(jsonContainerDivs).data("currentMousePosition");
    }
};

jQuery.fn.lockMousePosition = function() {
    var jsonContainerDiv = $(this).getJsonContainerDiv();
    $(jsonContainerDiv).data("lockedMousePosition", $(jsonContainerDiv).currentMousePosition());
};

jQuery.fn.lockedMousePosition = function() {
    return $(this).getJsonContainerDiv().data("lockedMousePosition");
};

$(document).ready(function() {
    $().mousemove(function(e) {
        $("#[isjsonrendercontainer]").currentMousePosition({ X: e.pageX, Y: e.pageY });
    });
});

jQuery.fn.getJsonContainerDiv = function() {
    var jsonContainerDiv = $(this).parents().andSelf().filter("#[isjsonrendercontainer]:first");
    return jsonContainerDiv;
};

function atl_ToggleDisplay(divId) {
	var div = document.getElementById(divId);
	if (div)
		div.style.display = (div.style.display=='block' ? 'none' : 'block');
	return true;
}
function atl_SwapDisplay(div1Id, div2Id) {
	atl_ToggleDisplay(div1Id);
	atl_ToggleDisplay(div2Id);
	return true;
}
function atl_Go(url,t) {
	if ((t == null) || (t == '')) { t="_self"; }
	window.open(url,t);
}
function atl_PopHelp(url) {
	var win = window.open(url, 'spop', 'left=20,top=20,resizable=yes,scrollbars=yes,width=610,height=620');
}
function atl_PopUp(url, name, features) {
	var win = window.open(url, name, features);
}
var atl_quickhelp_source;
function atl_GetQuickHelpContent(name, setQuickHelpDiv, onQuickHelpError, sourceObject) {
    if (typeof(atl_GetQuickHelpUrl) != "undefined") {
        var wsUrl = atl_GetQuickHelpUrl();
        atl_quickhelp_source = sourceObject;
        $.ajax({
            type: "POST",
            url: wsUrl,
            data: "{'keyName':'" + name + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: setQuickHelpDiv,
            error: onQuickHelpError
        });
    }
}
var atl_HideInvoked = false;
function atl_ShowQuickHelp(event, name) {
    atl_HideInvoked = false;
    var popupDiv = document.getElementById('atl_quickhelp');
    if (popupDiv == null) {
        return;
    }
    var sourceObject;
    if (event.target != null) {
        sourceObject = event.target;
    }
    else {
        if (event.srcElement != null) {
            sourceObject = event.srcElement;
        }
        else {
            return;
        }
    }
    if (!$.jCache.hasItem(name)) {
        atl_GetQuickHelpContent(name, atl_SetQuickHelpDiv, atl_OnQuickHelpError, sourceObject);
    }
    else {
        popupDiv.innerHTML = $.jCache.getItem(name);
        atl_ShowHelpById(sourceObject, popupDiv);
        atl_ShowDivContent(popupDiv);
    }
}
function atl_HideQuickHelp() {
    atl_HideInvoked = true;
    var tempElem = document.getElementById('atl_quickhelp');
    if (tempElem != null) {
        tempElem.style.display = "none";
        tempElem.style.visibility = "hidden";
    }
}
function atl_OnQuickHelpError(result) {
    //alert("Error: " + result.get_message());
}
function atl_SetQuickHelpDiv(result, sourceObject) {
    sourceObject = atl_quickhelp_source;
    if (result != null) {
        result = result.d;
    }
    var popupDiv = document.getElementById('atl_quickhelp');
    if (popupDiv != null && result != null) {
        popupDiv.innerHTML = result.Html;
        atl_ShowHelpById(sourceObject, popupDiv)
        atl_ShowDivContent(popupDiv);
        if (!$.jCache.hasItem(result.Name)) {
            $.jCache.setItem(result.Name, result.Html);
        }
    }
}
function atl_ShowDivContent(div) {
    if (div != null && !atl_HideInvoked) {
        div.style.display = "block";
        div.style.visibility = "visible";
    }
}
function atl_ShowHelpById(obj, helpObj) {
    if (helpObj) {
        var divWidth = 340;
        var offsetLeft = atl_getOffsetLeft(obj);
        var screenWidth = (window.innerWidth) ? window.innerWidth - 25 : document.body.clientWidth;
        if ((offsetLeft + divWidth) > screenWidth) offsetLeft = screenWidth - divWidth;
        newX = offsetLeft;
        var divHeight = helpObj.offsetHeight;
        var offsetTop = atl_ShowHelp(obj) + obj.offsetHeight;
        var screenHeight = (window.innerHeight) ? window.innerHeight - 25 : document.body.clientHeight;
        if ((offsetTop + divHeight) > screenHeight + atl_getScrollY()) offsetTop = atl_ShowHelp(obj) - divHeight;
        newY = offsetTop;
        helpObj.style.top = newY + 'px';
        helpObj.style.left = newX + 'px';
        helpObj.left = newX + 'px';
        helpObj.left = newY + 'px';
    }
}
function atl_ShowHelp(elm) {
    var mOffsetTop = elm.offsetTop;
    var mOffsetParent = elm.offsetParent;
    while (mOffsetParent) {
        mOffsetTop += mOffsetParent.offsetTop;
        mOffsetParent = mOffsetParent.offsetParent;
    }
    return mOffsetTop;
}
function atl_getOffsetLeft(elm) {
    var mOffsetLeft = elm.offsetLeft;
    var mOffsetParent = elm.offsetParent;
    while (mOffsetParent) {
        mOffsetLeft += mOffsetParent.offsetLeft;
        mOffsetParent = mOffsetParent.offsetParent;
    }
    return mOffsetLeft;
}
function atl_getScrollY() {
    var scrOfY = 0;
    if (typeof (window.pageYOffset) == 'number') {
        scrOfY = window.pageYOffset;
    }
    else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
        scrOfY = document.body.scrollTop;
    }
    else if (document.documentElement &&
      (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        scrOfY = document.documentElement.scrollTop;
    }
    return scrOfY;
}
function atlCookieDomain() {
    var hname = window.location.hostname;
    var tldstart = hname.lastIndexOf('.');
    if (tldstart < 0) {
        return '.' + hname;
    }
    else {
        var dname = '';
        if (hname.lastIndexOf('.', tldstart - 1) > -1) {
            dname = hname.substr(hname.lastIndexOf('.', tldstart - 1));
        }
        else {
            dname = '.' + hname;
        }
        return dname;
    }
}
function atlSetMemCookie(name, value, years) {
    var currentDT = new Date();
    var curCookie = name + "=" + value + "; path=/; domain=" + atlCookieDomain();
    document.cookie = curCookie;
}
function atlSetCookie(name, value, years) {
    var currentDT = new Date();
    var expires = new Date(Date.parse(currentDT.getDay() + "/" + currentDT.getMonth() + "/" + (currentDT.getFullYear() + years)));
    var curCookie = name + "=" + value +
      "; expires=" + expires.toGMTString() + "; path=/; domain=" + atlCookieDomain();
    document.cookie = curCookie;
}
function atlReadCookie(name) {
    var cookiecontent = new String();
    if (document.cookie.length > 0) {
        var cookiename = name + '=';
        var cookiebegin = document.cookie.indexOf(cookiename);
        var cookieend = 0;
        if (cookiebegin > -1) {
            cookiebegin += cookiename.length;
            cookieend = document.cookie.indexOf(";", cookiebegin);
            if (cookieend < cookiebegin) {
                cookieend = document.cookie.length;
            }
            cookiecontent = document.cookie.substring(cookiebegin, cookieend);
        }
    }
    return unescape(cookiecontent);
}

Type.registerNamespace("Atlantis");

Atlantis.DynamicForm = function(formId) {
    Atlantis.DynamicForm.initializeBase(this);
    this._formId = formId;
    this._form = $get(this._formId);
}
Atlantis.DynamicForm.prototype = {
    setFormValue: function(keyName, formValue) {
        var input = this._getFormInput(keyName);
        input.value = formValue;
    },

    _getFormInput: function(keyName) {
        var input = null;
        for (var i = 0; i < this._form.length; i++) {
            if (this._form.elements[i].id == keyName) {
                input = this._form.elements[i];
                break;
            }
        }
        if (input == null) {
            var newInput = document.createElement("input");
            newInput.setAttribute("id", keyName);
            newInput.setAttribute("type", "hidden");
            newInput.name = keyName;
            input = newInput;
            this._form.appendChild(input);
        }
        return input;
    },

    submit: function() {
        this._form.submit();
    },

    submitAction: function(action) {
        this._form.action = action;
        this._form.submit();
    }
}

Atlantis.DynamicForm.registerClass("Atlantis.DynamicForm");

function atl_isemailvalid(email) {
    var at = "@";
    var dot = ".";
    var lat = email.indexOf(at);
    var lstr = email.length;
    var ldot = email.indexOf(dot);
    if (email.indexOf(at)==-1){return false;}
    if (email.indexOf(at)==-1 || email.indexOf(at)==0 || email.indexOf(at)==lstr){return false;}
    if (email.indexOf(dot)==-1 || email.indexOf(dot)==0 || email.indexOf(dot)==lstr){return false;}
    if (email.indexOf(at,(lat+1))!=-1){return false;}
    if (email.substring(lat-1,lat)==dot || email.substring(lat+1,lat+2)==dot){return false;}
    if (email.indexOf(dot,(lat+2))==-1){return false;}
    if (email.indexOf(" ")!=-1){return false;}
    return true;
}
function atl_isnoscript(text) {
    var regExInvalidChars = /[<>]+/;
    if (regExInvalidChars.test(text)) {
        return false;
    }
    return true;
}
function atl_textarea_trim(field, maxlength) {
    if (field.value.length <= maxlength) { return; }
    field.value = field.value.substr(0, maxlength);
}
function atl_textarea_canaddchar(field, maxlength) {
    var keyCode = null;
    if (typeof (field.onkeypress.arguments[0]) != 'undefined') {
        keyCode = field.onkeypress.arguments[0].keyCode;
    }
    else {
        if (document.selection.createRange().text.length != 0) { return true; }
        var keyCode = event.keyCode;
    }
    var allowedKeys = new Array(8, 37, 38, 39, 40, 46);
    for (var x = 0; x < allowedKeys.length; x++) {
        if (allowedKeys[x] == keyCode) { return true; }
    }
    if (field.value.length < maxlength) { return true; }
    return false;
}
(function(jQuery) {
    this.version = '(beta)(0.0.1)';
    this.maxSize = 10;
    this.keys = new Array();
    this.cache_length = 0;
    this.items = new Array();
    this.setItem = function(pKey, pValue) {
        if (typeof (pValue) != 'undefined') {
            if (typeof (this.items[pKey]) == 'undefined') {
                this.cache_length++;
            }

            this.keys.push(pKey);
            this.items[pKey] = pValue;

            if (this.cache_length > this.maxSize) {
                this.removeOldestItem();
            }
        }
        return pValue;
    }
    this.removeItem = function(pKey) {
        var tmp;
        if (typeof (this.items[pKey]) != 'undefined') {
            this.cache_length--;
            var tmp = this.items[pKey];
            delete this.items[pKey];
        }

        return tmp;
    }
    this.getItem = function(pKey) {
        return this.items[pKey];
    }
    this.hasItem = function(pKey) {
        return typeof (this.items[pKey]) != 'undefined';
    }
    this.removeOldestItem = function() {
        this.removeItem(this.keys.shift());
    }
    this.clear = function() {
        var tmp = this.cache_length;
        this.keys = new Array();
        this.cache_length = 0;
        this.items = new Array();
        return tmp;
    }
    jQuery.jCache = this;
    return jQuery;
})(jQuery);

/* SIMPLE TAB SCRIPT for Project 35033 */
var stDivsLoadedList = "";

function piPositionDiv(targetDiv) {
    
    var targetLeft = -1;
    var targetTop = -1;

    if ($(targetDiv).args().doCenterToScreen) {
        $(targetDiv).centerToScreen();
    }
    else {
        var lockedMousePosition = $(targetDiv).lockedMousePosition();

        if (lockedMousePosition != undefined && lockedMousePosition != null) {
            targetLeft = lockedMousePosition.X - 10;
            targetTop = lockedMousePosition.Y - 10;
        }

        if ($(targetDiv).args().overridePosition != null) {
            targetTop = $(targetDiv).args().overridePosition.top;
            targetLeft = $(targetDiv).args().overridePosition.left;
        }

        var clientWidth = document.body.clientWidth;

        if ((targetLeft + $(targetDiv).width()) > clientWidth) {
            targetLeft = targetLeft - $(targetDiv).width() + 20;
        }

        if ($(targetDiv).args().doOffsetFromBottom === true) {
            targetTop -= $(targetDiv).height() - 20;
        }

        if (targetLeft > 0 && targetTop > 0) {

            $(targetDiv).css({ postion: "absolute",
                top: targetTop,
                left: targetLeft
            });
        }
    }

    $(targetDiv).css({ postion: "absolute",
        "z-index": getMaxZ() + 1
    });
}

function stHideElement(elmID, overDiv) {
    for (i = 0; i < document.getElementsByTagName(elmID).length; i++) {
        obj = document.getElementsByTagName(elmID)[i];
        if (!obj || !obj.offsetParent){ 
            continue;
        }
        // Find the element's offsetTop and offsetLeft relative to the BODY tag.
        objLeft = obj.offsetLeft - overDiv.offsetParent.offsetLeft;
        objTop = obj.offsetTop;
        objParent = obj.offsetParent;
        while ((objParent.tagName.toUpperCase() != 'BODY') && (objParent.tagName.toUpperCase() != 'HTML')) {
            objLeft += objParent.offsetLeft;
            objTop += objParent.offsetTop;
            objParent = objParent.offsetParent;
        }
        objHeight = obj.offsetHeight;
        objWidth = obj.offsetWidth;
        if ((overDiv.offsetLeft + overDiv.offsetWidth) <= objLeft){}
        else if ((overDiv.offsetParent.offsetTop + overDiv.offsetHeight + 20) <= objTop){}
        else if (overDiv.offsetParent.offsetTop >= objTop + objHeight){}
        else if (overDiv.offsetLeft >= objLeft + objWidth){}
        else {
            obj.style.visibility = 'hidden';
        }
    }
}

function getJsonCallback(data, textStatus) {
    var targetDiv = document.getElementById(data.TargetDivID);

    if (jQuery.trim(data.Html) == "") {
        $(targetDiv).trigger("popInLoadCompleteWithNoData", data);
    }

    $(targetDiv).html(data.Html);

    if ($(targetDiv).args() == undefined && $(targetDiv).doCacheContent === false) {
        return;
    }
    
    if (stDivsLoadedList.indexOf(data.TargetDivID + ";") < 0) {
        stDivsLoadedList += data.TargetDivID + ";";
    }

    $(targetDiv).trigger("jsonCallbackComplete", data);
}

function stShowTarget(targetDiv)
{
    if (targetDiv != null) {
        $(targetDiv).show();
    }
}

function stContentIsLoaded(targetDiv){
    return stDivsLoadedList.indexOf(targetDiv.id + ";") >= 0;
}

function stHideSiblings(targetDiv)
{
    if (targetDiv != null) {
        $(targetDiv).siblings().hide();
    }    
}

function stShowInt(targetDiv) {
    if (targetDiv != null) {
        stHideSiblings(targetDiv);

        stShowTarget(targetDiv);            

        if (atl_vei_is_ie6under) {
            stHideElement('SELECT', targetDiv);
        }
    }
}

function stShow(sourceUrl, targetDivId) {
    var targetDiv = document.getElementById(targetDivId);

    stShowInt(targetDiv);

    if (sourceUrl != "" && !stContentIsLoaded(targetDiv)) {
        $.ajax({
            url: sourceUrl,
            dataType: "json",
            success: getJsonCallback,
            error: function() {
                var targetDiv = $("#" + targetDivId);
                $(targetDiv).html("<div style='width:100%; text-align:center; padding:14px;'>No Results Available.</div>");
                stShowTarget(targetDiv);
            }
        });
    }
}

/* SIMPLE TAB NAVIGATION FUNCTIONS */
function stTabActivate(tabId)
{
    var tabToActivate = document.getElementById(tabId);
    
    var srcUrl = $(tabToActivate).attr("src");
    var targetDivId = $(tabToActivate).attr("targetdiv");
    
    $(tabToActivate).parent().siblings(".simple_tab_active").addClass("simple_tab_inactive");
    $(tabToActivate).parent().siblings(".simple_tab_active").removeClass("simple_tab_active");
    
    $(tabToActivate).parent().addClass("simple_tab_active");
    $(tabToActivate).parent().removeClass("simple_tab_inactive");

    var targetDiv = $("#" + targetDivId);
    stShow(srcUrl, targetDivId);
}

/* JSON POP INS */
jQuery.fn.jsonGet = function() {
    var args = $(this).args();

    var doCache = args.cache !== false;

    var ajaxOptions = {
        url: args.url,
        dataType: "json",
        cache: args.doCacheContent,
        success: function(data, textStatus) {
            processJsonResult(data, textStatus, args.success);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            handleJsonError(textStatus, args.timeoutFunction);
        }
    };

    $.ajax(ajaxOptions);
};

jQuery.fn.jsonPost = function() {
    var args = $(this).args();

    var ajaxOptions = {
        url: args.url,
        type: "POST",
        dataType: "json",
        data: args.postData,
        success: function(data, textStatus) {
            processJsonResult(data, textStatus, args.success);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            handleJsonError(textStatus, args.timeoutFunction);
        }
    };

    $.ajax(ajaxOptions);
};

function processJsonResult(data, textStatus, success) {
    if (data.Properties != null) {
        var tempProperties = new Object();
        $.each(data.Properties, function() {
            if (this.Key != undefined && this.Value != undefined) {
                tempProperties[this.Key] = this.Value;
            }
        });

        data.properties = tempProperties;
    }
    success(data, textStatus);
}

function handleJsonError(textStatus, timeoutFunction)
{
    if (textStatus == "timeout" && timeoutFunction != null) {
        timeoutFunction();
    }
    else {
        //alert("AJAX Error Occurred: " + textStatus);
    }
}

jQuery.fn.args = function(args) {
    if (args !== null && args !== undefined) {
        this.data("args", args);
        this.data("lockedMousePosition", null);
    }
    else {
        return this.data("args");
    }
};

jQuery.fn.showAndSetVisible = function() {
    this.css({ visibility: "visible" });
    this.fadeIn();
};

jQuery.fn.piSetTimeout = function(args) {
    var timeoutCodeString = "piHidePopIn({targetDivId:'" + this[0].id + "',forcePageRefresh:" + args.forcePageRefreshOnTimeout + "})";
    var timerId = setTimeout(timeoutCodeString, 2000);
    $(this).args().timerId = timerId;
};


jQuery.fn.piClearMousedOverPopInTimeout = function() {
    if ($(this).args().timerId != null) {
        clearTimeout($(this).args().timerId);
    }
    else {
        var what = "wtf?";
    }
}

function piJsonCallback(data, textStatus) {
    var targetDiv = $("#" + data.TargetDivID);

    getJsonCallback(data, textStatus);

    if (jQuery.trim(data.Html) == "") {
        return;
    }
    else {
        $(targetDiv).piClearMousedOverPopInTimeout();
        $(targetDiv).trigger("popInLoadComplete");
    }
}

function piRenderPopIn(targetDiv) {
    var args = $(targetDiv).args();
    
    if (args.showBeforeContentLoaded === true) {
        $(targetDiv).getJsonContainerDiv().showAndSetVisible();
        piPositionDiv(targetDiv);
    }

    if (args.sourceUrl != null && args.sourceUrl != "") {
        var queryStringDelimiter = "?";

        if (args.sourceUrl.indexOf("?") >= 0) {
            queryStringDelimiter = "&";
        }

        var jsonUrl = args.sourceUrl + queryStringDelimiter + "TargetDivID="
            + args.targetDivId;

        args.url = jsonUrl;
        args.success = piJsonCallback;  

        if (args.postData != null && args.postData != undefined && args.postData.length > 0) {
            $(targetDiv).jsonPost();
        }
        else {
            $(targetDiv).jsonGet();
        }
    }
}

function piShowPopIn(args) {
    var targetDiv = $("#" + args.targetDivId);

    $(targetDiv).args(args);

    if (args.doMoveToMousePosition == true) {
        $(targetDiv).lockMousePosition();
    }

    var jsonContainerDiv = $(targetDiv).getJsonContainerDiv();

    piRenderPopIn(targetDiv);
    
    $(targetDiv).mouseover(function(){
        $(targetDiv).piClearMousedOverPopInTimeout();
    });

    $(targetDiv).mouseenter(function() {
        if ($(targetDiv).is(":visible")) {
            $(targetDiv).piClearMousedOverPopInTimeout();
        }
    });

    $(targetDiv).mouseleave(function() {
        if ($(targetDiv).is(":visible")) {
            // Clear any old timeouts that may still be hanging out before setting up a new one.
            $(targetDiv).piClearMousedOverPopInTimeout();
            $(targetDiv).piSetTimeout(args);
        }
    });

    $(targetDiv).one('popInLoadComplete', function(e) {
        if ($(targetDiv).args().doCenterToScreen === true) {
            $(targetDiv).centerToScreen();
            $(targetDiv).getJsonContainerDiv().showAndSetVisible();
        }
        else {
            piPositionDiv(targetDiv);
            $(targetDiv).getJsonContainerDiv().showAndSetVisible();
        }
    });
}

function piShowPopInWithStaticContent(args) {
    var targetDiv = $("#" + args.targetDivId);
    
    piShowPopIn(args);

    piPositionDiv(targetDiv);

    $(targetDiv).getJsonContainerDiv().showAndSetVisible();
}

function piHidePopIn(args) {
    var targetDiv = $("#" + args.targetDivId);

    $(targetDiv).getJsonContainerDiv().fadeOut("fast");

    $(targetDiv).args("");

    if(args.forcePageRefresh == true)
    {
        document.location.replace(window.location);
    }
}

function piShowPopInModal(args) {
    var targetDivId = args.targetDivId;
    var targetDiv = $("#" + targetDivId);
    $(targetDiv).args(args);

    $(targetDiv).getJsonContainerDiv().fillScreen(); 

    $(targetDiv).getJsonContainerDiv().css({ "z-index": getMaxZ() + 1 });
    
    $(targetDiv).one('popInLoadComplete', function(e) {
        $(targetDiv).piResizeToScreen();
        piBindContainerDivToAutoHideOnClick(targetDiv);
        $(targetDiv).showAndSetVisible();
    });

    $(window).wresize(function() {
        $(targetDiv).piResizeToScreen();
    });

    $(targetDiv).mouseenter(function() {
        if ($(targetDiv).is(":visible")) {
            $(targetDiv).getJsonContainerDiv().unbind('click');
        }
    });

    // Set up binding for the enter/leave of the children so that the 
    // click events of the targetDiv don't override the links on the pop in
    $(targetDiv).mouseleave(function() {
        if ($(targetDiv).is(":visible")) {
            // Clear any old timeouts that may still be hanging out since this is not meant to auto-hide.
            $(targetDiv).piClearMousedOverPopInTimeout();
            piBindContainerDivToAutoHideOnClick(targetDiv);
        }
    });

    piRenderPopIn(targetDiv);

}

function piBindContainerDivToAutoHideOnClick(targetDiv) {
    var containerDiv = $(targetDiv).getJsonContainerDiv();

    var containerDivEvents = $(containerDiv).data("events");
    
    if (containerDivEvents == null || containerDivEvents.click == null) {
        $(containerDiv).bind('click', function() {
            piHidePopIn($(targetDiv).args());
        });
    }
}

jQuery.fn.fillScreen = function() {
    var b = $("body");
    var w = $(window);
    var height = Math.max(b.height(), w.height());
    var width = Math.max(b.width(), w.width());

    $(this).css({ width: width, height: height, left: 0, top: 0, "z-index": getMaxZ() + 1 });
};

jQuery.fn.centerToScreen = function() {
    return this.each(function() {
        var width = $(this).width();
        var height = $(this).height();

        var clientWidth = $(window).width();
        var clientCenter = clientWidth / 2;

        var clientHeight = $(window).height();
        var clientMiddle = clientHeight / 2;

        var scrollLeft = $(document).scrollLeft();
        var scrollTop = $(document).scrollTop();

        var top = clientMiddle + scrollTop - (height / 2);
        var left = clientCenter + scrollLeft - (width / 2);

        $(this).css({ top: top + "px" });
        $(this).css({ left: left + "px" });
    });
};

jQuery.fn.piResizeToScreen = function() {
    $(this).getJsonContainerDiv().fillScreen();

    if ($(this).args().doCenterToScreen === true) {
        $(this).centerToScreen();
    }
};

/* *************************************** */
