//--Generally useful stuff goes in this file

// ------- Dom Assembler ----------------------------------
//Legend tp = type, cn = css class name, id = css id, at = attribute, tx = innerHTML, ps = parent node, sc = single child, st: style object
domAssemble = function(items) {
    this.init = function () {
        this.root = this.build(items[1]);
        this.reference = this.root;
        this.array = new Array();
        var i = 0;
        var element;
        for (var el in items) {
            if (items[el].ob !== undefined) {
                element = items[el].ob;
            }
            else {
                element = this.build(items[el]);
            }
            if (i == 1) {
                this.append(element);
            }
            if (i > 1) {
                //if 0 or does not exist append to current node
                if ((items[el].ps === 0) || (!items[el].p)) {
                    this.append(element);
                }
                if (items[el].ps > 0) {
                    var x = (items[el].ps - 1);
                    if (items[el].sc == "true") {
                        var oldRef = this.reference;
                    }
                    this.reference = this.array[x];
                    this.append(element);
                    if (items[el].sc == "true") {
                        this.reference = oldRef;
                    }
                }
            }
            this.array[i] = element;
            i++;
        }
    };
    this.build = function (el) {
        if (!el.tp) { alert("no type was defined"); }
        var newEl = document.createElement(el.tp);
        if (el.cn !== undefined) { newEl.className = el.cn; }
        if (el.id !== undefined) { newEl.id = el.id; }
        if (el.at !== undefined) { for (var a in el.at) { newEl.setAttribute(a, el.at[a]); }}
        if (el.tx !== undefined) { newEl.innerHTML = el.tx; }
        if (el.st !== undefined) { for (var s in el.st) { newEl.style[s] = el.st[s]; }}
        return newEl;
    };
    this.append = function (el) {
        this.reference.appendChild(el);
    };
    this.init();
};

// ------- Dom Style ----------------------------------
//Legend cn = css class name, id = css id, at = attribute, tx = innerHTML, st: style object
function domStyle (el) {
		if (!el.ms){alert("please provide object to be changed");}
		var ms = document.getElementById(el.ms);
        if (el.cn !== undefined) { ms.className = el.cn; }
        if (el.id !== undefined) { ms.id = el.id; }
        if (el.at !== undefined) { for (var a in el.at) { ms.setAttribute(a, el.at[a]); }}
        if (el.tx !== undefined) { ms.innerHTML = el.tx; }
        if (el.st !== undefined) { for (var s in el.st) { ms.style[s] = el.st[s]; }}
		return true;
}

// ------- Create a Button ----------------------------------
newButton = function(txt, type) {
    this.init = function () {
        var buttonDef = {
            1: {tp: "div",cn: "button-container"},
            2: {tp: "span",cn: type, tx: txt},
            3: {tp: "span",cn: type + "-r"}
        };
        var newButton = new domAssemble(buttonDef);
        this.main = newButton;
        this.container = newButton.root;
        this.setRollover(this);
    };
    this.setRollover = function (id) {
        this.container.onmouseover = function () {
            id.main.array["1"].className = type + "-roll";
            id.main.array["2"].className = type + "-r-roll";
        };
        this.container.onmouseout = function () {
            id.main.array["1"].className = type;
            id.main.array["2"].className = type + "-r";
        };
    };
    this.init();
};
// ------- General rollover ----------------------------------
var genRollover = {
    over : function(type, id) {
           id.firstChild.className = type + "-roll";
           id.lastChild.className = type + "-r-roll";
    },
    out : function(type, id) {
           id.firstChild.className = type;
           id.lastChild.className = type + "-r";
    }
};


// Search Box state handling
var initSearchState = {
    init : function(target) {
    var searchbox = "searchbox"+target;
    var sbox = "sbox"+target;
    this.mainbox = $("#"+searchbox)[0];
    this.box = $("#"+sbox)[0];
    },
    focus : function(target) {
    this.init(target);
    this.mainbox.style.background = "url(images/common/searchbox"+ target +"-hilite.jpg) no-repeat";
    this.box.style.background = "#ffffcc";
    this.box.style.color = "#000";
    var val = this.box.value;
    if (((val == "Search...")||(val == "Search resources...")||(val == "Search projects..."))) {
        this.box.value = "";}
    },
    blur : function(target) {
    this.init(target);
    this.mainbox.style.background = "url(images/common/searchbox"+ target +".jpg) no-repeat";
    this.box.style.background = "#fff";

    if ((this.box.value === "") && (this.box.name === "projectSearchTerm")) {
        this.box.style.color = "#666";
        this.box.value = "Search projects...";
    }

    if ((this.box.value === "") && (this.box.name === "resourceSearchTerm")) {
        this.box.style.color = "#666";
        this.box.value = "Search resources...";
    }

    if ((this.box.value === "") && (this.box.name === "searchTerm")) {
        this.box.style.color = "#666";
        this.box.value = "Search...";
    }
    },
    setColor : function() {
    this.box = $("#sbox1")[0];
    if (this.box.value !== "Search...") {
        this.box.style.color = "#000";
        }
    }
};

// General search box focus handling
var genSearchFocus = {
    setFocus : function() {
    var box = $("#sbox2")[0];
    var value = box.value;
    // some trickery so the cursor is at the end of the line in ie6
    box.value = "";
    box.focus();
    box.value = value;
    }
};

// ------- Message Handling ----------------------------------
messageShow = function(msg, type) {
    this.message = msg;
    this.container = document.getElementById("pbody");

    this.init = function () {
    if (!type){
    this.configure(type);
    this.show(2500);
    }

    if(type == "warning-message"){
    this.configure(type);
    this.show(4000);
    }

    if(type == "error-message"){
    this.configure(type);
    this.closeButton(this);
    $(this.message).fadeIn();

    }
  };

    this.configure = function (type) {
        var mbox;
        if(type){mbox = type;}
        else{ mbox = "message-box"; }
        this.check();
        this.position();
        var messageDiv = { 1: {tp: "div", id: "message-box", cn: mbox, st: {top: this.top, left: this.left}},
                           2: {tp: "div", id: "message-bar-top"},
                           3: {tp: "div", id: "message-bar"},
                           4: {tp: "div", id: "message-content", tx: msg, ps: 3, sc: "true"},
                           5: {tp: "div", id: "close-box", ps: 3, sc: "true"},
                           6: {tp: "a", at: { href: "javascript:void(0);", title: "close"}, tx: "x", ps: 5, sc: "true"},
                           7: {tp: "div", id: "message-bar-bottom"}};
        this.box = new domAssemble(messageDiv);
        this.message = this.box.root;
        this.container.insertBefore(this.message, this.container.firstChild);
    };
    this.check = function () {
    if(document.getElementById("message-box")){
        var old = document.getElementById("message-box");
        old.parentNode.removeChild(old);
    }
    };
    this.closeButton = function(id) {
            this.box.array[5].onclick = function() {
            id.remove(id);
                return;
            };
    };
    this.remove = function(id) {
            id.message.parentNode.removeChild(id.message);
            };
    this.position= function () {
	var vheight = $(window).height();
    var x = $(window).width();
    var y;
    var footer = $("#footer").offset().top;
    var end = $("#end").offset().top;
    if (footer > end) {y = footer;} else {y = end;}
	var wtop;
	if(document.documentElement && typeof(document.documentElement.scrollLeft) == 'number')
	{ wtop = document.documentElement.scrollTop; }
	else { wtop = document.body.scrollTop;}
    if(wtop < 50){this.top = "70px";}
    else {this.top = (wtop + 20) +"px";}

    var leftPosition = "0";
    if (x > 900){leftPosition = Math.floor(( x/ 2) - 448);}
    this.left = leftPosition+"px";

    };


    this.show = function (delay) {
                      
    var mBox = $("#message-box");

    mBox.animate({opacity: "show"}, 500);

    setTimeout(function(){ mBox.animate({opacity: "hide", complete: function(){ mBox.remove(); }}, 500);}, delay + 500);
    };
this.init();
};

function newWindow(url, name, h, w) {
   	var x = $(window).width();
	var y = $(window).height();
    //calculate position
    var leftPosition = Math.floor((x / 2) - (w/2));
    var topPosition = Math.floor((y / 2) - (h/2));

    var dimensions = 'height=' + h + ', width=' + w + ",top=" + topPosition + ", left=" + leftPosition;
    var newWindow = window.open(url, name, dimensions);

    if (window.focus) {newWindow.focus();}
	return false;
}





//Define base overlay class this has all the base methods and properties associated with overlays
function baseOverlay(){}

