// Copyright 2006-2008 ClickTale Ltd.
var h = DomBuilder.apply();

// custom events
var PlaybackEndedEvent = new YAHOO.util.CustomEvent("PlaybackEndedEvent", this);
var ReadyToPlayEvent = new YAHOO.util.CustomEvent("ReadyToPlayEvent", this);

// fit layout to screen size
var URLCutWidth=[6,10];
if(screen.width>=1152)
	URLCutWidth=[8,14];
if(screen.width>=1280)
	URLCutWidth=[10,18];


/**
 * URL formatting function taken from ctn in Users.js
 * TODO: refactor and remove
 */

// define logic for parsing referrer
var ReferrerUrlParser={
	re: [
		[/^https?\:\/\/(?:www\.)?(google\.[a-zA-Z]{2,7}(?:\.[a-zA-Z]{2,7})?)\/search.*[\?\&]q=([^&]+).*/,[1],2],
		[/^https?\:\/\/(?:images\.)?(google\.[a-zA-Z]{2,7}(?:\.[a-zA-Z]{2,7})?\/images).*[\?\&]q=([^&]+).*/,[1],2],
		[/^https?\:\/\/(?:www\.)?search.((?:msn|live)\.[a-zA-Z]{2,7}(?:\.[a-zA-Z]{2,7})?)\/[a-zA-Z]+\.aspx.*[\?\&]q=([^&]+).*/,[1],2],
		[/^https?\:\/\/(?:www\.)?search.((?:msn|live)\.[a-zA-Z]{2,7}(?:\.[a-zA-Z]{2,7})?\/images)\/[a-zA-Z]+\.aspx.*[\?\&]q=([^&]+).*/,[1],2],
		[/^https?\:\/\/([a-zA-Z]{2,7}\.)?search.(yahoo\.[a-zA-Z]{2,7}(?:\.[a-zA-Z]{2,7})?)\/search.*[\?\&]p=([^&]+).*/,[1,2],3],
		[/^https?\:\/\/([a-zA-Z]{2,7}\.)?search.(yahoo\.[a-zA-Z]{2,7}(?:\.[a-zA-Z]{2,7})?)\/images.*[\?\&]p=([^&]+).*/,[1,2],3]
		],

	parse: function(url)
	{
		// check for empty
		if(!url) return;
		// search
		for(var i in this.re)
		{
			var e=this.re[i];
			//alert(e + typeof e);
			if(typeof e!="object" || !e.length) continue;
			var m=e[0].exec(url);
			if(m)
			{
				var se="", q=m[e[2]];
				//alert(e[1]);
				for(var r in e[1])
				{
					if(typeof e[1][r]=="number" && m[e[1][r]])
						se+=m[e[1][r]];
				}
				q=q.replace(/\+/g, " ");
				try {q=decodeURIComponent(q);} catch(e){} // handles utf8, ignores the rest
				var s=se+": "+q;
				//var s=se+": "+unescape(q.replace(/\+/g, " "));
				
				return {title: s, url: url, text: FormatURL(s,URLCutWidth[0]+URLCutWidth[1],0)};
			}
		}
		// default
		//alert(url);
		return {title: url, url: url, text: FormatURL(url,URLCutWidth[0],URLCutWidth[1])};
	}
};


/**
 * END
 */











// globals
var PHlength;

