﻿/*
    This is the True_lib.js file.  It contains javascript common around the site.
    The site does not use this file, it is compressed into True_lib_compressed.js.
    
    Sections should be documented clearly.  Current sections are:
    
    Section         Date Added  Project  Description
    --------------- ----------- ------- ----------------------------------------------
    TBHead          2008-06-12  SPS4887 All scripts previously contained in TBHead.inc
    Chat 2.0        2008-06-12  SPS4887 Copied from chat.js -> chat.js should be changed too
    ImageSwap       2008-06-12  SPS4887 Copied from imageswap.js
    Jsincs          2008-06-12  SPS4887 Copied from jsincs.js
    
*/


/*  Section: TBHead */

// Non-ie browsers don't implement window.execScript. This fixes it and handles window.navigate too.
if(!window.execScript){
    window.execScript = function(script){
        if(/window.navigate/.test(script)){
            var url = /\('(.*)'\)/.exec(script);
            window.location = url[1];
        }else{
            eval(script);
        }
    }
}

True.Cookie = {
    setCookie: function(name, value, expirationDays, path, domain, secure) {
        var expires = null;
        if(expirationDays != null){
            expires = new Date();
            expires.setTime(expires.getTime()+(expirationDays*24*60*60*1000));
        }
        var cookie = name + "=" + escape(value);
        if(expires != null)
            cookie += '; expires=' + expires.toGMTString();
        if(path != null)
            cookie += '; path=' + path;
        if(domain != null)
            cookie += '; domain=' + domain;
        if(secure != null)
            cookie += '; secure=' + secure;
        document.cookie = cookie; 
    }
    , getCookie: function(name) {
        var ca = document.cookie.split(';');
        var kvPair, key, value;
        for(var i = 0; i < ca.length; i++){
            kvPair=ca[i].split('=');
            key=kvPair[0].trim();
            value=kvPair[1].trim();
            if(key==name)
                return value;
        }
        return null;
    }
    , deleteCookie: function(name) {
        this.setCookie(name,"",-1, null, null, null);
    }
};


// Denotes whether a pop up can start or not
var isPop = true;

// Set the pop up window start to false
var setIsPop = function(){
    isPop = false;
}

function checkNoPop()
{
    var queryparms = window.location.href.toQueryParams();
    if (queryparms.exitpop)
    {
        if ((queryparms.exitpop == 'no') || (queryparms.exitpop == 'no,no')) 
        {
            if (IsOnSignupStep2())
                isPop = true;
            else 
                isPop = false;
        }
    }   
}

function IsOnSignupStep2()
{
    try
	{
	    var signupFrmDiv = document.getElementById('signupForm');
	    
	    if (signupFrmDiv != null)
	    {
	        if (signupFrmDiv.style.display.toUpperCase() != 'NONE')
	            return true;
	    }
	    else
	        if (IsSignupStep_step2Visible())
	            return true;
    }
	catch(excp)
	{
	}
	     
	return false;
}

function disposeOfFrames(){ 
    try{
        var allowExec = true;
        var frameLength = 0;
        var source = '';
        if(parent.document.frames && parent.document.frames.length > 0){																							
            source = new String(parent.document.frames[0].frameElement.src);													
            if(source.toLowerCase().indexOf("browsercheck") > -1) {	
                if (parent.document.frames["signupFrame"] != undefined) {
                    allowExec = false;
                }		
            }	
        }
        if(parent.document.frames && parent.document.frames.length > 0 && allowExec){							
            if (parent.document.frames["signupFrame"] != undefined){								
                parent.execScript("setIsPop();");							
                parent.document.location = document.location.href;	
            }
        }
    }catch(ex){}
}
function handleLink(url){
    try{			
        if(parent.document.frames.length > 0){				
            if (parent.document.frames["signupFrame"] != undefined){					
                parent.execScript("setIsPop();");
                parent.document.location = url;
            }
        }else{				
            document.location = url;
        }
    }
    catch(ex){
        document.location = url;
    }
}
function MM_showHideLayers() { //v6.0
    var i,p,v,obj,args=MM_showHideLayers.arguments;
    for (i=0; i<(args.length-2); i+=3){
        if ((obj=MM_findObj(args[i]))!=null){
            v=args[i+2];
            if (obj.style){
                obj=obj.style;
                v=(v=='show')?'visible':(v=='hide')?'hidden':v;
                obj.display=(v=='visible'? 'block':obj.display);
            }
            obj.visibility=v;
        }
    }
}