baseOverlay.prototype.baseInit = function () {
    this.bcontrol = document.getElementById("bcontrol");
    this.checkDom();
    this.create();
    this.resize();
    $(window).bind( "resize", this.resize);
};
baseOverlay.prototype.checkDom = function () {
 if (document.getElementById("overlay")){
     var overlay = document.getElementById("overlay");
     overlay.parentNode.removeChild(overlay);
 }

 if (document.getElementById("overlaybox")){
    var ovbox = document.getElementById("overlaybox");
    ovbox.parentNode.removeChild(ovbox);
 }
};
baseOverlay.prototype.create = function () {
    var overlayDef = {1: {tp: "div",id: "overlay", st:{filter: "alpha(opacity=80)", opacity: "0.8"}},
                      2: {tp: "div",id: "ospinner", at: {src: "../images/common/progressbar_green.gif"}}
                      };
    var overlayBoxDef = { 1: {tp: "div",id: "overlaybox"}};
    var ov = new domAssemble(overlayDef);
    this.overlay = ov.root;
    var ovbox = new domAssemble(overlayBoxDef);
    this.box = ovbox.root;
    document.body.insertBefore(this.overlay, document.body.firstChild);
    document.body.appendChild(this.box, document.body.firstChild);


    };
baseOverlay.prototype.cleanup = function (display) {
        $(".rcontrols").toggle();
	};
baseOverlay.prototype.resize = function (id) {
	//Display scroll bar if less than overlay height
	var vheight =  $(window).height();
	var box = document.getElementById("overlaybox");
	var bcontrol = document.getElementById("bcontrol");
	var overlay = document.getElementById("overlay");
if ((box.clientHeight + 40) > vheight){ bcontrol.style.overflow = "auto"; }
	else { bcontrol.style.overflow = "hidden"; }

    this.page = document.getElementById("pbody");
    this.page.style.margin = "0 0 0 0";
    //set overlay div width
	var x = $(window).width();
	if (x < 1000) {overlay.style.width = "1000px";}
	else {overlay.style.width = x+"px";}
	//set overlay div height
    var y;
    var footer = $("#footer").offset().top;
    var end = $("#end").offset().top;
    if (footer > end) {y = footer;} else {y = end;}
    overlay.style.height = (y+35)+"px";
    //set left position of overlay
    var leftPosition = "0";
    if (document.getElementById("overlay-small") || document.getElementById("overlay-small-scroll")) {
        box.style.width = "550px";
        if (x > "540"){ leftPosition = Math.floor((x / 2) - 275); }
    }
    else {
        if (x > "790"){ leftPosition = Math.floor((x / 2) - 400); }
    }
    box.style.left = leftPosition + "px";
    this.left = leftPosition;
};
baseOverlay.prototype.cancel = function () {
	this.box.innerHTML ="";

    //reset padding for scrollbar
    this.page.style.margin = "0 0 0 0";

    //Clean up the Dom
    this.overlay.parentNode.removeChild(this.overlay);
    this.box.parentNode.removeChild(this.box);

	//Remove event handler from body
	$(window).unbind("resize");

    //Re-enable scroll bar
    this.bcontrol.style.overflow = "scroll";

	//Re-enable drop downs
	this.cleanup("inline");
    //Force memory clean up for IE
	this.garbage();
    };

baseOverlay.prototype.garbage = function () {
    this.overlay = null;
    this.box = null;
    this.title = null;
    this.boxcontent = null;
    this.actions = null;
    this.button1 = null;
    this.button2 = null;
    this.bcontrol = null;
    this.dropdown = null;
    this.left = null;
    this.page = null;
    this.buttonCancel = null;
    this.buttonAction = null;
};

//Modal overlay inherits from baseOverlay and adds methods and properties specific to the general green overlay
function modalOverlay(){}

modalOverlay.prototype = new baseOverlay();

modalOverlay.prototype.init = function () {
    this.baseInit();
    this.build();
};

modalOverlay.prototype.build = function () {
var modalDef = {
    1: {tp: "div"},
    2: {tp: "div",cn: "top"},
    3: {tp: "div",id: "boxcontent"},
    4: {tp: "div",id: "form-controls"},
    5: {tp: "div",cn: "bottom"},
    6: {tp: "p", ps: 5}
    };

    var ovbox = new domAssemble(modalDef);
    this.box.innerHTML = ovbox.root.innerHTML;

    this.title = this.box.childNodes[0];
    this.boxcontent =  this.box.childNodes[1];
    this.actions =  this.box.childNodes[2];
};


modalOverlay.prototype.loadbox = function () {
	//scroll to top
    $("#bcontrol").scrollTop(0);

    //Turn on blank container divs
    this.overlay.style.display = "block";
};

modalOverlay.prototype.populate = function (form) {
	//populate box with string
    this.boxcontent.innerHTML = form;
    this.configure();
    //active controls
    this.loadControls(this);
    this.resize();
    this.loadbox();
	this.cleanup("none");
    this.box.style.visibility = "visible";
    $('qa-button-action').focus();
};

modalOverlay.prototype.setFocus = function () {
	//setFocus to first field of overlay
	var field = document.getElementById("overlaybox").getElementsByTagName('*');
    var length = field.length;
    for(var i = 0; i < length; i++){
  		if((field[i].style.display !== "none" && field[i].style.visibility !== "hidden") &&
             (field[i].tagName.toUpperCase() == 'INPUT' &&
              (field[i].type == 'text' || field[i].type == 'password' || (field[i].type == 'radio') && (field[i].checked))) || field[i].tagName.toUpperCase() == 'TEXTAREA' || field[i].tagName.toUpperCase() == 'SELECT' || field[i].tagName.toUpperCase() == 'A') { field[i].focus(); return; }}
};

modalOverlay.prototype.configure = function () {
    this.title.innerHTML = "";
    this.actions.innerHTML = "";
    //populate title
    var title = document.getElementById("overlayTitle");
    this.title.appendChild(title);

    //hookup custom cancel button if it exists or go with default cancel
    if (document.getElementById("overlayCancel")) {
    this.buttonCancel = document.getElementById("overlayCancel");
    var button1;
    button1 = new newButton(this.buttonCancel.innerHTML, "button-standard");
    this.button1 = button1.container;
    this.button1.setAttribute("name", "qa-button-action");
    this.button1.id = "qa-button-action";
    this.actions.appendChild(this.button1);
    this.buttonCancel.style.display = "none";
    }
    else{
    button1 = new newButton("CANCEL", "button-standard");
    this.button1 = button1.container;
    this.button1.setAttribute("name","qa-button-close");
    this.actions.appendChild(this.button1);
    }

    //hookup overlay action
    if (document.getElementById("overlayAction")) {
    this.buttonAction = document.getElementById("overlayAction");
    var button2 = new newButton(this.buttonAction.innerHTML, "button-action");
    this.button2 = button2.container;
    this.button2.setAttribute("name","qa-button-action");
    this.button2.id = "qa-button-action";
    this.actions.appendChild(this.button2);
    this.buttonAction.style.display = "none";
    }
};

modalOverlay.prototype.loadControls = function(id) {
            this.button1.onclick = function() {
               if(document.getElementById("overlayCancel")){
               id.buttonCancel.onclick();}
                else {
                id.cancel();
                }
                return;
            };

        if (document.getElementById("overlayAction") && id.buttonAction.onclick != undefined ) {
          this.button2.onclick = function() {
               id.buttonAction.onclick();
                return;
            };
        }
    };

//Confirm dialog inherits from baseOverlay and adds methods and properties specific to the confirmation dialog
function confirmDialog(){}

confirmDialog.prototype = new baseOverlay();

confirmDialog.prototype.init = function(action, actionButton, cancelButton, message, hide) {
    this.baseInit();
    this.hide = hide;
    this.action = action;
    this.message = message;
    this.button1 = new newButton(cancelButton, "button-standard", "ovcancel");
    this.button2 = new newButton(actionButton, "button-action");
    this.build();
    this.loadB(this);
    };

confirmDialog.prototype.build = function () {
        var dialogDef = {
            1: {tp: "div",cn: "alertChanges"},
            2: {tp: "div",cn: "alertHeader", tx: this.message },
            3: {tp: "div", st: {position: "relative", margin: "0 0 0 120px"} },
            4: {ob: this.button1.container, ps: 3},
            5: {ob: this.button2.container }
        };
        var popDialog = new domAssemble(dialogDef);

        if(document.getElementById("cancelButton")){
           popDialog.array[2].style.margin = "0 0 0 85px";
            }

        this.box.appendChild(popDialog.root);
	    this.cleanup("none");
        this.box.style.visibility = "visible";
        this.overlay.style.background = "#fdfdfd";
        this.overlay.style.display = "block";
        this.box.style.left = "32%";
    };

confirmDialog.prototype.loadB = function (ids) {
        this.button1.container.onclick = function() {
           ids.cancel();
            return;
        };
        this.button2.container.onclick = function() {
            if(document.getElementById("cancelButton")){
                var cancelButton = document.getElementById("cancelButton");
                cancelButton.onclick();
            }
            if(ids.hide === true){
                ids.cancel();
                }
            if(ids.hide !== true){
               ids.button1.container.onclick = null;
                }
            location.href = ids.action;
            return;
        };
    };


