if( typeof dj == "undefined" ) { var dj = {}; }
if( typeof dj.blogs == "undefined" ) { dj.blogs = {}; }
if( typeof dj.blogs.util == "undefined" ) { dj.blogs.util = {}; }

String.prototype.replaceAll = function(strTarget, strSubString ){
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1){
		strText = strText.replace( strTarget, strSubString )
		intIndexOfMatch = strText.indexOf( strTarget );
	}
	return( strText );
}


dj.blogs.util.UTF8=function(){
	var _public={
		encode : function (str) {
	        var string = str.replace(/\r\n/g,"\n");
	        var utftext = "";
	
	        for (var n = 0; n < string.length; n++) {
	
	            var c = string.charCodeAt(n);
	
	            if (c < 128) {
	                utftext += String.fromCharCode(c);
	            }
	            else if((c > 127) && (c < 2048)) {
	                utftext += String.fromCharCode((c >> 6) | 192);
	                utftext += String.fromCharCode((c & 63) | 128);
	            }
	            else {
	                utftext += String.fromCharCode((c >> 12) | 224);
	                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
	                utftext += String.fromCharCode((c & 63) | 128);
	            }
	
	        }
	
	        return utftext;
	    },
	
	    // private method for UTF-8 decoding
	    decode : function (utftext) {
	        var string = "";
	        var i = 0;
	        var c = 0;
	        var c1 = 0;
	        var c2 = 0;
	
	        while ( i < utftext.length ) {
	
	            c = utftext.charCodeAt(i);
	
	            if (c < 128) {
	                string += String.fromCharCode(c);
	                i++;
	            }
	            else if((c > 191) && (c < 224)) {
	                c2 = utftext.charCodeAt(i+1);
	                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
	                i += 2;
	            }
	            else {
	                c2 = utftext.charCodeAt(i+1);
	                c3 = utftext.charCodeAt(i+2);
	                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	                i += 3;
	            }
	
	        }
			return string.replaceAll("+"," ");
	    }
	}
	return _public;
}();

dj.blogs.util.Url=function(){
	var _public={
		encode : function (string) {
			return escape(dj.blogs.util.UTF8.encode(string));
		},
		decode: function (string){
			return dj.blogs.util.UTF8.decode(unescape(string));
		}
	}
	return _public;
}();