// Global var used to track whether a body.onunload event is triggered from a page event (link or button onclick, etc..)
// or an outside event (browser being closed, refreshed, etc...)
var isOnUnloadFromPage = false;

// This should usually be called by listening for an onclick event in a dom
var setIsOnUnloadFromPage = function(e){
    e = e || window.event;
    var obj = e.target || e.srcElement;
    
    //for now we only want to track links triggering onunload events
    if(obj.nodeName == 'A')
        isOnUnloadFromPage = true;
} 

// Starts the pop up
var loadPopUp = function(){
    
    checkNoPop();    

    var CurrentPage = -1;    
    if (!documentWasClicked){
        CurrentPage = window.location.href.toLowerCase().indexOf("signup");
    }
    
    if((isPop) && (CurrentPage > -1)){
        //Sigup Exit Pop
        url = ExitPopLandingPageURL;       
        //RootPath + '/popups/exit_popup_rotator.aspx';
        specs = 'menubar=0,resizable=0,scrollbars=0,width=720,height=270,top=100,left=100';
        var windowHandle = window.open(url, '', specs);
        if(windowHandle != null)
            windowHandle.focus();
    } else {
        CurrentPage = window.location.href.toLowerCase().indexOf("payment_received");
        if((isPop) && (CurrentPage > -1)){
            //Payment Received Exit Pop
            parentUrl = window.location.href;                            
            url = RootPath + '/am_adaptivemarketingrotator.htm' + parentUrl.substring(parentUrl.indexOf('?'),parentUrl.length); 

            //If the onunload event is triggered by interaction with our page then
            //just point the current window to where we need to go 
            if(isOnUnloadFromPage){
                window.location.href = url;
            }else{
                //otherwise pop a new window
                var windowHandle = window.open(url, '', '');
                if(windowHandle != null)
                    windowHandle.focus();  
            }                     
        }
    }
}
// <summary>Extending the Date class.</summary>
Date.prototype.format = function(format){
    return format.replace("yyyy", this.getFullYear()).replace("mm", this.thisMonth("mm")).replace("dd", this.thisDate("dd"));
}

Date.prototype.thisMonth = function(format){
    switch(format){
        case("m"):
            return this.getMonth()+1;
            break;
        case("mm"):
            return (((this.getMonth()+1) < 10) ? "0" + (this.getMonth()+1) : (this.getMonth()+1));
            break;
        default:
            return this.getMonth();
            break;
    }
};
Date.prototype.thisDate = function(format){
    switch(format){
        case("d"):
            return this.getDate();
            break;
        case("dd"):
            return ((this.getDate() < 10) ? "0" + this.getDate() : this.getDate());
            break;
        default:
            return this.getDate();
            break;
    }
};

Date.prototype.add = function(days){
    return new Date(Date.parse(this.toString()) + days * 86400000);
}
Date.prototype.getMonths = function(){
    var months = [];
    months.push('January');
    months.push('February');
    months.push('March');
    months.push('April');
    months.push('May');
    months.push('June');
    months.push('July');
    months.push('August');
    months.push('September');
    months.push('October');
    months.push('November');
    months.push('December');
    return months;
}
Date.prototype.getMonthName = function(){
    return this.getMonths()[this.getMonth()];
}


/*  Section: Chat 2.0
    Chat 2.0 Functions
    These are the currently-used chat functions. The functiones below this 
    block are depricated, but left in place in case they are still used in 
    other places.
*/

function popVideoChat(room_id, room_name,chat_size, version){

//if(room_id == "room_02") version = '2';

    var windowName = 'ChatRoom';
    var pad = 20;
    var width, Height;

    if(chat_size=="large"){
        width = 1004;
        Height = 633;
    }
    else
    {
        width = 780;
        Height = 580;
    }

    var windowUrl = RootPath + '/chat/popVideoChat'+ (version=='2'?'2':'') +'.aspx?room_id=' + room_id + '&room_name=' + room_name +'&chatsize='+ chat_size +'&width='+ (width-pad*2) +'&height='+ (Height-pad*2);
    var windowOptions = 'width='+ width +',height='+ Height +',menubar=0,scrollbars=0,status=1,toolbar=0,resizable=0';

    window.open(windowUrl,windowName,windowOptions);

}

