﻿//create a unique id
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
var isLooping = false;

// Prefetch images
var dpImg1 = new Image();
dpImg1.src = 'images/gradient.png';
var dpImg2 = new Image();
dpImg2.src = 'images/close.png';

var isDpPlaying = null;
var isDpLooping = false;

var clipperStyle = 1;

var tabs = new Array();
var useShort = false;
var showContact = false;

function changeContactStatus()
{
    if (showContact)
    {
        showContact = false;
        document.getElementById('dem').style.display = 'inline';
        document.getElementById('conTab').getElementsByTagName('table')[0].style.display = 'inline';
        document.getElementById('conTab').getElementsByTagName('table')[1].style.display = 'none';
        document.getElementById('con').style.display = 'none';
        window.setTimeout('onTabClick(activeTab(), activeTab());', 150);
    }
    else
    {
        showContact = true;
        document.getElementById('dem').style.display = 'none';
        document.getElementById('conTab').getElementsByTagName('table')[0].style.display = 'none';
        document.getElementById('conTab').getElementsByTagName('table')[1].style.display = 'inline';
        document.getElementById('con').style.display = 'inline';
        onTabClick(activeTab(), activeTab());
    }
}

var displayedContact = null;
function displayContact(item)
{
    if (displayedContact != null)
    {
        displayedContact.parentNode.className = '';
        document.getElementById('C' + displayedContact.getAttribute('contactId')).style.display = 'none';
    }
        
    displayedContact = item;
    
    if (displayedContact != null)
    {
        displayedContact.parentNode.className = 'SelectedCity';
        var contactContent = document.getElementById('C' + displayedContact.getAttribute('contactId'))
        contactContent.style.display = 'inline';
        var contentSPAN = contactContent.getElementsByTagName('span');
        var sCount = 0;
        for (; sCount < contentSPAN.length; sCount++)
        {
            if (contentSPAN[sCount].getAttribute('dType') == '1')
                contentSPAN[sCount].innerHTML = activeName();
        }
    }
}

function displayContactForTab(idNumber)
{
    var agentId = null;
    // Check if the currently 
    if (displayedContact != null)
    {
        if (displayedContact.parentNode.parentNode.parentNode.id.substring(1) == idNumber && idNumber != '0')
            return;
        else
            agentId = displayedContact.getAttribute('agentId');
    }
    
    var cityTable = document.getElementById('c' + idNumber);
    if (agentId != null)
    {
        // Find that agent in the list and highlight them
        var tCount = 0;
        for(;tCount < cityTable.rows.length;tCount++)
            if (cityTable.rows[tCount].cells[0].getAttribute('agentId') == agentId)
            {
                displayContact(cityTable.rows[tCount].cells[0]);
                return;
            }
    }
    
    // Select the first contact
    if (cityTable.rows.length > 0)
        displayContact(cityTable.rows[0].cells[0]);
    else if (displayedContact != null)
	 {
		  displayedContact.parentNode.className = '';
		  document.getElementById('C' + displayedContact.getAttribute('contactId')).style.display = 'none';
		  displayedContact = null;
	 }
}

function onTabClick(activeTabName, previousActiveName)
{
    if (activeTabName == 'none')
        return;

    stopPlayer();
    var count = 0;
    var activeName = activeTabName;
    
    // Change the media tabs
    if (document.getElementById(previousActiveName) != null)
        document.getElementById(previousActiveName).style.display = 'none';
    if (document.getElementById(activeTabName) != null)
        document.getElementById(activeTabName).style.display = 'inline';
    
    // Change the contact tabs
    if (document.getElementById('c' + previousActiveName.substring(1)) != null)
        document.getElementById('c' + previousActiveName.substring(1)).style.display = 'none';    
    if (document.getElementById('c' + activeTabName.substring(1)) != null)
        document.getElementById('c' + activeTabName.substring(1)).style.display = 'inline';
        
    if (document.getElementById('c' + activeTabName.substring(1)) == null && document.getElementById('c0') != null)
    {
        activeName = 'C0';
        document.getElementById('c0').style.display = 'inline';
    }

    // Should we show the "Download All" button?
    document.getElementById('downloadDemoButton').style.visibility = 'hidden';

    if (showContact)
    {
        displayContactForTab(activeName.substring(1));
    }
    else
    {
        var flash = document.getElementById('inlineDpPlayer');
        flash.parentNode.scrollTop = 0;
        playFirstItem();
    }
}

function showContactTab() {}

