/*
 * Embedder object - created on request by the resultsCSO object for each embedded audio/video object required.
 * Stores required streamer info for passing around between callbacks
 */
function Embedder( fileHandle, vcodec, acodec, vsize, maxFileSize, hinted, stream, prettyName, mediaUrl, id ) {
	this.fileHandle = fileHandle;
	this.vcodec = vcodec;
	this.acodec = acodec;
	this.vsize = vsize;
	this.maxFileSize = maxFileSize;
	this.hinted = hinted;
	this.stream = stream;
	this.prettyName = prettyName;
	this.mediaUrl = mediaUrl;
	this.id = id;
	this.status = -1;
	this.iteration = 0;
	this.iterationLimit = 5;
	
	this.getFileHandle = function() { return fileHandle; }
	this.getVCodec = function() { return vcodec; }
	this.getACodec = function() { return acodec; }
	this.getVsize = function() { return vsize; }
	this.getMaxFileSize = function() { return maxFileSize; }
	this.getHinted = function() { return hinted; }
	this.getStream = function() { return stream; }
	this.getPrettyName = function() { return prettyName; }
	this.getMediaUrl = function() { return mediaUrl; }
	this.getId = function() { return id; }
	this.getIteration = function() { return this.iteration; }
	this.setIteration = function( iteration ) { this.iteration = iteration; }
	this.getIterationLimit = function() { return this.iterationLimit; }
}


/*
 * The Ajax callback function handler - processes the result from the ajax server (webui /a/ajax)
 */
function Callback() {
	this.object = null;
	this.status = -1;
}
Callback.prototype.process = function() {

	//alert( "object = " + this.object.getFileHandle() );
	var payload = eval("(" + this.status + ")" );
	
	if ( payload && payload.res ) {
		
		var id = this.object.getId();
		
		if ( payload.res == "READY" ) {

			var inner = QT_WriteOBJECT( payload.embed, 16,16, '', 'autoplay', 'false', 'type', 'video/x-m4v');
			//alert( "id = " + id + "\nInner = " + inner );
			$( id ).innerHTML = inner;
		}
		else if ( payload.res == "NOT_AVAILABLE" ) {
			
			//alert( payload.res );
			$( id ).innerHTML = "";
		}
		else {

			if ( this.object.getIteration() < this.object.getIterationLimit() ) {
				
				// if the streamer is not yet ready, try a few more times
				this.object.setIteration( this.object.getIteration() + 1 );
				var myobj = this.object;
				var func = function() { pollStatusCallback( myobj ) };
				var ti = setTimeout( func, 1000 );
			}
		}
	}
}
Callback.prototype.setObject = function( object ) {
	this.object = object;
}
Callback.prototype.setStatus = function( status ) {
	this.status = status;
}


/*
 * Kick off an Ajax request for a particular Embedder object
 */
function pollStatusCallback( object ) {
	
	/* The streamer provides a status method, but it accesses the relevant object
	 * via the set of params which were used to originally construct it, so we have
	 * to pass all this guff around on every poll.
	*/ 

	if ( object ) {
		
		var url = "/a/ajax?ajax=pollstreamer&fileHandle=" + encodeURIComponent( object.getFileHandle() );
		url += "&vcodec=" + encodeURIComponent( object.getVCodec() );
		url += "&acodec=" + encodeURIComponent( object.getACodec() );
		url += "&vsize=" + encodeURIComponent( object.getVsize() );
		url += "&maxFileSize=" + encodeURIComponent( object.getMaxFileSize() );
		url += "&hinted=" + encodeURIComponent( object.getHinted() );
		url += "&stream=" + encodeURIComponent( object.getStream() );
		url += "&prettyName=" + encodeURIComponent( object.getPrettyName() );
		url += "&vhandle=" + encodeURIComponent( object.getMediaUrl() );
		url += "&id=" + encodeURIComponent( object.getId() );
		func = new Callback();
		func.setObject( object );
		doThreadedAjax( url, func );
	}
}



/*
 * Process the stack of embedded object requests
 */
function processEmbedders() {
	// var emb = new Embedder( "${cso.fileHandle}", "mpeg4", "libfaac", "qcif", "${maxSize}", "[#if hinted]1[#else]0[/#if]", 0, "${prettyName}", "${vhandle}", "${cso.id}" ); addEmbedder( emb );
	// <div id="ipembed-${cso.id}" fh="${cso.fileHandle}" vc="mpeg4" ac="libfaac" sz="${maxSize}" hinted=[#if hinted]"1"[#else]"0"[/#if] stream="0" pretty="${prettyName}" vhandle="${vhandle}" csoid="${cso.id}" ></div>

	var root = $( "resultsContainer" );
	var divs = root.getElementsByTagName( "div" ); // construct a list of divs
	//alert( "found " + divs.length + " divs" );
	for ( var i = 0; i < divs.length; i++ ) {
		
		var name = divs[i].id;
		
		if ( name.substring(0,7) == "ipembed" ) {
			
			if ( divs[i].innerHTML == "" ) {
				
				var fh = divs[i].getAttribute( "fh" );
				var vc = divs[i].getAttribute( "vc" );
				var ac = divs[i].getAttribute( "ac" );
				var vsz = divs[i].getAttribute( "vsz" );
				var maxsz = divs[i].getAttribute( "maxsz" );
				var hinted = divs[i].getAttribute( "hinted" );
				var stream = divs[i].getAttribute( "stream" );
				var pretty = divs[i].getAttribute( "pretty" );
				var vhandle = divs[i].getAttribute( "vhandle" );
				var id = name;
				var emb = new Embedder( fh, vc, ac, vsz, maxsz, hinted, stream, pretty, vhandle, id );
				pollStatusCallback( emb );
			}
		}
	}
}