function popPrivateChat(from, to){
var windowName = 'private_'+ from +'_'+ to;
var windowSize = {width: 700, height: 400};
switch(True.ChatVersion){
    case(1):
        windowSize = {width: 440, height: 440};
        break;
    default:
        break;
}
var windowUrl = RootPath + '/chat/popChatPrivate.aspx?from_id='+ from +'&to_id='+ to;
    var win = window.open(windowUrl, windowName, 'width=' + windowSize.width + ',height=' + windowSize.height + ',menubar=0,scrollbars=0,status=0,toolbar=0,resizable=0');
    if(!win){
        alert('The private chat window was blocked. Please turn off your pop up blockers for this site to send char requests.');
    }
}

/*  End Chat 2.0 Functions */

//  02/05/2004 SKM : Chat helper functions 
//  03/16/2004 SKM : Modified conditionalOpen to focus if window already open   
//  03/24/2004 SKM : Added function captureChatRoomExit

var win = null;

function captureChatRoomExit(user_id,room_id,roomTypeID) {
// alert('captureChatRoomExit(' + user_id + ',' + room_id + ',' + roomTypeID + ')');
var windowUrl = RootPath + '/chat/chatdata.aspx?action=chatexit&user_id=' + user_id +'&room_id=' + room_id + '&roomTypeID=' + roomTypeID;
var windowName = 'ChatData';
var windowOptions = 'width=1,height=1,menubar=0,scrollbars=0,status=0,toolbar=0,resizable=0';
var MyWin = window.open(windowUrl,windowName,windowOptions);
}

function conditionalOpen(windowUrl,windowName,windowOptions) {
// alert('actualVersion=' + actualVersion + '\n' + 'requiredVersion=' + requiredVersion + '\n' + 'Acceptable Version =' + (actualVersion >= requiredVersion));
if(actualVersion >= requiredVersion){
if(!(win && win.open && !win.closed)){
win = window.open(windowUrl,windowName,windowOptions); 
win.focus();
}else{
win.focus();
}
}else{
popFlashNotice(); 
}
}

function popChatHelp() {
var windowUrl = RootPath + '/popMoreText.aspx?id=63'; 
var windowName = 'ChatHelp';
var windowOptions = 'width=500,height=350,menubar=0,scrollbars=0,status=0,toolbar=0,resizable=0';
var myWin = window.open(windowUrl, windowName, windowOptions);        
myWin.focus();
}

function popAbuseReport() {
var windowUrl = RootPath + '/service.htm?id=748';
opener.location.href=windowUrl;
opener.focus();
}

function popFlashNotice() {
var windowUrl = '';
var windowName = 'FlashUpgrade';
var windowOptions = 'width=500,height=350,menubar=0,scrollbars=0,status=0,toolbar=0,resizable=0';
if (actualVersion == 0)
windowUrl = RootPath + '/popMore.aspx?id=156'; 
else
windowUrl = RootPath + '/popMore.aspx?id=157'; 
var myWin = window.open(windowUrl, windowName, windowOptions);        
myWin.focus();
}

function popVideoChatSetLobbyMemberHome(room_id, room_name, chat_size, room_count){
location.href = RootPath + '/Chat/VideoChatLobby.htm?svw=lnavbar&linkid=18545';
popVideoChat(room_id, room_name, chat_size);
}

function popVideoChatSetLobby(room_id, room_name,chat_size){
location.href = RootPath + '/Chat/VideoChatLobby.htm?svw=lnavbar&linkid=21';
popVideoChat(room_id, room_name, chat_size);
}

function popUserProfile(user_id){
var windowName = 'profile';
var windowUrl = RootPath + '/chat/popProfileView.aspx?uid=' + user_id + '&chat=true';
var myWin = window.open(windowUrl, windowName, 'width=710,height=680,menubar=1,scrollbars=1,status=0,toolbar=1,location=1,resizable=1');
myWin.focus();
}