// ------- Shuttle ----------------------------------
shuttle = function(div, box1, box2) {
    this.shuttle = document.getElementById(div);
    this.box1 = document.getElementById(box1);
    this.box2 = document.getElementById(box2);
    this.init = function() {
        this.array1 = new Array();
        this.array2 = new Array();
    };
    this.add = function() {
        this.init();
        this.loop(this.box1, this.box2);
    };
    this.remove = function() {
        this.init();
        this.loop(this.box2, this.box1);
    };
    this.addAll = function() {
        this.init();
        this.loopAll(this.box1, this.box2);
    };
    this.removeAll = function() {
        this.init();
        this.loopAll(this.box2, this.box1);
    };
    this.loop = function(list, container) {
        for (var i = 0; i < list.length; i++) {
            if (list[i].selected === true) {
                //list[i].selected = true;
                this.move(list[i], list, this.array1);
                i--;
            }
        }
        this.insert(container);
    };
    this.loopAll = function(list, container) {
        for (var i = 0; i < list.length; i++) {
            list[i].selected = true;
            this.move(list[i], list, this.array1);
            i--;
        }
        this.insert(container);
    };
    this.move = function(option, container, array) {
        array.push(option);
        container.removeChild(option);
    };
    this.alphaCheck = function (a, b) {
        var aVal = a.text.toLowerCase();
        var bVal = b.text.toLowerCase();
        if (aVal < bVal) {
            return -1;
        }
        if (aVal > bVal) {
            return 1;
        }
        return 0;
    };
    this.insert = function(container) {
        var selected = container.getElementsByTagName("option");

        for (var i = 0; i < selected.length; i++) {
            this.move(selected[i], container, this.array2);
            i--;
        }
        var combine = this.array2.concat(this.array1);
        combine.sort(this.alphaCheck);
    	var xj = "";
        for (var j = 0; j < combine.length; j++) {
            container.appendChild(combine[j]);
        }
    };
    this.hide = function (a, b) {
    this.shuttle.style.display = "none";
    };
    this.show = function (a, b) {
    this.shuttle.style.display = "block";
    };
    this.selectAll = function() {
        var length = this.box2.length;
        for (var i = 0; i < length; i++) {
            if (this.box2[i].selected === false) {
                this.box2[i].selected = true;
            }
        }
    };
    this.init();
};


function submitShuttleOverlay(formName, event, hasFileUpload){

    if (document.getElementById("c-shuttle")){

    if (cShuttle.box2.length > 0){
        //contacts shuttle
        cShuttle.selectAll();}
    }
    if (document.getElementById("p-shuttle")){
        //permissions shuttle
        if (pShuttle.box2.length > 0){
            pShuttle.selectAll();
        }
    }
    submitOverlay(formName, event, hasFileUpload);
}//end of Shuttle Overlay


function initJs(){
    if (document.getElementById("c-shuttle")){
      //contacts shuttle
      cShuttle = new shuttle("c-shuttle","cbox1","cbox2");
      }
    if (document.getElementById("p-shuttle")){
      //permissions shuttle
      pShuttle = new shuttle("p-shuttle","pbox1","pbox2");
      }
    if (document.getElementById("change-passwd-link")){
      //show password fields in my profile
      showPassword.init();
      }
    if (document.getElementById("cal1Container")){
      //initialize calendar

        popUpCal.init();
      }
}










$(document).ready(function() {
    $.MT.common.init();


});

if ($.MT == undefined) {
    $.MT = {};
}

$.MT.common = {

    init: function() {
        $.MT.common.events();
        
        $.MT.common.globalHeaderInit();
        
        // Check if it's the login page, if so globalheader wont load.
        if ($('.login-page').length > 0) {
            $.MT.common.loginPageInit();
        }
    },

    message: function(msg, t){

        var message = new messageShow(msg, t);        

    },


    events: function() {
       $(".load-overlay").click(function(e){
          e.preventDefault(); 
          var action = $(this).attr("action");
          var event = $(this).attr("event"); 
          $.MT.common.loadOverlay( action, event );
          
       }); 
    },

    loadOverlay: function(action, event){

   if (!document.getElementById("overlay")) {
        overlay = new modalOverlay();
        overlay.init();
    }

    var url;    

    if(event){
        url = action + "?" + event;
    } else{
       url = action;
    }


    $.ajax({
        type: "GET",
        cache: false,
        url: url,
        param: {  isajax: "true"},
        success: function(data) {

         $.MT.common.overlayEvents(data);
        },
        error: function(msg){
              var error = new messageShow(msg);
        }
    });


    },
    loadForm: function(ob){

        if(!ob.type){
            ob.type = "GET";
        }

        if(!ob.async){
            ob.async = true;
        }


       if($(ob.formId)){

        $(ob.formId).ajaxSubmit({
            async: ob.async,
            cache: false,
            type: ob.type,
            success: function(data) {

                $(ob.target).empty().append(data);


             try {
                pageInitialize();
                } catch (exception) {
            /*some pages do not have this defined.*/
                }


            },
            error: function(msg){
              var error = new messageShow(msg);
            }
        });
       }

        },    


    submitOverlay: function(formId){

        $("#"+formId).ajaxSubmit({
            type: "POST",
            cache: false,
            success: function(data) {
                if (data == PortalConstants.NOT_LOGGED_IN) {
                    location.href = 'Login.action';
                    return;
                }
                $.MT.common.overlayEvents(data);
            },
        error: function(msg){
              var error = new messageShow(msg);
        }
        });

        },


    overlayEvents: function(responseText){

         if (responseText == PortalConstants.NOT_LOGGED_IN) {
                location.href = 'Login.action';
                return;
            }
            if (responseText !== null) {
                var responseDiv = { 1: {tp: "div", id: "tempDiv", tx: responseText, st:{ display: "none"}}};
                var rDiv = new domAssemble(responseDiv);
                var status = null;
                try {
                    status = rDiv.root.firstChild;
                } catch (Exception) {
                }

                if (status.id == "overlay-success") {
                    var message = status.firstChild;
                    if (overlay) {
                        overlay.cancel();
                        if (message.innerHTML !== "") {
                            //in some cases we will pass back an empty message
                            //for this <overlay-success> to appear...
                            var x = new messageShow(message.innerHTML);
                        }
                    }
                    var js = null;
                    if (status.childNodes.length > 1) {
                        js = status.childNodes[1];
                    }
                    if (js !== null && js.id === "overlay-javascript") {

                        eval(js.innerHTML);
                    }
                } else {
                    if (overlay) {
                        overlay.populate(responseText);
                    }
                    if (document.getElementById("customJs")) {
                        initJs();
                    }
                }
            }        
    },
    
    // New Globalheader Initialization
    globalHeaderInit: function(){
        
        // Start with apps not loaded yet
        var appsLoaded = false;
        
        // Initialize typical dropdown functionality
        $.MT.controls.dropDown.init({
            name: "globalDrop",
            usage: "multi",
            menuPosition: "right",
            menuOffset: 20,		
            resize: false, 
            defaultBehavior: false,			
            method: function(context) {
                window.location.href = $(context).attr("href");
                return false;
            }
        });
        
        // Initialize special case Work Area drop down
        // Check if it's there...
        if ($('.global-workarea-list').length > 0) {
            $.MT.controls.dropDown.init({
                name: "global-workarea",
                usage: "multi",
                menuPosition: "right",
                menuOffset: 20,
                autoComplete: "auto",			
                resize: false, 
                defaultBehavior: false,
                method: function(context) {
                	$(context).preventDefault();
                    alert($(this).parents("li").attr("workarea"))
                	$("#currentWorkarea").val($(this).parents("li").attr("workarea"));
                	$("#portalSelect").submit();
                }
            });
            $(".global-workarea-list li a").click(function(e){
                e.preventDefault();
                $("#currentWorkarea").val($(this).parents("li").attr("workarea"));				
                $("#portalSelect").submit();
            });
        // Otherwise just take out down arrow
        } else {
            $('.global-workarea').removeClass('dropDown');
        };
        
        // Initialize onclick products list
        $('[listname="global-products-list"]').click(function(){  
            
            if (!appsLoaded) {
                //build products drop down list
                $.ajax({
                	dataType: "jsonp",
                	cache: false,
                	url: $("#mtiAppsUrl").val(),
                	success: function(d){					
                		//alert('success');
                		//alert(d);
                		var apps = d.apps;
                		var container = $(".global-products-list");
                		var bottom = '<li class="globalDrop-listbottom"><span></span></li>';
                		var item = '';
                		for(var x = 0; x < apps.length; x++){						
                			item += '<li><a href="' + apps[x].value + '"><span>' + apps[x].name  + '</span></a></li>';									
                		}
                		container.html(item + bottom);
                        appsLoaded = true;		
                	},
                	error: function() {
                	    //if there isn't a list, kick user out
                	    window.location = $('[name="mtilogout"]').attr('href') || '/Login.action?logout';
                	}
                });
            }
        });
    },
    loginPageInit: function() {
        // Grab Product List
        $.ajax({
            dataType: "jsonp",
            url: $('#loginAppsUrl').val(),
            cache: false,
            success: function(d){
                var apps = d.apps;
                var defUrl = d.selectedAppValue;
                var $default = $('[listname="login-app-list"]');
                var $container = $(".login-app-list");
                var $targetField = $('[name="selectedAppUrl"]');
                var gomsg = ( $default.attr('gotomessage') || 'Go to ');
                
                $targetField.val(defUrl);
                
                $default.html('Go to '+apps[0].name);
                
                $container.empty();
                
                for(var x = 0; x < apps.length; x++){
                    var item = $('<li val='+apps[x].value+'><a href="javascript:void(0);">'+gomsg+apps[x].name+'</a></li>');
                    if (apps[x].value == defUrl) {  
                        $default.html(gomsg+apps[x].name);
                    };
                    $container.append(item);
                }
                
                $.MT.controls.dropDown.init({
                    name: "drop10",
                    usage: "multi",
                    method: function(context){
        				$('[name="selectedAppUrl"]').val($(context).parents("li").attr("val"));
                        return false;
                    }
                });
        
                
            },
            error: function() {
                $('[listname="login-app-list"]').parents('.login-app').hide();
            }
        });   
    
    }
};

