﻿if (!window.ArtsAndArchitecture)
   window.ArtsAndArchitecture = {};


Array.prototype.remove = function(from, to){
    this.splice(from, !to || 1 + to - from + (!(to < 0 ^ from >= 0) && (to < 0 || -1) * this.length));
    return this.length;
};

ArtsAndArchitecture.DetailView = function(control, target)
{
   this.control = control;
   this.target = target;
   
   this._detailView = this.target.FindName("DetailView");
   this._detailViewBackground = this.target.findName("DetailViewBackground");
   this._detailViewHighlightCanvas = this.target.findName("DetailViewHighlightCanvas");
   this._detailViewHighlightTextCanvas = this.target.findName("DetailViewHighlightTextCanvas");
   this._detailViewHighlightBackground = this.target.findName("DetailViewHightlightBackground");
   //this._detailViewHighlightTitle = this.target.findName("DetailViewHighlightTitle");
   this._detailViewHighlightTitleCanvas = this.target.findName("DetailViewHighlightTitleCanvas");
   //this._detailViewHighlightText = this.target.findName("DetailViewHighlightText");
   this._detailViewHighlightHSpacer = this.target.findName("DetailViewHighlightHSpacer");
   this._detailViewHighlightButtonCanvas = this.target.findName("DetailViewHighlightButtonCanvas");
   this._detailViewHighlightButtonCanvasMaxTop = this._detailViewHighlightButtonCanvas["Canvas.Top"];
   this._detailViewHighlightButtonMainView = this.target.findName("DetailViewHighlightButtonMainView");
   this._detailViewHighlightButtonNext = this.target.findName("DetailViewHighlightButtonNext");
   this._detailViewHighlightButtonBack = this.target.findName("DetailViewHighlightButtonBack");
   
   this._detailViewImage = this.target.findName("DetailViewImage");
   this._storyboardSlideIn = this.target.findName("SlideIn");
   this._storyboardSlideOut = this.target.findName("SlideOut");
   this._storyboardSlideOut.addEventListener("Completed", Silverlight.createDelegate(this, this.handleSlideOutCompleted));
   this._storyboardSlideIn.addEventListener("Completed", Silverlight.createDelegate(this, this.handleSlideInCompleted));
   this._storyboardDetailOut =  this.target.findName("DetailOut");
   this._storyboardDetailIn = this.target.findName("DetailIn");
   this._detailViewSubSpotCanvas = this.target.findName("DetailViewSubSpotCanvas");
   this._subSpotXaml = AADownloader.getResponseText("SubSpot.xaml");
   
   this._upBTN = this.target.findName("upBTN");
   this._downBTN = this.target.findName("downBTN");

   // width value of DetailViewHighlightTextOld in DetailView.xaml (used as placeholder)
   this._detailViewHighlightTextOldWidth = this.target.findName("DetailViewHighlightTextOld").Width;
   
   this._upBTN.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.btnUP_MouseLeftButtonDown));
   this._upBTN.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.btnUP_MouseLeftButtonUp));
   this._upBTN.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.btnUP_MouseEnter));
   this._upBTN.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.btnUP_MouseLeave));
   this._downBTN.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.btnDOWN_MouseLeftButtonDown));
   this._downBTN.addEventListener("MouseLeftButtonUp", Silverlight.createDelegate(this, this.btnDOWN_MouseLeftButtonUp));
   this._downBTN.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.btnDOWN_MouseEnter));
   this._downBTN.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.btnDOWN_MouseLeave));
   
   
   this._titleTextBlocks = null;
   
   this._detailViewHighlightTitleMargin = this._detailViewHighlightTitleCanvas["Canvas.Left"];

   //this._detailViewHighlightText.setFontSource(AAFonts);
   //this._detailViewHighlightText["FontFamily"] = "LOC_SB_BK_B";
   
    this._scrollTimer = this.target.findName("ScrollTimer");
    this._scrollTimer.Duration = "00:00:00.0007";
    this._scrollTimer.addEventListener("Completed", Silverlight.createDelegate(this, this.handleCompleted_scrollTimer));
	
   this._isScrolling = false;
   this._scrollDirection = null;
   this.spacerBorderHeight = 16;
		  
   this._detailViewHighlightButtonMainView.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseLeftButtonDown_ButtonMainView));
   this._detailViewHighlightButtonMainView.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.handleMouseEnter_ButtonMainView));
   this._detailViewHighlightButtonMainView.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.handleMouseLeave_ButtonMainView));
   this._detailViewHighlightButtonNext.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseLeftButtonDown_ButtonNext));
   this._detailViewHighlightButtonNext.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.handleMouseEnter_ButtonNext));
   this._detailViewHighlightButtonNext.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.handleMouseLeave_ButtonNext));
   this._detailViewHighlightButtonBack.addEventListener("MouseLeftButtonDown", Silverlight.createDelegate(this, this.handleMouseLeftButtonDown_ButtonBack));
   this._detailViewHighlightButtonBack.addEventListener("MouseEnter", Silverlight.createDelegate(this, this.handleMouseEnter_ButtonBack));
   this._detailViewHighlightButtonBack.addEventListener("MouseLeave", Silverlight.createDelegate(this, this.handleMouseLeave_ButtonBack));
            
}