function alertClient (fromID, fromName, to, msg, room_id){
var windowName = 'private_chat';
var windowUrl = RootPath + '/chat/popChatInviteRecv.aspx?fromid=' + fromID + '&fromname=' + fromName + '&msg=' + msg.substr(0,500) + '&room_id=' + room_id;
var windowOptions = 'width=200,height=220,menubar=0,addressbar=0,scrollbars=0,status=0,toolbar=0,resizable=0';

//conditionalOpen(windowUrl,windowName,windowOptions);
var myWin = window.open(windowUrl,windowName,windowOptions);
myWin.focus();
}

function popPrivateInvite(user_id){
var windowName = 'ChatInvite';
var windowUrl = RootPath + '/chat/popChatInviteSend.aspx?userID=' + user_id;
var windowOptions = 'width=200,height=220,menubar=0,scrollbars=0,status=1,toolbar=0,resizable=0';
conditionalOpen(windowUrl,windowName,windowOptions);
}

//  2/5/2004 SKM : Flash version detection 
var requiredVersion = 7;  // set version required
var actualVersion = 0;          // version the user really has
var maxVersion = 7;             // highest version we can actually detect
var flash2Installed = false;    // boolean. true if flash 2 is installed
var flash3Installed = false;    // boolean. true if flash 3 is installed
var flash4Installed = false;    // boolean. true if flash 4 is installed
var flash5Installed = false;    // boolean. true if flash 5 is installed
var flash6Installed = false;    // boolean. true if flash 6 is installed
var flash7Installed = false; // boolean. true if flash 7 is installed

// Check the browser...we're looking for ie/win
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;    // true if we're on ie
var isWin = (navigator.appVersion.indexOf("Windows") != -1) ? true : false; // true if we're on windows

// Write vbscript detection on ie win

if(isIE && isWin){
document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');
document.write('on error resume next \n');
document.write('flash2Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.2"))) \n');
document.write('flash3Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.3"))) \n');
document.write('flash4Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.4"))) \n');
document.write('flash5Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.5"))) \n');  
document.write('flash6Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.6"))) \n');  
document.write('flash7Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.7"))) \n');
document.write('</SCR' + 'IPT\> \n'); // break up end tag so it doesn't end our script
}

// detect using the navigator.plugins array
function detectFlash() {  
if (navigator.plugins) {
// ...then check for flash 2 or flash 3+.
if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
// Some version of Flash was found. Time to figure out which.

// Set convenient references to flash 2 and the plugin description.
var isVersion2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
var flashDescription = navigator.plugins["Shockwave Flash" + isVersion2].description;

// DEBUGGING: uncomment next line to see the actual description.
// alert("Flash plugin description: " + flashDescription);
var flashVersion = parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1));

// found version, set flags, use >= on the highest version
flash2Installed = flashVersion == 2;    
flash3Installed = flashVersion == 3;
flash4Installed = flashVersion == 4;
flash5Installed = flashVersion == 5;
flash6Installed = flashVersion == 6;
flash7Installed = flashVersion >= 7;
}
}

// loop through versions and set actualVersion to highest detected
for (var i = 2; i <= maxVersion; i++) {	
if (eval("flash" + i + "Installed") == true) actualVersion = i;
}

// webtv support (2 pre-summer2000, or 3 post-summer2000)
if (navigator.userAgent.indexOf("WebTV") != -1) actualVersion = 2;	
}

detectFlash();	// call our detector now that it's safely loaded.	
               


/*  Section: ImageSwap
    Copied from /includes/imageswap.js */

var MM_swapImgRestore = function() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

var MM_preloadImages = function() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

var MM_findObj = function(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

var MM_swapImage = function() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
} 



/*  Section: jsincs
    Copied from /includes/jsincs.js */


function Len(str)
{
	return String(str).length;
}

function Mid(str, start, len)
{
	if (start < 0 || len < 0) return "";
	
	var iEnd, iLen = String(str).length;
	if (start + len > iLen)
		iEnd = iLen;
	else
		iEnd = start + len;
	
	return String(str).substring(start,iEnd);
}

function InStr(strSearch, charSearchFor)
{
	for (i=0; i < Len(strSearch); i++)
	{
	    if (charSearchFor == Mid(strSearch, i, Len(charSearchFor)))
	    {
			return i;
	    }
	}
	return -1;
}

function DoEmpty(cnfmsg)
{	
	return confirm(cnfmsg);
}

