var timeout;
var images = new Array();
var selectedImage = -1;
var lastImage = -1;
var slideInAnimationDuration = 1000; //milliseconds

$(document).ready(function() 
{       
    $.ajax({type:"GET", url: contentXmlUrl, success: loadSlideshow, dataType: "xml"});

    // Loads the slideshow from xml
    function loadSlideshow(xml)
    {
        $("image", xml).each(function(){ images.push($("url", this).text());});
	    setTimeout(startSlideshow, 1); // Fixes an Opera Issue
	    startSlideshow(); // Start the slideshow
    }
    
    // Starts the slideshow
    function startSlideshow()
    {
	    selectImage(0, true);
    }
    
    // Displays the specified image 
    function selectImage(num, init)
    {
	    var image = images[num];
	    if(init || isBrowserEarlyIE())
	    {
		    $("#Image").attr("src", escape(image));
		    $("#Image").css("display", "block");
		    if(!isBrowserEarlyIE())
			    $("#DummyImage").attr("src", escape(image));
	    }
	    else
	    {
		    $("#DummyImage").attr("src", escape(image));
		    $("#DummyImage").css("display", "block");
		    if(!init)
		    {
    		    $("#Image").animate(
	    		    {'opacity' : 0.0},
	    		    slideInAnimationDuration,
	    		    "swing",
	    		    function(){replaceImage(num);});
    	    }
	    }
	    selectedImage = num;
	    startTimer();
	    if(isBrowserEarlyIE()) // IE 6 fixes
	    {
    	    $("#Slideshow span").remove();
    	    $(".jcarousel-item span").remove();
    	    $("#TransparentGif").remove();
    	    var img = $("<img id='TransparentGif' src='" + transparentGifUrl + "' alt=''/>");
    	    $("#Slideshow").prepend(img);
    	    $("#Slideshow").pngFix();	
	    }
    }
    
    // Animates the image transition
    function replaceImage(num)
    {
	    var image = images[num];
	    $("#Image").attr("src", escape(image));
	    $("#Image").css("left", "0");
	    $("#Image").css("right", "0");
	    $("#Image").css("top", "0");
	    $("#Image").css("bottom", "0");
	    $("#Image").css("opacity", "1.0");
	    $("#DummyImage").css("display", "none");
    }
    
    // Method fired by the timer
    function scrollImage()
    {	
        var num = selectedImage + 1;
        num = num >= images.length ? 0 : num;
        selectImage(num);
    }
    
    // Starts the timer
    function startTimer()
    {
	    if(timeout != null)
		    clearTimeout(timeout);
	    timeout = setTimeout(scrollImage, scrollInterval * 1000);
    }
    
    // Detects early IE
    function isBrowserEarlyIE()
    {
	    var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
	    var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
	    return $.browser.msie && (ie55 || ie6);
    }
});