// Load global data fields into player UI
function PHFieldsLoaded(a)
{
	var b=$('PHbrowserImg');
	b.title=a.userAgent;
	b.src="img/browsers/"+a.navigator+".png";
	PHSetText('PHtime', GetShortDate(parseInt(a.rtime)) );
	//$('PHtime').title=GetShortDate(parseInt(a.itime));
	
	var e=$('PHlocation');
	e.href=a.location;
	e.title=a.location;
	e.firstChild.nodeValue=FormatURL(a.location,URLCutWidth[0],URLCutWidth[1]);
	
	PHSetText('PHbrowser',a.navigator);
	
	var ref=a.referrer;
	if(ref)
	{
		var e=$('PHreferrer');
		/*
		var refOb = ReferrerUrlParser.parse(ref);
		e.href=refOb.url;
		e.title=refOb.title;
		e.firstChild.nodeValue=FormatURL(refOb.text,URLCutWidth[0],URLCutWidth[1]);
		*/
		e.href=ref;
		e.title=ref;
		e.firstChild.nodeValue=FormatURL(ref,URLCutWidth[0],URLCutWidth[1]);
	}
	else
		PHSetText('PHreferrer',"-");
		
	PHSetText('PHplatform',a.platform);
	PHSetText('PHscrw',a.scrw);
	PHSetText('PHscrh',a.scrh);
	PHSetText('PHscrdepth',a.scrDepth);
	
	PHSetText('PHip',a.ip);
	//PHSetText('PHerrors',a.errorCount);
	PHSetText('PHcountry',a.countryCode);
	$('PHcountry').title=a.country;
	$('PHcountryImg').src="img/flags/"+a.countryCode+".gif";
	$('PHcountryImg').title=a.country;
	
	var tz=parseInt( a.timeZone );
	if(tz<=-10) tz=tz.toString();
	else if(tz>=10) tz='+'+tz.toString();
	else if(tz<0) tz='-0'+(-tz).toString();
	else tz='+0'+tz.toString();
	var tzm=Math.abs(60*( parseFloat( a.timeZone )-parseInt( a.timeZone ) ));
	PHSetText('PHtz', tz+":"+(tzm<10?"0"+tzm:tzm) );
	
	PHSetText('PHlang',LanguageNames[a.languageCode]?LanguageNames[a.languageCode]:a.languageCode);
	
	PHSetText('PHactiveTime',GetTimeLen(a.activeTime?a.activeTime:a.length));
	PHSetText('PHlength',GetTimeLen(a.length));
	//PHSetText('PHtime2',GetTimeLen(a.length));
	PHlength=a.length; // save into global variable

	PHSetText('PHload_time',a.loadTime?GetTimeLen(a.loadTime):"N/A");
	
	if(a.tags)
	{
		var s=a.tags.join(", ");
		PHSetText('PHtags',s==""?"-":s);	
	}

	// tooltips changed, we need to notify our nice tooltips module
	if(typeof TooltipsReconnect=="function") TooltipsReconnect();
}

// cross platform set text
function PHSetText(id,t)
{
	$(id).firstChild.nodeValue=t; // do we need to use elm.innerText for ei?
}

function PHAddText(id,t)
{
	$(id).firstChild.nodeValue+=t; // do we need to use elm.innerText for ei?
}

// once a frame has been loaded
function PHFrameLoaded(a)
{
	//alert('b');
	// remove loader animation
	var loader=$("PHloaderImg");
	if(loader)
		loader.style.display="none";
	ReadyToPlayEvent.fire();
}

// once loading starts
function PHInitLoading()
{
	// remove loader animation
	var loader=$("PHloaderImg");
	if(loader)
		loader.style.display="inline";
}


function PHUpdatePlaybackStatuses(a)
{
	if(a.totalActions==a.curAction)
	{
		if(myLogReader) YAHOO.log("PHUpdatePlaybackStatuses: "+JSON.stringify(a));
		PHSetText('PHtimeToNext',"Playback ended");
		PlaybackEndedEvent.fire();
	}
	else
		PHSetText('PHtimeToNext',GetTimeToNextLen( Math.max(a.timeToNext,0) )+(a.skipping?" Skipping":"") );

	//PHSetText('PHcurAction',a.curAction);
	PHSetText('PHcurTime',GetTimeLen(Math.max(a.curTime,0) ));
	
	// update bar
	if(PHlength>0)
	{
		var r=a.curTime/PHlength;
		//alert(a.curTime);
		//alert(PHlength);
		r=Math.max(r,0);
		r=Math.min(r,1);
		$("PHtimeBar").style.width=100*r+"%";
	}
}

function PHUpdateStatus(text)
{
}

function PHGetMiscContainer()
{
	return $("PHmiscActions");
}

var PHAutoZoomData;
function PHInstallFrame(f,s, gcursor)
{
	$('PageDisplayFrame').appendChild(f);
	PHAutoZoomData={frame:f,RemScrSize:s}; // cache data for auto zoom
	//WRAddEvent(window,"resize",PHConfigureZoom);// setup resize handler for automatic mode
	YUIEvent.addListener(window, "resize", PHConfigureZoom); 
	PHConfigureZoom(); // initial zoom
	// display legend once frame has size
	$(gcursor?'legend2':'legend').style.display='block';
}

// read speed setting
function PHGetSpeed()
{
	return $("PHSpeed").value;
}

// read zoom setting
function PHGetZoom()
{
	return $("PHZoom").value;
}

