var handle;
var downloader;

var thumbs=new Array();
var thumbwidth=140;
var thumbheight=140;

var imagecount=8;

var centerX,centerXM,radiusX;
var centerY,radiusY;
var hyperlink;

var roty=0;
var active=true;
var selected=false;


function createCarousel(domref) {

    Silverlight.createObjectEx({
        source: 'casestudies.xaml',
        parentElement: document.getElementById(domref),
        id: domref,
        properties: {
            width: '500', 
            height: '500', 
            inplaceInstallPrompt: true, 
            background: '#FFFFFF',
            framerate: '24',
            version: '1.0',
            enableHtmlAccess: 'true'
        },
        events: {
            onError: slerror, 
            onLoad: slonload },
        initParams: null
    });
}

function slerror(sender, errorArgs) {
// The error message to display.
    var errorMsg = "Silverlight Error: \n\n";
    
    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";
    
    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0)
            {
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}

function slonload(control,usercontext,sender) {

    handle = sender;
    downloader = sender.getHost().CreateObject("downloader");
    downloader.addEventListener("Completed",imageLoaded);

    // Retrieve canvas properties and size/locate carousel appropriately
    var content=sender.getHost().content;
    //centerX=(content.actualWidth/2)-(thumbwidth/2)+10;
    centerX=250-(thumbwidth/2)+10;
    centerXM=250;
    radiusX=centerX-(thumbwidth/4)+10;
    centerY=70;
    radiusY=50;

    loadImages();
}


// ---------- Mouse events for thumbnail images ----------

function thumbMouseEnter(sender) {
	var i=sender.name.split("_")[1]
	sender.findName("frame_"+i).fill="#0095da"
}

function thumbMouseLeave(sender) {
	var i=sender.name.split("_")[1]
	sender.findName("frame_"+i).fill="#000000"
}

function thumbButtonDown(sender) {

        // Use the title, hyperlink & introduction from the object array
        sender.findName("selectedImageTitle").Text=thumbs[sender.name].title;
        sender.findName("selectedImageIntro").Text=thumbs[sender.name].intro;
        hyperlink=thumbs[sender.name].link;
	// Set the cursor to a hand for the hyperlink
        sender.findName("selectedImageLink").Cursor="Hand";
        // Take the file part of the the thumb path and use it as the image file name
	// Pass the request to the media downloader
	filename=sender.source.split("/")[1]
        downloader.open("GET","images/"+filename);
        downloader.send();

        selected=true;
}

// ---------- Mouse events for main image ----------

function imageButtonDown(sender) {

    if (selected) {
        // fade the image and send to the back
        handle.findName("fadeout").begin();
        sender.findName("selectedImageCanvas")["Canvas.ZIndex"]=0;
        sender.findName("selectedImageLink").Cursor="Arrow";
        selected=false;
    }
}

// ---------- Mouse events for full case study link ----------

function linkButtonDown(sender) {
   window.location=hyperlink;
}

// ---------- Mouse events for the outer canvas ----------

function mainMouseEnter() {
    active=true;
}

function mainMouseLeave() {
    active=false;
}

function MouseMove(sender, e) {	
	var pointer = e.getPosition(null);
	mouseX = pointer.x;
	roty=((centerXM-mouseX)/centerXM) * 0.05;
}

// ---------- Create a thumbnail canvas for each image and start animation loop ----------

function loadImages() {
    addImage(0,"Ascot","Ascot Racecourse","The multi-million pound facelift of this sporting landmark has included the building of a traffic underpass below the course where impulse fans have been installed for safety in case of fire or any other incident which may contaminate the air.","pdfs/Case-Ascot.pdf");
    addImage(1,"Type45","BAE Systems","The Type 45 Anti Air Warfare Destroyer is a major addition for the Royal Navy's capability to respond flexibly to challenges in the years ahead. In concert with the Future Aircraft Carrier, it will provide the backbone of the Royal Navy's air defences for much of the first half of this century.","pdfs/Case-BAESystems.pdf");
    addImage(2,"Bridgewater","Bridgewater Place","In a gateway position at the corner of Water Lane and overlooking Granary Wharf, Bridgewater Place is centred around a breathtaking, eight-storey high atrium. The development will provide office, residential and hotel use, with the upper 22 floors dedicated to luxury loft-style apartments.","pdfs/Case-Bridgewater.pdf");
    addImage(3,"Derriford","Derriford Hospital","To supply Mineral Insulated Cables to Plymouth Hospitals NHS Trust’s Plateau Project to bring about long awaited improvements to cardiology services in the region.","pdfs/Case-Derriford.pdf");
    addImage(4,"DubaiAirport","Dubai Airport","The rapid expansion programme at Dubai International Airport includes construction of the terminal, concourse 2 and concourse 3, all dedicated for the Emirates airline and a Mega Cargo Terminal.","pdfs/Case-DubaiAirport.pdf");
    addImage(5,"RedArrows","RAF Scampton","RAF Scampton, home to the Red Arrows aerobatic display team, has reopened as a rapidly expanding expeditionary communications hub supporting military operations around the world at short notice and wanted to upgrade its electrical systems.","pdfs/Case-RedArrows.pdf");
    addImage(6,"QEHospital","Queen Elizabeth Hospital","The Private Finance Initiative for Consort Healthcare’s state-of-the art teaching hospital by Birmingham New Hospital Joint Venture North is a testament to new ways of working as the shiny contemporary shape of buildings rise and shimmer across the skyline of Birmingham. Balfour Beatty are working with Haden Young to construct the first new hospital for the city in 70 years. ","pdfs/Case-QEHospital.pdf");
    addImage(7,"ManchesterAirport","Manchester Airport","MANCHESTER Airport is using high level fire performance cables from AEI Cables to ensure the performance of its critical voice alarm systems. The overhaul of the life safety systems in Terminal One represented the first and most important phase of a £35million radical revamp of the site.","pdfs/Case-ManchesterAirport.pdf");

    drawItems();
    redrawInt=setInterval("redraw()",40);
}