/* Define a list of constants to be used in portal. */
var PortalConstants = new Object;
PortalConstants.NOT_LOGGED_IN = "NOT_LOGGED_IN";
//end of def

function loadOverlay(action, event){
    $.MT.common.loadOverlay(action, event);
}

//
///* method to edit / delete a contact. see my-contacts.jsp. */
function myContactsAction(formName, eventName, contactId) {
    document.forms[formName].contactId.value = contactId;
    if (eventName == 'deleteContact') {
        if (!confirm("Do you want to delete this contact?")) {
            return;
        }
    }
    submitOverlay(formName, eventName);
}

function checkJavaScript() {
    if (document.getElementById) {
        var lbox = document.getElementById("showlogin");
        lbox.style.display = "block";
    }
}


function submitOverlay(formId, event){

    if (event) {
        var eventName = $("<input type='hidden' name='"+event+"' value='"+event+"'>");
        $("#"+formId).append(eventName);
    }

    $.MT.common.submitOverlay(formId);
  }

function checkJavaScript() {
    if (document.getElementById) {
        var lbox = document.getElementById("showlogin");
        lbox.style.display = "block";
    }
}

//avoid possible multiple submits.
var loginSubmitted = false;
/** called from login pg. */
function loginPortal(formName) {
    if (loginSubmitted) {
        return true;
    }
    var dt = new Date();
    with (document.forms[formName]) {
        tzoffset.value = -1*dt.getTimezoneOffset()*60*1000;
        submit();
    }
    loginSubmitted = true;
    return true;
}

/* refresh the page.  If location is Login.action, we're going to redirect
to Home page instead of re-authenticating. */
function refreshPage() {
    if (location.href.indexOf("/Login.action") != -1) {
// setting empty string makes the page reloaded within context.      
        location.href = "";
    } else {
        location.reload(true);//do GET.
    }
}


//new common code from EPM

$.log = function (msg) {
    if(!$("#inspector")[0]){
        var window = $("<div id='inspector'><ul><li>" + msg + "</li></ul></div>");
        $("body").append(window);
    }else{
      $("#inspector").find("ul").append("<li>"+msg+"</li>");
      var height = $("#inspector").find("ul").height();
      $("#inspector").scrollTop(height);
    }
    return this;
};

//set caching to false for all ajax calls
$.ajaxSetup({cache:false});


$.MT.qData = {
    name: {},
    init: function(queue, settings){
        if($.MT.qData.name[queue] == undefined){
            $.MT.qData.name[queue] = {
                requests: [],
                status: "inactive"
            };
        }

        settings.date = Date();

        if ($.MT.qData.name[queue].status == "inactive"){
        $.MT.qData.name[queue].requests.push(settings);

        //set delayInSec for debugging queue
        //setTimeout(function(){$.MT.qData.processQ(queue);}, 15000);

        $.MT.qData.processQ(queue);

        } else if ($.MT.qData.name[queue].status == "active"){

           $.MT.qData.name[queue].requests.push(settings);
        }

    },
    processQ: function(queue){

        //$.log("<b>"+ $.MT.qData.name[queue].requests.length + "</b> request(s) in queue")

        if($.MT.qData.name[queue].requests.length > 0){

       //$.log("Processing request...<b>")

       var request =  $.MT.qData.name[queue].requests[0];

        request.complete = function(){
//            $.log("Request completed");
            $.MT.qData.remove(queue, request);
        };

        if(request.callType == "formSubmit"){
//            $.log("Request completed");
            $.MT.ajaxSubmit(request, queue);
        }

        if(request.callType == "directCall"){
            $.MT.ajax(request, queue);
        }

       $.MT.qData.name[queue].status = "active";

    } else{
       $.MT.qData.name[queue].status = "inactive";
        //$.log("<b>Queue is empty</b>")
    }

    },
    remove: function(queue, request){
        //$.log("Removing request...");
        $.MT.qData.name[queue].requests.shift(request);

//        set delayInSec for debugging queue
//        setTimeout(function(){$.MT.qData.processQ(queue);}, 15000);

        $.MT.qData.processQ(queue);
    },
    empty: function(queue){
        $.MT.qData.name[queue] = [];
        //need to generify this part
        $(".condition-body").unblock();
    }
};



$.MT.ajaxSubmit = function(x, q){

    var settings = {
        dataType: "html",
        type: "GET"
    };
    $.extend(settings, x);


    $(settings.form).ajaxSubmit({
        type: settings.type,
        dataType: settings.dataType,
        success: function(data) {
            if($(data).find("#showlogin")[0] !== undefined){
				window.location = "/Login.action";
				return false;
			}

            if((data.status || $(data).find("#data-status").text()) == "error"){
                if(q != undefined){
                    $.MT.qData.empty(q);
                }                
                alert("Oops, something went wrong... Please try again");
                return false;
            } else{
                if(q != undefined){
                    settings.complete();
                }
                settings.success(data);
            }
        },
        error: function(){
                if(q != undefined){
                    $.MT.qData.empty(q);
                }
            return false;

        }
    });
};




$.MT.ajax = function(x, q){

    var standardMessage = "This service is temporarily unavailable.";

    var settings = {
        dataType: "html",
        type: "GET",
        cache: false,
        error: function(){
              if(q != undefined){
                $.MT.qData.remove(q);
              }
              if(settings.ajaxFail){
                settings.ajaxFail({ errorMessage: standardMessage });
              }else{
                $.MT.common.message(standardMessage);
              }
        }
    };
    $.extend(settings, x);

    var ajaxComplete;
    if(settings.complete){
       ajaxComplete = settings.complete;
    } else{
       ajaxComplete = function(){};
    }


    $.ajax({
        type: settings.type,
        dataType: settings.dataType,
        url: settings.url,
        cache: settings.cache,
        success: function(data){

            var errorMessage;
                if($(data).find("#showlogin")[0] != undefined){
                    window.location = "/Login.action";
                    return false;
                }
                if((data.status || $(data).find("#data-status").text()) == "error"){
                    if(q != undefined){
                        $.MT.qData.remove(q);
                    }
                    if(data.redirectUrl != undefined && data.redirectUrl != ""){
                        window.location = data.redirectUrl;
                    }
                    if(settings.ajaxFail){
                        settings.ajaxFail(data);
                    }else {
                        errorMessage = data.errorMessage != undefined ? data.errorMessage : standardMessage;
                        $.MT.common.message(errorMessage);
                    }
                } else{
                    settings.success(data);
                }

        },
        error: settings.error,
        complete: ajaxComplete
    });
};




