//* Global Functions *//
function registerNS(ns){
   if(typeof ns == "undefined")return;
	var nsParts = ns.split(".");
	var root = window;
	for(var i=0; i<nsParts.length; i++){
  		if(typeof root[nsParts[i]] == "undefined"){
   			root[nsParts[i]] = new Object();
   		}
  	root = root[nsParts[i]];
 	}
}

registerNS("TSCM.pages.PageInfo");
registerNS("TSCM.metadata");
registerNS("TSCM.cfg");




//LEGACY
registerNS("TSCM");

TSCM.register=function(ns){
   registerNS(ns);
}

//






//called by radio pages and search
function audioPlayer(clip, author){

	var cookieSelectedFormat = null;
	var editPreference = false;
	var cookieName = "selectedAudioFormat"; // cookie name
	var wmaplayer = "wma_player.html";
	var mp3player = "audio_player.html";

	if(author != null) {
		wmaplayer = author + "_wma_player.html";
		mp3player = author + "_audio_player.html";
	}

	// read the cookie
	if(document.cookie.indexOf(cookieName) > -1) {
		cookieSelectedFormat = TSCM.util.GetCookie(";",cookieName);
	
		// if wma, pop up the player
		if( (cookieSelectedFormat != null) && (cookieSelectedFormat == "formatSelectedWMA") ) {
			url = "http://www.thestreet.com/radio/" + wmaplayer + "?clip=" + clip;
			window.open(url,"clip","WIDTH=400,HEIGHT=490,top=50,left=50,status=yes,toolbar=no,menubar=no,location=no,resizable=yes");
		} else {
			var url = "http://www.thestreet.com/radio/" + mp3player + "?clip=" + clip;
			window.open(url,"clip","WIDTH=400,HEIGHT=490,top=50,left=50,status=yes,toolbar=no,menubar=no,location=no,resizable=yes");		
		}
	
	} else {
		var url = "http://www.thestreet.com/radio/" + mp3player + "?clip=" + clip;
		window.open(url,"clip","WIDTH=400,HEIGHT=490,top=50,left=50,status=yes,toolbar=no,menubar=no,location=no,resizable=yes");
	}
}

//END LEGACY

function numOrdA(a, b){ return (a-b); }
function numOrdD(a, b){ return (b-a); }

function properCase(theLabel){	//needed b/c text-transform:capitalize bug when used w/ innerHTML
	return theLabel.toLowerCase().replace(/\b\w/g,function(p){return p.toUpperCase()});
}

/* DOUBLE LINKED LIST */

// Constructor for list nodes
// DLListNode(elem) - constructor. Creates unlinked node with elem as data
// Interface:
// extract() - unlinks node, linking its predecessor and successor.
// insertAfter(node) - insert node after this node, updating links.

function DLListNode(elem) {
	this.elem = elem;
	this.prev = this.next = null;
}

DLListNode.prototype.extract = function () {
	if (this.prev) {
		this.prev.next = this.next;
	}
	if (this.next) {
		this.next.prev = this.prev;
	}
	this.prev = this.next = null;
}

DLListNode.prototype.insertAfter = function (newNode) {
	if (this == newNode) { return; } // don't be daft!
	newNode.extract();
	newNode.prev = this;
	if (this.next) {
		newNode.next = this.next;
		this.next.prev = newNode;
	}
	this.next = newNode;
}

// The list itself
// Interface:
// getFirst() - returns first node, or null if none
// getLast() - returns last node, or null if none
// add(elem[,afterNode]) - creates new node with elem as data and
// inserts it at end of list, or optionally
// after afterNode
// foreach(func) - calls func on all elements stored in list
// find(func[,afterNode]) - finds first node in list (optionally after
// afterNode) where func returns true when
// called on the element.
function DLList() {
	this.prev = this.next = this;
}
DLList.prototype.insertAfter = DLListNode.prototype.insertAfter;
DLList.prototype.getFirst = function () {
	return (this.next == this)?null:this.next;
};
DLList.prototype.getLast = function () {
	return (this.prev == this)?null:this.prev;
};
DLList.prototype.add = function (elem,afterNode) {
	var newNode = new DLListNode(elem);
	if (!afterNode) {
		if (this.prev) {
			afterNode = this.prev;
		} else {
			afterNode = this;
		}
	}
	afterNode.insertAfter(newNode);
	return newNode;
};
DLList.prototype.foreach = function (func) {
	for (var node = this.next;node != this;node = node.next) {
		func(node.elem);
	}
};