dj.blogs.util.omni = Class.create({
    
    initialize: function() {
      this.roles = [];
      this.userinfo = {};
      this.loggedIn = false;
      new Ajax.Request("/auth/userinfo.json?rnd="+new Date().getTime().toString()+'R'+Math.floor(Math.random()*99999999999999999),
          { 
            method:'get',
            asynchronous:false,
            onSuccess: this.loadUserInfo.bindAsEventListener(this)
          });
      this.TR = this.getCookie( 'TR' );
    },  
    
    loadUserInfo : function(response) {
        var json = response.responseText.gsub("'", '"').evalJSON();
        this.userinfo = (json) ? json : null;
        this.roles = (this.userinfo.roles) ? dj.blogs.util.Url.decode(this.userinfo.roles).split(',') : null;
        this.loggedIn = (this.userinfo.session) ? true : false;
    },
    
    hasRole : function(rolename) {
        return ((this.roles) && (this.roles.indexOf(rolename) !== -1)) ? true : false;
    },
    
    isSubscriber : function() {
        return (this.loggedIn && (this.hasRole('WSJ') || this.hasRole('WSJ-TRANSIENT'))) ? true : false;
    },
    
    isLoggedIn : function() {
        return this.loggedIn;
    },
        
        
    getCookie : function( c_name ) {
    
        if( document.cookie.length <= 0 ) return null;
    
        c_start = document.cookie.indexOf( c_name + "=" );
    		  
        if( c_start == -1 ) return null;
     
        c_start = c_start + c_name.length + 1; 
        c_end = document.cookie.indexOf( ";", c_start );
        if( c_end == -1 ) c_end = document.cookie.length;
        return document.cookie.substring( c_start, c_end );
    },

    
    getViewByRegion : function() {
        return editionToNameMap[dj.blogs.util.Url.decode(this.getCookie( 'wsjregion' ))];
    },
    
    getQueryParam : function(pname) {
        hQuery = new Hash(location.search.replace(/^\?/, "").parseQuery());
        return (typeof hQuery.get(pname) !== "undefined") ? hQuery.get(pname) : "";
    },
    
    getHashParam : function(pname) {
        hHash = new Hash(location.hash.replace(/^#/, "").parseQuery());
        return (typeof hHash.get(pname) !== "undefined") ? hHash.get(pname) : "";
    }

   
});


dj.blogs.Tracking = Class.create({

    initialize: function() {
        this.omni    = new dj.blogs.util.omni();  
        this.site    = 'WSJ';
        this.channel = 'Online Journal';
        //this.link    = s.getQueryParam( 'mod' );
        //this.reflink = s.getQueryParam( 'reflink' );
        //this.refresh = s.getQueryParam( 'refresh' );
        
        this.link    = (this.omni.getQueryParam('mod') || this.omni.getHashParam('mod'));
        this.reflink = (this.omni.getQueryParam('reflink') || this.omni.getHashParam('reflink'));
        this.refresh = (this.omni.getQueryParam('refresh') || this.omni.getHashParam('refresh'));
  
        
        this.TR      = this.omni.TR;

        if( ! this.refresh ) { this.refresh = 'off'; }
        if( this.reflink ) { this.link = ""; }
        else if( this.link ) { this.reflink = ""; }

        this.targeturl   = s.getQueryParam( 'url' );
        this.fullurl     = document.location.href;
        this.baseurl     = document.location.protocol + '//' + document.location.host + document.location.pathname;
        this.caccess     = ( ( typeof loggedIn !== "undefined" ) && ( loggedIn === true ) ) ? "subscriber" : "free";
        this.showGeography = true;
        this.c8 = ' Online';
        this.c19 = 'blogs';
        
        s.server  = document.location.protocol + '//' + document.location.host; 
        s.baseurl = this.baseurl;
        s.fullurl = this.fullurl;
        s.refresh = this.referesh;
        s.caccess = this.caccess;

		if( this.link ) { s.link = this.link; }
   	    if( this.reflink ) { s.reflink = this.reflink; }
    },
    
    freeRegType: function() {
    	var that = this;
    	var return_value = '';

        if( typeof this.omni == "undefined" ) {

            if(that.TR == null)
	            return that.site + '_free';
	        else
	            return that.site + '_reg_yes';
        }

       if (this.omni.isLoggedIn()){
           if(this.omni.isSubscriber()) {
           
             return_value = that.site + '_sub_yes';
           }else{
             return_value = that.site + '_mem_yes';
           }
       }else{
           if(that.TR == null){
	         return_value = that.site + '_free';
	       }else{
	         return_value = that.site + '_reg_yes';
	       }
       }
       return return_value;
    },
    
    firePixel: function() {
        s.channel = this.channel;
    	this.pageName = this.blogName + '_' + this.title;
    	s.pageName = this.site + '_' + this.pageName;
    	s.prop1 = 'Community';
    	s.prop2 = this.site  + '_' + this.section;
    	s.prop26 = this.site + '_' + this.subsection;
    	s.prop3 = this.site + '_' + s.prop1 + '_' + this.blogName;
    	if ((this.pageType == 'comments')||(this.pageType == 'category'))
    	  s.prop3 += '_' + this.pageType;
    	if (this.pageType == 'post')
    	  s.prop4 = 'blog_' + this.title;
    	s.prop5 = this.baseurl;
    	s.prop6 = this.fullurl;
    	s.prop7 = this.refresh;
    	s.prop8 = this.site + this.c8;
    	s.prop9 = 'free';  //All blog articles are marked as free for now.  Non-free blogs don't exist yet.
    	s.prop10 = this.link;
    	s.prop11 = this.reflink;
    	s.prop13 = (!this.adzone) ? this.ad_zone : this.adzone;
    	s.prop19 = this.c19;
    	if (this.pageType == 'comments')
    	  s.prop19 += '_' + this.pageType + '_tab';
    	else if (this.pageType == 'category')
    	  s.prop19 += '_' + this.pageType;
    	s.prop22 = this.site + '_' + s.prop1 + '_' + this.blogName;
    	s.prop23 = this.publishTime;
    	if (this.showGeography) {
    	  s.prop24 = this.omni.getViewByRegion();
    	}
    	s.prop25 = this.TR;
    	s.prop27 = (this.TR == null) ? (this.site + '_free') : (this.site + '_sub_yes');
    	s.prop27 = this.freeRegType();
    	
    	s.hier1  = [s.channel, s.prop1, s.prop2, s.prop26, s.pageName, s.prop5].join(",");
    	s.hier2  = [s.channel, s.prop19, s.prop2, s.prop3].join(",");
    	s.hier3  = [s.channel, s.prop2, s.prop26, s.pageName].join(",");
    	s.hier4  = [s.channel, s.prop2, s.prop1, s.pageName].join(",");
    	if (this.showGeography) {
    	  s.hier5  = [s.channel, s.prop24, s.prop1, s.prop2, s.prop26, s.pageName].join(",");
    	}
    	
    	s.events = s.events ? ( s.events + ",event12" ) : "event12";
    	s.events = s.events ? ( s.events + ",event32" ) : "event32";
    	
    	s.eVar3  = this.TR;
        s.eVar4  = s.pageName;
        s.eVar5  = s.prop10;
        s.eVar6  = s.prop11;
        s.eVar11 = s.channel;
        s.eVar25 = s.prop2 + '_' + this.subsection;
        
    	var currentTime = new Date();
        var mday = {
            0: 'Sunday',
            1: 'Monday',
            2: 'Tuesday',
            3: 'Wednesday',
            4: 'Thursday',
            5: 'Friday',
            6: 'Saturday' };       

        s.eVar31 = mday[ currentTime.getDay() ];
        s.eVar32 = currentTime.getHours() + ':00';

        this.firePixelCount = this.firePixelCount + 1;
        
        var s_code = s.t();
        if( s_code ) { document.write( s_code ); }
    }
});

