// Dependencies: YUI dom-event, YUI dialog

var NS4=(document.layers);
var IE=(document.all);
var W3=(document.getElementById && !IE);
var refreshPage='';

// used to send the listen log data from the tuner to the server
var globalVar;
var FixPng;
var FixPngNode;

var waitDialog;

//  ... to be called from link buttons
function PostTheForm(formName, eventTarget, eventArgument)
{
    var theForm;
    if( formName != undefined && formName != null )
    {
		theForm = document.getElementById( formName );
    }
    else
    {
		theForm = document.forms[0];
    }
    
    if( ( theForm != undefined )  && ( theForm != null ) 
		&& ( theForm.__EVENTTARGET != undefined ) && ( theForm.__EVENTARGUMENT != null )
		&& ( eventTarget!=null ) )
    {
	    theForm.__EVENTTARGET.value = eventTarget.split("$").join(":");
	    theForm.__EVENTARGUMENT.value = eventArgument;
	}
	
	if( theForm != undefined || theForm != null )
	{
		theForm.submit();
	}
}

function IsEnterKeyPressed(event)
{
	var code = 0;
	if (NS4)
		code = event.which;
	else
		code = event.keyCode;
	return code == 13;
}

function ChangeEndTime(startHourIn, startMinIn, durationHourIn, durationMinIn, endTimeIn)
{
	//	... depending on what values are selected in start time and duration
	//	... we will have to change the end time
	
	var startHour = document.getElementById(startHourIn);
	var startMin = document.getElementById(startMinIn);
	var durationHour = document.getElementById(durationHourIn);
	var durationMin = document.getElementById(durationMinIn);
	var endTime = document.getElementById(endTimeIn);

	var newDate = new Date();
	newDate.setHours(startHour.options[startHour.selectedIndex].value);
	newDate.setMinutes(startMin.options[startMin.selectedIndex].value);
	
	startTimeOnForm = newDate;
	
	var hrDuration = durationHour.options[durationHour.selectedIndex].value;
	var minDuration = durationMin.options[durationMin.selectedIndex].value;
	
	var newTime = newDate.getTime() + (hrDuration*60*60*1000) + (minDuration*60*1000);
	
	var finalDate = new Date(newTime);
	var ampmString =  (finalDate.getHours() >= 12) ? "PM" : "AM"
	var hours = (finalDate.getHours()%12 == 0) ? 12 : finalDate.getHours()%12;
	var minutes = finalDate.getMinutes() < 10 ? "0" + finalDate.getMinutes() : finalDate.getMinutes();
	
	var finalDateString = hours + ":" + minutes + " " + ampmString;
	
	endTime.innerHTML = finalDateString;
}
	
function HideDiv(divToHide)
{
    var divToHideJs = GetElementId(divToHide);
    if(divToHideJs==null) return;
    
    divToHideJs.style.display = "none";
}

function ShowDiv(divToShow)
{
    var divToShowJs = GetElementId(divToShow);
    if(divToShowJs==null) return;
    
    //  ... make the div visible
    divToShowJs.style.display = "inline";
}

function toggleDiv() {
	for(i=0;i < toggleDiv.arguments.length;i++){
		o_toggleDiv = document.getElementById(toggleDiv.arguments[i])
		s_toggleDiv = (o_toggleDiv.style.display!="") ? o_toggleDiv.style.display : "none";
		o_toggleDiv.style.display = (s_toggleDiv=="none") ? (o_toggleDiv.nodeName=="SPAN") ? "inline" : "block" : "none";
	}
}

function ShowDivBlock(divToShow)
{
    var divToShowJs = GetElementId(divToShow);
    if(divToShowJs==null) return;
    
    //  ... make the div visible
    divToShowJs.style.display = "block";
}

/* Routine to refresh the contents in the browser */
function RefreshMe()
{
    self.location = self.location;
}

function RefreshMyParent()
{
	if( window.opener != undefined && window.opener != null )
	{
		window.opener.location = window.opener.location;
	}
}