DLList.prototype.count = function() {
	var i = 0;
	for (var node = this.next;node != this;node = node.next) {
		i++;
	}
	return i;
};

DLList.prototype.find = function (func, startNode) {
	if (!startNode) { startNode = this; }
	for (var node = startNode.next; node != this; node = node.next) {
		if (node && func(node.elem)) {return node;}
	}
};

/* END DOUBLE LINKED LIST */

function updateFlashVar(flash, varName, varVal){
	YAHOO.util.Dom.get(flash).SetVariable(varName,varVal);
}

function log(msg) { 
   // use the error console if available (FF+FireBug or Safari) 
   if (typeof console != "undefined") { 
      console.log(msg); 
      // write the msg to a well-known div element 
   } else { 
      var el = document.getElementById("consoleelement"); 
      if (el) { 
         el.innerHTML += "<p>" + msg + "</p>"; 
      } 
   } 
} 

function debug(msg){
   try {
      h = document.getElementById("debug").innerHTML;
      document.getElementById("debug").innerHTML = msg + "<br>" + h;
   
   }catch(e){
      //alert(e.message);
   }
}

//* String Methods *//
/* sorry these are evil if you need one rewrite it as a util func.
String.prototype.ucFirst=function(){return(this.charAt(0).toUpperCase()+this.substr(1,this.length));};
String.prototype.stripSlashes=function(){return(this.replace(new RegExp("/+","g"),"/"));};
String.prototype.ltrim=function(){return this.replace(/^\\s+/,'');};
String.prototype.rtrim=function(){return this.replace(/\\s+$/,'');};
String.prototype.trim=function(){return this.replace(/^\\s+|\\s+$/g,'');};
*/

String.prototype.chop=function(n){if(isNaN(n)){n=this.length-1;}return(this.substring(0,n));};
/*
String.prototype.stripPrecedingSlashes=function(){
	try{
		return this.replace(new RegExp("/+","g"),"/").substring(1);
	} catch(e){}
};
*/


//* TSCM.util *//
registerNS("TSCM.util");
TSCM.util.isDefined=function(v){if(typeof v=='undefined'||v==null||v==''||v=='undefined'){return false}else{return true};}

TSCM.util.popgallery=function(name){
var url = TSCM.cfg.contextRoot + "/gallery/" + name + "/index.html";
window.open (url, "photogallery","location=0,status=1,scrollbars=0, width=970,height=700"); 
}




TSCM.util.GetCookie = function (splitby,name) {

    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return TSCM.util.getCookieVal(splitby,j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }

    return null;
}

function GetCookie (splitby,name) {
   return TSCM.util.GetCookie(splitby,name);
}