$.MT.general = {

    pageInit: function() {

        if ($("#page-name") && $.MT.pages[$("#page-name").attr("name")]) {
            $.MT.pages[$("#page-name").attr("name")]();
        }


        if($("#page-name").attr("debug") == "true"){
            //set debug code here
            alert($("#page-name").attr("name")  + " is initialized");

        }

    },

	formEvents: function(form, method) {

	  	$(".navi-action").click(function(e) {
		            e.preventDefault();

		            if($(this).hasClass("cancel-action")){
		             history.back();
		            } else{

					if(method){
						method();
					}

		            var action = $(this).attr("action");

		            //set form action
		            $("#form-action").val(action);

					var blockTarget = $(this).attr("btarget");

					if(blockTarget !== undefined){

						var bMessage;
		                var bElem = $(this).attr("belem");

		                if(bElem !== undefined){

		                    bMessage = $(bElem);

		                } else {

	                        var message = $(this).attr("bmessage") != undefined ? $(this).attr("bmessage") : "Loading...";

		                    bMessage = "<div class='generic-busy'>" + message + "</div>";

		                }

		                $(blockTarget).block({message: bMessage });
					}

	                //submit form
	                setTimeout(function(){
	  	            $(form).submit();
	                }, 10);    
		            }
		        });


	    }
};


$.MT.controls = {
	
	fontGrow: function(id){
		$(id).hover(function(){
			$(this).animate({ fontSize: '14px' }, 300 );			
		},	function(){
			$(this).animate({ fontSize: '1em' }, 70 );
			});
        
		$(id).blur(	function(){
			$(this).css({ fontSize: '1em' });
			}		
		);		
	},
	
	
	checkRow: function(table){
		//add row hover
		$.MT.controls.tableHover(table);
		
		//add row select
		$.MT.controls.rowSelect(table);		
	},

    tableHover: function(target){
		var table = (target == undefined ? ".table-all" : target); 

        $(table + " td").css("cursor","pointer");
        $(table + " td a").css("cursor","pointer");
        //hover state for member search results
        $(table + " td").hover(
                function(){
                    $(this).parents("tr").find("td").each(function(){
                        $(this).addClass("survey-list-hover");
                    });
                },
                function(){
                    $(this).parents("tr").find("td").each(function(){
                        $(this).removeClass("survey-list-hover");
                    });
                }
                );

        $(table + " td").blur(
                function(){
                    $(this).parents("tr").find("td").each(function(){
                        $(this).removeClass("survey-list-hover");
                    });
                });
    },

	rowSelect: function(table){
		$(table + " td").click(function(e){
			if(!$(e.target).hasClass("con-option")){
				$(e.target).parents("tr").find(".con-option").click();
			}
		});		
	},


    fileBrowser: function(field, label){
        $(field).css({opacity:0});
        if ($.browser.mozilla) {
            $(field).css("margin-left","-176px");
        }

        $(field).bind("change", function() {
            var str =  $(field).val();
            var idx = str.lastIndexOf("\\");
            if(idx>-1){
                $("#file-label").val(str.substring(idx+1,str.length));
            }else{
               $("#file-label").val(str);
            }
        });
    },

    options: function(parent, field, custom) {

        $(parent + " .con-option").click(function(event) {

            $(parent + " .con-option").removeClass("selected");

            $(this).addClass("selected");

            var value = $(this).attr("val");

            $(field).val(value);

            if (custom) {
                $.MT.controls.options[custom.method](this);
            }

            event.stopPropagation();

        });
    },

    checkbox: function(instance, field, type, method) {
        $(instance).click(function(event) {
                
                $(this).toggleClass("selected");
                var value = $(this).attr("val");

                var set;
                
                set = (type == "multi" ? $(this).parent().find(field) : $(field));

				if($(this).attr("val2") != undefined){
					var value2 = $(this).attr("val2");
                	set.val((set.val() == value ? value2 : value));
				}else{
			    	set.val((set.val() == value ? "" : value));
				}
				
                if(method){
                    method(this);
                }
        });
    },

	hover: {
	
	  init: function(x){		
		if(x.target == "multi"){
			$.MT.controls.hover.multi(x.element);			
		} else{
			$.MT.controls.hover.single(x.element);
		}
	},
		
	  single: function(y){
			var el = (y == Object ? y : $(y) );
					
			el.hover(
				function(){
					$(this).addClass("hover");
				},
				function(){
					$(this).removeClass("hover");				
				});

			el.blur(
				function(){
					$(this).removeClass("hover");				
				});									
		},
		
	  multi: function(y){
			var el = (y == Object ? y : $(y) );		
		
			el.hover(
				function(){
					$(this).children().eq(0).addClass("hover");					
					$(this).children().eq(1).addClass("hover");	
				},
				function(){
					$(this).children().eq(0).removeClass("hover");					
					$(this).children().eq(1).removeClass("hover");				
				});

			el.blur(
				function(){
					$(this).children().eq(0).removeClass("hover");					
					$(this).children().eq(1).removeClass("hover");				
				});									
		}				
	} 
};

$.MT.controls.valueList = {
    init: function(ob){
        $("#add-field").click(function(){
            $("#value-items").prepend("<input type='text'>");
        });
    }
};


$.confirmIt = function(o){
    $.MT.controls.confirm.init(o);
};

$.MT.controls.confirm = {

    overlay: $('<div id="simpleOverlay"></div>'),

    box: $('<div class="confirm-box"><div class="text"></div><div class="button-bar"></div></div>'),
    
    button: $('<div class="button-holder"><a href=""></a><div></div></div>'),

    cancel: function(){
      $("#simpleOverlay").remove();
      $('.confirm-box').remove();
      $("#pbody").css("margin","0 0 0 0");
      $("#bcontrol").css("overflow","auto");
    },

    init: function(options){

        if(options && options.buttons && options.text){
            var confirm = $.MT.controls.confirm;

            var box = $(confirm.box).clone();

            //add confirmation text
            box.find(".text").html(options.text);

            var y = options.buttons.length;
            var ob = options.buttons;
            
            //create the buttons
            for( var item in ob ){
                var el = ob[item];
                var b = $(confirm.button).clone();

                b.find("a").text(el.name);
                b.addClass(el.className);
                if(el.method == "cancel"){
                b.click(function(e){
                    e.preventDefault();
                    $.MT.controls.confirm.cancel();
                });
                }else{
                b.click(el.method);
                }
                
                box.find(".button-bar").append(b);
            }

            var overlay = $(confirm.overlay).clone();            

            overlay.css({
                width: $(window).width(),
                height: $(window).height(),
                top: $("#bcontrol").scrollTop(),
                display: "block",
                opacity: 0.6
            });

            $("body").append(overlay).end().find("#pbody").css("margin","0");

            //options buttons
            $("body").append(box);

            $("#bcontrol").css("overflow","hidden");

            //set the width if specified
            if(options.width){
                box.css("width", options.width);
            } else {
                options.width = box.width();
            }
            
            options.height = box.height();

            //set position
            box.css({top: $("#bcontrol").scrollTop() + ( parseInt($(window).height() / 2) - (parseInt(options.height / 2) + 200)),
                     left: ( parseInt($(window).width() / 2) - parseInt(options.width / 2) )
            });

            $("#simpleOverlay").click(function(e){
                e.preventDefault();
                e.stopPropagation();
                $.MT.controls.confirm.cancel();
            });
        }
    }
};



$.MT.controls.editInPlace = {

    init: function(){
        $(".editable-field").unbind();

        $(".editable-field").hover(function(){
            $(this).addClass("edit-hilite");
        },function(){
            $(this).removeClass("edit-hilite");
        });


        $(".editable-field").click(function(e){
            e.preventDefault();
            $(this).hide();
            var value =  $(this).text();
            $(this).next(".editing").addClass("busy").val(value);
            $(this).next(".editing").show();

            $("#bcontrol").bind('click.eid', function(e){
                if(!$(e.target).hasClass("editable-field") && !$(e.target).hasClass("edit-field")){

                $.MT.controls.editInPlace.edit(e.target, this);

                }
               $(e.target).next(".editing").find(".edit-field").focus();

              });

            $("#bcontrol").bind('keypress.eid', function(e){
                if(e.which == 13){
                $.MT.controls.editInPlace.edit(e.target, this);
                }
                });


        });
    },

    edit: function(x, y){
            $(".edit-field").each(function(){

                if($(this).parents(".editing").hasClass("busy")){

                    if($(this).val() == ""){
                        $(y).find(".editing").hide();       
                        $(this).parent().prev(".editable-field").removeClass("edit-hilite").show();
                        $(this).parents(".editing").removeClass("busy"); 
                        $("#bcontrol").unbind(".eid");
                    }   else{
                        var action = $(this).attr("action");
                        if(action !== undefined){
                            $.MT.controls.editInPlace.save(action, $(this));
                       }
                        else{
                            $(y).find(".editing").hide();       
                            $(this).parent().prev(".editable-field").removeClass("edit-hilite").text($(this).val()).show();
                            $(this).parents(".editing").removeClass("busy");
                        }
                        $("#bcontrol").unbind(".eid");
                    }
                }
            });
    },

    save: function(action,target){

        var groupId = $(target).parents(".query-group").attr("groupid");

        $.MT.ajax({
            dataType: "json",
            url: action+target.val()+"&groupId="+groupId,
            success: function(data){
            target.parent().prev(".editable-field").removeClass("edit-hilite").text(target.val()).show();
            target.parents(".editing").removeClass("busy").hide();
            }
        });

    }
};



