﻿var mt={
    appPath:'',
    location:'',
    domain:'',
    imageServer:'',
    imageUploads:''
};

mt.repository = function() {
    var _this = this;

    this.length = 125;
    this.currentPage = 0;
    this.pages = new Array();
    this.maxResults = 25;
    this.maxPages = 0;

    this.load = function(objects) {
        objects = (!objects ? [] : ($.isArray(objects) ? objects : [objects]));
        var acc = 0;
        var counter = 0;

        if (objects.length == 0) {
            _this.pages.length = 0;
            _this.maxPages = 0;
        }
        else
            _this.currentPage = 0;
        _this.maxPages = Math.ceil(objects.length / _this.maxResults);

        for (l = 0; l < _this.maxPages; l++) {
            var pageLength = 25;
            var page = new Array();
            _this.pages[l] = page;

            for (i = 0; i < pageLength; i++) {
                var obj = objects[acc];
                if (obj) {
                    _this.pages[l].push(obj);
                    acc++;
                }
            }
        }
    };
    this.current = function() {
        var current = _this.pages[_this.currentPage];
        return (current ? current : []);
    };
    this.forward = function() {
        if (_this.currentPage <= _this.maxPages) {
            _this.currentPage++;
            return _this.pages[_this.currentPage];
        } else {
            return false;
        }

    };
    this.backward = function() {
        if (_this.currentPage > 0) {
            _this.currentPage--;
            return _this.pages[_this.currentPage];
        } else {
            return false;
        }

    };
    this.jumpTo = function(pageNumber) {
        _this.currentPage = pageNumber;
        return _this.pages[_this.currentPage];
    };
    this.hasMoreForward = function() {
        if ((_this.currentPage + 1) < _this.pages.length) {
            return true;
        } else { return false; }
    };
    this.hasMoreBackward = function() {
        if (_this.currentPage > 0) {
            return true;
        } else { return false; }
    };
};

/*
Array.prototype.remove=function(s){
    for(var i=0; i<this.length; i++){
        if(s==this[i]) this.splice(i, 1);
    }
};

Array.prototype.clear=function(){
    this.length=0;
};
*/
mt.array={
    remove: function(myArray, element){
        for(var i=0; i<myArray.length; i++){
            if(element==myArray[i]) myArray.splice(i, 1);
        }
    },
    clear: function(myArray){
        myArray.length=0;
    }
}

String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/gm,'');
    //return( this.replace(new RegExp("^([\\s]+)|([\\s]+)$", "gm"), "") );
};

String.prototype.stripHtml=function(){
    return this.replace(/(<([^>]+)>)/ig,"");
};

String.prototype.replaceAll=function(s1, s2){ 
   return this.replace(new RegExp(s1,"g"), s2);
};

//mt.events = new EventPublisher();
mt.events = {};

mt.events.highlight = function(input){
    var onFocus = function(event){
        $(this).select();
    };
    input.focus(onFocus);
};

mt.events.boldKeywords = function(input, keyword) {
    input = input.replace(input.match(keyword, 'i'), "<b>" + input.match(keyword, 'i') + "</b>");
    return input;
};

mt.events.createAbstract = function(text, length) {
    text = text.slice(0, length);
    var words = text.split(" ");
    words.pop();
    text = words.join(" ");
    return text;
};

mt.events.capitolize = function(input){
    var onKeyUp = function(event){
        var _this=$(this);
        _this.val(_this.val().toUpperCase());
    };
    input.keyup(onKeyUp);
};

mt.events.onEnter = function(input, callback){
    var checkKey = function(event){
        if(event.keyCode == 13)
            callback();
    };
    input.keyup(checkKey);
};

mt.events.characterCount = function(input, element, length) {
    var warning = length - 20;

    var textChangeEvent = function(event) {
        var _this = $(this);
        var _length = _this.val().length
        element.html(length - _length);
        if (_length > warning){
            if(_length >= length){
                element.removeClass('CharCountWarning');
                element.addClass('CharCountError');
                //element.css({color:"#D40D12"});
            }
            else{
                element.removeClass('CharCountError');
                element.addClass('CharCountWarning');
                //element.css({color:"#5C0002"});
            }
        }
        else{
            element.removeClass('CharCountWarning');
            element.removeClass('CharCountError');
            //element.css({color:"#000"});
        }
    };
    element.html(length);
    input.bind('change keyup keydown',textChangeEvent);
};