TSCM.util.getCookieVal =function(splitby,offset) {
    var endstr = document.cookie.indexOf (splitby,offset);
    if (endstr == -1)
    endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

/* save/retrieve object from cookie 
usage:
   var state = new TSCM.util.PersistenceManager();
   state.id = "some_unique_string"; 
   state.expiry_days = <int number_of_days> 
   save object:       state.save(object o);
   get  object:       var o = state.get();
*/
TSCM.util.PersistenceManager = function(ob){
   
   this.data = null;
   this.id = "tscs_data";
   this.expiry_days = 365;
   this.path = "/";
   this.flashid = null;
   this.session_cookie = false;

   this.get = function(){
      var s = this.getCookie(this.id);
      try {
         var str = "var o = " + s + "";
         eval(str);
         this.data = o;
      }catch(e){
      return null;
      }
      return this.data;
   }

   this.getstr = function(){
      return this.data_str;
   }

   this.getdata = function(){
      return this.data;
   }

   this.setData = function(ob){
      if(typeof ob == "object"){
         this.data = ob;
         try{
            this.data_str = YAHOO.ext.util.JSON.encode(ob);
         }catch(e){
         	//alert(e);
            this.data_str = "";
         }
      }else if (typeof ob == "string"){
         this.data_str = ob;
         try{
             eval("var o = " + this.data_str);
             this.data = o;
         }catch(e){
            this.data = e;
         }
      }
   }

   this.setDataStr = function(str){
      this.data_str = str;
   }

   this.save = function(ob){
      if(typeof ob!="undefined"){ 
         //alert(ob);
         this.setData(ob);
      }
      this.setCookie(this.id,this.data_str,this.expiry_days);
   }
   
   this.setCookie = function (cookieName,cookieValue,num_days) {
      var today = new Date();
      var expiry = new Date();
      if (num_days==null || num_days==0) num_days=this.expiry_days;
      expiry.setTime(today.getTime() + 3600000*24*num_days);
      try {
         var cs;
         if(this.session_cookie == true){
            cs = escape(cookieName ) + "=" + escape(cookieValue) + ";path=" + this.path; 
         }else{
            cs = escape(cookieName ) + "=" + escape(cookieValue) + ";expires=" + expiry.toGMTString() + ";path=" + this.path; 
         }
         document.cookie = cs;
      } catch(e){}
   }

   this.getCookie = function(name) {
       var prefix = name + "=";
       var begin = document.cookie.indexOf(prefix);
       if (begin == -1) {
           begin = document.cookie.indexOf(prefix);
           if (begin != 0) { 
              return null;
           }
       } else {
           //begin += 2;
       }
       var end = document.cookie.indexOf(";", begin);
       if (end == -1) {
           end = document.cookie.length;
       }
       var t = unescape(document.cookie.substring(begin + prefix.length, end));
       return t;
   }

   this.serialize = function(ob){
      window.status = 'flash-save not implemented';
      return;
      if(typeof ob!="undefined")this.setData(ob);
      if(this.flashid == null){
         throw "error-flash object not defined";
      }else{
         var fl = document.ElementById(this.flashid);
         fl.SetVariable("mtvi_yeti_data",this.data_str);
      }
   }

   /* main */
   this.setData(ob);
}

TSCM.util.getParameter = function(name){
   var qs = window.location.search;
   //var qs = top.window.location.search;

   if(top.location != self.location){
      qs = top.window.location.search;
   }
   
   var EQ = "=";
   var AMP = "&";
   var param = name + EQ;

   try {
      var loc = qs.indexOf(param);
      if(loc !=-1){
         var start = loc + param.length;
         var ss = qs.substring(start);
         var end = ss.indexOf(AMP);
         if(end != -1){
            return ss.substring(0,end);
         }else{
            return ss.substring(0);
         }
      }
   }catch(e){
      return "";
   }
}

TSCM.util.setText = function(id,txt){
   try {
      YAHOO.util.Dom.get(id).innerHTML = txt;
   }catch(e){
   }
}
   
TSCM.util.rmnonAlpha = function(txt){
   try {
      return txt.replace(/\ |\[|\]|\*|\!|\@|\#|\$|\%|\^|\&|\(|\)|\-|\:|\'|\"|\<|\>|\?|\\|\/|\~|\`/g,"");
   }catch(e){
      return;
   }
}
 
TSCM.util.attachScript = function(id,url){
   // your thing should have a callback
   var scr= document.createElement("script");
   scr.type = "text/javascript";
   scr.defer = true;
   scr.id = id;
   scr.src = url;
   var s = document.getElementById(id);
   var head = document.getElementsByTagName('head')[0]; 
   try {
      if(s){
         head.removeChild(s); 
      }
   }catch(e){
      //debug(e.message);
   }
   head.appendChild(scr);
   return;
}

TSCM.util.getEl = function(id){
   return YAHOO.util.Dom.get(id);
}

TSCM.util.Quote =  function(callback,symb){

   // http://custom.marketwatch.com/custom/thestreet-com/xml-quote.asp?symb=dj,bby,xyq19,notasymbol&output=json&callback=quoteResultHandler
   this.server="http://custom.marketwatch.com"; 
   this.path="/custom/thestreet-com/xml-quote.asp?";
   this.params = {
      output:"json",
      symb:null,
      callback:null
   }

   this.params.callback = callback;
   this.params.symb = symb;

   this.getParams = function(){
      var s ='';
      for (var i in this.params){
         var o = this.params[i];
         if(o instanceof Array){
            var str = i;
            for(var j=0;j<o.length;j++){
               str+=o[j];
            }
            if(s!='') s+= '&';
            s += str;

         } else {
            if(s!='') s+= '&';
            str = i + "=" + this.params[i];
            s += str;
         }
      }
      return s;
   }

   this.url= this.server + this.path + this.getParams();
   this.get = function(){
     return attachScript(YAHOO.util.Dom.generateId(),this.url);
   }
   return this.url;
}

TSCM.util.addCommas = function(str){

   str += '';
   x = str.split('.');
   x1 = x[0];
   x2 = x.length > 1 ? '.' + x[1] : '';
   var rgx = /(\d+)(\d{3})/;
   while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + ',' + '$2');
   }
   return x1 + x2;
}