$.MT.controls.dropDown = {

    active: {},

    init: function(ob){
        //unbind any events attached to this drop down
        $("."+ob.name).unbind();
        $("."+ ob.name +"-container a").unbind();

        //default behavior
        ob.defaultBehavior = (ob.defaultBehavior !== undefined ? ob.defaultBehavior : true); 

        //animation speed for drop down list
		$.MT.controls.dropDown.speed = (ob.speed != undefined ? ob.speed : 10);

		//check status of dropdown
        if($.MT.controls.dropDown.view !== "hidden"){
            $.MT.controls.dropDown.hide();
        }

        //if checbox drop down
        if(ob.type !== undefined && ob.type == "checkbox"){
            $("."+ob.name).addClass("cbox-control");
            //set hide to false; 
            ob.defaultBehavior = false;
        }

        if(ob.resize == undefined){
            ob.resize = true;
        }

        //call back after the list is hidden
        if(ob.hideCallback){
            $.MT.controls.dropDown.hideCallback = ob.hideCallback;
        }

        //keyboard shortcuts
        if(ob.keyboard){
            $.MT.controls.dropDown.keyboard.init();    
        }

        //initialize callback event
        if(!ob.dynamicList){
            $.MT.controls.dropDown.callback(ob);
        }
        
        //if drop down is used more than once on same page handle multiple lists
        if(ob.usage == "multi"){
            $("."+ob.name).each(function(){

                var listname = $(this).attr("listname");
                
                //grab list and append at the body root level for positioning
                $("body").append($("."+listname).eq(0));                

                //check if dynamic resize is enabled
				if(ob.resize !== undefined && ob.resize !== false){
				    $("."+listname).attr("style"," "); 	
					var width = $("."+listname).width() + 20;
                	$(this).css("width", width);
                	$("."+listname).attr("style"," ").css("width", width + 6);
				}

            });

      		$.MT.controls.dropDown[ob.name] = "."+$("."+ob.name).eq(0).attr("listname");

        } else{
			$.MT.controls.dropDown[ob.name] = "."+ ob.name +"-container";
		}


        //property that tracks whether a drop down list is visible
		if($.MT.controls.dropDown.view == undefined){
			$.MT.controls.dropDown.view = "hidden";
		}
                                                                        
		var list = $.MT.controls.dropDown[ob.name];   

        //for non-multi drop down -- should move this
		$("body").append($(list));

        //init reposition event -- needs to be called only once regardless of drop down type or instances
		if(!$.MT.controls.dropDown.reposition){
            $.MT.controls.dropDown.reposition();
		}

        //event that is triggered when clicking on a drop down
        $("."+ob.name).click(function(e){
            
            //check height of list and fix height if it is too tall
            mx = $(window).height()-$(this).offset().top-50;
            if($(list).height() > mx){ $(list).css("height", mx+"px");  } else { $(list).css("height", "auto"); }
            
            e.preventDefault();

            if($(this).hasClass("disabled")){
                return false;
            } else{

            	$(this).focus();
                
           	 	$.MT.controls.dropDown.active = this;

                $.MT.controls.dropDown.settings = ob;     

                //if dynamic list
                if(ob.dynamicList && !$(this).hasClass("drop-active")){

                    //clean up dom first
                    $(".dynamic-list").remove();

                    //get new list
                    var x = ob.dynamicList.call(this);

                    //append to body
                    $("body").append(x);

                    $.MT.controls.dropDown.callback(ob);

                }

                //check to see if active, if true de-activate
		        if($(".drop-active").size() > 0 && !$(this).hasClass("drop-active")){
		            $(".dropDown").removeClass("drop-active");
		            $(".drop-list").hide();
		        }

		        $(this).toggleClass("drop-active");

                //cleanup for auto complete when toggling
		        if($.MT.controls.dropDown.view == "visible" && $.MT.controls.dropDown.autoComplete.enable == "enabled"){
                    $.MT.controls.dropDown.autoComplete.cleanup("hide");
                } 

                //set visible status
		        $.MT.controls.dropDown.view = ("hidden" ? "visible" : "hidden");

                //determine list name
	            if(ob.usage == "multi"){
	                list = "."+$(this).attr("listname");
	            } else{
			 	    if($(this).attr("listname") != "" && $(this).attr("listname") != undefined ){
			            list = "#"+ $(this).attr("listname");
			         }
				}
                //set active list
				$.MT.controls.dropDown.activeList = list;

                //if auto complete intialize auto complete box
                if(ob.autoComplete == "auto"){
                    $.MT.controls.dropDown.autoComplete.init();
                }

                // NEW MENU OPTIONS
                
                //menu offset (padding on edges)
                var menuOffset = (ob.menuOffset)?ob.menuOffset:false;
                
                //position the drop down list
                if(ob.menuPosition != undefined && ob.menuPosition == "right") {
                    
                    // Special Right Positioning
                    // Get Offset Options...
                    //horizOffset = (ob.options.horizOffset)?ob.options.horizOffset:0;
                    //vertOffset = (ob.options.vertOffset)?ob.options.vertOffset:0;

                    // Do the Math...
                    rightPos = $(window).width() - $(this).offset().left - $(list).width();
                    topPos = $(this).offset().top + $(this).height();
                    
                    // Output positioning... if menu is under 50px to the right edge, default to 50px...
                    var positioning = {right: (menuOffset && rightPos<menuOffset)?menuOffset:rightPos, top: topPos};
                       
                } else {
                    leftPos = $(this).offset().left;
                    
                    // Default Positioning on Left.
                    var positioning = {left: (menuOffset && leftPos<menuOffset)?menuOffset:leftPos, top: $(this).offset().top + 22};
                }
                
                $(list).css(positioning).slideToggle($.MT.controls.dropDown.speed);

                //position the drop down list (old)
		        //$(list).css({left: $(this).offset().left, top: ($(this).offset().top + 22)}).slideToggle($.MT.controls.dropDown.speed);
			}
        });

    },

    defaultBehavior: function(ob){

        //hide drop down and set the value -- standard behavior for a drop down

        var d = $.MT.controls.dropDown;
        var settings = d.settings;

        if(d.autoComplete.enable == "enabled"){
            d.autoComplete.cleanup();
        }

        if(!ob.dynamicList){
        if($(d.active).find("a").size() > 0){
            $(d.active).find('a').html($(this).html());
        } else {
            $(d.active).html($(this).html());
        }
        }
        
        $("."+ settings.name +"-container").hide();

        $(d.active).removeClass("drop-active");

    },

    callback: function(ob){
        //default call back method
        $("."+ ob.name +"-container a").click(function(e) {
            if(!ob.standardLinks){
                e.preventDefault();
            }
            var d = $.MT.controls.dropDown;
            var settings = d.settings;

            //default drop down behavior of hiding and setting value when clicking on option
            //can be overriden with setting default to false
            if( settings.defaultBehavior ){
                d.defaultBehavior.call(this, ob);
            }

            //execute pre-callback for checkbox functionality
            if($(d.active).hasClass("cbox-control")){

                d.checkbox.init(this, ob);
                
            } else{

                //custom callback method
                if(ob.method){
                    ob.method(this);
                }
            } 

        });
    },

    reposition: function(){
		   $.MT.controls.dropDown.reposition = true;
           $(window).bind(
            	   "resize",
                   function() {
					   if($.MT.controls.dropDown.view == "visible"){
						   var active = $.MT.controls.dropDown.active;
						   var activeList = $.MT.controls.dropDown.activeList;
                           $(activeList).css({left: $(active).offset().left, top: $(active).offset().top + 25});
						}
            }).trigger("resize");
    },

    hide: function(){
        $("#bcontrol").click(function(e){
            if(!$(e.target).parents().hasClass("drop-list") && !$(e.target).parents("div").hasClass("dropDown") && !$(e.target).hasClass("dropDown")){
                $(".drop-list").hide();
                var d = $.MT.controls.dropDown;
                
                $(d.active).removeClass("drop-active");
				d.view = "hidden";

                if(d.autoComplete.enable == "enabled"){
                    d.autoComplete.cleanup("hide");
                }

                if(d.hideCallback && d.active !== null){
                    d.hideCallback();
                }

                if($(d.active).hasClass("cbox-control") && d.active !== null){
                    d.checkbox.onHide();
                }

                d.active = null;
            }
        });
    },

    checkbox: {

        tempKey: [],

        tempLabel: [],

        currentKey: [],

        currentLabel: [],

        init: function(context, ob){
            var c = $.MT.controls.dropDown.checkbox;
            var active = $.MT.controls.dropDown.active;
            var parent = $(context).parents("li");
            var valueLabel = $.trim($(context).text());

            if(parent.hasClass("mt-cbox")){

                var value = parent.attr("val");
                if(parent.hasClass("mt-cbox-selected")){
                    parent.toggleClass("temp-unselected");
                } else{
                    parent.toggleClass("temp-selected");
                }

                //if it does not exist in the array add it else remove it
                if($.inArray(value, c.tempKey) == -1){
                    c.tempKey.push( value );
                    c.tempLabel.push( valueLabel );
                    //console.log("added value");
                } else{
                    c.tempKey.splice($.inArray( value, c.tempKey ), 1);
                    c.tempLabel.splice($.inArray( valueLabel, c.tempLabel ), 1);
                }

            } else if(context.hasClass = "apply-button"){
                var list = $.MT.controls.dropDown.activeList;
                var param;

                $(list).find(".temp-selected").removeClass("temp-selected").addClass("mt-cbox-selected");
                $(list).find(".temp-unselected").removeClass("temp-unselected").removeClass("mt-cbox-selected");

                c.currentKey = c.tempKey.slice(0);
                c.currentLabel = c.tempLabel.slice(0);

                if(c.currentKey.length > 0 && c.currentKey.length !== $(".mt-cbox").size()){
                    param = c.currentKey.join(",");
                    $(active).html(c.currentLabel.sort().join(", "));

                } else{
                    param = "any";
                    $(active).html("Any");
                };

                if(ob.method){
                    ob.method({context: context, param: param});
                }


            }},

        onHide: function(){
            var c = $.MT.controls.dropDown.checkbox;
            //set values back to current
            c.tempKey = c.currentKey.slice(0);
            c.tempLabel = c.currentLabel.slice(0);
            $("li.mt-cbox").removeClass("temp-selected temp-unselected");
        }

    },

    keyboard: {

        keyName:  {
            UP: 38,
            DOWN: 40,
            RETURN: 13,
            ESC: 27
        },

        init: function(){

            $(".drop-list li").hover(
                    function(){
			$(this).addClass("hover-item");
		},
		function(){
			$(this).removeClass("hover-item");
		}

		);

		$.MT.controls.dropDown.keyboard.keyEvents();

		//console.log("controls activated")
		},
		checkView: function(item, direction){
			var height = 200;
			var active = $.MT.controls.dropDown.activeList;
			//var active = $(".execute");
			var top = $(active).scrollTop();
			var itemHeight = 21.5;
			var current;


			if(direction === "up"){
				current = (item - 1) * itemHeight;
				if(top > current){
					$(active).scrollTop(top - itemHeight);
				}

			} else{
				current = (item + 1) * itemHeight;
				if((height + top) < current){
					$(active).scrollTop(top + itemHeight);
				}

			}

		},
		keyEvents: function(keys){

		$("#bcontrol").unbind('keyup.dropDown');

		$("#bcontrol").bind('keyup.dropDown', function(e){
			var key = $.MT.controls.dropDown.keyboard.keyName;
			if(e.which == (key.Down || key.UP)){
				e.stopPropagation();
			}



			setTimeout(function(){

			var active = $.MT.controls.dropDown.activeList;
			//var active = $(".execute");

			var k = $.MT.controls.dropDown.keyboard;

			var selected = $(active).find("li.hover-item").eq(0);

			var index =  selected.parent().children("li:visible").index(selected);

			var items = $(".drop-list li:visible");

			//console.log(" #of visible items: "+items.size());

	        switch(e.which){

				case key.UP:
				e.preventDefault();

				if(index > 0 ){
					//console.log("up arrow "+index);
					items.removeClass("hover-item");
					k.checkView(index-1, "up");
					items.eq(index-1).addClass("hover-item");

				}else{
					//console.log("up -- empty ");
					items.removeClass("hover-item");
					$(active).scrollTop($(active).height());
					items.eq(items.size() - 1).addClass("hover-item");
				}

				break;


				case key.DOWN:
				e.preventDefault();

				if(index > -1  && ( index + 1) < items.size() ){
					//console.log("down arrow "+index);
					items.removeClass("hover-item");
					k.checkView(index+1);
					items.eq(index+1).addClass("hover-item");

				}else{
					//console.log("down -- empty ");
					items.removeClass("hover-item");
					$(active).scrollTop(0);
					items.eq(0).addClass("hover-item");
				}

				break;

				case key.RETURN:
				e.preventDefault();

				//select the current drop down
				$(".hover-item a").click();

				//console.log("hit enter");
				//check if sel exists if so click it
				break;

				case key.ESC:
				e.preventDefault();

				//escape the current drop down and selection
				$("#bcontrol").click();

				//console.log("escape");

				break;

	        }
		return false;
	    }, 30)});


}
	},

    autoComplete : {
		init: function(){

            $.MT.controls.dropDown.autoComplete.enable = "enabled";

            //create input box and bind events

            var input = $('<input id="auto-input" type="text"/>').width($($.MT.controls.dropDown.active).width() - 2);

            var old = $($.MT.controls.dropDown.active).text();

            $($.MT.controls.dropDown.active).append(input);

            $("#auto-input").focus();

            //bind events
            $.MT.controls.dropDown.autoComplete.events(); 

		},

	 	refine : function(parent, term){
			var auto = $.MT.controls.dropDown.autoComplete;
			var items = $(parent).find("a");

			if($.trim(term) !== ""){
			items.parent().hide();

                items.each(function() {

                    var x = $(this).text().toLowerCase();
                    var t = term.toLowerCase();

                    var i = x.indexOf(t);

                    var k = new RegExp("\\b(" + term + ")", "i");

                    if (k.test(x)) {
                        var hilite = auto.hilite($(this).text(), term);
                        $(this).html(hilite).parent().show();
                    }
                });
            } else {
                $("span.Alite").each(function() {
                    $(this).after($(this).text()).remove();
                });
                items.parent().show();


            }
	    },
        
		hilite: function(value, term){

				 return value.replace(new RegExp("\\b("+ term +")", "gi"), '<span class="Alite">$1</span>');

		},
        
        cleanup: function(hide){
          if(hide == "hide"){
            $("#auto-input").remove();    
          }
          //remove highlights
            $("span.Alite").each(function() {
                $(this).after($(this).text()).remove();
            });
          //reset list so all items are shown by default  
          $($.MT.controls.dropDown.activeList).find("li").show();
          //change flag
          $.MT.controls.dropDown.autoComplete.enable = "disabled";
        },
        
        events: function(){

			var dropList = $($.MT.controls.dropDown.activeList);

			$("#auto-input").bind("keyup.complete",function (e) {

				var c = $("#auto-input").val();

 				$.MT.controls.dropDown.autoComplete.refine(dropList, c);
		    });


        }

	}
};