mt.events.defaultText = function(input, defaultText){
    var onFocusEvent = function(event){
        var _this=$(this);
        if(_this.val() == defaultText){
            _this.val('');
            _this.css({'font-style':'normal','font-weight':'bold'});
        }
    };

    var onBlurEvent = function(event){
        var _this=$(this);
        if (_this.val().length == 0){
            _this.val(defaultText);
            _this.css({'font-style':'italic','font-weight':'normal'});
        }
    };
    input.css({'font-style':'italic','font-weight':'normal'});
    input.val(defaultText);
    input.focus(onFocusEvent);
    input.blur(onBlurEvent);
};

mt.events.cancelBubble = function(e){
    if (!e) e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
};

mt.quotes = function(tickerArray, callback){
    var useProxy=function(){
        mt.ajax(
           'proxy.asmx/GetQuotes',
            '{tickers:"'+tickerArray+'"}',
            function(response){
                var obj=mt.util.eval(response);
                if(obj.quotelist)
                    callback(obj.quotelist);
            }
        );
    };

    useProxy();
//    try{
//        if(tos && tos.pods){
//            // For lightweight quotes
//            tos.pods.providers.quotes(tickerArray, callback);
//            // For thinkPod
//            //tos.pods.data.provider.quotes(tickerArray, callback);
//        }
//        else{
//            useProxy();
//        }
//    }
//    catch(msg){
//        useProxy();
//    }
};

mt.modalDialog = function(linkElement) {
    linkElement.click(function(e) {  
        //Cancel the link behavior  
        e.preventDefault();  
        //Get the A tag  
        var id = $(this).attr('href');  

        //Get the screen height and width  
        var maskHeight = $(document).height();  
        var maskWidth = $(window).width();  

        //Set heigth and width to mask to fill up the whole screen  
        $('#mask').css({'width':maskWidth,'height':maskHeight});  

        //transition effect       
        $('#mask').fadeIn(1000);      
        $('#mask').fadeTo("slow",0.8);    

        //Get the window height and width  
        var winH = $(window).height();  
        var winW = $(window).width();  

        //Set the popup window to center  
        $(id).css('top',  winH/2-$(id).height()/2);  
        $(id).css('left', winW/2-$(id).width()/2);  

        //transition effect  
        $(id).fadeIn(2000);   
    });

    //if close button is clicked  
    $('.window .close').click(function (e) {  
        //Cancel the link behavior  
        e.preventDefault();  
        $('#mask, .window').hide();  
    });

    //if mask is clicked  
    $('#mask').click(function () {  
        $(this).hide();  
        $('.window').hide();  
    });
};

mt.header={
    closeTempTab: function(e){
        var tab=$(e.target).parent('a').parent('li.TempTab').css({display:'none'});
        var isCurrent=tab.hasClass('Current');

        var callback=function(){
            if(isCurrent){
                var redirect=mt.appPath+mt.session.referrer;
                if(window.location == redirect)
                    window.location=mt.appPath+'thinkshare/';
                else
                    window.location=mt.appPath+mt.session.referrer;
            }
        };

        var tabID=tab.attr('id');
        tabID=tabID.replace(/Mytrade_/,'');

        mt.ajax(
            'users.asmx/CloseTempTab',
            '{tabID:"'+tabID+'"}',
            callback
        );

        mt.events.cancelBubble(e);
    }
};

mt.session = {
    key: '',
    userID: '',
    username: '',
    slashname: '',
    photo: '',
    email: '',
    firstName: '',
    middleName: '',
    lastName: '',
    displayName: '',
    allStar: '',
    isGuest: true,
    singleWindowMode: false,
    //guestTabs: new Array(),
    //guestPods: new Array(),
    //guestTabCookie: null,
    //guestPodCookie: null,
    //guestPodDataCookie: null,
    setIsGuest: function(isGuest){
        this.isGuest=mt.util.parseBool(isGuest);
    }
//    initialize: function(){
//        this.fullName=this.firstName+' '+this.lastName;
//        if(mt.session.isGuest){
//            $('span#HeaderGreetingName').text(this.fullName);
//            mt.login.setLoggedIn();
//        }
//    }
//    logout: function(){
//        this.key='';
//        this.userID='';
//        this.username='';
//        this.email='';
//        this.firstName='';
//        this.middleName='';
//        this.lastName='';
//        this.allStar='';
//        this.isGuest=true;
//        this.guestTabs=null;
//        this.guestPods=null;
//    }
};