/* ************************** */
/*Check/replace img file with ajax*/

// these are our globals
var req, imagepath, imgEl, replacementImg;

// our function to load the image
TSCM.util.loadimage = function(_imagepath, _imgEl, _replacementImg) {
	//alert(_imagepath + " : " + _imgEl + " : " + _replacementImg)
	
    // set our constants
    TSCM.util.imagepath = _imagepath;
	TSCM.util.imgEl = Ext.get(_imgEl);
	//alert(_imgEl);
	//alert(Ext.get(_imgEl));

    TSCM.util.replacementImg = _replacementImg;

    // our XMLHttpRequest to grab the image
    TSCM.util.req = TSCM.util.getreq();
    TSCM.util.req.onreadystatechange = TSCM.util.imagexists;
    TSCM.util.req.open("get", TSCM.util.imagepath, true);
    TSCM.util.req.send(null);     
}
TSCM.util.imagexists = function() {
    // if the XMLHttpRequest is finished loading
    if(TSCM.util.req.readyState == 4) {        // and the file actually exists
        if(TSCM.util.req.status == 200) {
            // set to the desired image
            TSCM.util.imgEl.src = TSCM.util.imagepath;
        } else {
            // set to the default image
            TSCM.util.imgEl.src = TSCM.util.replacementImg;
        }
    }
}
TSCM.util.getreq = function() {
    if(window.XMLHttpRequest)
        return new XMLHttpRequest();
    else if(window.ActiveXObject)
        return new ActiveXObject("Microsoft.XMLHTTP");
}
/*End image file replace*/








//* END TSCM.util *//

/**
 * @class YAHOO.ext.util.JSON
 * Modified version of Douglas Crockford's json.js that doesn't
 * mess with the Object prototype 
 * http://www.json.org/js.html
 * @singleton
 */

registerNS("YAHOO.ext.util");
YAHOO.ext.util.JSON = new function(){
    var useHasOwn = {}.hasOwnProperty ? true : false;
    
    // crashes Safari in some instances
    //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
    
    var pad = function(n) {
        return n < 10 ? '0' + n : n;
    };
    
    var m = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };

    var encodeString = function(s){
        if (/["\\\x00-\x1f]/.test(s)) {
            return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                var c = m[b];
                if(c){
                    return c;
                }
                c = b.charCodeAt();
                return '\\u00' +
                    Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }) + '"';
        }
        return '"' + s + '"';
    };
    
    var encodeArray = function(o){
        var a = ['['], b, i, l = o.length, v;
            for (i = 0; i < l; i += 1) {
                v = o[i];
                switch (typeof v) {
                    case 'undefined':
                    case 'function':
                    case 'unknown':
                        break;
                    default:
                        if (b) {
                            a.push(',');
                        }
                        a.push(v === null ? "null" : YAHOO.ext.util.JSON.encode(v));
                        b = true;
                }
            }
            a.push(']');
            return a.join('');
    };
    
    var encodeDate = function(o){
        return '"' + o.getFullYear() + '-' +
                pad(o.getMonth() + 1) + '-' +
                pad(o.getDate()) + 'T' +
                pad(o.getHours()) + ':' +
                pad(o.getMinutes()) + ':' +
                pad(o.getSeconds()) + '"';
    };
    
    /**
     * Encodes an Object, Array or other value
     * @param {Mixed} o The variable to encode
     * @return {String} The JSON string
     */
    this.encode = function(o){
        if(typeof o == 'undefined' || o === null){
            return 'null';
        }else if(o instanceof Array){
            return encodeArray(o);
        }else if(o instanceof Date){
            return encodeDate(o);
        }else if(typeof o == 'string'){
            return encodeString(o);
        }else if(typeof o == 'number'){
            return isFinite(o) ? String(o) : "null";
        }else if(typeof o == 'boolean'){
            return String(o);
        }else {
            var a = ['{'], b, i, v;
            for (var i in o) {
                if(!useHasOwn || o.hasOwnProperty(i)) {
                    v = o[i];
                    switch (typeof v) {
                    case 'undefined':
                    case 'function':
                    case 'unknown':
                        break;
                    default:
                        if(b){
                            a.push(',');
                        }
                        a.push(this.encode(i), ':',
                                v === null ? "null" : this.encode(v));
                        b = true;
                    }
                }
            }
            a.push('}');
            return a.join('');
        }
    };
    
    /**
     * Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError.
     * @param {String} json The JSON string
     * @return {Object} The resulting object
     */
    this.decode = function(json){
        // although crockford had a good idea, this line crashes safari in some instances
        //try{
            //if(validRE.test(json)) {
                return eval('(' + json + ')');
           // }
       // }catch(e){
       // }
       // throw new SyntaxError("parseJSON");
    };
}();