$.MT.controls.grid ={

    //default container id
    container: "#grid-container",

    //callback method
    callback: null,

    //grid url params used to build url
    url: {
        action: "/MemberSearch.action",
        eventLabel: "?_eventName=",
        event: "generateTableView",
        params: {
            pageNumber: "1",
            sortColIndex: "0",
            pageSize: "15"
        }
    },

    init: function(call, options){

        if(options){
            //set data type for ajax calls
            $.MT.controls.grid.dataType = ( options.dataType === undefined ? "html" : options.dataType );
            //if json view
            if( options.jsonView ){
                $.MT.controls.grid.jsonView = options.jsonView;
            }
            //if custom action
            if( options.action ){
                $.MT.controls.grid.url.action = options.action;
            }
            //container that holds the grid
            if( options.container ){
                $.MT.controls.grid.container = options.container;
            }
            //custom callback that is executed after default grid events are loaded
            if( options.callback ){
                $.MT.controls.grid.callback = options.callback;
            }
            if( options.refreshPagination ){
                $.MT.controls.grid.refreshPagination = options.refreshPagination;
            }
            if( options.params ){
                $.extend($.MT.controls.grid.url.params, options.params);
            }
        }

        if(call){
            switch(call){
                case "events":
                //init events for grid -- html is already present on the page
                    $.MT.controls.grid.events();
                    break;
                case "getGrid":
                //load entire grid
                    $.MT.controls.grid.getGrid();
                    break;
                case "getPage":
                //load the body of a specific page
                    $.MT.controls.grid.getPage();
                    break;
            }

        }
      return false;
    },

    events: function(){
        $.MT.controls.grid.blockSettings();
        //if grid is present load events
        if($(".grid").size() > 0){
            $.MT.controls.grid.paginate();
            $.MT.controls.grid.sort();

            //if initial view is generated in a JSP execute callback now
            if($.MT.controls.grid.callback != null){
                $.MT.controls.grid.callback();
            }  
        }
    },
    //url builder method
    buildUrl: function(){

        var urlObj = $.MT.controls.grid.url;

        var param = "";

        for( var item in urlObj.params ){
            param += "&" + item + "=" + urlObj.params[item];
        }

        var url = $.MT.fullContext + urlObj.action + urlObj.eventLabel + urlObj.event + param ;

        return url;
    },
    //loading message overlay settings
    blockSettings: function(){
        $.blockUI.defaults = {
            css: {
                padding: 0,
                margin: 0,
                width: '30%',
                top: '10%',
                left: '38%',
                textAlign: 'center',
                backgroundColor:'#fff',
                cursor: 'wait',
                fontFamily: 'arial'
            },
            baseZ: 1000,
            overlayCSS:  {
                backgroundColor:'#fff',
                opacity:        '0.6'
            }
        };
    },

    //loads the entire grid. header body and pagination bar
    getGrid: function(){

        var container = $.MT.controls.grid.container;

        if($.MT.controls.grid.state !== "loading"){

            $.MT.controls.grid.state = "loading";

            $(container).block({message: "<div class='generic-busy'>Loading...</div>"});

            $.MT.controls.grid.url.event = "generateTableView";

            var url = $.MT.controls.grid.buildUrl();

            $.MT.ajax({
                dataType: $.MT.controls.grid.dataType,
                url: url,
                success: function(data){

                    $(container).empty().append(data);

                    $.MT.controls.grid.events();

                    $.MT.controls.grid.state = "display";

                }});
        }
    },
    //sort method for sorting the grid
    sort: function(tableId){

        $(".grid th a").click(function(e){
            e.preventDefault();
			if($(this).parents("th").hasClass("sortable")){
            var column = $(this).parents("th").attr("column");

            if($(this).parents("th").hasClass("ascending")){
                $(this).parents("table").find("th").removeClass("descending").removeClass("ascending");
                $(this).parents("th").addClass("descending");
                $.MT.controls.grid.url.params.sortDir = "desc";
            } else{
                $(this).parents("table").find("th").removeClass("descending").removeClass("ascending");
                $(this).parents("th").addClass("ascending");
                $.MT.controls.grid.url.params.sortDir = "asc";
            }
            $.MT.controls.grid.url.params.pageNumber = 1;
            $(".current-page").text("1");
            $(".paging-prev").removeClass("direction-active");    
            $(".paging-prev").removeClass("direction-active"); 
            $.MT.controls.grid.url.params.sortColIndex = column;
            $.MT.controls.grid.url.event = "getGridBody";

            var url = $.MT.controls.grid.buildUrl();

            $(".grid tbody").block({message: "<div class='generic-busy'>Loading...</div>"});

            var container = $.MT.controls.grid.container;

            $.MT.ajax({
                dataType: $.MT.controls.grid.dataType,
                type: "GET",
                url: url,
                success: function(data){

                    var tBody = ($.MT.controls.grid.jsonView === undefined ? data : $.MT.controls.grid.jsonView(data)); 

                    $(container +" tbody").after(tBody).remove();
                    if ($.MT.controls.grid.callback != null) {
                        $.MT.controls.grid.callback(this);
                    }
                	
					$(container).unblock();

				}
            });
		}else{
			return false;
		}
        });

    },
    //pagination events
    paginate: function(){

        if($.MT.controls.grid.jsonView == undefined){
            //determine total pages
            $.MT.controls.grid.totalPages = parseInt($(".total-pages").eq(0).text());
        }    

        //show or hide pagination box based on number of pages
        if($.MT.controls.grid.totalPages > 1){
            $(".paging-next").addClass("direction-active");
        }else{
            $(".pagination-controls").hide();
        }

        //event that gets triggered when clicking next of previous
        $(".paging-action a").click(function(e){
            e.preventDefault();

            if($(this).hasClass("direction-active")){
                $.MT.controls.grid.getPage(this);
            }
        });

        //page box events, track whether active, highlight on focus
        $(".page-direct").blur(function(){
            $(this).removeClass("active-field");
            $.MT.controls.grid.gomsgField = "passive";
        });
        $(".page-direct").click(function(){
            $.MT.controls.grid.gomsgField = "active";
            $(this).addClass("active-field");
            $(this).val("");
        });

        //enter button event go to specific page
        $("#bcontrol").bind('keypress.eid', function(e){
            if(e.which == 13){

                if( $.MT.controls.grid.gomsgField == "active"){
                    var value =  $(".page-direct").val();

                    if( value > 0 && value <= $.MT.controls.grid.totalPages ){
                        $.MT.controls.grid.url.params.pageNumber = value;
                        $.MT.controls.grid.init("getPage");
                    }
                }
                return false;
            }
        });

    },

    //loads a particular page and handles pagination bar view
    getPage: function(x){
        var container = $.MT.controls.grid.container;

        if($.MT.controls.grid.state !== "loading"){

            $.MT.controls.grid.state = "loading";

            var gridUrl = $.MT.controls.grid.url;

            if(x){
                var action = $(x).attr("action");

                if(action == "previous"){
                    gridUrl.params.pageNumber = parseInt(gridUrl.params.pageNumber) - 1;
                }

                if(action == "next"){
                    gridUrl.params.pageNumber = parseInt(gridUrl.params.pageNumber) + 1;
                }
            }

            $(".current-page").empty().append(gridUrl.params.pageNumber);

            gridUrl.event = "getGridBody";

            var url = $.MT.controls.grid.buildUrl();

            $(container).block({message: "<div class='generic-busy'>Loading...</div>"});

            $.MT.ajax({
                dataType: $.MT.controls.grid.dataType,
                type: "GET",
                url: url,
                success: function(data){

                    //insert snippet here
                    var tBody = ($.MT.controls.grid.jsonView === undefined ? data : $.MT.controls.grid.jsonView(data)); 

   
                    $(container +" tbody").after(tBody).remove();

                     //if JSON view get the first page of the grid
                    if($.MT.controls.grid.jsonView !== undefined){
                         $.MT.controls.grid.totalPages = parseInt(data.totalPages);
                    } else if($(data).find("#pTotal")[0] !== undefined){
                         $.MT.controls.grid.totalPages = parseInt($(data).find("#pTotal").val());                    
                    }


                    if($.MT.controls.grid.refreshPagination == "refresh"){
                        $(".current-page").text("1");
                        $.MT.controls.grid.url.params.pageNumber = 1;
                        $(".total-pages").text($.MT.controls.grid.totalPages);

                        $.MT.controls.grid.refreshPagination = "done";
                             //console.log($.MT.controls.grid.totalPages)
                        if($.MT.controls.grid.totalPages < 2){
                            $(".pagination-controls").hide();
                        } else {
                            $(".pagination-controls").show();
                        }

                    }


                    var currentPage = parseInt($(".current-page").text());

                    if(currentPage < $.MT.controls.grid.totalPages){
                        $(".paging-next").addClass("direction-active");
                    } else{
                        $(".paging-next").removeClass("direction-active");
                    }
                    if(currentPage > 1){
                        $(".paging-prev").addClass("direction-active");
                    }else{
                        $(".paging-prev").removeClass("direction-active");
                    }

                    $(".page-direct").blur();

                    $.MT.controls.grid.state = "display";



                    if($.MT.controls.grid.jsonView != null && $.MT.controls.grid.jsonInit == undefined){
                         $.MT.controls.grid.events();
                         $.MT.controls.grid.jsonInit = true;
                    }

                    if ($.MT.controls.grid.callback != null) {
                        $.MT.controls.grid.callback(this);
                    }

                    $(container).unblock();

                }
            });

        }

    }

};