mt.util = {
    parseBool: function(val) {
        if (!val || val == "False" || val == "false")
            return false;
        else
            return true;
    },
    parseChecked: function(val) {
        if (val == "checked")
            return true;
        else
            return false;
    },
    getHeight: function() {
        //return document.height;
        return $(document).height();
        //return window.innerHeight;
        //return document.viewport.getHeight();
    },
    getWidth: function() {
        //return document.width;
        return $(document).width();
        //return window.innerWidth;
        //return document.viewport.getWidth();
    },
    getRandom: function(min, max) {
        //return (Math.round((max-min)*Math.random()+min));
        return (Math.floor((max - min + 1) * Math.random()) + min);
    },
    loadScript: function(url) {
        //        var regexp=/^mt\./gi;
        //        if(url == "")
        //            return;
        //        else if(regexp.exec(url))
        //            url=('Javascript/'+url);

        //        var e=new Element('script');
        //        e.src=url;
        //        e.type='text/javascript';
        //        document.body.appendChild(e);
    },
    createClass: function(objName, args) {
        if (!objName) return;
        var str = 'new ' + objName + '()';
        var obj = eval(str);
        obj.initialize(args);
        return obj;
    },
    eval: function(json) {
        return eval('(' + json + ')');
    },
    serializeToJson: function(obj) {

        var json = "{";
        var count = 0;
        for (var prop in obj) {
            if (typeof (obj[prop]) != "function") {

                if (count > 0) {
                    json = json + ",";
                }
                var propValue;
                if (typeof (obj[prop]) == "string") {
                    propValue = '"' + obj[prop] + '"';
                }
                else {
                    propValue = obj[prop];
                }

                json = json + prop + ":" + propValue;
                count++;
            }
        }

        json = json + "}";
        return json;

    },
    parseEpochDate: function(epochDate) {

        if (typeof epochDate == 'string') {

            var expression = new RegExp(/\d{10}/gi);
            epochDate = epochDate.match(expression);
            var returnDate = new Date(epochDate * 1000);
            return returnDate;
        }
        else
            return epochDate;
    },
    getTickerArray: function(tickers) {
        var array = [];
        tickers = tickers.replace(/,\s/g, ",");
        tickers = tickers.replace(/\s/g, ",");
        var tempArray = tickers.split(",");
        for (var i = 0; i < tempArray.length; i++) {
            if (tempArray[i] != "")
                array.push(tempArray[i]);
        }
        return array;
    },
    replaceLinks: function(text) {
        var linkExpression = new RegExp(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi);

        return text.replace(linkExpression, '<a href="$1" target="_blank">$1</a>');
    },
    stripDomainName: function(text) {
        var domainExpression = new RegExp(/(www.)?(\w+\.)(\w+(\/)?)/gi);

        var domain = text.match(domainExpression);
        if (domain && domain[0])
            return domain[0];
        else
            return text;
    },
    truncateText: function(text, length) {
        if (text.length > length)
            return text.substr(0, length - 1) + "…";

        return text;
    },
    //    replaceUrlsWithLinks: function(text) {
    //        return text.replace(
    //             /(ftp|http|https:\/\/)?(\w+\.)(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))/gi,
    //            '<a href="$1" target="_blank">$1</a>');
    //    },
    addHttpToLink: function(url) {
        url = url.trim().toLowerCase();
        if (url.length > 0) {
            if (url.indexOf("http://") != 0 && url.indexOf("https://") != 0 && url.indexOf("ftp://") != 0) {
                url = "http://" + url;
            }
        }
        return url;
    },
    isTrade: function(trade) {
        var isFullTrade;

        var fullTest = new RegExp("(BUY|SELL|BOT|SOLD)\\s([\\+\\-]\\d+)(\\s\\d\\/\\d)?\\s([A-Z]+\\s)+([\\d\\s\\w\\/]+)?(@[\\+\\-\\d\\.]+)\\s(\\w+)", "gi");
        var partTest = new RegExp("(\\w{3,6})\\s([\+-]\\d+)\\s", "gi");

        isFullTrade = fullTest.test(trade);

        if (isFullTrade) {
            return true;
        }
        else if (partTest.test(trade)) {
            if (confirm("I think what you entered is a trade, but it didn't pass the format test. Did you enter a trade?")) {
                return true;
            }
        }
        return false;
    },
    createCopyIcon: function(tradeID, text, width, height) {
        if (!width) width = 26;
        if (!height) height = 26;

        text = escape(text);
        text = text.replace(/\+/, '%2B');
        return $('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' +
        'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"' +
	    'width="' + width + '" height="' + height + '" id="CopyIcon' + tradeID + '" align="middle">' +
	    '<param name="FlashVars" value="clipboardText=' + text + '&tradeStreamID=' + tradeID + '&appPath=' + escape(mt.appPath) + '"/>' +
	    '<param name="allowScriptAccess" value="sameDomain" />' +
	    '<param name="allowFullScreen" value="false" />' +
	    '<param name="movie" value="../Flash/CopyIcon.swf" />' +
	    '<param name="quality" value="high" />' +
	    '<param name="wmode" value="transparent"/>' +
	    '<embed src="../Flash/CopyIcon.swf"' +
	    'flashvars="clipboardText=' + text + '&tradeStreamID=' + tradeID + '&appPath=' + escape(mt.appPath) + '" wmode="transparent"' +
	    'quality="high" width="' + width + '" height="' + height + '" name="CopyIcon" align="middle" allowScriptAccess="sameDomain"' +
	    'allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />' +
	    '</object>');
    },
    expandImage: function(img) {
        var width;
        img.click(function() {
            var _this = $(this);
            if (_this.css('width') == width)
                _this.animate({ width: '100%' }, 500, 'easeInOutExpo');
            else
                _this.animate({ width: width }, 500, 'easeInOutExpo');
        });
        width = img.css('width');
    }
};