TSCM.util.saveQuoteTickerToMiniBox = function(ticker){
	state = new TSCM.util.PersistenceManager();
			state.id = "tsc_recentquotes"; 
			state.expiry_days = 365;

	var o = state.get();
	var found = false;
		
	if(o != null){
		if(o.length > 20){ o.shift(); }
		for(i=0;i<o.length;i++){ if(o[i] == ticker.toUpperCase()){ found=true; break;} }
		if(!found){ o.push(ticker.toUpperCase()); }
	}else{
		var o = new Array(ticker.toUpperCase());
	}
	state.save(o);
}

TSCM.util.MONTH_NAMES = new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
TSCM.util.DAY_NAMES = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
TSCM.util.LZ = function(x) {return(x<0||x>9?"":"0")+x}
TSCM.util.formatDate = function(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=TSCM.util.LZ(M);
	value["MMM"]=TSCM.util.MONTH_NAMES[M-1];
	value["NNN"]=TSCM.util.MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=TSCM.util.LZ(d);
	value["E"]=TSCM.util.DAY_NAMES[E+7];
	value["EE"]=TSCM.util.DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=TSCM.util.LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=TSCM.util.LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=TSCM.util.LZ(value["K"]);
	value["kk"]=TSCM.util.LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=TSCM.util.LZ(m);
	value["s"]=s;
	value["ss"]=TSCM.util.LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
}

TSCM.util.formatCurrency = function(v, returnSign){
    v = (Math.round((v-0)*100))/100;
    v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    var sub = ps[1] ? '.'+ ps[1] : '.00';
    var sign = "";
    if (returnSign) {
    	if ((whole + sub) > 0)
    		sign = "+";
    	else
    		sign = "-";
    }
    whole = String(Math.abs(whole));
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + ',' + '$2');
    }

    return sign + whole + sub ;
}


TSCM.util.Glom = function(el,cfg){

	var expandedHeight;
   	if (document.all) {
		expandedHeight = 354;			//set expanded height ie
	} else {
		expandedHeight = 343;			//set expanded height
	}

   /********* * * * *********/
   this.backgroundColor = "#cccccc";
   this.mousedownColor = "#888888";
   this.width = 200;

   // font sizes in percent //
   this.maxfont = cfg.maxfontsize !== undefined ? cfg.maxfontsize : 400;
   this.minfont = cfg.minfontsize !== undefined ? cfg.minfontsize : 70;

   this.big = (cfg.maxed === false) ? false : true;

   cfg.iframe = false;
   TSCM.util.Glom.superclass.constructor.call(this, el,cfg); 

   this.el = this.element;
   if(typeof el == "string"){
      var ob = dom.get(el);
      if(typeof el == "undefined"){
         this.render(document.body);
      }else{
         // its already there
      }
   }else{
      //this.render(el);
   }

   if(this.big){
	  this.initheight = Math.floor(YAHOO.util.Dom.getStyle(this.element.id, 'height').replace("px","")); 
      var h = YAHOO.util.Dom.getStyle(this.element.id, 'height');
      if(this.browser.indexOf("ie")!=-1){
      	var d = YAHOO.util.Dom.get(this.element.id);
      	this.initheight = d.offsetHeight;
      }
   }else{
	   this.initheight = expandedHeight;
   }
   this.glom();
};

//YAHOO.extend(TSCM.util.Glom,YAHOO.widget.Module); 