// ui to buttons
function PHPlayButDisable(b)
{
	ButtonDisable("PHPlayBut",b);
}

function PHNextActionButDisable(b)
{
	ButtonDisable("PHNextActionBut",b);
}

function PHPauseButDisable(b)
{
	ButtonDisable("PHPauseBut",b);
}

function PHStopButDisable(b)
{
	ButtonDisable("PHStopBut",b);
}

function PHGetAutoSkip()
{
	return $("PHAutoSkip").value;
}

// utilities for button management
function IsButtonEnabled(b)
{
	b=$(b);
	if(b.tagName.toLowerCase()=='a')
	{
		return !YUIDom.hasClass(b,'off');
	}
	return false; // default for 'button' or 'input'
}

function ButtonDisable(b,dis)
{
	b=$(b);
	if(b.tagName.toLowerCase()=='a')
	{
		if(dis)
			YUIDom.addClass(b,"off");
		else
			YUIDom.removeClass(b,"off");
	}
	else if(b.tagName.toLowerCase()=='button' || b.tagName.toLowerCase()=='input')
		b.disabled=dis;
}

// zoom
var WPNonClientHeight=130; // assumed non client area of remote browser window (the toolbars and menus) (smaller is safer)

// uses WPRemScrSize and Zoom drop-down to scale the frame
// this property works in ie only
function PHConfigureZoom()
{
	if(!PHAutoZoomData) return; // not initialized yet
	
	var z=PHGetZoom();
	if(z=="") // auto
	{
		var b=document.documentElement, xy=YUIDom.getXY(PHAutoZoomData.frame),z;

		z=(YUIDom.getViewportWidth()-xy[0])/PHAutoZoomData.RemScrSize.w; 

		z=Math.min(z, (YUIDom.getViewportHeight()-xy[1])/(PHAutoZoomData.RemScrSize.h-WPNonClientHeight) );
		z=Math.min(z,1);// don't zoom in
		z=Math.max(z,0.1); // don't over zoom out
	}
	PHAutoZoomData.frame.style.zoom=z; // in IE only
}

// new input/keys container
PHInputPanel={
	reset: function()
	{
		var p=$("PHinputPanel");
		while ( p.childNodes.length >= 1 )
			p.removeChild( p.firstChild );       
	},
	renderCharCode: function(cc)
	{
		if(cc=="s")
			return "-";
		else if(cc=="c")
			return "?";
		else if(cc=="p")
			return "*";
		else if(!isNaN(parseInt(cc)) && cc>27) // if there is value and it is more than 27 (ESC and Enter codes)
			return String.fromCharCode(cc);
		return false;
	},
	addCharCode: function(cc)
	{
		cc=this.renderCharCode(cc);
		if(cc)
			this.addText(cc);
	},
	addKeyCode: function(kc,k)
	{
		if(!isNaN(parseInt(kc)) && keyCodeNames && keyCodeNames[kc]) // ignore kc which are not numeric such as censored data
		{
			if(keyCodeNames[kc]===true)
			{
				if(k)
					this.addPlaybackIcon("prefix"+k);
				this.addPlaybackIcon("key"+kc);
			}
			else
			{
				var s="[";
				if(k && eventKeys && eventKeys[k])
					s+=eventKeys[k];
				s+=keyCodeNames[kc]+"]";
				this.addText(s);
			}			
		}
	},
	addMouseChange: function(mb, mk)
	{
		if(mk)
			this.addPlaybackIcon("prefix"+mk);
		this.addPlaybackIcon("mouse"+mb);
		/*
		if(eventMouse && eventMouse[mb])
		{
			var s="(";
			if(mk && eventKeys && eventKeys[mk])
				s+=eventKeys[mk];
			s+=eventMouse[mb]+" "+(up?"up":"down")+")";
			this.addText(s);
		}
		*/
	},
	// private helpers
	addPlaybackIcon: function(name)
	{
		// <img class="playback_icon pbicon-key8" src="s.gif" />
		$("PHinputPanel").appendChild(h.IMG({"class": "playback_icon pbicon-"+name, src: "img/blank.gif" }));
	},
	addText: function(text)
	{
		var p=$("PHinputPanel");
		if(p.lastChild && p.lastChild.nodeType==3/*text*/)
			p.lastChild.nodeValue+=text;
		else
			p.appendChild( document.createTextNode(text));
	}
};