$.MT.controls.barGraphs = {
	
	init: function(ob){

					$.MT.controls.barGraphs[ob.name] = 0;				
					
					$(ob.target).each(function(i){
					
						var width = parseInt($(this).attr("bwidth"));

						//$.log( width + " > "+ $.MT.controls.barGraphs.batch)
						//$.log( width > $.MT.controls.barGraphs.batch)
															
						if( width > $.MT.controls.barGraphs[ob.name] ){
							$.MT.controls.barGraphs[ob.name] =  width;
						}
						
					});
					
					//$.log($.MT.controls.barGraphs.batch)

					var multip, lnum = $.MT.controls.barGraphs[ob.name];
					
			        if( lnum < 20 ){ multip = 9; }
			        if( lnum > 19 && lnum < 40 ){ multip = 4; }
			        if( lnum > 39 && lnum < 70 ){ multip = 2; }
			        if( lnum > 69 ){ multip = 1; }			
									         
			   
					//$.log(multip)

					$(ob.target).each(function(){
  						var multiplier = (	multip == undefined ? 1 : multip  );
  		        		var outCont = $(this).attr("bwidth") * multiplier;
  		        		var inCont = $(this).find("div").attr("bwidth") * multiplier;

  		        		$(this).animate({"width": outCont}, "slow");
  		        		$(this).find("div").animate({"width": inCont}, "slow");

  		    		});

		}
};


$.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }

        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};