TSCM.util.Glom.prototype.glom = function(cfg){
   
   var dom = YAHOO.util.Dom; 
   var evt = YAHOO.util.Event;
   var collapsedHeight;
    
   	if (document.all) {
    	collapsedHeight = 185;			//set collapsed height ie
	} else {
	    collapsedHeight = 178;			//set collapsed height
	}
	
   if(!this.big){ dom.setStyle( this.el, "height", collapsedHeight + "px"); }

   // hides the content when minimized
   dom.setStyle( this.el, "overflow","hidden");

	// do something on mousedown
   evt.on(this.el,"mousedown",function(e){},this,true);

	// do something on  mouseup
   evt.on(this.el,"mouseup",function(e){},this,true);

   var maxprops = { height: { to: this.initheight } };
   this.maxanim = new YAHOO.util.Anim(this.el, maxprops, 0.5, YAHOO.util.Easing.easeOut);
   this.maxanim.onComplete.subscribe(this.maximize,this,true);

   var minprops = { height: { to: collapsedHeight } };
   this.minanim = new YAHOO.util.Anim(this.el, minprops, 0.5, YAHOO.util.Easing.easeIn);
   this.minanim.onComplete.subscribe(this.minimize,this,true);

   evt.on("expandButton", 'click', function(){
		TSC.reporting.sendLinkEvent("Quote|button|viewmore");
   		var elem = document.getElementById("expandButton");
   		var imgIndex;
   		var basepath;
		
		for( var i = 0; i < elem.childNodes.length; i++ ) {
			if (elem.childNodes[i].nodeType == 1 ) {
				if (elem.childNodes[i].tagName.toUpperCase() == "IMG") {
					var imgsrc = elem.childNodes[i].src;
   	  				basepath = imgsrc.substring(0, imgsrc.lastIndexOf("/") + 1);
					imgIndex = i;
				}
			}
		}
			  
      	if(!this.big){
      		this.maxanim.animate();
    		elem.childNodes[imgIndex].src = basepath + "closeExpandView.jpg";
      	} else {
      		this.minanim.animate();
    		elem.childNodes[imgIndex].src = basepath + "viewMoreQuote.jpg";
      	}
      	this.big = !this.big;

   },this,true);
};

TSCM.util.Glom.prototype.minimize = function(){
   this.setBody("");
   this.setFooter('');
};

TSCM.util.Glom.prototype.maximize = function(){};


/**
      function createEl -- create a new dom node, with options: 
      -- append it to some other node right away
      -- fill it with text
      -- set attributes on it like class or whatever 

      @param parentNode -- dom node to attach to 
      @param nodeName  -- the type of dom node to create
      @param properties  -- object literal of attributes to set
      @param text --  text for the new element
      @param html -- : innerHTML for the new element -- will stomp text param
      @return -- a dom element

      usage: 

      var El = createEl({
         parentNode:someparent,
         nodeName:"div",
         text:"foobar",
         properties:{id:"someid","class",classname}
         });

*/

TSCM.util.createEl = function(config){
   var el = null;
   var cfg = config;

   if(typeof cfg == "undefined"){
      cfg = {};
   }
   if(typeof cfg.nodeName == "undefined"){
      cfg.nodeName="div";
   }

   try {
      el = document.createElement(cfg.nodeName);
      el.setAttribute('id' ,YAHOO.util.Dom.generateId());
      if(cfg.text != undefined){
         el.appendChild(document.createTextNode(cfg.text));
      }
      if(cfg.html != undefined){
         el.innerHTML = cfg.html;
      }
      if(cfg.properties != undefined){
         for (var i in cfg.properties ){
            el.setAttribute(i,cfg.properties[i]);
         }
      }
      var p = null;
      if(typeof cfg.parentNode == 'string'){
         p = YAHOO.util.Dom.get(cfg.parentNode);
      }else if (typeof cfg.parentNode == 'object')  {
         p = cfg.parentNode;
      }else if (cfg.parentNode instanceof Array)  {
         throw "can't add " + cfg.nodeName + " to parent array " ;
      }else if(typeof cfg.parentNode == "undefined"){
         return el;
      }
      try {
         p.appendChild(el);
      }catch(e){
         throw "couldn't append element " + el.toString();
      }
      try {
         // reset for ie
         p.innerHTML = p.innerHTML; 
      }catch(e){
         // probably a tbody or something readonly
         throw "couldn't set innerHTML to itself";
      }
   }catch(e){
   }
   return el;

};

/**
 * positionToPlaceholder
 * repositions an element to a placeholder element
 *
 * @param el (string) : id of element to be positioned
 * @param placeholder (string) : id of the 'anchor' element to use for positioning reference
 */

TSCM.util.positionToPlaceholder = function(el, placeholder) {
	var Yud = YAHOO.util.Dom;
	var e = Yud.get(el);
	var p = Yud.get(placeholder);

	Yud.setXY(e, Yud.getXY(p)); //position the ad over the placeholder

	//unhide when complete
	if(e.style.display === 'none') {e.style.display = 'block'};
	if(e.style.visibility === 'hidden') {e.style.visibility = 'visible'};
};