function numChecked()
{
	var frm;
	if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1)
	{
		frm = document.forms["frmMain"];
	}
	else
	{
		frm = document.frmMain;
	}
	var j=0;
	for(var i=0;i< frm.length;i++)
	{
		e=frm.elements[i];
		if (e.type=='checkbox' && InStr(e.name, 'RowSelectorColumnAllSelector') < 0 && e.checked)
			j++;		
	}
	return j;
}

function ValidateDropDown(ddlist)
{
	var selValue = ddlist.options[ddlist.selectedIndex].value;
	if(selValue == "--------------------" || selValue == "00000000-0000-0000-0000-000000000000")
	{
		ddlist.selectedIndex = 0;
		return false;
	}
	if(selValue == "CreateFldr")
	{
		return true;
	}
	if(!ValidateChecked('You didn\'t select any messages. Click the check box next to the message(s) you want to select.'))
	{
		ddlist.selectedIndex = 0;
		return false;
	}
	return true;
}

function ValidateChecked(alrtmsg)
{
	num = numChecked();
	if (num>0)
	{
		return true;
	}
	alert(alrtmsg);
	return false;
}

function ValidateOnlyOneChecked(alrtifnone, alrtifmore)
{
	num = numChecked();
	if (num==0)
	{
		alert(alrtifnone);
		return false;
	}
	if (num>1)
	{
		alert(alrtifmore);
		return false;
	}
	return true;
}

function ValidateHTMLdd(ddlist)
{
	var selValue = ddlist.options[ddlist.selectedIndex].value;
	if(selValue == 1)
	{
		return true;
	}
	else
	{
		if(!confirm('All formatting will be lost. This can NOT be undone!\nAre you sure you want to continue?'))
		{
			ddlist.options[1].selected = true;
			return false;
		}
		else
		{
			return true;
		}
	}
}

function Details(odiv, obtn)
{
	var btn_more = new Image();
	btn_more.src = "images/moredetails.jpg";
	var btn_less = new Image();
	btn_less.src = "images/lessdetails.jpg";

	var source = document.getElementById(obtn).src;
	var btnIndex = source.indexOf(btn_less.src);
	
	if(document.getElementById(odiv).style.display!="")
		document.getElementById(odiv).style.display="";
	else
		document.getElementById(odiv).style.display="none";
	
	if(btnIndex == -1)
		document.getElementById(obtn).src = btn_less.src;
	else
		document.getElementById(obtn).src = btn_more.src;
	return;
}

function PopCompatW(url, name, height, width, scrollbars)
{
	var popwin;
	var opts = "toolbar=no,status=no,location=no,menubar=no,resizable=no";
	opts += ",height=" + height + ",width=" + width + ",scrollbars=yes";

	popwin = window.open(url, name, opts);
	popwin.focus();
}

var debugConsole = {
    init: function(height){
        $$('body')[0].insert({bottom: '<div id="console" style="z-index: 3000;overflow: auto;font-family: Courier;font-size: 1em;position: absolute;bottom:0px;width: 100%;height:60px;background: #000000;color: #00CC00;"><ul></ul></div>'});
        this.view = $('console');
        this.console = this.view.select('ul')[0];
        this.console.setStyle({margin: 0, padding: 0});
        this.view.setStyle({height: height + 'px'});
        this.write('Welcome to the True.com browser console.');
        this.write("Usage: debugConsole.write('some message here')");
    }
    , messages: $A([])
    , console: null
    , view: null
    , add: function(message){
        if(this.view){
            this.messages.push(message);
        }
    }
    , write: function(message){
        this.add(message);
        if(this.console){
            this.truncate(100);
            var now = new Date();
            this.console.insert({
                top:'<li style="list-style-type: square;"><span>#{count} #{hours}:#{minutes}:#{seconds}-></span> #{body}</li>'.interpolate({count: this.messages.length, hours:now.getHours()
                    , minutes:now.getMinutes(), seconds: now.getSeconds(), body: message})
            });
        }
    }
    , truncate: function(amount){
        var items = this.console.select('li');
        if(items.length > amount){
            items.last().remove();
        }
    }
}

document.observe('dom:loaded', function(){
    var query = window.location.href.toQueryParams();
    if(!query.console){
        query.console = 'off';
    }
    if(query.console == 'on'){
        if(query.height == undefined){
            query.height = 60;
        }
        debugConsole.init(query.height);
    }
});
