/*  FUNCTION  ajaxCrossfader
 *  AUTHOR    Ted Young, Radical Designs
 * 
 *  SUMMARY	  Continuesly loads a crossfader-style slideshow with content from a given url.
 *			  Content must be in the form of a json object containing two variables:
 *				html: data to load
 *				id: (optional) id to append to the next request
 *
 *  ARGUMENTS 	url: location of json data
 *			  	container_id: id of the container to put the crossfader in
 *			  	append_id: (optional, default false) true to append the current id 
 *						    onto the url of the next request
 *				speed: (optional, default 6000) length of delay between fades
 *
 *				Arguments are passed in as a single object.
 *
 *  RETURNS:	True if successfully executed, otherwise false.
 */

var ajaxCrossfader = function( options){

//  initialize options
    options = {
        url: options.url || false,
        container_id: options.container_id || false,
        append_id: options.append_id || false,
        speed: options.speed || 6000
    };

// add URI query question mark to url, if it doesn't exist
	if (options.url && !(options.url.match(/\?/))){
		options.url = options.url + "?";	
	}
//  toggle keeps track of what container 
//  we are loading data into
    var toggle = 1;

//  x is a counter for the array of cached images
    var x = 0;

//  data contains the currently loaded json object
    var data;

//  timeout prevents the crossfade from happening if the new data
//  hasn't been loaded yet
    var timeout;
//  processData loads the json data
//	and writes the html block
    var processData =  function(json){
        data = eval("("+json+")");

//		Use regex to extract the image src from the incoming html
        var regexPattern = '<img[^>]*src\s*=\s*["\']([^"\']*)["\'][^>]*>';
        var regex = new RegExp(regexPattern);
        var regexMatch = regex.exec(data.html);

//		preload the images by creating an Image object for each image
        var img = new Array();
        var i;
        for ( i = 1; i < regexMatch.length; i++) {   
            img[x] = new Image(); 
            img[x].src = regexMatch[i];
            x++;
        }

//		load the html into the dom        
        $( "#" + options.container_id + "-ajaxCrossfader-item-next").
            html("<div>"+data.html+"</div>");

//		let the fader know the next item is ready        
        timeout = false;

    }

//  fade crossfades between the current
//  item and the next item, then calls getData
//  for a new item
    var fade = function( ){
		if (!timeout){ 
			$( "#"+options.container_id+"-ajaxCrossfader-item-"+toggle).
			    html($("#"+options.container_id+"-ajaxCrossfader-item-next").html()).
				fadeIn( 800);
			toggle == 1 ? toggle = 2 : toggle = 1;
			$( "#"+options.container_id+"-ajaxCrossfader-item-"+toggle).
				fadeOut( 800);
			if ( options.append_id){
				getData( options.url+'&id='+data.id);
			} else{
				getData( options.url);
			}
			timeout = true;
		}
    }

//  getData makes an ajax call and returns the
//  json data to processData
    var getData = function ( url){
        var request = new XMLHttpRequest();
        request.open("GET", url, true);
        request.onreadystatechange = function(){
            if ( request.readyState == 4){
                processData(request.responseText);
                request = null;
            }
        }
        request.send("");
    }

//  execute builds the neccessary html 
//  and starts the crossfader
    var execute = function( ){
        original_html = $( "#"+options.container_id).html(); 
        $( "#"+options.container_id).html( 
            '<div id="'+options.container_id+'-ajaxCrossfader-container" style="position:relative">'+
                '<div id="'+options.container_id+'-ajaxCrossfader-item-1" style="position:absolute"></div>'+
                '<div id="'+options.container_id+'-ajaxCrossfader-item-2" style="position:absolute">'+original_html+'</div>'+
                '<div id="'+options.container_id+'-ajaxCrossfader-item-next" style="position:absolute;width:0;height:0;overflow:hidden;"></div>'+
            '</div>');
        getData( options.url);
        setInterval( function( ){
			fade();
        }, options.speed);
    }

// 	Verify necessary options exist, and then execute the crossfader
    if ( options.url && options.container_id) {
		execute( );
		return true;
	} else {
		return false;
	}



}