function log(m){ if(typeof console != "undefined"){ console.log(m); } };

TSCM.util.getTrackingPixel = function(url){
	var ord = Math.floor(Math.random() * 100000000000);
	if(typeof url != "undefined"){
		if(url.indexOf('?')!= -1){
			url += "&";
		}else{
			url += "?";
		}
		url += "ord=" + ord;
		return "<img border='0' width='1' height='1' src='" + url + "'>";
	}
}


// rss utils
TSCM.util.Rss = new function(){

   return {
   	/* this is for redirecting to the first link in a video rss
   	 * it depends upon the video rss proxy file
   	 * the video rss proxy file expects a bc lineup id so
   	 * @param: lineupid
   	 * TSCM.util.Rss.latestVid(1137812485);
   	 */
     latestVid:function(lineupid){
     var callback = {
         success:function(o){
          var url;
		  try {
             // var id = o.responseText.match(/bctid[0-9]+/)[0].substring(6);
             
			   url = TSCM.cfg.contextRoot + "/video/index.html?bctid=" + id;
               
			   var xml = o.responseXML;
			   var links = xml.getElementsByTagName("link");
			   var link = links[1];
			   url = link.firstChild.nodeValue;
           }catch(e){ 
              url = TSCM.cfg.contextRoot + "/video/index.html";    
              }
			  document.location.href = url;
        },
         failure:function(){ 
		 log('connection failed');
		  var url = TSCM.cfg.contextRoot + "/video/index.html";
          document.location.href = url;
		 //log(url);
         },
         scope:this,
         argument:null
         }

		var rssurl = TSCM.cfg.contextRoot + "/util/videoRSSProxy.jsp?id=" + lineupid; 
		log(rssurl);
        var conn =YAHOO.util.Connect.asyncRequest('GET', rssurl, callback, null);

        }
   }
}




registerNS("TSCM.util.Format");

TSCM.util.Format.currency = function(v, returnSign){
    if(isNaN(v)){
           return ("N/A");
          alert("Grace");
       }
    else{
    v = (Math.round((v-0)*100))/100;
    v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    var sub = ps[1] ? '.'+ ps[1] : '.00';
    var sign = "";
    if (returnSign) {
    	if ((whole + sub) > 0){
    		sign = "+";
      }else{
    		sign = "-";
      }
    }
    whole = String(Math.abs(whole));
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + ',' + '$2');
    }
    
    return sign + whole + sub ;
    }
}

TSCM.util.Format.percentage = function(v, returnSign){
    v = (Math.round((v-0)*10))/10;
    v = String(v);
    var ps = v.split('.');
    var whole = ps[0];
    var sub = ps[1] ? '.'+ ps[1] : '.0';
    var sign = "";
    if (returnSign) {
    	if ((whole + sub) > 0){
    		sign = "+";
      }else{
    		sign = "-";
      }
    }
    whole = String(Math.abs(whole));
    var r = /(\d+)(\d{3})/;
    while (r.test(whole)) {
        whole = whole.replace(r, '$1' + ',' + '$2');
    }
    
    return sign + whole + sub + "%";

}


var expandableList = new function() {
         var dom = YAHOO.util.Dom;
         return {
               init:function(){

                     try {
                        var els = dom.getElementsByClassName("expandableBtn","img","twoCol_left",function(a){
                           YAHOO.util.Event.on(a,"click",expandableList.doclick,expandableList,true);
                        });
                        dom.getElementsByClassName("authImg","img",p,
                        function(i){ if(i.getAttribute("src").indexOf("1x1")!=-1){ i.setAttribute("src",i.getAttribute("title")); } });

                        try {

                        dom.getElementsByClassName("exTitle","div","twoCol_left",function(a){
                           var z = a.getElementsByTagName("a")[0];
                           z.setAttribute("title","find articles by " + z.innerHTML);
                        });
                        }catch(e){}

                     }catch(e){ log (e.message); }

               },
               doclick:function(evt,b){
                        try {
                           var t = null;
                           // ??
                     if(YAHOO.env.ua.ie){ t = evt.srcElement; }else{ t = evt.target; }
			    	      TSC.reporting.sendLinkEvent("HLP|BTL|button|" + t.title);
                     var p = dom.getAncestorByClassName(t,"expandItem");
                     var otxt = dom.getElementsByClassName("openedText","div",p);
                     var ctxt = dom.getElementsByClassName("closedText","div",p);
                     if( t.getAttribute("src").indexOf("plus")!=-1){
                        t.setAttribute("src", "http://i.thestreet.com/files/tsc/v2008/css/images/minus.png");
                        dom.setStyle(otxt,"display","block");
                        dom.setStyle(ctxt,"display","none");
                        dom.getElementsByClassName("authImg","img",p,
                        function(i){ if(i.getAttribute("src").indexOf("1x1")!=-1){ i.setAttribute("src",i.getAttribute("title")); } });
                     }else{
                        t.setAttribute("src", "http://i.thestreet.com/files/tsc/v2008/css/images/plus.png");
                        dom.setStyle(ctxt,"display","block");
                        dom.setStyle(otxt,"display","none");
                     }
                        }catch(e){log(e);}
                 }
           }
      }

