/* 
 * silverlight program for Heroes Happen Here
 * 
 * [a] Stijn Van Minnebruggen
 * [c] These Days
 * [w] www.thesedays.com
 * 
*/

var overlayerOffset = 10;
var defaultImage = 'img/silverlight/pas/template.png';

var rootElement, allRowsY, rowsY, btnClicked, inbetweenZ, oldZ;
var overlayerOpen = false;
var scrollableTextBlock;


if (!window.program) { window.program = {}; }
program.Program = function() {
    this.selectedDayId =1;    
    this.buttonClickedWhenHidingSlow = null;
    this.hidingSlow = false;
}
program.Program.prototype =
{
	switchPage: function(dayId) {
	    oldDayId = this.selectedDayId;
	
	    this.selectedDayId = dayId;
	    
	    var newZIndex = rootElement.findName("Day" + oldDayId.toString())["Canvas.ZIndex"] +1;
	    
	    this.control.content.findName("hideOverlayerBgSlow").Stop();
	    this.control.content.findName('overlayer').Opacity = 0;
	    this.control.content.findName('overlayer')["Canvas.Top"] = allRowsY+50;
	    this.control.content.findName('overlayer_bg').Opacity = 0;
        this.control.content.findName('overlayer_bg').Visibility = 'Collapsed';
			
	    	    
	    rootElement.findName("Day" + dayId.toString())["Canvas.ZIndex"] = newZIndex;
	    rootElement.findName("Day" + dayId.toString()).Height = 3000;
	    rootElement.findName("Day" + dayId.toString() +"_FlyIn").Begin();
	},
	handleLoad: function(control, userContext, re) {
		
		this.control = control;
		rootElement = re;
		this.maxRows = 0;
		
		var plugin = rootElement.getHost();
		var ypos = 0;
		rowsY = new Array();
		
		
		
		rootElement.findName("Day0")["Canvas.Left"]=800;
		rootElement.findName("Day1")["Canvas.Left"]=800;
		rootElement.findName("Day2")["Canvas.Left"]=800;		
        rootElement.findName("Day".concat(this.selectedDayId) )["Canvas.Left"]=0;				
        
        rootElement.findName('overlayer').Opacity = 0; //.5;// 'Collapsed';						
				
	    for(var d in days) {
	        var day = days[d];
	        //alert(d);
	        var ypos_in_day = 0;
	        
	        
		    for(var i in day.get_Content()) {
    			
    			
			    // GET CONTENT
				    var row = day.get_Content()[i];
				    var cols = 0;
				    for(var c in row['data']) cols++;
    			
			    // SET ROW SETTINGS
				    var op = (i%2 != 0) ? 0 : 1;
    				
				    var xName = day.get_Id() + 'row_'+i;
    					
    					
    						
			    // CREATE XAML
				    switch(cols) {
    					
					    case 1:
						    // CREATE XAML
							    var xaml = '<Canvas Width="686" Height="30" Canvas.Top="' + ypos_in_day + '" Canvas.ZIndex="'+i+'" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="' + xName + '">';
							    xaml += '<Rectangle Width="686" Height="30" Fill="#FFf7f6f6" Opacity="'+op+'" />';
							    xaml += '<Rectangle Width="595" Height="30" Fill="#FFdfe1e3" Canvas.Left="90" Opacity="0" x:Name="' + xName + '_0_bg" />';
							    xaml += '<Path Width="1" Height="31" Stroke="#FFebebeb" Stretch="Fill" Data="M30,56 L30,90.014703" Canvas.Top="-0.5" Canvas.Left="0" />';
							    xaml += '<Path Width="1" Height="31" Stroke="#FFebebeb" Stretch="Fill" Data="M30,56 L30,90.014703" Canvas.Top="-0.5" Canvas.Left="90" />';
							    xaml += '<Path Width="1" Height="31" Stroke="#FFebebeb" Stretch="Fill" Data="M30,56 L30,90.014703" Canvas.Top="-0.5" Canvas.Left="685" />';
							    xaml += '<TextBlock Text="'+this.makeXamlReady(row['hour'])+'" TextWrapping="Wrap" FontFamily="Arial" FontSize="11" Canvas.Top="4" Canvas.Left="4" x:Name="' + xName + '_hour" />';
							    xaml += '<TextBlock Text="'+this.makeXamlReady(row['data'][0]['title'])+'" TextWrapping="Wrap" FontFamily="Arial" FontSize="11" Canvas.Top="4" Canvas.Left="94" x:Name="' + xName + '_txt" />';
							    xaml += '<Rectangle Width="595" Height="30" Fill="#00000000" Canvas.Left="90" x:Name="' + xName + '_0_btn" Tag="'+i+'" />';
							    xaml += '</Canvas>';
    						
						    // PLACE XAML
							    var createXaml = plugin.content.createFromXaml(xaml);
							    //rootElement.children.add(createXaml);
							    rootElement.findName("Day" + d.toString() ).Children.add(createXaml);
    						
						    // CENTER TEXT
							    var bg = rootElement.findName(xName+'_0_bg');
							    var txt = rootElement.findName(xName+'_txt');
							    var left = (bg.Width - txt.ActualWidth) / 2;
							    var top = (bg.Height - txt.ActualHeight) / 2;
							    txt["Canvas.Left"] = bg["Canvas.Left"]+left;
							    txt["Canvas.Top"] = top-1;
    						
						    // SET ACTIONS
						        if (row['data'][0]['issession'] == true) {
						            rootElement.findName(xName+'_'+c+'_btn').Cursor="Hand";
							        rootElement.findName(xName+'_'+c+'_btn').addEventListener("MouseEnter", Silverlight.createDelegate(this, this.rowOver));
							        rootElement.findName(xName+'_'+c+'_btn').addEventListener("MouseLeave", Silverlight.createDelegate(this, this.rowOut));
							        rootElement.findName(xName+'_'+c+'_btn').addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.showDetail));							    
						        }
    						
						    // BREAK
							    rowsY.push(ypos);
							    ypos += 30;
							    ypos_in_day += 30;
							    break;
    					
					    default:
					        var col_width = (686-90) / cols;
						    // CREATE XAML
							    xaml = '<Canvas Width="686" Height="150" Canvas.Top="' + ypos_in_day + '" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="' + xName + '" Canvas.ZIndex="'+i+'">';
							    xaml += '<Rectangle Width="686" Height="150" Fill="#FFf7f6f6" Opacity="'+op+'" />';
							    xaml += '<Path Width="1" Height="151" Stroke="#FFebebeb" Stretch="Fill" Data="M30,56 L30,90.014703" Canvas.Top="-0.5" Canvas.Left="0" />';
							    xaml += '<Path Width="1" Height="151" Stroke="#FFebebeb" Stretch="Fill" Data="M30,56 L30,90.014703" Canvas.Top="-0.5" Canvas.Left="685" />';
							    xaml += '<TextBlock Text="'+this.makeXamlReady(row['hour'])+'" TextWrapping="Wrap" FontFamily="Arial" FontSize="11" Canvas.Top="4" Canvas.Left="4" x:Name="' + xName + '_hour" />';
							    for(c=0; c<cols; c++) {
								    var rowData = row['data'][c];
								    var x = (c==0) ? 90 : 90+(col_width*c);
								    xaml += '<Canvas Width="'+col_width+'" Height="150" Canvas.Left="'+x+'">';
								    xaml += '<Path Width="1" Height="151" Stroke="#FFebebeb" Stretch="Fill" Data="M30,56 L30,90.014703" Canvas.Top="-0.5" />';
								    xaml += '<Rectangle Width="'+col_width+'" Height="150" Fill="#FFdfe1e3" Opacity="0" x:Name="' + xName + '_'+c+'_bg" />';
								    xaml += '<Rectangle Width="'+col_width+'" Height="17" Fill="#FF'+this.makeXamlReady(rowData['color'])+'" RadiusX="2" RadiusY="2" Canvas.Left="0" Canvas.Top="0" Opacity="0.5" />';
								    xaml += '<Rectangle Width="13" Height="13" Fill="#FF'+this.makeXamlReady(rowData['color'])+'" RadiusX="2" RadiusY="2" Canvas.Left="'+(col_width - 15)+'" Canvas.Top="2" />';
								    xaml += '<Image Source="img/silverlight/arrow_white_r.png" Canvas.Left="'+(col_width - 12)+'" Canvas.Top="4"/>';
								    xaml += '<TextBlock Text="'+this.makeXamlReady(rowData['code'])+'" FontFamily="Arial" FontSize="11" x:Name="' + xName + '_'+c+'_code" Canvas.Left="4" Canvas.Top="4" FontWeight="Bold" />';
								    xaml += '<TextBlock Text="'+this.makeXamlReady(rowData['speaker'])+'" Width="81" TextWrapping="Wrap"  FontFamily="Arial" FontSize="10" x:Name="' + xName + '_'+c+'_speaker" Canvas.Left="4" Canvas.Top="18" TextDecorations="Underline" />';
								    xaml += '<TextBlock Text="'+this.makeXamlReady(rowData['title'])+'" Width="81" TextWrapping="Wrap" FontFamily="Arial" FontSize="10" x:Name="' + xName + '_'+c+'_txt" Canvas.Left="4" Canvas.Top="40" />';
								    xaml += '<Rectangle Width="'+col_width+'" Height="150" Fill="#00000000" x:Name="' + xName + '_'+c+'_btn" Tag="'+i+'" />';
								    xaml += '</Canvas>';
							    }
							    //if(cols < 7) xaml += '<Path Width="1" Height="151" Stroke="#FFebebeb" Stretch="Fill" Data="M30,56 L30,90.014703" Canvas.Top="-0.5" Canvas.Left="'+(x+85)+'" />';
							    xaml += '</Canvas>';
    						
						    // PLACE XAML
							    var createXaml = plugin.content.createFromXaml(xaml);
							    //rootElement.children.add(createXaml);
							    rootElement.findName("Day" + d.toString()).children.add(createXaml);
    						
						    // SET ACTIONS
							    for(c=0; c<cols; c++) {
							        var rowData = row['data'][c];							    
							        if (rowData['issession']) {
							            rootElement.findName(xName+'_'+c+'_btn').Cursor="Hand";
								        rootElement.findName(xName+'_'+c+'_btn').addEventListener("MouseEnter", Silverlight.createDelegate(this, this.rowOver));
								        rootElement.findName(xName+'_'+c+'_btn').addEventListener("MouseLeave", Silverlight.createDelegate(this, this.rowOut));
								        rootElement.findName(xName+'_'+c+'_btn').addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.showDetail));							    
							        }
							    }
    						
						    // BREAK
							    rowsY.push(ypos);
							    ypos += 150;
							    ypos_in_day += 150;
							    break;
    					
				    }
    			
			    // PLACE XAML
				    this.maxRows++;
    			
		    }
	        
	        
	    }
		
		allRowsY = ypos;
		
		// OVERLAYER SETTINGS
			rootElement.findName('closeOverlay').addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.hideDetail));
			rootElement.findName('overlayer_title').addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.showOLText));
			rootElement.findName('overlayer_speaker_btn').addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.showOLSpeakerText));
			//rootElement.findName('overlayer_more').addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.getURL));
		
		// OVERLAYER POSITIONING
			var overlayerBg = rootElement.findName('overlayer_bg');
			//overlayerBg.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.overlayerBgClick));
			this.control.content.findName("overlayer").addEventListener("MouseLeave", Silverlight.createDelegate(this, this.hideDetailSlow));			
			this.control.content.findName("overlayer").addEventListener("MouseEnter", Silverlight.createDelegate(this, this.hideDetailSlowInterupted));			
			this.control.content.findName("hideOverlayerBgSlow").addEventListener("Completed", Silverlight.createDelegate(this, this.hideDetailSlowCompleted));

			this.control.content.findName("hideOverlayer").AddEventListener("Completed", Silverlight.createDelegate(this, this.resetOverlayer));
		    this.control.content.findName('hideOverlayerBg').AddEventListener("Completed", Silverlight.createDelegate(this, this.resetOverlayerBg));
		    
			overlayerBg["Canvas.ZIndex"] = (this.maxRows+1);
			overlayerBg["Height"] = allRowsY;
			
			var overlayer = rootElement.findName('overlayer');
			overlayer["Canvas.ZIndex"] = (this.maxRows+5);
			overlayer["Canvas.Top"] = allRowsY+50;
			
			//var overlayer1 = rootElement.findName('row_overlayer1')["Canvas.ZIndex"] = (this.maxRows+3);
			//var overlayer2 = rootElement.findName('row_overlayer2')["Canvas.ZIndex"] = (this.maxRows+4);		
		
		// END SETTINGS
			inbetweenZ = this.maxRows+2;
			
			rootElement.findName('speaker_image_container').addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.speakerImageContainerClick));
			
			this.handleControlsLoad(this, null);
		
	},

	handleControlsLoad: function(sender, eventArgs) {
		var xaml = ""; //sender.getResponseText("");
		var destination = this.control.content.findName("overlayer_scrollabletextblock");
		scrollableTextBlock = new program.ScrollableTextBlock();
		scrollableTextBlock.initialize(xaml, destination);
		scrollableTextBlock.location(20,60);
		this.overlayer_scrollabletextblock = scrollableTextBlock;
	},	
	rowOver: function(sender, eventArgs) {
		var timeline = this.control.content.findName('row_rollover');
		var animation = timeline.FindName("anim_rollover")
		timeline.stop();
		animation["Storyboard.TargetName"] = sender.name.split('_btn').join('_bg');
		timeline.Begin();
	},
	rowOut: function(sender, eventArgs) {
		if(btnClicked != sender.name) {
			var timeline = this.control.content.findName('row_rollout');
			var animation = timeline.FindName("anim_rollout")
			timeline.stop();
			animation["Storyboard.TargetName"] = sender.name.split('_btn').join('_bg');
			timeline.Begin();
		}
	},
	showDetail: function(sender, eventArgs) {
		// GET BUTTON VARS (row/btn)
			btnClicked = sender.name;
			overlayerOpen = true;
			//this.hidingSlow == false;
			
			var s = sender.name.split("_");						
			var containingCanvas = this.control.content.findName( s[0] + "_" + s[1]);															
			
			var btnI = sender.name.split( days[this.selectedDayId].get_Id() + 'row_'+sender["Tag"]+'_').join('').split('_btn').join('');
			var detailData = days[this.selectedDayId].get_Content()[sender["Tag"]]['data'][btnI];
			
		
		// BTN OVER OVERLAYER BG
			//this.control.content.findName(days[this.selectedDayId].get_Id() + 'row_'+sender["Tag"])["Canvas.ZIndex"] = inbetweenZ;
						
            if (detailData != null) {
            
            /*
			    if(days[this.selectedDayId].get_Content()[sender["Tag"]]['data'][1]) {
				    if(days[this.selectedDayId].get_Content()[sender["Tag"]]['data'][1]) {
					    var left = this.control.content.findName('row_overlayer1');
					    left['Visibility'] = 'Visible';
					    left['Canvas.Top'] = this.control.content.findName(btnClicked)['Canvas.Top'];// rowsY[sender["Tag"]];
					    left['Width'] = btnI*85;
					    var right = this.control.content.findName('row_overlayer2');
					    right['Visibility'] = 'Visible';
					    right['Canvas.Top'] = rowsY[sender["Tag"]];
					    right['Canvas.Left'] = (btnI*85)+85+91;
					    right['Width'] = 685-right['Canvas.Left'];
				    }
			    }
    		*/
		    // SET OVERLAYER DATA
			    if(detailData['pic'] == '') this.control.content.findName('img_overlayer')['Source'] = defaultImage;
			    else this.control.content.findName('img_overlayer')['Source'] = detailData['pic'];
			    var color = (detailData['color'] == '') ? '#FF999999' : '#FF'+detailData['color'];
			    this.control.content.findName('overlayer_title')['text'] = detailData['title'];
			    //this.control.content.findName('overlayer_title')['Foreground'] = color;
			    this.control.content.findName('overlayer_date')['text'] = detailData['date'];
			    this.control.content.findName('overlayer_speaker')['text'] = detailData['speaker'];
			    this.control.content.findName('overlayer_speaker_text')['text'] = detailData['speaker_text'];
			    this.control.content.findName('overlayer_text')['text'] = detailData['text'];
			    this.control.content.findName('Text')['text'] = detailData['text'];
			    this.control.content.findName('border_overlayer')['Stroke'] = color;
			    this.control.content.findName('close_overlayer')['Fill'] = color;
			    //this.control.content.findName('overlayer_more')['Tag'] = detailData['more_url'];
    		
		    // SHOW OVERLAYER
			    var thisH = (days[this.selectedDayId].get_Content()[sender["Tag"]]['data'][1]) ? 30 : sender["Height"];
			    //overlayerY = Math.round(rowsY[sender["Tag"]]+thisH+overlayerOffset);
		        this.control.content.findName('overlayer')['Canvas.Top'] = containingCanvas["Canvas.Top"] + 50;
			    this.control.content.findName('overlayer_bg').Visibility = 'Visible';
			    this.control.content.findName("showOverlayerBg").Begin();
			    this.control.content.findName("showOverlayer").Begin();
    		
		    // SCROLLER
			    scrollableTextBlock.resetScrollBar();
            
            
            }						
						
		
	},
	hideDetailSlow: function(sender, eventArgs) {
	    this.hidingSlow = true;
	    this.buttonClickedWhenHidingSlow = this.control.content.findName(btnClicked);
        this.control.content.findName("hideOverlayerBgSlow").Begin();        
	},
	hideDetailSlowInterupted: function(sender, eventArgs) {
	    if (this.hidingSlow == true) {
	        this.hidingSlow == false;
	        this.control.content.findName("hideOverlayerBgSlow").Stop();
	        this.control.content.findName('overlayer_bg').Opacity = 0.5;// 'Collapsed';
	        this.control.content.findName('overlayer').Opacity = 1;// 'Collapsed';
	        
	    }
	},
	hideDetailSlowCompleted: function(sender, eventArgs) {
	    this.hidingSlow = false;
	    this.control.content.findName('overlayer_bg').Visibility = 'Collapsed';
	    var selectedDayId = days[this.selectedDayId].get_Id();
	    this.rowOut(this.buttonClickedWhenHidingSlow, eventArgs);	    
	    overlayerOpen = false;
	    this.resetOverlayer();
	    //this.control.content.findName("hideOverlayer").Begin();
	},
	overlayerBgClick: function(sender, eventArgs) {
	    this.control.content.findName("hideOverlayerBgSlow").Stop();  
	    this.hideDetailSlowCompleted(null, null);
	},
	hideDetail: function(sender, eventArgs) {
        
        var selectedDayId = days[this.selectedDayId].get_Id();
	
		// OVERLAYER SETTINGS
			overlayerOpen = false;
			var backupBtnClicked = btnClicked; 
			//btnClicked = false;
			this.rowOut(this.control.content.findName(backupBtnClicked), eventArgs);
		
		// ROW UNDER OVERLAYERBG
		   /* for(var d in days) {
                var day = days[d];
                for(var i in day.get_Content()) {
                    var xName = selectedDayId + 'row_'+i;
                    rootElement.findName(xName)["Canvas.ZIndex"] = i;
                }
            }*/
		
		/*
			var ziv; var zMaxRows = this.maxRows;
			clearInterval(ziv); var i=0;
			ziv = setInterval(function() { // delay because of silverlight zindex error in for-loop
			
				if(i>=zMaxRows) clearInterval(ziv);
				else { 
				 var xName = selectedDayId + 'row_'+i;// days[this.selectedDayId]+'_row_'+i;
				 
				rootElement.findName(xName)["Canvas.ZIndex"] = i; i++;
				}
			}, 5);*/
		
		this.control.content.findName("hideOverlayer").Begin();
		this.control.content.findName('hideOverlayerBg').Begin();
			
			
	},
	makeXamlReady: function(txt) {
		// REPLACE NON-XAML-FRIENDLY CHARS
			if(txt == undefined || txt == null || !txt) txt = '';
			//var txt = unescape(txt);
			var txt = txt.split('&').join('and');
			return txt;
	},
	resetOverlayer: function(sender, eventArgs) {
		if(!overlayerOpen) this.control.content.findName('overlayer')['Canvas.Top'] = allRowsY+50;
	},
	resetOverlayerBg: function(sender, eventArgs) {
		this.control.content.findName('overlayer_bg').Visibility = 'Collapsed';
		//this.control.content.findName('row_overlayer1')['Visibility'] = 'Collapsed';
		//this.control.content.findName('row_overlayer2')['Visibility'] = 'Collapsed';
	},
	isDefined: function(variable){
		return (typeof(window[variable]) == "undefined") ? false : true;
	},
	showOLText: function(sender, eventArgs) {
		this.control.content.findName('Text')['text'] = this.control.content.findName('overlayer_text')['text'];
		scrollableTextBlock.resetScrollBar();
	},
	showOLSpeakerText: function(sender, eventArgs) {
		this.control.content.findName('Text')['text'] = this.control.content.findName('overlayer_speaker_text')['text'];
		scrollableTextBlock.resetScrollBar();
	},
    speakerImageContainerClick: function(sender, eventArgs) {
        this.showOLSpeakerText();
    }
	
	/*,
	getURL: function(sender, eventArgs) {
		var url = sender.Tag;
		if(url) window.location = url;
	}*/
}