mt.validate = {
    spaces: function(input, allowNull) {
        if (allowNull && (input == "")) {
            return true;
        }
        else {
            if (input.match(' ')) {
                return false;
            }
            else {
                return true;
            }
        }
    },
    email: function(input, allowNull) {
        if (allowNull && (input == "")) {
            return true;
        }
        else {
            var pattern = /^([+a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
            if (pattern.test(input)) {
                return true;
            }
            else {
                return false;
            }
        }
    }
};

mt.updater = function(handler, interval){
    this.intervalID=null;
    this.handler=handler;
    this.interval=interval;
    this.isStarted=false;

    this.start=function(){
        if(!this.intervalID){
            this.intervalID=setInterval(this.handler, this.interval);
            this.isStarted=true;
        }
    };
    this.stop=function(){
        if(this.intervalID){
            clearInterval(this.intervalID);
            this.isStarted=false;
        }
    };
};

mt.ajax = function(url, data, onSuccess, onError, timeout) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        /*url: mt.appPath + 'services/' + url,*/
        url: '/services/' + url,
        data: (data == null ? "{}" : data),
        dataType: 'json',
        timeout: timeout ? timeout : 5000,
        success: function(response) {
            if (response.hasOwnProperty("d")) {
                response = response.d;
            }
            if(onSuccess) onSuccess(response);
        },
        error: onError
    });
};

mt.images = {
    preload: function(src){
        var image=new Image();
        image.src=src;
    }
};

mt.footer = {
    openSuggestions: function(mode, title, path){
        var shadowBox = new mt.ui.shadowBox('mytrade | ' + title, 'destroy', 600);
        shadowBox.initialize();

        var iframe=$('<iframe style="width:100%;height:340px;border:none;"></iframe>');
        iframe.attr('src',path+'?Mode='+mode);
        iframe.attr('frameborder','0');

        shadowBox.addContent(iframe);
        shadowBox.show();
    }
}