/*
 * initiate an ajax request
 */
function doThreadedAjax( url, func ) {

   // OK, not strictly threaded, but ensure that multiple requests can run simultaneously
   // (the standard doAjax method is global in scope so only supports a single AJAX session at one time)
	
   var myAjax = zXmlHttp.createRequest();
   myAjax.open( "GET", url, "true" );
   myAjax.onreadystatechange = function() {

        try {
            if ( myAjax.readyState == 4 ) {
              var hstat = myAjax.status;
              if ( hstat == 200 ) {
            	  func.setStatus( myAjax.responseText );
                  func.process();
              }
              else {
                  // do nothing on error
              }
            }
          }
          catch( e) {
          }
    };

    try {
    	myAjax.send( null );
    }
    catch( e) {
    }
}






function openStack( stackId, height, max, step ) {
	$("stack" + stackId).style.height = height + "px"; 
	height += step;
	if ( height < max ) {
		var ti = setTimeout( "openStack(" + stackId + "," + height + "," + max + "," + step + ")", 2 );
	}
	else {
		$("stack" + stackId).style.height = max + "px";
	}
	
}
function closeStack( stackId, height, min, step ) {
	$("stack" + stackId).style.height = height + "px"; 
	
	if ( height > min ) {
		height -= step;
		var ti = setTimeout( "closeStack(" + stackId + "," + height + "," + min + "," + step + ")", 2 );
	}
	else {
		$("stack" + stackId).style.height = min + "px";
		$("stack" + stackId).style.display = "none";
	}
	
}


function clearDispStates() {
	// make sure all CSO backgrounds are neutral
	var rpos = 0;
	var lop = true;
	while ( lop ) {
		var rid = "result-" + type + "-" + rpos;
		if ( $(rid) ) {
			$(rid).style.backgroundImage = "";
		}
		else {
			lop = false;
		}
		rpos++;
	}
}


function checkTypeReload( curr ) {

	if ( curr.match(/ty\=/) ) {
		var comps = curr.split("?");
		
		if ( comps.length > 1 ) {
			var newurl = comps[0] + "?";
			var params = comps[1].split("&");
			var p = params.length;
			for ( var i = 0; i < p; i++ ) {
				if ( params[i].substring(0,2) != "ty" ) {
					newurl = newurl + params[i] + "&"; 
				}
			}
			if ( lastfilter != "all" ) {
				newurl += "ty=" + lastfilter;
			}
			window.location = newurl;
		}
		else {
			if ( lastfilter != "all" ) {
				curr = curr + "&ty=" + lastfilter;
			}
			window.location = curr; 
		}
	}
	else {
		// we can reasonably guarantee that there's at least one param on the URL already, namely t=
		curr = curr + "&ty=" + lastfilter;
		window.location = curr;
	}

	
}



function closeMsgContainer() {
	
	if ( $("csoMsgContainer") ) {
		var c = $("csoMsgContainer");
		c.innerHTML = "";
		c.style.display="none";
	}
	if ( $("msgContainer") ) {
		var c = $("msgContainer");
		c.innerHTML = "";
		c.style.display="none";
	}
}





function doFlash() {

	var id = 0;
	
	if ( $("fpbdiv") ) {
		var url = $("fpbdiv").getAttribute( "mediasrc" );
		buildFlash( id, url );
	}
	if ( $("fpbvdiv") ) {
		var vurl = $("fpbvdiv").getAttribute( "videosrc" );
		var iurl = $("fpbvdiv").getAttribute( "imagesrc" );
		var w = parseInt( $("fpbvdiv").style.width );
		var h = parseInt( $("fpbvdiv").style.height );
		buildVideoFlash( id, vurl, iurl, w, h );
	}

}

function buildFlash(id, url ) {

	   var so = new SWFObject("/corp/images/audioplayer.swf", "fpbdiv", "19", "19", "7", "#ffffff");
	   so.addParam("URI", url);
	   so.addParam("mediaFormat", "a");
	   so.addParam("quality", "high");
	   so.addParam("autostart", "false");
	   so.addParam("wmode", "transparent");
	   so.addVariable("URI", url );
	   so.addVariable("mediaFormat", "a");
	   so.addVariable("quality", "high");
	   so.addVariable("wmode", "transparent");
	   so.addVariable("autostart", "false");
	   so.write( "fpbdiv" );
}



