results = {};

// { name: true/false }
pollers = {};

rendering = {};

function exists(i) {
    return typeof i != "undefined";
}

function statusCodeCondition(targetStatus) {
    return function (d) { return d.split(" ")[0]==targetStatus; };
}

function jsonCondition(property,value,intermediate) {
    return function (d) { 
	clog('jsonCondition called.');
	var d = $.parseJSON(d);
	if (typeof intermediate == "function") {
	    intermediate(d);
	} else {
	    clog(d);
	}
	return d[property]==value; 
    }
}

function stop_poll(name) {
    clog("Stopping poll: "+name);
    pollers[name] = false;
}

// name = identifier
// url = url target
// callback = function (data, textStatus, request) {}
// exitcondition = function (data) { return true if we got what we want }
// 
// later add this signature:
// poll(url,[[condition,callback],...])
function poll(name,url,callback,exitcondition) {
//    ajaxopts = { url: url, success: callback };
    pollers[name] = true;
    $.smartPoller(function (retry) {
	$.get(url,function (data,textStatus,request) {
	    if (!exists(results[url]) || data!=results[url]) {
		if (typeof callback=="object") {
		    var any = false;
		    for (index in callback) {
			var condition = callback[index][0]
			var local_callback = callback[index][1]
			if (condition(data)) {
			    local_callback(data,textStatus,request);
			     any = true;
			}
		    }
		    if (!any) {
			if (pollers[name])
			    retry();
		    }
		} else {
		    if (exists(exitcondition)) { // if an exit condition is specified
			if (exitcondition(data)) {
			    callback(data,textStatus,request);
			    return;
			} else {
			    if (pollers[name])
				retry();
			}
		    } else { // no exit condition specified
			if (statusCodeCondition('0')(data)) {
			    callback(data,textStatus,request);
			    return;
			} else {
			    if (pollers[name])
				retry();
			}
		    }
		}
		results[url] = data;
	    }
	    if (pollers[name])
		retry();
	});
    });
}

function addScript(url) {
    var id = "json"+url;
    var e = document.getElementById(id);
    if (e)
	e.parentNode.removeChild(e);
    var scriptTag = document.createElement("script");
    scriptTag.setAttribute("type", "text/javascript");
    scriptTag.setAttribute("id",id);
    scriptTag.setAttribute("src", url+"?"+(new Date().getTime()));
    document.getElementsByTagName("head")[0].appendChild(scriptTag);
}    

function parseJSONP(j) {
    var local_uuid = j.uuid;
    if ((local_uuid in results) && (results[local_uuid].toSource()==j.toSource()))
	return
    if (j.completed==1) {
	clog("Finished with the file!");
	pollers[local_uuid] = false;
    }
    // handling updated json!
    //
    if (rendering[local_uuid]) {
	// need to update render box
	var d = $('#renderCheckBox');
	if (j.message) {
	    $('.message',d).text(j.message);
	}
    } else {
	p = $('.processing_box[original_uuid='+local_uuid+']');

	if (j.thumbnail_url) {
	    var thumb = $('img.thumb',p.parents('.uploadbox'));
	    thumb.attr('src',j.thumbnail_url);
	    thumb.attr('static',j.thumbnail_url);
	    thumb.attr('animated',j.thumbnail_url);
	    if (j.animated_thumbnail_url) {
		thumb.attr('animated',j.animated_thumbnail_url);
	    }
	}

	if (j.duration) {
	    $('h2',p).html(' (Original <span class="playlength" length="'+j.duration+'">Length: '+parseDuration(j.duration)+'</span>)');
	}

	if (j.message) {
	    $('.message',p).text(j.message);
	}
    }


    // set the results cache
    results[local_uuid] = j;

}

function jsonp_poll(uuid,render) {
//    ajaxopts = { url: url, success: callback };
    pollers[uuid] = true;
    if (render)
	rendering[uuid] = true;
    clog("Setting up JSONP poller for uuid "+uuid);
    var poll_exec = '$.smartPoller(function (retry) {'+
	'if (pollers["'+uuid.toString()+'"]) {'+
	    'addScript("http://json.highlightcam.com/json_'+uuid.toString()+'.json");'+
	    'retry();'+
	'} '+
    '});';
    eval(poll_exec);
}