function downloadNextRead(currentRead)
{
    var nextItem = findNextItem(currentRead);

    if (nextItem != null)
    {
        document.getElementById('downloadNow').innerHTML =
            '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="1" height="1">' +
                '<param name="movie" value="' + appPath + '/flash/Background_Downloader.swf?url=' + escape(createFileName(nextItem)) + '" />' +
                    '<param name="quality" value="high" />' +
                    '<embed src="' + appPath + '/flash/Background_Downloader.swf?url=' + escape(createFileName(nextItem)) + '" width="0" height="0" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash"></embed></object>';
    }
}

function downloadSoundComplete(success)
{
    // This is called when the item in the background is done downloading...
}

function findNextItem(readItem)
{
    var mediaNumbers = readItem.id.substring(14).split('.');
    var nextItem = parseInt(mediaNumbers[1], 10) + 1;
    
    return document.getElementById(readItem.id.substring(0,14) + mediaNumbers[0] + '.' + nextItem);
}

function jsReadComplete()
{
    var currentItem = stopPlayer();
    if (isLooping && currentItem != null)
    {
        var nextItem = findNextItem(currentItem);

        if (nextItem != null)
        {
            if (document.getElementById('con') == null)
                window.setTimeout("playDpItem(document.getElementById('" + nextItem.id + "'));", 400);
            else
                playDpItem(nextItem);
        }
    }
}

var shownCity = null;
function showCity(item, contactId)
{
    if (shownCity != null)
        shownCity.style.display = 'none';
    
    shownCity = document.getElementById('C' + contactId);
    
    if (shownCity != null)
        shownCity.style.display = 'inline';

    // Put the selected class on the row                
    if (item != null)
        item = item.parentNode;
    
    // Change the city
    var cityListing = document.getElementById('CityListing');
    var count;
    
    for(count = 0; count < cityListing.rows.length; count++)
        if (cityListing.rows[count] == item)
            cityListing.rows[count].className = 'SelectedCity';
        else
            cityListing.rows[count].className = '';
}

function noDownloadAvailable()
{
//    document.getElementById('DownloadFrame').src = 'DemoDownloadNotify.aspx?c=' + escape(document.getElementById('clientId').value)
//        + '&o=' + escape(document.getElementById('ownerId').value) + '&m=' + activeTab().substring(1);
    alert('Sorry, the maximum number of downloads has been reached.  Please contact the talent to obtain their demo.');
}

function checkTabs()
{
    if(parseInt('0' + document.getElementById('theTabs').offsetWidth, 10) > 385)
    {
        useShort = true;
        document.getElementById('theTabs').innerHTML = createTabSequence(activeTab(), useShort);
    }
}
function onLoadBody()
{
    try
    {
        if (window.parent.setIframeSize)
            window.parent.setIframeSize(document.getElementById('DemoPlayer').offsetWidth, document.body.offsetHeight);
    } catch(e) {}

    setInitialLoopStatus();
    
    // Center the talent's name on the basic player
    if (document.getElementById('BasicPlayerAdditions') != null)
    {
        var dptn = document.getElementById('DemoPlayerTalentName');
        var tabLength = parseInt('0' + document.getElementById('theTabs').offsetWidth, 10);
        
        dptn.style.left = tabLength + 'px';
        dptn.style.width = (document.getElementById('DemoPlayer').offsetWidth - tabLength) + 'px';
    }

    if (BrowserDetect.browser == "Safari" || BrowserDetect.browser == "Netscape")
    {
        // Fix the tab problem
        document.getElementById(activeTab()).style.display = 'none';
        document.getElementById(activeTab()).style.display = 'inline';

        // Move flash around        
        var flash = document.getElementById('inlineDpPlayer');
        flash.parentNode.scrollTop = 5;
        flash.parentNode.scrollTop = 0;
    }
    
    // Start playing the first read (Safari cache bug, need separate thread to read cache)
    if (BrowserDetect.browser == "Safari")
        window.setTimeout('playFirstItem();', 200);
    else
        window.setTimeout('playFirstItem();', 100);
}

function playFirstItem()
{
    var startItem = document.getElementById('demoPlayerItem' + activeTab().substring(1) + '.1');

    if (startItem == null)
    {
        document.getElementById('downloadDemoButton').style.visibility = 'hidden';
        return;
    }
    
    document.getElementById('downloadDemoButton').style.visibility = 'visible';
    
    if (isLooping && startItem != null)
        playDpItem(startItem);
}

function hideDemoPlayer()
{
    if (typeof (dpFlashProxy) !== 'undefined') {
        dpFlashProxy.call('stopRead');
    } else {
        stopPlayer();
    }
    if (window.parent.closeIframe)
        window.parent.closeIframe();
}

function checkPlaying(itemId)
{
    if (isPlaying.id ==temId)
        logEvent(isPlaying.parentNode.getAttribute('pId'), 1);
}

var savedDpItem = null;
var savedDpFileName = null;