function addImage(i,image,title,intro,link) {
	thumbfile="thumbs/"+image+".jpg";

	xaml='<Canvas Name="thumb_'+i+'" Canvas.Left="0" Canvas.Top="0">';
	xaml+='  <Rectangle Name="frame_'+i+'" Canvas.Top="-1" Canvas.Left="-1" Fill="#222" Height="142" Width="142"></Rectangle>'
	xaml+='  <Image Cursor="Hand" MouseEnter="thumbMouseEnter" MouseLeave="thumbMouseLeave" MouseLeftButtonDown="thumbButtonDown" Stretch="UniformToFill" Name="thumbimage_'+i+'" Height="'+thumbheight+'" Width="'+thumbwidth+'" Source="'+thumbfile+'" Opacity="1" />'
        xaml+='  <Rectangle Canvas.Top="0" Canvas.Left="0" Width="140" Height="20" Fill="#111" Opacity="0.5"></Rectangle>'
        xaml+='  <TextBlock FontSize="11" Canvas.Top="2" Canvas.Left="4" Foreground="#fff">'+title+'</TextBlock>'

	xaml+= 	'<Canvas Canvas.Top="280" Opacity="1">'
	xaml+= 	' <Canvas.OpacityMask>'
	xaml+= 	'   <LinearGradientBrush  StartPoint="0,0" EndPoint="0,1">'           
	xaml+= 	'     <GradientStop Offset="0.3" Color="#00000000"  />'      
	xaml+= 	'     <GradientStop Offset="1" Color="#60000000"  />'
	xaml+= 	'    </LinearGradientBrush>'          
	xaml+= 	' </Canvas.OpacityMask>'
	xaml+= 	' <Canvas.RenderTransform><TransformGroup><ScaleTransform ScaleY="-1" ScaleX="1" CenterX="0" CenterY="0" /></TransformGroup></Canvas.RenderTransform>'		
	xaml+=	' <Image Stretch="UniformToFill" Height="'+thumbheight+'" Width="'+thumbwidth+'" Source="'+thumbfile+'" />'
	xaml+=	'</Canvas>'		

	xaml+='  <Canvas.RenderTransform><ScaleTransform Name="thumbScale_'+i+'" ScaleX="1" ScaleY="1" CenterX="0.5" CenterY="0.5"/></Canvas.RenderTransform>'			
	xaml+='</Canvas>';

	xamlcont=handle.getHost().content.createFromXaml(xaml);
	handle.findName("carousel").children.add(xamlcont);		
		
	thumbs["thumbimage_"+i]=new Object();
	thumbs["thumbimage_"+i].angle=i*((Math.PI*2)/imagecount);
        thumbs["thumbimage_"+i].title=title;
        thumbs["thumbimage_"+i].intro=intro;
        thumbs["thumbimage_"+i].link=link;
}

// ---------- Image swapping ----------

function imageLoaded(sender,evntArgs) {
    handle.findName("selectedImage").setSource(sender,"");
    handle.findName("selectedImageCanvas")["Canvas.ZIndex"]=200;
    handle.findName("fadein").begin();
}


// ---------- Animation loop ----------

function redraw() {
    if(active && !selected) { drawItems() }
}


function drawItems() {
    for(i=0;i<imagecount;i++) {
        // position
        var angle=thumbs["thumbimage_"+i].angle;
	var tx=Math.cos(angle)*radiusX + centerX;
	var ty=Math.sin(angle)*radiusY + centerY;
	handle.findName("thumb_"+i)["Canvas.Left"]=tx;
	handle.findName("thumb_"+i)["Canvas.Top"]=ty;

        // scale & opacity
        var scale=0.4+(0.6*(ty/(centerY+radiusY)));
	var thumbscale=handle.findName("thumbScale_"+i);
	thumbscale.scaleX=scale;
	thumbscale.scaleY=scale;
	handle.findName("thumb_"+i)["Opacity"]=scale;

	// Z-index
	handle.findName("thumb_"+i)["Canvas.ZIndex"]=parseInt(ty);

	// rotate around y-axis
        angle+=roty;
        if (angle>Math.PI*2) angle-=Math.PI*2;
        if (angle<0) angle+=Math.PI*2;
	thumbs["thumbimage_"+i].angle=angle;
    }
}