mt.login = {
    source: '',
    login: function() {
        this.source = 'login';
        $('div#LoginError').css({ display: 'none' });
        //var username=$('input#Username').val();
        //var password=$('input#Password').val();
        var form = $('form#LoginForm');
        form.submit();
    },
    signUp: function() {
        this.source = 'signup';

        var loader = $('img#Loading').css({ display: 'block' });
        var inputs = $('input').attr("readonly", true);
        var select = $('select').attr("readonly", true);

        var username = $('input#Username').val();
        var password = $('input#Password').val();
        var email = $('input#Email').val();

        var isValid = mt.signUp.validate();

        var callback = function(response) {
            $("input#UserHash").val(response);
            var form = $('form#SignUpForm')
            form.submit();
        };

        //this.loader=new mt.ui.loader('SignUpForm');
        //this.loader.mask.css({background:'#fff'});

        if (isValid == true) {
            var data = '{username:"' + username + '",password:"' + password + '",email:"' + email + '"}';

            mt.ajax(
                'authentication.asmx/GetUserHash',
                data,
                callback
            );
            //Mytrade.Services.Authentication.GetUserHash(username, password, email, callback);
        }
        else {
            //this.loader.stop();
            inputs.removeAttr("readonly");
            select.removeAttr("readonly");
            loader.css({ display: 'none' });
            $('ul#Errors').css({ display: "block" });
        }
    },
    failed: function(msg) {
        var username;
        var password;
        if (this.source == "login") {
            //username=$('input#username').value;
            //password=$('input#password').value;

            var error = $('div#LoginError');
            error.text(msg);
            error.css({ display: 'block' });
        }
        else if (this.source == "signup") {
            $('input').removeAttr("readonly");
            $('select').removeAttr("readonly");
            $('img#Loading').css({ display: 'none' });
            $('li#FailedError').text('Registration failed: ' + msg).css({ display: "block" });
            $('ul#Errors').css({ display: "block" });
            //            this.loader.stop();
            //            username=$('SignUpUsername').value;
            //            password=$('SignUpPassword').value;
        }
        else {
            alert('Login or Sign Up failed due to technical difficulties. Please contact support@mytrade.com');
        }
    },
    success: function(slashname) {
        var appPath = mt.appPath.replace(/https/gi, 'http');
        //appPath=appPath.replace(/\/$/,"")
        if (mt.session.referrer == 'mypage/')
            window.location = appPath + slashname;
        else if (mt.session.referrer)
            window.location = appPath + mt.session.referrer;
        else
            window.location = appPath + 'thinkshare/';
    }
};

mt.chartShare = {
    shadowBox: null,
    callback: null,
    open: function() {
        var shadowBox = new mt.ui.shadowBox('Share a Chart', 'destroy', 420);
        shadowBox.initialize();

        var iframe = $('<iframe class="Backdrop" style="width:405px;height:330px;"></iframe>');
        iframe.attr('src', "/pods/ChartShare.aspx");
        iframe.attr('frameBorder', '0');
        iframe.attr('scrolling', 'no');
        iframe.attr('allowTransparency', 'true');

        shadowBox.addContent(iframe);
        shadowBox.show();
        mt.chartShare.shadowBox = shadowBox;
    },
    close: function() {
        if (mt.chartShare.shadowBox) {
            mt.chartShare.shadowBox.close();
            mt.chartShare.shadowBox = null;
            return true;
        }
        return false;
    }
};

mt.ui = {
    headerHeight:46,
    footerHeight:32
};

mt.ui.bindToWindowHeight=function(container, offset, minHeight, property){
    var setHeight=function(){
        var h=$(window).height()-mt.ui.headerHeight-mt.ui.footerHeight-offset;
        h = (h > minHeight ? h : minHeight);
        if(property == 'height')
            container.height(h);
        else
            container.css({'min-height':h+'px'});
    }

    setHeight();

    $(window).bind('resize', setHeight);
};

mt.ui.clear=function(){
    return $('<div class="Clear"></div>');
};

mt.ui.hover=function(id,className){
    $(id).hover(
        function(){$(this).addClass(className);},
        function(){$(this).removeClass(className);}
    );
};

mt.ui.openLink=function(title, href){
    var shadowBox=new mt.ui.shadowBox(title, "destroy", 800, 600);
    shadowBox.initialize();

    var iframe = new $('<iframe style="width:100%;height:580px;border:none;background:#fff;"></iframe>');
    iframe.attr('src',href);
    iframe.attr('frameborder','0');

    shadowBox.addContent(iframe);
    shadowBox.show();
};

mt.ui.createLink=function(href, text){
    var link=$('<a style="cursor:pointer;"></a>');
    //if(mt.session.singleWindowMode){
    //    link.href="javascript:mt.ui.openLink('"+text+"','"+href+"');";
    //}
    //else{
        link.attr('target','_blank');
        link.attr('href',href);
    //}
    link.html(text);
    return link;
};

mt.ui.createNewLink = function(href, text){
  var link=$('<a></a>');
  //link.target='_blank';
  link.attr('href',href);
  link.css({cursor:'pointer'});
  link.html(text);
  return link;
};