/**
* MZINGA LOGIN LINKS
* checks if a user ID is present in the REGIS cookie
* writes 'login' or 'your account' links accordingly
*/
TSCM.util.loginLinks = {

 	//configs
	loginId: 'login',
	accountId: 'account',
	bottomLoginId: 'loginBottom',

	loginUrl: TSCM.cfg.contextRoot + '/k/community/login.html?targetUrl=',
	logoutUrl: TSCM.cfg.contextRoot + '/user/logoff.html?redirectTo='+ TSCM.cfg.commerceBaseUrl +'%2fcap%2fuserLogoff.do%3furl%3dhttp%253a%252f%252fwww.thestreet.com%252findex.html%253flogoff%253dtrue',
	joinUrl: TSCM.cfg.contextRoot + '/k/community/register.html?targetUrl='+location.href,
	accountUrl: TSCM.cfg.commerceBaseUrl + '/cap/selfserve/SSMainMenu.jsp?site=tsc&url=http://www.thestreet.com/index.html',

	referringUrl: new String(window.location),


	updateLink: function(o) {
		o.link.href = o.href;
		o.link.innerHTML = o.text;
	},
	
	/**
	* if user is logged in
	*/
	handleAuthenticated: function() {
		TSCM.util.loginLinks.updateLink({ //top login/logout link
			link: YAHOO.util.Dom.get(this.loginId),
			href: this.logoutUrl,
			text: 'Log Out'
		});
		TSCM.util.loginLinks.updateLink({ //top account link
			link: YAHOO.util.Dom.get(this.accountId),
			href: this.accountUrl,
			text: 'Your Account'
		});
		TSCM.util.loginLinks.updateLink({ //bottom login/logout link
			link: YAHOO.util.Dom.get(this.bottomLoginId),
			href: this.logoutUrl,
			text: 'Log Out'
		});
	},

	/**
	* if user is not logged in
	*/
	handleUnathenticated: function() {
		TSCM.util.loginLinks.updateLink({ //top login/logout link
			link: YAHOO.util.Dom.get(this.loginId),
			href: this.loginUrl + this.referringUrl,
			text: 'Log In'
		});
		TSCM.util.loginLinks.updateLink({ //top account link
			link: YAHOO.util.Dom.get(this.accountId),
			href: this.joinUrl,
			text: 'Join for Free!'
		});
		TSCM.util.loginLinks.updateLink({ //bottom login/logout link
			link: YAHOO.util.Dom.get(this.bottomLoginId),
			href: this.loginUrl + this.referringUrl,
			text: 'Log In'
		});
	},

	init: function() {

		//checks if cookie is present, and if the user id is greater than 0
		if(YAHOO.util.Cookie.get('RGIS')) {
			var cookie = YAHOO.util.Cookie.get('RGIS');

			//decide which character to use for splitting the cookie
			if(cookie.indexOf('|') != -1) {
				var userId = YAHOO.util.Cookie.get('RGIS').split('|')[0];
			} else {
				var userId = YAHOO.util.Cookie.get('RGIS').split(',')[0];
			};

			//purge quote marks from the string
			var cleanId = userId.replace('"', '');

			//check if the number is positive or negative
			if(parseInt(cleanId) > 0) {
				this.handleAuthenticated();
			} else {
		    		this.handleUnathenticated();
			};
		} else {
			this.handleUnathenticated();
		};
	}
};
YAHOO.util.Event.onDOMReady(TSCM.util.loginLinks.init, TSCM.util.loginLinks, true);


/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;