function buildVideoFlash( id, url, iurl, w, h ) {
    var so = new SWFObject("/corp/images/audioplayer.swf", "fpbvdiv", w, h, "7", "");
    so.addParam("URI", url );
    so.addParam("imgURI", iurl );
    so.addParam("mediaFormat", "v");
    so.addParam("wmode", "transparent");
    so.addParam("quality", "high");
    so.addParam("salign", "tl");
    so.addParam("align", "tl");
    so.addParam("autostart", "false");
    so.addParam("videoWidth", w-20);
    so.addParam("videoHeight", h );
    so.addParam("videoOffsetX", "20" );
    so.addParam("videoOffsetY", "0" );
    so.addVariable("URI", url);
    so.addVariable("imgURI", iurl );
    so.addVariable("mediaFormat", "v");
    so.addVariable("wmode", "transparent");
    so.addVariable("quality", "high");
    so.addVariable("salign", "tl");
    so.addVariable("align", "tl");
    so.addVariable("autostart", "false");
    so.addVariable("videoWidth", w-20 );
    so.addVariable("videoHeight", h );
    so.addVariable("videoOffsetX", "20" );
    so.addVariable("videoOffsetY", "0" );
    so.write("fpbvdiv");
}




// #################################################
// AJAX completion functions
// #################################################
function compMoreResults( type ) {

	var atype = type;
	if ( type == "")
		atype = "mixed";

    var el = document.createElement("div");
    el.innerHTML = status;
    $( "spinner-" + type ).style.display="none";
    $( "moreResultsContainer-" + type ).appendChild( el );
    var tot = parseInt( $("total-" + atype).value );
    var off = parseInt( $("offset-" + atype).value );
    var lim = parseInt(limit[atype]|10);
    
    //alert( "total: " + tot + "off: " + off + " comp: " + (off + lim) );
    if ( off + lim < tot ) {
    	if ( off + lim*2 > tot ) {
    		$("more-" + atype).innerHTML = ( tot - off + lim );
    	}
        $( "moreResults-" + type ).style.display="block";
    }
}



function compMoreImageResults() {

    var el = document.createElement("div");
    el.innerHTML = status;
    $("spinner").style.display="none";
    $("moreImageResultsContainer").appendChild( el );
    if ( ioffset + origilimit < itotal ) {
        $("moreImageResults").style.display="block";
    }
}





function setFilterState( pos, filter ) {

	for ( var i = 1; i < 6; i++ ) {
		if ( $("filter" + i) ) {
			$("filter" + i).className = "lgbutton";
		}
		if ( $("ftext" + i) ) {
			$("ftext" + i).className = "offtop rgry";
		}
		if ( $("variableFilter") ) {
			$("variableFilter").className = "offtop rgry";
		}
	}
	if ( $("filter" + pos) ) {
		$("filter" + pos).className = "dgbutton";
	}
	if ( $("ftext" + pos) ) {
		$("ftext" + pos).className = "offtop wht";
	}
	else if ( $("variableFilter") ) {
		$("variableFilter").className = "offtop wht";
	}
	if ( filter != "" && filter != undefined && $("variableFilter") ) {
		$("variableFilter").innerHTML = filterText[ filter ];
		$("variableFilter").className = "offtop wht";
	}
	
	if ( pos < 5 && $("moreFilters") ) {
		$("moreFilters").style.display = "none";
	}
}

function home() {
	window.scrollTo(0,1);
}

function animOut( element, from, to ) {
	
	setTimeout( "animUp(\"" + element + "\"," + from + "," + to + ")", 5 );
}

function animUp( element, current, max ) {
	
	$(element).style.height = current + "px";
	if ( current < max ) {
		current += 80;
		setTimeout( "animUp(\"" + element + "\"," + current + "," + max + ")", 5 );
	}
	else {
		$(element).style.height = max + "px";
	}
}




function revealSearch() {

    var box = document.getElementById("tbox"); 
    var ty = box.offsetTop;
    setTimeout( "moveUp(" + ( ty - 180 ) + "," + ( ty - 100) + ")", 5 );
};

function moveUp( current, end ) {

    window.scrollTo( 0, current );
    current = current + 10;
    if ( current < end ) {
        setTimeout( "moveUp(" + current + "," + end + ")", 5 );
    }
};

function moveDown( pos ) {

    window.scrollTo( 0, ip.decelScroll[pos]  );
    pos = pos + 1;
    if ( pos < ip.decelScroll.length ) {
    
        setTimeout( "moveDown(" + pos + ")", 5 );
    }
    
};


function checkEmail( email ) {
	var splits = email.split("@");
	return !( email.indexOf("@") < 0 || splits.length < 2 || ( splits.length == 2 && splits[1].indexOf(".") < 1 ) || splits[0] == "" || splits[0] == undefined );
}



function patchUrl( url ) {
	
	try {
		if ( WebuiData ) {
			for ( param in WebuiData ) {
				url = url + "&" + param + "=" + WebuiData[ param ];	
			}
				
		}
	}
	catch (e) {
		// no WebuiData - failsafe silently
	}

	return url;
}


function setRegister() {
	$("registerBox").style.display="block";
	$("loginBox").style.display="none";
}

function setLogin() {
	$("registerBox").style.display="none";
	$("loginBox").style.display="block";
}