mt.ui.loader=function(container, height, opacity){
    this.container=$(container);
    this.container.css({position:'relative'});

    var w=this.container.width();
    var h=(this.container.height() | height);
    var t=Math.round(h/2-21);
    var l=Math.round(w/2-32);

    opacity=(opacity || opacity == 0 ? opacity : 20);
    if(opacity > 0){
        this.mask=$('<div></div>');
        this.mask.css({position:'absolute',top:'0px',left:'0px',width:w+'px',height:h+'px',
            'background-color':'#000','text-align':'center',filter:'alpha(opacity='+opacity+')',opacity:opacity/100});
        this.container.append(this.mask);
    }

    var img='loader_light.gif';
    if(mt.session.lookAndFeel == "TosDark")
        img='loader_dark.gif';

    this.loader=$('<img src="../Images/'+img+'" />');
    this.loader.css({position:'absolute',width:'48px',height:'48px',top:t+'px',left:l+'px'});

    this.container.append(this.loader);

    this.stop=function(){
        this.loader.remove();
        if(this.mask)
            this.mask.remove();
    };
};

mt.ui.shadowBox = function(title, closeAction, width, height){
    var _this=this;

    var justShadow=(title == null ? true : false);

    this.width=width;
    this.height=height;

    this.closeAction=closeAction;

    this.initialize=function(){
        var body=$(document.body);

        this.mask=$('<div class="ShadowBoxDrop"></div>');
        body.append(this.mask);

        if(!justShadow){
            this.pod=new mt.pod(null,title, this.close, true);

            this.pod.element.css({display:'none', position:'absolute', top:'6em',
                width:'600px','z-index':1001});
            this.pod.shadowBox=this;
            body.append(this.pod.element);

            this.setSize();
        }
    };

    this.addContent=function(element){
        this.pod.content.append(element);
        element.show();
    };

    this.setSize=function(){
        if(this.width){
            var w=mt.util.getWidth();
            var l=w/2-this.width/2;
            //var t=(document.body.scrollTop | window.scrollY);
            var t=(window.pageYOffset || document.documentElement.scrollTop || 0);
            this.pod.element.css({width:this.width+'px', left:l+'px', top:(t+30)+'px'});
        }
        if(this.height)
            this.pod.element.css({height:this.height+'px'});
    };

    this.show=function(){
        if(!justShadow){
            this.setSize();
            this.pod.element.show();
        }

        var maskHeight=document.body.scrollHeight+(window.scrollMaxY ? window.scrollMaxY : 0);
        if(maskHeight < window.innerHeight)
            maskHeight=window.innerHeight;
        this.mask.css({width:document.body.offsetWidth+'px', height:maskHeight+'px'});
        this.mask.show();
    };

    this.hide=function(){
        if(!justShadow)
            this.pod.element.hide();
        this.mask.hide();
    };

    this.close=function(){
        if(_this.closeAction=="hide")
            _this.hide();
        else
            _this.destroy();
    };

    this.destroy=function(){
        if(!justShadow)
            _this.pod.element.remove();
        _this.mask.remove();
    };
};