function stopPlayer()
{
    // Get the current item
    var currentItem = isDpPlaying;
    
    // Change the old icon if necessary
    if (isDpPlaying != null)
    {
        isDpPlaying.getElementsByTagName('img').item(0).src = 'images/speakerOff.gif';
        stopRead();
        isDpPlaying = null;
    }
    
    return currentItem;
}

function playDpItem(item)
{
	var fileName;
	if (item == null)
	{
		item = savedDpItem;
		fileName = savedDpFileName;
		isDpPlaying = null;
	}
	else
		fileName = createFileName(item);

	// Get the flash object
	var flash = document.getElementById('inlineDpPlayer');

	// Change the old icon if necessary
	if (isDpPlaying != null)
	{
		if (stopPlayer() == item)
			return;

		savedDpItem = item;
		savedDpFileName = fileName;
		playDpItem();
		return;
	}

	isDpPlaying = item;
	positionDpFlash();

	// In order IE to work, the flash player MUST be visible in the DOM before calling "playRead", so must set visible and thread the playRead execution
	playRead(fileName);

	// Scroll the item being played onto the screen
	if ((isDpPlaying.offsetTop + flash.offsetHeight) > (flash.parentNode.scrollTop + flash.parentNode.offsetHeight))
		flash.parentNode.scrollTop = isDpPlaying.offsetTop - flash.parentNode.offsetHeight + flash.offsetHeight + 2;

	if (isDpPlaying.offsetHeight < flash.parentNode.scrollTop)
		flash.parentNode.scrollTop = isDpPlaying.offsetTop - 2;

	// Set the new icon
	isDpPlaying.getElementsByTagName('img').item(0).src = 'images/speakerOn.gif';

	// Create an event for the player
	zamEvent = new ReadPlayerEvent(document.getElementById('clientId').value, ZamtisticsEvent.PLAYED + ZamtisticsEvent.READ);
	zamEvent.CreateEvent(activeName(), item.parentNode.getElementsByTagName('nobr')[0].innerHTML, document.getElementById('portal').value);
	if (!logOnlyOwner)
		zamEvent.AddOwner(document.getElementById('clientId').value);

	if (document.getElementById('ownerId').value != '' && document.getElementById('ownerId').value != null)
		zamEvent.AddOwner(document.getElementById('ownerId').value);
	  
	zamEvent.SetLegacyOwner(document.getElementById('key').value);
	zamEvent.Send();

	// Start downloading the next read
	downloadNextRead(item);
}

function positionDpFlash()
{
    if (isDpPlaying != null)
    {
        var flash = document.getElementById('inlineDpPlayer');

        flash.style.top = (isDpPlaying.offsetTop + (document.all ? 0 : -1)) + 'px';
        flash.style.left = (isDpPlaying.offsetLeft + isDpPlaying.clientWidth) + 'px';
    }
}

function setLoop(item)
{
    isLooping = !isLooping;
    createCookie('VPPLAYER_Looping', (isLooping ? '1' : '0'), 365);
    showLoop(1, false);
}

function setInitialLoopStatus()
{
    // Find the cookie if it exists
    var checkLoopStatus = readCookie('VPPLAYER_Looping');
    
    // Make sure the volume is between 0 and 100
    if (checkLoopStatus == null)
        checkLoopStatus = false;
    else
        checkLoopStatus = (checkLoopStatus == '1' ? true : false);

    isLooping = checkLoopStatus;
    if (document.getElementById('cId') != '')
        isLooping = true;

    // Follow the directions of the user
    if (document.getElementById('autoStart').value == '0')
        isLooping = false;

    showLoop(null, true);
}

function startPlayer()
{
    isLooping = true;
    showLoop(null, true);
    playFirstItem();
}

function showLoop(typeItem, startNow)
{
    if (isLooping)
    {
        document.getElementById('dpLoop').getElementsByTagName('img').item(0).src = 'images/loopOn.png';

        // Start playing the first item
        if (startNow && document.getElementById('demoPlayerItem1') != null)
            playDpItem(document.getElementById('demoPlayerItem1'));
    }
    else
        document.getElementById('dpLoop').getElementsByTagName('img').item(0).src = 'images/loopOff.png';
}

function createFileName(item)
{
    var theReturn = item.parentNode.getAttribute('url');
    if (theReturn.indexOf('?') != -1)
        return theReturn + '&o=' + document.getElementById('ownerId').value.toUpperCase();
    else
        return theReturn + '?o=' + document.getElementById('ownerId').value.toUpperCase();
}