ArtsAndArchitecture.DetailView.prototype = 
{
   
   // hotspot x and y
   showDetails: function(detailIndex, detailInStartX, detailInStartY)
   {
        this.setDetails(detailIndex);
        this.slideIn();
   },
   
   setDetails: function(detailIndex)
   {   
   	    // look away! look away!
	
		// reset
		this.clearSubSpots();
		this._downBTN.Visibility = "Collapsed";
		this._upBTN.Visibility = "Collapsed";
       
		this._detailIndex = detailIndex;
		var details = AACurrentData.hotSpots[detailIndex];
       
		this.centerTitleText(details.title.toUpperCase());
       
        // position spacer
		var newTop = this.getTitleCanvasHeight() + this._detailViewHighlightTitleCanvas["Canvas.Top"] + this.spacerBorderHeight; 
		this._detailViewHighlightHSpacer["Canvas.Top"] = newTop;

		// set clipping area
		this._detailViewHighlightTextCanvas.Clip = "M8.5," + (newTop + this.spacerBorderHeight) + " L283.5," + (newTop + this.spacerBorderHeight) + " L283.5,419.5 L8.5,419.5 z";
	   
		var detailTextXaml = '<TextBlock xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="DetailViewHighlightText"'
                           +'      Width="252" Height="192" Canvas.Left="20" Canvas.Top="123"'
                           +'      TextWrapping="Wrap" FontFamily="Arial " FontSize="12" Foreground="#FFEEE8DF"'
                           +'      RenderTransformOrigin="0.5,0.5"><Run></Run></TextBlock>';
       
	   	// remove old TextBlock
		var oldObject = this._detailViewHighlightTextCanvas.children.findName("DetailViewHighlightText");
		if (oldObject != null) {
			this._detailViewHighlightText.Inlines.Clear();
			this._detailViewHighlightTextCanvas.children.remove(oldObject);
		}
        
		// create new TextBlock
		var newObject = this.control.content.createFromXaml(detailTextXaml, false);
		this._detailViewHighlightTextCanvas.children.add(newObject);
        
		this._detailViewHighlightText = this._detailViewHighlightTextCanvas.findName("DetailViewHighlightText");
		
		this._detailViewHighlightText["Canvas.Top"] = this._detailViewHighlightHSpacer.height + this._detailViewHighlightHSpacer["Canvas.Top"] + this.spacerBorderHeight;
  
		newObject.setFontSource(AAFonts);
		newObject["FontFamily"] = "LOC_SB_BK_B"; 
       
	    // NOTE: AAData.js text cannot contain "<" or ">" since switching to Runs
        //details.text = details.text.replace(/</g, "&lt;");
        //details.text = details.text.replace(/>/g, "&gt;");
		
        // original data from the kiosk has /r/n/r/n, should be backslashes
	   	details.text = details.text.replace(/\/r\/n{1,}/g, "\r\n");
        
		// build font runs for bold/italics in detail text
		var runXaml = details.text.replace(/<i>/ig, '</Run><Run FontStyle="Italic" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">');
		runXaml = runXaml.replace(/<\/i>/ig, '</Run><Run xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">');
		runXaml = runXaml.replace(/<b>/ig, '</Run><Run FontWeight="Bold" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">');
		runXaml = runXaml.replace(/<\/b>/ig, '</Run><Run xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">');
		runXaml = '<Run xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">' + runXaml + '</Run>';
		
		var runs = runXaml.split("</Run>");
		var newRun;
		for (var run = 0; run < runs.length - 1; run++) {
			var tempRunXaml = runs[run] + '</Run>';
			newRun = this.control.content.createFromXaml(tempRunXaml, false);
	        this._detailViewHighlightText.Inlines.Add(newRun);
		}
		
		// enable scrolling if it's too long
		var clipTop = this._detailViewHighlightHSpacer.height + this._detailViewHighlightHSpacer["Canvas.Top"] + this.spacerBorderHeight;
		var clipHeight = this._detailViewHighlightButtonCanvas["Canvas.Top"] - clipTop;
		if (this._detailViewHighlightText.ActualHeight > clipHeight) {
			this._detailViewHighlightText.Width = this._detailViewHighlightTextOldWidth;
			this._upBTN["Canvas.Top"] = clipTop;
			this._downBTN.Visibility = "Visible";
			this._upBTN.Visibility = "Visible";
		}		
       
	   // display detail image
       this._detailViewImage.setSource(AADownloader, details.image);
	  
	   // disable buttons if first or last item
	   this._detailViewHighlightButtonNext.Visibility = (this._detailIndex == AACurrentData.hotSpots.length - 1) ? "Collapsed" : "Visible";
	   this._detailViewHighlightButtonBack.Visibility = (this._detailIndex == 0) ? "Collapsed" : "Visible";
	   if (this._detailViewHighlightButtonNext.Visibility == "Collapsed") this._detailViewHighlightButtonNext.Source = "Content/detail_view/button_dk_next_u.png";
	   if (this._detailViewHighlightButtonBack.Visibility == "Collapsed") this._detailViewHighlightButtonBack.Source = "Content/detail_view/button_dk_back_u.png";
       
       // load any sub spots
       if (details.subHotSpots != null) {
        this.addSubSpots(details.subHotSpots);
       }
       
   },
   
   detailOut: function()
   {
    this.clearSubSpots();
        AAViewSelect.slideIn();
        this._storyboardDetailOut.Begin();
   },
   
   detailIn: function()
   {
        AAViewSelect.slideOut();
        AAViewSelect.slideButtonsOut();
        this._storyboardDetailIn.Begin();
   },
   
   slideOut: function(sender, args)
   {
       // TODO: hack.  Sometimes the navBar slides in when it shouldn't???
       AANavBar._navBarReturnButton.IsHitTestVisible = false;
        this.detailOut();
        this._storyboardSlideOut.Begin();
   },
   
   handleSlideOutCompleted: function(sender, args)
   {
        // TODO: hack.  Sometimes the navBar slides in when it shouldn't???
       AANavBar._navBarReturnButton.IsHitTestVisible = true;
       this._detailView.Visibility = "Collapsed";
   },
   
   slideIn: function(sender, args)
   {
   	  // TODO: hack.  Sometimes the navBar slides in when it shouldn't???
      AANavBar._navBarReturnButton.IsHitTestVisible = false;
      this._detailView.Visibility = "Visible";
      this.detailIn();
      this._storyboardSlideIn.Begin();
   },
   
   handleSlideInCompleted: function(sender, args)
   {
        // TODO: hack.  Sometimes the navBar slides in when it shouldn't???
       AANavBar._navBarReturnButton.IsHitTestVisible = true;
   },
   
   getVisibility: function()
   {
       return this._detailView.Visibility;
   },
   
   adjustHighlightTitleTextBlock: function(element)
   {
      // resizes text until it fits, used by centerTitleText()
	  
       while(element.ActualWidth > this._detailViewHighlightTitleCanvas.Width) {
           element.FontSize -= 0.5; 
	   } 

       var newLeft = ((element.Width - element.ActualWidth) / 2) ;
       element["Canvas.Left"] = newLeft;
       element.Height = element.ActualHeight;
   },
   
   centerTitleText: function(heading)
   {  
   	   // manually centers text
	    
       var textArray = new Array();
       textArray = heading.split(" ");
       
       // if total chars per line less than Max, try to join
       for (var j = 0; j < textArray.length; j++) {
            if (j+1 < textArray.length) {
                if (textArray[j].length + textArray[j+1].length <= 14) {
                    textArray[j] = textArray[j] + " " + textArray[j+1];
                    textArray.remove(j+1);
                    j--;
                }
            }
       }
       
       if (this._titleTextBlocks != null) this._titleTextBlocks.length = 0;
       this._titleTextBlocks = null;
       this._titleTextBlocks = new Array();
       
       if (this._detailViewHighlightTitleCanvas.children != null) this._detailViewHighlightTitleCanvas.children.clear();
       
       for (var i = 0; i < textArray.length; i++) {
            var textXaml = '<TextBlock xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="TextBlock' + i + '"'
                           +'      Width="' + this._detailViewHighlightTitleCanvas.width + '" Height="' + this._detailViewHighlightTitleCanvas.height + '" Canvas.Left="0" Canvas.Top="0"'
                           +'      TextWrapping="NoWrap" FontFamily="Arial" FontSize="24" Foreground="#FFF2DBAD"'
                           +'      RenderTransformOrigin="0.5,0.5" Text=""></TextBlock>';

            this._titleTextBlocks.push(this.control.content.createFromXaml(textXaml, false));
            this._detailViewHighlightTitleCanvas.children.add(this._titleTextBlocks[i]);
       
            this._titleTextBlocks[i].Text = textArray[i];
            this._titleTextBlocks[i].setFontSource(AAFonts);
            this._titleTextBlocks[i]["FontFamily"] = "LOC_LL_TITLE";
            
            this.adjustHighlightTitleTextBlock(this._titleTextBlocks[i]);
            if (i > 0) {
                this._titleTextBlocks[i]["Canvas.Top"] = this._titleTextBlocks[i-1]["Canvas.Top"] + this._titleTextBlocks[i-1].ActualHeight;
            }
      }
  	},
  
	getTitleCanvasHeight: function()
	{
       if (this._titleTextBlocks == null) return this._detailViewHighlightTitleCanvas.Height;
    
       var height = 0;
       for (var i = 0; i < this._titleTextBlocks.length; i++) {
          height += this._titleTextBlocks[i].ActualHeight;    
       }
    
       return height;
    },
  
    addSubSpots: function(subSpots)
    {
        for (var i = 0; i < subSpots.length; i++) {
            var subSpot = this.control.content.createFromXaml(this._subSpotXaml, true);

            this._detailViewSubSpotCanvas.children.add(subSpot);
            var x = this._detailViewImage.width * subSpots[i].x;
            var y = this._detailViewImage.height * subSpots[i].y;
            var ss = new ArtsAndArchitecture.SubSpot(this.control, subSpot, x, y, subSpots[i].title, subSpots[i].text, subSpots[i].isLeft);
			ss.setText(subSpots[i].title);			
        }
    },
    	
    clearSubSpots: function()
    {
 	    if (this._detailViewSubSpotCanvas.children.Count > 0) {
		    this._detailViewSubSpotCanvas.children.Clear();
	    }
    },
	
	handleCompleted_scrollTimer: function(sender, args)
    {
        var newTop = this._detailViewHighlightText["Canvas.Top"];
        var scrollStep = 5;
        
        if (this._isScrolling) {

            if (this._scrollDirection == "Up") {
                newTop += scrollStep;
            } else {
				newTop -= scrollStep;
			}               
			
			newTop = Math.min(newTop,this._detailViewHighlightHSpacer.height + this._detailViewHighlightHSpacer["Canvas.Top"] + this.spacerBorderHeight);
			var clipTop = this._detailViewHighlightHSpacer.height + this._detailViewHighlightHSpacer["Canvas.Top"] + this.spacerBorderHeight;
			var clipHeight = this._detailViewHighlightButtonCanvas["Canvas.Top"] - clipTop;
	        
			if (newTop < clipTop - this._detailViewHighlightText.ActualHeight + clipHeight - this.spacerBorderHeight) newTop = clipTop - this._detailViewHighlightText.ActualHeight + clipHeight - this.spacerBorderHeight;
	        
            this._detailViewHighlightText["Canvas.Top"] = newTop;
            
            this._scrollTimer.Begin();
        }
     },
	     
    stopScrolling: function()
    {
        this._isScrolling = false;
    },
	
	btnUP_MouseLeftButtonDown: function(sender, args) {
		this.startScrollingUp();
	},

	btnUP_MouseLeftButtonUp: function(sender, args) {
		this.stopScrolling();
	},

	btnDOWN_MouseLeftButtonDown: function(sender, args) {
		this.startScrollingDown();
	},

	btnDOWN_MouseLeftButtonUp: function(sender, args) {
		this.stopScrolling();
	},

	btnDOWN_MouseEnter: function(sender, args) {
		this._downBTN["Cursor"] = "Hand";
	},

	btnDOWN_MouseLeave: function(sender, args) {
		this._downBTN["Cursor"] = "Arrow";
		this.stopScrolling();
	},

	btnUP_MouseEnter: function(sender, args) {
		this._upBTN["Cursor"] = "Hand";
	},

	btnUP_MouseLeave: function(sender, args) {
		this._upBTN["Cursor"] = "Arrow";
		this.stopScrolling();
	},
	
	handleMouseEnter_ButtonNext: function(sender, args)
   {
       sender.source = "Content/detail_view/button_dk_next_d.png";
   },
   
   handleMouseLeave_ButtonNext: function(sender, args)
   {
       sender.source = "Content/detail_view/button_dk_next_u.png";
   },
   
   handleMouseLeftButtonDown_ButtonNext: function(sender, args)
   {
   
       sender.source =  "Content/detail_view/button_dk_next_d.png";
       ++(this._detailIndex);
       this._detailIndex = (this._detailIndex == AACurrentData.hotSpots.length) ? 0 : this._detailIndex;
       this.setDetails(this._detailIndex);
   },
   
   handleMouseEnter_ButtonBack: function(sender, args)
   {
       sender.source = "Content/detail_view/button_dk_back_d.png";
   },
   
   handleMouseLeave_ButtonBack: function(sender, args)
   {
       sender.source = "Content/detail_view/button_dk_back_u.png";
   },
   
   handleMouseLeftButtonDown_ButtonBack: function(sender, args)
   {
       sender.source =  "Content/detail_view/button_dk_back_d.png";
       --(this._detailIndex);
       this._detailIndex = (this._detailIndex == AACurrentData.hotSpots.length) ? 0 : this._detailIndex;
       this.setDetails(this._detailIndex);
   },
   
   handleMouseEnter_ButtonMainView: function(sender, args)
   {
       sender.source = "Content/detail_view/button_dk_bkoverview_d.png";
   },
   
   handleMouseLeave_ButtonMainView: function(sender, args)
   {
       sender.source = "Content/detail_view/button_dk_bkoverview_u.png";
   },
   
   handleMouseLeftButtonDown_ButtonMainView: function(sender, args)
   {
       sender.source = "Content/detail_view/button_dk_bkoverview_d.png";
       AAViewSelect.slideButtonsIn();
       this.slideOut();
   },
	
	startScrollingUp: function()
    {
        this._isScrolling = true;
        this._scrollDirection = "Up";
        this._scrollTimer.Begin();        
    },
    
    startScrollingDown: function()
    {
        this._isScrolling = true;
        this._scrollDirection = "Down";
        this._scrollTimer.Begin();        
    },
    
    stopScrolling: function()
    {
        this._isScrolling = false;
    }
}