mt.pod=function(id, title, onClose, disableMin){
    var _this=this;

    this.id=id;
    this.content;
    this.element=$('<table border="0" cell-padding="0" cell-spacing="0"></table>');
    this.element.attr('id','Pod_'+id);
    this.element.addClass('Pod');
    this.element.pod=this;
    this.onClose=function(){onClose(_this);};
    this.isMoved=false;

    var r,c;

    var header=$('<table class="PodHeader" border="0"></table>');
    r=$('<tr></tr>').appendTo(header);

    this.xButton=$('<div class="PodX"></div>');
    this.xButton.mouseup(function(){_this.onClose();});
    mt.mouse.wireup(this.xButton);

    if(!disableMin){
        var arrow=$('<div class="PodArrow"></div>');
        this.arrow=arrow;
        arrow.click(function(){
            if(_this.content.css('display') == "none"){
                _this.content.css('display','block');
                _this.arrow.removeClass('PodArrowMin');
		        _this.arrow.addClass('PodArrow');
	        }
	        else{
		        _this.content.css('display','none');
		        _this.arrow.removeClass('PodArrow');
		        _this.arrow.addClass('PodArrowMin');
	        }
        });

        c=$('<td></td>').appendTo(r);
        c.addClass('PodMin');
        c.append(arrow);
    }

    this.title=$('<td></td>').appendTo(r);
    this.title.addClass('PodTitle');
    this.title.html(title);

    this.buttons=$('<td></td>').appendTo(r);
    this.buttons.addClass('PodButtons');
    this.buttons.append(this.xButton);

    r=$('<tr></tr>').appendTo(this.element);
    c=$('<td></td>').appendTo(r);
    c.addClass('PodTopLeft');

    this.podTop=$('<td></td>').appendTo(r);
    this.podTop.addClass('PodTop');
    this.podTop.append(header);

    c=$('<td></td>').appendTo(r);
    c.addClass('PodTopRight');
    r=$('<tr></tr>').appendTo(this.element);
    c=$('<td></td>').appendTo(r);
    c.addClass('PodLeft');
    c=$('<td></td>').appendTo(r);
    c.addClass('PodBody');
    this.content=c;
    this.content.pod=this.element;
    c=$('<td></td>').appendTo(r);
    c.addClass('PodRight');
    r=$('<tr></tr>').appendTo(this.element);
    c=$('<td></td>').appendTo(r);
    c.addClass('PodBottomLeft');
    c=$('<td></td>').appendTo(r);
    c.addClass('PodBottom');
    c=$('<td></td>').appendTo(r);
    c.addClass('PodBottomRight');

    mt.pod.count++;

    this.setID=function(id){
        _this.id=id;
        _this.element.attr('id','Pod_'+id);
    };

    this.setTitle=function(title){
        _this.title.text(title);
    };

    this.enableMove=function(){
        _this.podTop.css({cursor:'move'});
        _this.podTop.mouseover(function(){
            this.className='PodTopOver';
            this.previousSibling.className='PodTopLeftOver';
            this.nextSibling.className='PodTopRightOver';
        });
        this.podTop.mouseout(function(){
            this.className='PodTop';
            this.previousSibling.className='PodTopLeft';
            this.nextSibling.className='PodTopRight';
        });
        //mt.events.attachEventHandler("resetPodMoved", function(){_this.isMoved=false;});
    };

    this.enableRefresh=function(callback){
        if(!callback) return;
        if(!this.refreshButton){
            this.refreshButton=$('<div class="PodRefresh"></div>');
            mt.mouse.wireup(this.refreshButton);
            this.buttons.append(this.refreshButton);
        }
        this.refreshButton.mouseup(callback);
    };

    this.enableEdit=function(callback){
        if(!callback) return;
        if(!this.editButton){
            this.editButton=$('<div class="PodEdit"></div>');
            mt.mouse.wireup(this.editButton);
            this.buttons.append(this.editButton);
        }
        this.editButton.mouseup(callback);
    };
};
mt.pod.count=0;

mt.mouse={
    addStyle: function(obj, style){
        obj=$(obj);
        if(obj.attr('active') && obj.attr('active'))
            return;
        if(!style){
            mt.mouse.removeStyles(obj);
        }
        else if(!obj.hasClass(style)){
            mt.mouse.removeStyles(obj);
            obj.addClass(style);
        }
    },
    removeStyles: function(obj){
        obj=$(obj);
        if(obj.attr('base')){ 
            var base=obj.attr('base');
            obj.removeClass(base+'Over');
            obj.removeClass(base+'Down');
        }
    },
    over: function(){
        var _this=$(this);
        mt.mouse.addStyle(_this,_this.attr('base')+'Over');
    },
    out: function(){
        var _this=$(this);
        mt.mouse.addStyle(_this);
    },
    up: function(){
        var _this=$(this);
        mt.mouse.addStyle(_this,_this.attr('base')+'Over');
    },
    down: function(){
        var _this=$(this);
        mt.mouse.addStyle(_this,_this.attr('base')+'Down');
    },
    wireup: function(obj, active){
        obj=$(obj);
        if(!obj.attr('base'))
            obj.attr('base',obj.attr('class'));
        obj.bind('mouseover', mt.mouse.over);
        obj.bind('mouseout', mt.mouse.out);
        obj.bind('mousedown', mt.mouse.down);
        obj.bind('mouseup', mt.mouse.up);
        if(active == true){
            obj.mousedown();
            obj.attr('active',true);
        }
    },
    unwire: function(obj){
        obj=$(obj);
        mt.mouse.removeStyles(obj);
        obj.unbind('mouseover', mt.mouse.over);
        obj.unbind('mouseout', mt.mouse.out);
        obj.unbind('mousedown', mt.mouse.down);
        obj.unbind('mouseup', mt.mouse.up);
    }
};

 //Some common format strings
