//* 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");
registerNS("TSCM.util");
registerNS("TSCM"); //LEGACY
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 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);
   }
}

TSCM.util.isDefined=function(v){
    if ( !YAHOO.lang.isUndefined(v) ) {
        return true; 
    } else {
        return false;
    };
};

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.lang.JSON.stringify(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.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.ImgError = function(img){
    img.width=0;
    img.height=0;
    img.src=TSCM.cfg.imagesBaseUrl + "/css/images/1x1.gif";
    img.style.margin=0;
    var vImg = document.getElementById(img.id);

    if (vImg) {
        vImg.style.display = "none";
    }
}

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;
}


//* END TSCM.util *//


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);
}


/**
 * 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);

        }
   }
}



/**
* 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) {
        if ( !YAHOO.lang.isUndefined(o) || !YAHOO.lang.isNull(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.accountUrl,
			text: 'Your Account'
		});
		//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;






