
// AddThis:
var addthis_pub = 'G4TVDevTeam';
var addthis_options = 'google, favorites, digg, delicious, reddit, technorati, newsvine, fark, live, more';

// global variables
var phoenixBase = "http://g4tv.com/";
var applicationPath = "/";
var imageURL = "http://cache.g4tv.com/images/";
var mediaURL = "http://media.g4tv.com/";

var G4TV = {};

if (typeof(jQuery) != 'undefined') {
    jQuery.noConflict();
}

if (typeof(console) === 'undefined') {
    console = {
        log: function(string) {
            //empty function
        }
    }
}

function urlencode(string, doubleEncode) {  
    // The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
	    		    "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
				    "abcdefghijklmnopqrstuvwxyz" +
				    "-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < string.length; i++ ) {
	    var ch = string.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    //alert( "Unicode Character '" 
                //        + ch 
                //       + "' cannot be encoded using standard URL encoding.\n" +
				//         "(URL encoding only supports 8-bit characters.)\n" +
				//	      "A space (+) will be substituted." );
				encoded += "+";
			    } else {
				    encoded += "%";
				    encoded += HEX.charAt((charCode >> 4) & 0xF);
				    encoded += HEX.charAt(charCode & 0xF);
			    }
		 }
	 } // for

	 return (typeof(doubleEncode) == 'undefined') ? encoded : this.encode(encoded);
}


// Legacy Google Analytics tracking replacement
function urchinTracker(url) {
    if ((typeof(url) !== 'undefined')) {
        G4TV.Track.page(url);
    } else {
        G4TV.Track.page();
    }
}


G4TV.Track = {
    page: function(url) {
        if ((typeof(url) == 'undefined') || (url === null) ) {
            pageTracker._trackPageview();
            void(s.t());
        } else {
			url = url.replace('/http://g4tv.com', '');
			url = url.replace('http://g4tv.com', '');
            pageTracker._trackPageview(url);
            if (url.indexOf('/events/') == -1)
            {
				url = url.replace('?', '/');
				url = url.replace('&', '/');
				url = url.replace('=', '');
				s.pageName = url;
				void(s.t());
            }
        }
        
        if (typeof(_qoptions) != 'undefined') {
			_qoptions={qacct:"p-98dv-nOkjKpU6", event:"refresh", labels:"AJAX"};
			quantserve();
		}
    },
    
    event: function(category, action, label, value) {
        if ( (typeof(label) != 'undefined') && (typeof(value) != 'undefined') ) {
            pageTracker._trackEvent(category, action, label, value);
        }
        else if (typeof(label) != 'undefined') {
            pageTracker._trackEvent(category, action, label);
        }
        else {
            pageTracker._trackEvent(category, action);
        }
    },
    
    setVar: function(value) {
        pageTracker._setVar(value);
    }
};


G4TV.Dom = {
    methods: new Array(),
    
    ready: function(func) {
        jQuery(document).ready(func);
    },
    
    addLoadEvent: function(method) {
        this.methods.push(method);
    },
    
    executeEvents: function() {
        for(i=0; i<this.methods.length; i++) {
            eval(this.methods[i]);
        }
    }
};



G4TV.Cookie = {
    cookies: new Array(),
    
    set: function(name, value, expiration, secure) {
        expiration = typeof(expiration) != 'undefined' ? expiration : 631138519494; // Defaults to 20 years
        secure = typeof(secure) != 'undefined' ? secure : false;
        
        if (expiration > 0)
        {
            var date = new Date();
            date.setTime(date.getTime()+(expiration));
            var expires = date.toGMTString();
        }
        else
        {
            var expires = "-1";   
        }
    
        document.cookie = name+"="+value+"; expires=" + expires + "; path=/; domain=.g4tv.com";
    
        G4TV.Cookie.cookies[name] = value;
    },
    
    
    get: function(name, default_) {
        if (typeof(G4TV.Cookie.cookies[name]) !== "undefined") {
            return G4TV.Cookie.cookies[name];
        }
        
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') {c = c.substring(1,c.length);}
            if (c.indexOf(nameEQ) === 0) {
                var cookieVal = c.substring(nameEQ.length,c.length);
                
                if (cookieVal == 'true') {return true;}
                else if (cookieVal == 'false') {return false}
                    else { return cookieVal; }
            }
        }
        return typeof(default_) !== "undefined" ? default_ : null;
    },
    
    
    remove: function(name) {
        this.set(name, '', -1);
    }
};



function addCommas(nStr)
{
	nStr += '';
	x = nStr.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;
}




function addLoadEvent(func) 
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function') 
  {
    window.onload = func;
  } 
  else 
  {
    window.onload = function() 
    {
      if (oldonload) 
      {
        oldonload();
      }
      func();
    }
  }
}