mt.date={
	"default": "ddd mmm d yyyy HH:MM:ss",
	tradeDeck: "ddd mmm d H:MM TT",
	shortDate: "m/d/yy",
	mediumDate:"mmm d, yyyy",
	longDate:  "mmmm d, yyyy",
	fullDate:  "dddd, mmmm d, yyyy",
	shortTime: "h:MM TT",
	mediumTime:"h:MM:ss TT",
	longTime:  "h:MM:ss TT Z",
	isoDate:   "yyyy-mm-dd",
	isoTime:   "HH:MM:ss",
	isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime:"yyyy-mm-dd'T'HH:MM:ss.lo",
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

mt.date.getDate = function(str){
    var date=str;
    //YYYY-MM-DDThh:mm:ss[.f*](Z|-hh:mm|+hh:mm)
    var atomFormat = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d*)?(Z|[+-]\d{2}:\d{2})$/i;
    var yahooFormat = /Etc\//;

    if(atomFormat.test(str)){
        var months = new Array("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
        var year, month, day, hour, minute, second, offset;
        year = str.slice(0,4);
        month = months[1*str.slice(5,7)]; //Jan-Dec
        day = str.slice(8,10); //01-31
        hour = str.slice(11,13); //00-23
        minute = str.slice(14,16); //00-59
        second = str.slice(17,19); //00-59
        offset = "GMT";

        //time zone offset specified
        if(str.indexOf("Z") == -1){
            var x = str.lastIndexOf(":");
            offset += str.slice(x-3,x) + str.slice(x+1);
        }
        //DD MMM YYYY hh:mm:ss GMT[(+|-)hhmm]
        date=day+" "+month+" "+year+" "+hour+":"+minute+":"+second+" "+offset;
    }
    else if(yahooFormat.test(str)){
        date=str.replace(yahooFormat,'');
    }
    return new Date(date);
};

mt.date.shortFormat = function(date){
    var myDate=mt.date.getDate(date);
    var yesterday=new Date();
    yesterday.setDate(yesterday.getDate()-1);
    if(myDate<yesterday)
        date=mt.date.format(myDate, 'mm/dd/yy');
    else
        date=mt.date.format(myDate, 'hh:MM tt');
    return date;
};

mt.date.format = function(date, mask){
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(value, length){
			value  = String(value);
			length = parseInt(length) || 2;
			while(value.length < length)
				value = '0' + value;
			return value;
		};

	// Treat the first argument as a mask if it doesn't contain any numbers
	if( arguments.length == 1 &&
		(typeof date == "string" || date instanceof String) &&
		!/\d/.test(date)
	){
		mask = date;
		date = undefined;
	}

	date = date ? new Date(date) : new Date();
	if (isNaN(date))
	    return '';
	//throw 'invalid date';

	mask = String(mt.date[mask] || mask || mt.date['default']);

	var	d = date.getDate(),
		D = date.getDay(),
		m = date.getMonth(),
		y = date.getFullYear(),
		H = date.getHours(),
		M = date.getMinutes(),
		s = date.getSeconds(),
		L = date.getMilliseconds(),
		o = date.getTimezoneOffset(),
		flags = {
			d:    d,
			dd:   pad(d),
			ddd:  mt.date.dayNames[D],
			dddd: mt.date.dayNames[D + 7],
			m:    m + 1,
			mm:   pad(m + 1),
			mmm:  mt.date.monthNames[m],
			mmmm: mt.date.monthNames[m + 12],
			yy:   String(y).slice(2),
			yyyy: y,
			h:    H % 12 || 12,
			hh:   pad(H % 12 || 12),
			H:    H,
			HH:   pad(H),
			M:    M,
			MM:   pad(M),
			s:    s,
			ss:   pad(s),
			l:    pad(L, 3),
			L:    pad(L > 99 ? Math.round(L / 10) : L),
			t:    H < 12 ? 'a'  : 'p',
			tt:   H < 12 ? 'am' : 'pm',
			T:    H < 12 ? 'A'  : 'P',
			TT:   H < 12 ? 'AM' : 'PM',
			Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ''),
			o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
		};

	return mask.replace(token, function ($0) {
		return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
	});
};