function RefreshMyParentWithThisURL( url )
{
	if( window.opener != undefined && window.opener != null )
	{
		window.opener.location = url;
		window.opener.focus();
	}
	else
	{
		window.open( url, '_new' );
	}
}

function RefreshWindowWithURL()
{
    if(refreshPage.href!=undefined&&refreshPage.href!=null)
    {
        if(refreshPage.href.charAt(refreshPage.href.length-1) == '#')
            refreshPage.href = refreshPage.href.substring(0, refreshPage.href.length-1);
        window.location.href = refreshPage;
    }
    else
    {
         if(refreshPage.charAt(refreshPage.length-1) == '#')
            refreshPage = refreshPage.substring(0, refreshPage.length-1);
        window.location.href = refreshPage;
    }
}

function RefreshWindowWithThisURL(urlToRefresh)
{
    window.location.href = urlToRefresh;
}

/* get the actual browser size thanks to archrajan on www.experts-exchange.com */
function GetClientBrowserHeight() 
{
    var myHeight = 0;
    if( W3 )
        //Non-IE
        myHeight = window.innerHeight;
    else if( IE )
    {
        
	    if( document.documentElement &&
        ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
		    //IE 6+ in 'standards compliant mode'
		    myHeight = document.documentElement.clientHeight;
	    else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
		    //IE 4 compatible
		    myHeight = document.body.clientHeight;	    
    }
    return myHeight;
}

function GetClientBrowserWidth() 
{
    var myWidth = 0;
    if( W3 )
        //Non-IE
        myWidth = window.innerWidth;
    else if( IE )
    {
	    if( document.documentElement &&
        ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) 
		    //IE 6+ in 'standards compliant mode'
		    myWidth = document.documentElement.clientWidth;
	    else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
		    //IE 4 compatible
		    myWidth = document.body.clientWidth;
    }
      
    return myWidth;
}
/* end of the method to determine the width and height of the browser document */

//  ... general purpose methods that should be in common.js for all other client routines to use them
function focus( element )
{
	var el = YAHOO.util.Dom.get(element);
	
	el.select();
	el.focus();
}

function $(name) {
	return document.getElementById(name);
}

function GetElementId(elementName)
{
    return document.getElementById(elementName);
}

function AssignTextToElement(elementName, stringToDisplay)
{
    var elementJs = GetElementId(elementName);
    if(elementJs!=null) elementJs.innerHTML=stringToDisplay;
}

//  ... used to toggle states of radiobuttons and checkboxes
function UnCheckObject(boxName)
{
    SwitchBoxToState(boxName, false);
}

function CheckObject(boxName)
{
    SwitchBoxToState(boxName, true);
}

function SwitchBoxToState(boxName, state)
{
    var jsBox = GetElementId(boxName);
    if(jsBox==undefined || jsBox==null)
        return;
    
    jsBox.checked = state;
}
//  ... end of utility method to toggle states of radiobuttons and checkboxes

//  ... end of the general purpose routines

/* common functions to find the position of the event on the screen and move div to that position 
reference at http://javascript.about.com/library/blmousepos.htm */

function mouseX(evt) {
    if (evt.pageX) 
        return evt.pageX;
    else if (evt.clientX)
        return evt.clientX + (document.documentElement.scrollLeft ?document.documentElement.scrollLeft :document.body.scrollLeft);
    else return null;
}

function mouseY(evt) {
    if (evt.pageY) 
        return evt.pageY;
    else if (evt.clientY)
        return evt.clientY + (document.documentElement.scrollTop ?document.documentElement.scrollTop :document.body.scrollTop);
    else return null;
}

function MoveDivToPosition(divToMove, posX, posY){
    if(NS4)divToMove.moveTo(x,y);
    else{
        divToMove.style.left=posX+'px';
        divToMove.style.top=posY+'px';
    }
}

function LaunchBrowser(urlToLaunch)
{
	if(INTEGRATED_CLIENT)
	{
		var Ver = CLIENT_VERSION.split(".", 3);
		if(Ver[0]>2 || (Ver[0]==2 && Ver[1]>939) )
		{
			var url="radio:launch=";
			DispatchMessage(url + urlToLaunch);
			return false;
		}
	}
	return true;
}

//  ... fills a span with a message
function FillSpanWithMsg(spanElement, message)
{
    var spanElementJs = GetElementId(spanElement);
    if(spanElementJs!=null)
    {
        //  ... what browser
        if(spanElementJs.innerText!=undefined && spanElementJs.innerText!=null)
            spanElementJs.innerText = message;
        else if(spanElementJs.textContent!=undefined && spanElementJs.textContent!=null)
            spanElementJs.textContent = message;
        else
        {
            var newText = document.createTextNode(message);
            if(spanElementJs.childNodes.length > 0)
                spanElementJs.replaceChild(newText, spanElementJs.childNodes[0]);
            else
                spanElementJs.appendChild(newText);
        }
    }
}
/* end of common functions to find the position of the event on the screen and move div to that position */ 

function OpenFlashEnroll()
{
    var flashWidth = 750;
    var flashHeight = 500;
    
    var initX = 0;
	var initY = 0;
	
	initX = (screen.width-flashWidth)/2;
	initY = (screen.height-flashHeight)/2;
    
    window.open
    (APP_PATH + 'RtTour.htm', 'RtTour', 'toolbar=no, menubar=no, left=' + initX + ', top=' + initY + ', location=no, status=no, scrollbars=no, width=' + flashWidth + ', height=' + flashHeight);
    
}

function OpenFlash()
{
    var flashWidth = 750;
    var flashHeight = 500;
    
    var initX = 0;
	var initY = 0;
	
	initX = (screen.width-flashWidth)/2;
	initY = (screen.height-flashHeight)/2;

    window.open
    (APP_PATH + 'RtTour.htm', 'RtTour', 'toolbar=no, menubar=no, left=' + initX + ', top=' + initY + ', location=no, status=no, scrollbars=no, width=' + flashWidth + ', height=' + flashHeight);    
}

function newWindow() {
    priceWindow = window.open("Pricing.aspx", "priceWin", "width=650,height=350,scrollbars=yes")
}

function newWindowEnroll() {
    priceWindow = window.open(APP_PATH + "Pricing.aspx", "priceWin", "width=750,height=500,scrollbars=yes")
}

//added Feb22, travis
var state = 'none';

function showhide(layer_ref) 
{
    if (state == 'block') 
    {
        state = 'none';
    }
    else 
    {
        state = 'block';
    }
    if (document.all) 
    { //IS IE 4 or 5 (or 6 beta)
        eval( "document.all." + layer_ref + ".style.display = state");
    }
    if (document.layers) 
    { //IS NETSCAPE 4 or below
        document.layers[layer_ref].display = state;
    }
    if (document.getElementById &&!document.all) 
    {
        hza = document.getElementById(layer_ref);
        hza.style.display = state;
    }
}
function showtr(tr_ref) 
{
 var row = document.getElementById(tr_ref);
    row.style.display = '';
}
function hidetr(tr_ref){
var row = document.getElementById(tr_ref);
    row.style.display = 'none';
}
function pp(p)
{
	var hs = "pHndl.axd?pc=" + p;
	YAHOO.util.Connect.asyncRequest('GET', hs, {});
}

function ScheduleRecording( programId, stationId, topicId, scheduleId, scheduleTypeId, duration )
{
	showWait();
	var callback = { success: RecordSubmitCallback };
	var params = "SkipCheck=1";
	if( programId > 0 )
		params = params + "&ProgramId=" + programId;
	if( stationId > 0 )
		params = params + "&StationId=" + stationId;
	if( topicId > 0 )
		params = params + "&TopicId=" + topicId;
	if( scheduleId > 0 )
		params = params + "&ScheduleId=" + scheduleId;	
	if( null != duration && duration > 0 )
		params = params + "&Duration=" + duration;
	YAHOO.util.Connect.asyncRequest('GET', APP_PATH + "RecordPopup.aspx?" + params + "&Schedule=1&ScheduleToSchedule=" + scheduleTypeId + "&z=" + rand(), callback );
}

function OneClickRecordPopup( programId, stationId, topicId, scheduleId, BufferedMins )
{
	showWait();

	var callback = { success: RecordSubmitCallback };

	var params = "SkipCheck=1";
	if( programId > 0 )
		params = params + "&ProgramId=" + programId;
	if( stationId > 0 )
		params = params + "&StationId=" + stationId;
	if( topicId > 0 )
		params = params + "&TopicId=" + topicId;
	if( scheduleId > 0 )
		params = params + "&ScheduleId=" + scheduleId;
	if( BufferedMins != undefined && BufferedMins>0)
	    params = params + "&BufferedMins=" + BufferedMins;
	YAHOO.util.Connect.asyncRequest('GET', APP_PATH + "RecordPopup.aspx?SkipCheck=1&" + params + "&z=" + rand(), callback );
}

function SignupPopup( callback )
{
	var yCallback = { success: LoginSubmitCallback };
	if( callback )
	{
		callback = "callback=" + callback;
	}
		
	YAHOO.util.Connect.asyncRequest('GET', APP_PATH + "minilogin.aspx?SkipCheck=1&" + callback + "&z=" + rand(), yCallback );
}

function RecordSubmitFailure(obj) 
{
}

function dismissRecord() {
	var currentUrl = location.href;

	if (currentUrl && currentUrl.indexOf("RecordPopup") >= 0) {
		// Refresh without the popup parm to avoid dupe
		var refreshUrl = currentUrl.substring( 0, currentUrl.indexOf("?") );
		var qs = readQueryString();
		delete qs["RecordPopup"]

		location.href = refreshUrl + qs.toString();
	}

	if( popupDlg )
		popupDlg.cancel()
}
	
function RecordSubmitCallback(o)
{
	hideWait();
	_RecordSubmitCallback( o );
}

function _RecordSubmitCallback(obj)
{
	_ModalPopupCallback( obj, "550px", _RecordSubmitCallback );
}

// Displays a "please wait" interstitial
function showWait()
{
	if( waitDialog == null ) {
		var dialogDiv = document.getElementById( "interstitial" );

		if( dialogDiv == null ) {
			dialogDiv = document.createElement( "div" );
			dialogDiv.id = "interstitial";
			dialogDiv.innerHTML = "<div class=\"hd\">Please wait</div><div class=\"bd\"><img src=\"" + APP_PATH + "2.0/images/please-wait-tiny.gif\" /></div>";
			document.body.insertBefore( dialogDiv, document.body.firstChild );
		}
		
		waitDialog = new YAHOO.widget.Dialog( "interstitial", 
			{ modal:true, width: "300px", underlay:"none", fixedcenter:true, visible:false, constraintoviewport:true });
			
		waitDialog.render(document.body);
	}
	
	waitDialog.show();
}

function hideWait()
{
	if( waitDialog != null ) {
		waitDialog.hide();
	}
}

function openRadioMill( formId, formDiv, formKey, formWidth, formHeight )
{
	var callback = {
		success : _SimpleModalCallback,
		failure : _SimpleModalError,
		argument: [formId, formDiv, formKey, formWidth, formHeight]
	};
	
	showWait();

	YAHOO.util.Connect.asyncRequest( 'GET', APP_PATH + "RadioMill/FormGenerator.aspx?FormId=" + escape(formId) + "&FormDiv=" + escape(formDiv) + "&FormKey=" + escape(formKey) + "&z=" + rand(), callback );
}

function _SimpleModalError( context ) {
	hideWait();

	var handleOk = function() {
		this.cancel();
	}

	var dialogDiv = document.getElementById( context.argument[1] );
	dialogDiv.innerHTML = "<div class=\"hd\">Error occurred</div><div class=\"bd\">We're sorry, an error has occurred</div>";
	
	var dialog = new YAHOO.widget.Dialog( context.argument[1],
		{ modal:true, width: "300px", underlay:"none", fixedcenter:true, constraintoviewport:true });

	var buttons = [ { text:"Close", handler:handleOk, isDefault:true } ];

	dialog.cfg.queueProperty("buttons", buttons); 

	dialog.render(document.body);
	dialog.show();
}

function ShowThankYouDialog( divId )
{
	var handleOk = function() {
		this.cancel();
	}
	var dialogDiv = document.getElementById( divId );
    dialogDiv.innerHTML = "<div class=\"hd\">Done!</div><div class=\"bd\">Thank you for submitting changes. We'll check it out and post valid changes within a day or so.</div>";
    var dialog = new YAHOO.widget.Dialog( divId,
	    { modal:true, width: "400px", underlay:"none", fixedcenter:true, constraintoviewport:true });
    var buttons = [ { text:"Close", handler:handleOk, isDefault:true } ];
    dialog.cfg.queueProperty("buttons", buttons); 
    dialog.render(document.body);
    dialog.show();
}

function _SimpleModalCallback( context ) {
	var content = context.responseText.split("<!--SCRIPT BREAK-->");
	eval( content[0] );
	hideWait();

	var handleSubmit = function() {
		this.submit();
		ShowThankYouDialog( context.argument[1] );
	}

	var handleCancel = function() {
		this.cancel();
	}

	var dialogDiv = document.getElementById( context.argument[1] );	
	dialogDiv.innerHTML = content[1];
	
	var dialogWidth = "400px";
	if( context.argument.length > 3 && context.argument[3] > 0 ) {
		dialogWidth = context.argument[3] + "px";
	}
	var dialog = new YAHOO.widget.Dialog( context.argument[1], 
		{ modal:true, width:dialogWidth, zIndex:200, fixedcenter:true, constraintoviewport:true} );
	       var buttons = [ { text:"Submit", handler:handleSubmit, isDefault:true }, 
		    { text:"Cancel", handler:handleCancel } ];

	dialog.cfg.queueProperty("buttons", buttons); 

	dialog.render(document.body);
	dialog.show();
}

function _ModalPopupCallback(obj, width, callback, submit)
{
	var content = obj.responseText.split("<!--SCRIPT BREAK-->");
	var renderHtml = true;
	eval( content[0] );
	if( renderHtml )
	{
		var popup = document.getElementById( "popupDiv" );
		if( null == popup )
		{
			popup = document.createElement( "div" );
			atr( popup, "id", "popupDiv" );
		}
		popup.innerHTML = content[1];
		var handleSubmit = function() {
			this.submit();
		}
		var handleCancel = function() {
			this.cancel();
		}
		
		if( null != popupDlg )
			popupDlg.hide();
		
		// Using fixedCenter creates infinite scrolling issues in RedButton, so manually calculate the position
		var dialogWidth = 0;
		if( width.indexOf( "px" ) ) {
			dialogWidth = parseInt( width.substring(0, width.indexOf( "px" ) ) );
		}
		
		var bodyWidth = document.body.offsetWidth;
		var xPos = dialogWidth > 0 && bodyWidth > dialogWidth ? ( bodyWidth - dialogWidth ) / 2 : 50;
		popupDlg = new YAHOO.widget.Dialog(popup, { modal:true, visible:true, underlay:"none", zIndex:2000, width:width, x:xPos, y:50, constraintoviewport:true });
		
		popupDlg.callback.success = callback;
		
		if( submit )
		{
			popupDlg.cfg.queueProperty("buttons", [ { text:submit, handler:handleSubmit } ]);
		}
		
		var listeners = new YAHOO.util.KeyListener(document, { keys : 27 }, {fn:handleCancel,scope:popupDlg,correctScope:true} );
		popupDlg.cfg.queueProperty("keylisteners", listeners);
		popupDlg.render(document.body);
		popupDlg.show();
	}
	if( content.length > 2 )
		eval( content[2] );
}

function OneClickRedirectToRecord( stationNo, scheduleNo, ocRequestFromClient )
{
	var url;
	var queryString;
	
	if( scheduleNo != undefined && scheduleNo != null && scheduleNo > 0 )
	{
		queryString = "sch="+scheduleNo;
	}
	else if( stationNo != undefined && stationNo != null && stationNo > 0 )
	{
		queryString = "st="+stationNo;
	}
	
	url = 'record.aspx?'+queryString;
	
	RefreshMyParentWithThisURL( url );
	
	window.close();
}

function LoginPopup( signupRedir )
{
	var yCallback = { success: LoginSubmitCallback };
	url = APP_PATH + "minilogin.aspx?SkipCheck=1&z=" + rand();
	if( signupRedir )
		url = url + "&signUpRedir=" + signupRedir;
	YAHOO.util.Connect.asyncRequest('GET', url, yCallback );
}

function LoginSubmitFailure(obj) 
{
}

var popupDlg;

function LoginSubmitCallback(o)
{
	_LoginSubmitCallback( o );
}

function _LoginSubmitCallback(obj)
{
	_ModalPopupCallback( obj, "450px", _LoginSubmitCallback );
}

function FeedbackPopup( title, referralURL )
{
	var callback = { success: FeedbackSubmitCallback };
	YAHOO.util.Connect.asyncRequest('GET', APP_PATH + 'Feedback.aspx?title='+title+'&referral='+referralURL + '&z=' + rand(), callback );
}

function PostFeedback( title, referralUrl, comments, email, product )
{
	referralUrl = escape( referralUrl ).replace( /\//g, '%2f' );
	comments = escape ( comments ).replace( /\//g, '%2f' );
	var callback = { success: FeedbackSubmitCallback };
	YAHOO.util.Connect.asyncRequest('GET', APP_PATH + "Feedback.aspx?subm=1&title="+title+"&referral="+referralUrl + "&Comments=" + comments + "&Email=" + email + "&product=" + product + "&z=" + rand(), callback );
}

function FeedbackSubmitCallback(o)
{
	_FeedbackSubmitCallback(o);
}
function _FeedbackSubmitCallback(obj)
{
	_ModalPopupCallback( obj, "450px", _FeedbackSubmitCallback );
}
	
function AddMR( p, s, link, large )
{
	if( !LOGGED_IN )
	{
		var redir = APP_PATH + 'FavoriteAdd.axd?Redir=1&z=' + rand() + '&';
		if( p > 0 )
			redir = redir + "ProgramId=" + p;
		else
			redir = redir + "StationId=" + s;
		LoginPopup( escape( redir ) );
	}
	else
	{
		var url = APP_PATH + "FavoriteAdd.axd?z=" + rand() + "&";
		if( p > 0 )
			url = url + "ProgramId=" + p;
		else
			url = url + "StationId=" + s;
		YAHOO.util.Connect.asyncRequest('GET', url, {});
		document.getElementById( link ).parentNode.className = 'in_myradio';
		document.getElementById( link ).parentNode.innerHTML = '<a href="MyRadio.aspx">In Presets</a>';
	}
	
	return false;
}

function RequestCoverage( button, type, id, username )
{
	var url = APP_PATH + 'RequestCoverage.axd?';
	if( type == 'program' )
	{
		url = url + 'ProgramId=' + id;
	}
	else
	{
		url = url + 'StationId=' + id;
	}
	YAHOO.util.Connect.asyncRequest('GET', url, {});
	
	var thanks = document.createElement( "span" );
	thanks.className = "requestThanks";
	var h2 = document.createElement( "h2" );
	h2.appendChild( document.createTextNode( "Your request has been sent." ) );
	thanks.appendChild( h2 );
	thanks.appendChild( document.createTextNode( "Thank you for helping improve RadioTime. We will review your request and try to find coverage." ) );
	var div = button.parentNode;
	div.innerHTML = "";
	div.appendChild( thanks );
}

function e(element,className)
{
	var e=document.createElement( element );
	e.className = className;
	return e;
}

function atr(element,attribute,value)
{
	element.setAttribute( attribute, value );
}
function ac(node, child)
{
	node.appendChild( child );
}
function tn(text)
{
	return document.createTextNode( text );
}

function secureLink(target)
{
	if(INTEGRATED_CLIENT)
	{
		var Ver = CLIENT_VERSION.split(".", 3);
		if(Ver[0]>2 || (Ver[0]==2 && Ver[1]>939) )
		{
			if( target.indexOf("http") < 0 && !LOGGED_IN )
			{
				target = SECURE_AUTHORITY + target;
			}
			if( LOGGED_IN )
				target = SECURE_AUTHORITY + AUTOLOGIN_URL + "&orglnk=" + escape(target);
			return LaunchBrowser(target);
		}
	}
	window.location.href = target;
	return false;
}

function readQueryString() {

	var queryStringDictionary = {};
	var querystring = decodeURI(location.search);

	if (!querystring) {
		return {};
	}

	querystring = querystring.substring(1);

	var pairs = querystring.split("&");

	for (var i = 0; i < pairs.length; i++) {
		var keyValuePair = pairs[i].split("=");
		queryStringDictionary[keyValuePair[0]]
                = keyValuePair[1];
	}

	queryStringDictionary.toString = function() {

		if (queryStringDictionary.length == 0) {
			return "";
		}

		var toString = "?";

		for (var key in queryStringDictionary) {
			if (key == "toString") continue;
			toString += encodeURIComponent(key) + "=" +
                encodeURIComponent(queryStringDictionary[key]) + "&";
		}

		return toString;
	};

	return queryStringDictionary;
}

// Removes leading whitespaces
function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

// Removes ending whitespaces
function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

// Removes leading and ending whitespaces
function Trim( value ) {
	return LTrim(RTrim(value));
}

var rgOnLoad=new Array();
function AddLoadFn(szfn){window.onload=RunLoadFn;rgOnLoad[rgOnLoad.length]=szfn;}
function RunLoadFn(){for(var i=0;i<rgOnLoad.length;i++)eval(rgOnLoad[i]);} 

//change tab li classes on hover for IE
function tabOvr( a )
{
	a.parentNode.className = "tabOvr";
}
function tabOut(a, name)
{
	a.parentNode.className = "";
	a.innerHTML = name;
}

Function.prototype.closure = function(obj)
{
  // Init object storage.
  if (!window.__objs)
  {
    window.__objs = [];
    window.__funs = [];
  }

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;

  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;

  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function ()
  {
    return __funs[funId].apply(__objs[objId], arguments);
  };
};

function debug( o )
{
	var output = '';
	for( i in o )
	{
		output += i + " = " + o[i] + '\n';
	}
	return output;
}

function GetDateString( d )
{
	var s = (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	return s;
}

function rand()
{
	return Math.floor(Math.random()*1000000);
}

// =================================================================
// Object Timer
// -----------------------------------------------------------------
//
// =================================================================
function Timer()
{
	this.startTime = 0;
	this.stopTime = 0;
	this.timeDiff = 0;
}
Timer.prototype.Start = function()
{
	this.startTime = new Date().valueOf();
}
Timer.prototype.Stop = function()
{
	this.stopTime = new Date().valueOf();
	this.timeDiff += this.stopTime - this.startTime;
	return this.timeDiff / 1000;
}
Timer.prototype.GetTimeDiff = function()
{
	return this.timeDiff / 1000;
}
Timer.prototype.Reset = function()
{
	this.startTime = 0;
	this.stopTime = 0;
	this.timeDiff = 0;
}