function trackDownload(item)
{
	var fileName;
	fileName = createFileName(item);

	//enforce usage of file handler
	fileName = fileName.replace('.mp3', '.mp3d');

	if (navigator.userAgent.toLowerCase().indexOf('safari') != -1)
		document.getElementById('DownloadFrame').src = 'about:blank';

	document.getElementById('DownloadFrame').src = fileName;

	// Create an event for the read download
	zamEvent = new ReadPlayerEvent(document.getElementById('clientId').value, ZamtisticsEvent.DOWNLOADED + ZamtisticsEvent.READ);
	zamEvent.CreateEvent(activeName(), item.parentNode.getElementsByTagName('nobr')[0].innerHTML, document.getElementById('portal').value);

	if (!logOnlyOwner)
		zamEvent.AddOwner(document.getElementById('clientId').value);

	if (document.getElementById('ownerId').value != '' && document.getElementById('ownerId').value != null)
		zamEvent.AddOwner(document.getElementById('ownerId').value);

	zamEvent.SetLegacyOwner(document.getElementById('key').value);
	zamEvent.Send();
}

function trackDownloadAll()
{
	if (document.getElementById('ownerId').value == '')
		fileName = 'Legacy/DownloadDemo.aspx?k=' + escape(document.getElementById('key').value) +
			'&m=' + activeTab().substring(1);
	else
		fileName = '../PlayDemo.aspx?c=' + escape(document.getElementById('clientId').value) +
			'&m=' + activeTab().substring(1) + '&o=' + escape(document.getElementById('ownerId').value);

	if (navigator.userAgent.toLowerCase().indexOf('safari') != -1)
		document.getElementById('DownloadFrame').src = 'about:blank';

	document.getElementById('DownloadFrame').onreadystatechange=fnStartInit;
	document.getElementById('DownloadFrame').onload=fnCheck;
	document.getElementById('DownloadFrame').src = fileName;

	// Create an event for the demo download
	zamEvent = new ReadPlayerEvent(document.getElementById('clientId').value, ZamtisticsEvent.DOWNLOADED + ZamtisticsEvent.DEMO);
	zamEvent.CreateEvent(activeName(), '', document.getElementById('portal').value);
	if (!logOnlyOwner)
		zamEvent.AddOwner(document.getElementById('clientId').value);

	if (document.getElementById('ownerId').value != '' && document.getElementById('ownerId').value != null)
		zamEvent.AddOwner(document.getElementById('ownerId').value);

	zamEvent.SetLegacyOwner(document.getElementById('key').value);
	zamEvent.Send();
}

function fnCheck()
{
    alert('Your download failed.  Please refresh the page and try again.');
}

function fnStartInit()
{
    if (document.getElementById('DownloadFrame').readyState == "complete")
    {
        alert('Your download failed.  Please refresh the page and try again.');
    }
}

function openBrWindow(theURL,Name,popW,popH,scroll) { // V 1.0

    stopPlayer();
    
    var winLeft = 0;
    var winUp = 0;
	
    if(screen){
        if (navigator.appName == "Netscape"){
	        if(popW > (window.screenX/2)){
		        winleft = (window.screenX)+(popW/8);
	        }else{
		        winleft = (window.screenX)+(popW/2);
	        }
	        var winUp = (window.screenY-(popH/2));
        }else{
	        if(popW > (window.screenLeft/2)){
		        winleft = (window.screenLeft) + (popW/8);
	        }else{
		        winleft = (window.screenLeft) + (popW/2);
	        }
	        var winUp = (window.screenTop - (popH/2));
        }
    }
	
    // begin new popup code
	
    winProp = 'width='+popW+',height='+popH+',left='+winleft+',top='+winUp+',scrollbars='+scroll+',resizable=0,status=0'
    Win = window.open(theURL, Name, winProp)
	
    if (parseInt(navigator.appVersion) >= 4){
        Win.window.focus();
    }
}

function wStatus(item)
{
    window.status = item.getAttribute('title');
    return true;
}

function clearStatus() { window.status = ''; }

function showDemoList()
{
   sendMessage('HIDEOPTION');
   
   // Stop the player
   stopPlayer();
   
   var newTable = '<table>';
   var count = 0;
   for(; count < tabs.length; count++)
   {
      var tabItems = tabs[count].split('|');
      newTable += '<tr><td><a href="javascript:selectDemo(\'' + tabItems[2] + '\');">' + tabItems[0] + '</a></td></tr>';
   }
   newTable += '</table>';
   document.getElementById('DemoTabList').innerHTML = newTable;
   
   document.getElementById('DemoListPopup').style.display = 'block';
}

function hideDemoList()
{
   sendMessage('SHOWOPTION');
   document.getElementById('DemoListPopup').style.display = 'none';
}

function sendMessage(message)
{
   if (window.location.hash.length == 0) return;
   window.top.location = window.location.hash.substring(1) + '#' + message;
}

function selectDemo(tId)
{
   hideDemoList();
   window.setTimeout('selectTab("' + tId + '");', 0);
}