// ******************************************************************************
// The methods below are still in the process of being updated and consolidated.
// ******************************************************************************





function openPile(videoKey) {
    var params = '';
    
    if (videoKey != null)
        params = '?fromPilePlayer=true&video_key=' + videoKey;
        
    
        //new video detail page
            var url = 'http://g4tv.com/video_detail.aspx' + params;
            location.href = url;
    
    
    
    return;
}

function openChatWindow(params) {

    var url = 'http://g4tv.com/chat/chat_window.aspx?' + params; 
    var day = new Date();
    var id = day.getTime();
    eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=600,height=600');");
}

function openPileTab(categoryKey) {
    var params = '';
    
    if (categoryKey != null)
        params = '?fromPilePlayer=true&category_key=' + categoryKey;
        
     
        //new video detail page
            var url = 'http://g4tv.com/video_detail.aspx' + params;
            location.href = url;
    
     
    return;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
    


function Log(strPath)
{
    if(typeof urchinTracker != "undefined")
    {
        urchinTracker("/events" + strPath);
    }
}

function FlashLink(strEventPath, strURL)
{
    urchinTracker(strEventPath);
    location.href = strURL;
}

function toggleClass(strDiv,strClass)
 {  
    document.getElementById(strDiv).className = strClass; 
 }
 
 function toggleClass2(strDiv,strClass1,strClass2)
 {  
    objDiv = document.getElementById(strDiv);
    //debugAlert(objDiv.className,strClass1,strClass2);
    if(objDiv.className != strClass1)
    {
        objDiv.className = strClass1; 
    }
    else
    {
        objDiv.className = strClass2; 
    }
    
 }
 
 function toggleDisplay(strId)
 {
    theItem = document.getElementById(strId);
    if(theItem.style.display == "none")
    {
        theItem.style.display = "block";
    }
    else
    {
        theItem.style.display = "none";
    }  
 }
 
 

var arrBg = new Array(4);
    arrBg[1] = "#434343";
    arrBg[2] = "#21293a";
    arrBg[3] = "#22496F";
    arrBg[4] = "#1b1b1b";
random_bg = (Math.floor(Math.random()*4))+1; 


function RandomizeBackground()
{ 
    document.getElementById("outer_container").style.backgroundColor = arrBg[random_bg];
    //document.getElementById("outer_container").style.backgroundImage = "url(http://cache.g4tv.com/images/2007/header_3tier/body_bg_" + random_bg + "_126.jpg)";
}

function Randomize2007()
{
    document.getElementById("outer_container").style.backgroundColor = arrBg[random_bg];
    //document.getElementById("outer_container").style.backgroundImage = "url(http://cache.g4tv.com/images/2007/header_3tier/body_bg_" + random_bg + "_137.jpg)";

}

function SetBackground(bg)
{
    if(bg != undefined) {
        random_bg = 4;
        document.getElementById("outer_container").style.backgroundColor = arrBg[random_bg];
        //document.getElementById("outer_container").style.backgroundImage = "url(http://cache.g4tv.com/images/2007/header_3tier/body_bg_" + random_bg + "_126.jpg)";
    }
}





function hidePlayer()
{
    if(navigator.userAgent.indexOf('Safari') < 0)
    {
        ctlPlayer = document.getElementById('VideoPlayer');
        if(ctlPlayer)
        {
            ctlPlayer.style.visibility='hidden';
        }
    }
}


function showPlayer()
{
    if(navigator.userAgent.indexOf('Safari') < 0)
    {
        ctlPlayer = document.getElementById('VideoPlayer');
        if(ctlPlayer)
        {
            ctlPlayer.style.visibility='visible';
        }
    }
}

function debugAlert()
{
    var strAlert="";
    for (var iii = 0; iii < debugAlert.arguments.length; iii++)
    {
        if(debugAlert.arguments[iii] != null)
        {
            strAlert += debugAlert.arguments[iii] + "\n";
        }
    }
    alert(strAlert);
}


function nullFunc()
{
    //this is for a null submit function in the poll voting control
}


var ListGridButtonIds;

function AddLGButtonId(theID)
{
    if(ListGridButtonIds)
    {
        ListGridButtonIds += "," + theID;
        //debugAlert('2nd or more', theID, ListGridButtonIds);
    }
    else
    {
        ListGridButtonIds = theID;
        //debugAlert('1stTime', theID, ListGridButtonIds);
    }
}

function flipView(listID,gridID,listPath,gridPath,listSearchLabelID,gridSearchLabelID)
{
    objList = document.getElementById(listID);
    objGrid = document.getElementById(gridID);
   
    if(objList.style.display=="block")
    {
        objList.style.display="none";
        objGrid.style.display="block";
        document.cookie = 'list_preference=grid; expires=Fri, 3 Aug 2037 20:47:11 UTC; path=/'
        
        if(typeof(ListGridButtonIds) != 'undefined') {
            arrIDs = ListGridButtonIds.split(",");        
            for(iii = 0; iii < arrIDs.length; iii++)
            {
                document.getElementById(arrIDs[iii]).src = gridPath;
            }

            if (typeof(listSearchLabelID) != 'undefined' && typeof(gridSearchLabelID) != 'undefined') {
                document.getElementById(listSearchLabelID).style.display = "none";
                document.getElementById(gridSearchLabelID).style.display = "block";
            } 
         }
    }
    else
    {
        objList.style.display="block";
        objGrid.style.display="none";
        document.cookie = 'list_preference=list; expires=Fri, 3 Aug 2037 20:47:11 UTC; path=/'
        
        if(typeof(ListGridButtonIds) != 'undefined') {
        
            arrIDs = ListGridButtonIds.split(",");
            for(iii = 0; iii < arrIDs.length; iii++)
            {
                document.getElementById(arrIDs[iii]).src = listPath;
            }
     
            if (typeof(listSearchLabelID) != 'undefined' && typeof(gridSearchLabelID) != 'undefined') {
               document.getElementById(listSearchLabelID).style.display = "block";
               document.getElementById(gridSearchLabelID).style.display = "none";
            }
        }
 
        
    }
    
    //prompt('',document.cookie);
}




function sddOn(ctlUl)
{
    hidePlayer();
    ctlUl.className += ' ulHover'
}

function sddOff(ulID)
{
    ctlUl = document.getElementById(ulID);
    showPlayer();
    ctlUl.className = ctlUl.className.replace(new RegExp(' ulHover\\b'), '');
}


String.prototype.format = function()
{
    var str = this;

    for(var i=0;i<arguments.length;i++)
    {
        var re = new RegExp('\\{' + (i) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }

    return str;
}


String.prototype.replaceAll = function(pcFrom, pcTo){
    var i = this.indexOf(pcFrom);
    var c = this;
    while (i > -1){
        c = c.replace(pcFrom, pcTo);
        i = c.indexOf(pcFrom);
    }

    return c;

}

//Extension For 'titleCase'

String.noLC = new Object
  ({ the: 1, a: 1, an: 1, and: 1, or: 1, but: 1, aboard: 1,
      about: 1, above: 1, across: 1, after: 1, against: 1,
      along: 1, amid: 1, among: 1, around: 1, as: 1, at: 1,
      before: 1, behind: 1, below: 1, beneath: 1, beside: 1,
      besides: 1, between: 1, beyond: 1, but: 1, by: 1, 'for': 1,
      from: 1, 'in': 1, inside: 1, into: 1, like: 1, minus: 1,
      near: 1, of: 1, off: 1, on: 1, onto: 1, opposite: 1,
      outside: 1, over: 1, past: 1, per: 1, plus: 1,
      regarding: 1, since: 1, than: 1, through: 1, to: 1,
      toward: 1, towards: 1, under: 1, underneath: 1, unlike: 1,
      until: 1, up: 1, upon: 1, versus: 1, via: 1, 'with': 1,
      within: 1, without: 1
  });


String.prototype.titleCase = function() {

    var parts = this.split(' ');
    if (parts.length == 0) return '';

    var fixed = new Array();
    for (var i in parts) {
        var fix = '';
        if (String.noLC[parts[i]]) {
            fix = parts[i].toLowerCase();
        }
        else if (parts[i].match(/^([A-Z]\.)+$/i)) { // will mess up "i.e." and like
            fix = parts[i].toUpperCase();
        }
        else if (parts[i].match(/^[^aeiouy]+$/i)) { // voweless words are almost always acronyms
            fix = parts[i].toUpperCase();
        }
        else {
            fix = parts[i].substr(0, 1).toUpperCase() +
         parts[i].substr(1, parts[i].length);
        }
        fixed.push(fix);
    }
    fixed[0] = fixed[0].substr(0, 1).toUpperCase() +
         fixed[0].substr(1, fixed[0].length);
    return fixed.join(' ');
}

//End Extension For 'titleCase'


function validateEmail(email) 
{
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) 
   {
      return false;
   }
   else
   {
      return true;
   }
   
}

function isIE6()
{  
    return navigator.appVersion.indexOf('MSIE 6.0') > 0 && navigator.appName=="Microsoft Internet Explorer" ? true : false;        
}

function isIE() {
    return navigator.appVersion.indexOf('MSIE') > 0 && navigator.appName=="Microsoft Internet Explorer" ? true : false;    
}


function showAddThis(link, title, shortUrl, returnStr) {
    // Check Short Url 
    if(typeof(shortUrl) === "undefined" || shortUrl == '') {
        shortUrl = link;
    }
    // Transparent png
	transImg = '<img src="http://cache.g4tv.com/static/assets/trans.png" alt="" title=""/>';
	qeTitle  = title.replace(/'/g, "\\'"); // Single quote escaped title
	scTitle = escape(title).toLowerCase();
	
																	
	atHtml   = '<div class="addthis"><ul>';
																	
	// Email
	atHtml  += '<li><a class="at_email" href="#" onclick="return addthis_open(this, \'email\', \'' + link + '\', \'' + qeTitle + '\');" title="Email this to a friend">' + transImg + '</a></li>';
																	
	// N4G
	atHtml  += '<li><a class="at_n4g" href="http://www.n4g.com/tips.aspx?url=' + escape(link) + '&title=' + escape(title) + '" onclick="sTrackWidgetClick(\'share-ng4-' + scTitle + '\');" title="Share this on N4G" target="_blank" >' + transImg + '</a></li>';
																	
	// All other sites
	atHtml  += '<li><a class="at_buzz" href="http://buzz.yahoo.com/buzz?publisherurn=g4_tv518&targetUrl=' + urlencode(link) + '" onclick="sTrackWidgetClick(\'share-yahoo-buzz-' + scTitle + '\');" target="_blank" title="Share this on Yahoo! Buzz">' + transImg + '</a></li>';
	atHtml  += '<li><a class="at_stumbleupon" href="#" onclick="addthis_url=\'' + link + '\'; addthis_title=\'' + qeTitle + '\'; return addthis_sendto(\'stumbleupon\');sTrackWidgetClick(\'share-stumble-upon-buzz-' + scTitle + '\');" title="Share this on StumbleUpon">' + transImg + '</a></li>';
	atHtml  += '<li><a class="at_facebook" href="#" onclick="addthis_url=\'' + link + '\'; addthis_title=\'' + qeTitle + '\'; return addthis_sendto(\'facebook\');sTrackWidgetClick(\'share-facebook-' + scTitle + '\');" title="Share this on Facebook">' + transImg + '</a></li>';
	atHtml  += '<li><a class="at_myspace" href="#" onclick="addthis_url=\'' + link + '\'; addthis_title=\'' + qeTitle + '\'; return addthis_sendto(\'myspace\');sTrackWidgetClick(\'share-myspace-' + scTitle + '\');" title="Share this on MySpace">' + transImg + '</a></li>';
	atHtml  += '<li><a class="at_twitter" href="http://twitter.com/home/?status=Check+this+out+on+G4TV.com%3A+' + urlencode(shortUrl) + '" onclick="sTrackWidgetClick(\'share-twitter-' + scTitle + '\');"target="_blank" title="Tweet about this on Twitter">' + transImg + '</a></li>';
	
																	
	// More drop down
	atHtml  += '<li><a class="at_more" href="#" onclick="addthis_url=\'' + link + '\'; addthis_title=\'' + qeTitle + '\'; return addthis_click(this);">' + transImg + '</a></li>';
														
	atHtml  += '</ul></div>';
	
	if (typeof(returnStr) == "undefined") {						
	    document.write(atHtml);
	} else {
	    return atHtml;
	}
}

//Dynamically Load A StyleSheet
function LoadStyleSheet(path) {
    jQuery(document.createElement("link"))
    .attr({ type: "text/css", href: path, rel: "stylesheet" })
    .appendTo("head");
}


//Ban Users
function BanUser(UserID, UserName, EntityTypeKey, EntityKey, Destination) {
    if (typeof(G4TV.BanUser) == 'undefined') {
        jQuery.getScript("{0}js/BanUser.js".format(applicationPath), function() {
            G4TV.BanUser.SetBannedUserProperties(UserID, UserName, EntityTypeKey, EntityKey, Destination)
        });
    } else {
        G4TV.BanUser.SetBannedUserProperties(UserID, UserName, EntityTypeKey, EntityKey, Destination)
    }
}

if (typeof (jQuery) != 'undefined') {
    jQuery(document).ready(function() {
        G4TV.Dom.executeEvents();

		//add onclick events for nav tracking
		jQuery("#hd-nav a").click(function() { 
			var eventName = this.href.replace('http://g4tv.com/', '/events/navClick/');
			if (eventName == '/events/navClick/')
				eventName = '/events/navClick/home/';			
			urchinTracker(eventName);
		});
		
		//add onclick events for hot topic tracking
		jQuery("#hd-hot-topics a").click(function() { 
			var eventName = this.href.replace('http://g4tv.com/', '/events/hotTopicsClick/');
			urchinTracker(eventName);
		});
		
    });
}