﻿var plugin
var main

var currentScreen;
var otherScreen;

var screens = new Array();
var popups = new Array();
var currentIdx;

var navDots = new Array();
var navLabels = new Array();

var lightningAnim;
var lightningInterval;
var lightningBaseDelay;

var isUSLocation = true;

function PageLoaded(s) 
{

	//alert("main loaded")
		
	main=s.findName("Page")
	plugin = s.getHost()
	
	
	var cloudAnim = main.findName("CloudAnim");
	//cloudAnim.begin();
	
	lightningAnim = main.findName("LightningAnim");
	
	main.addEventListener("KeyDown", onKeyDown);
	
	screens[0] = main.findName("MainScreen");
	screens[1] = main.findName("RadarScreen");
	screens[2] = main.findName("ForecastScreen");
	screens[3] = main.findName("HourlyForecastScreen");
	currentIdx = 0;
	
	popups[0] = main.findName("CityPopup");
	popups[1] = main.findName("StationPopup");
	popups[2] = main.findName("RecentLocationPopup");
	popups[3] = main.findName("WeatherAlertPopup");
	popups[4] = main.findName("ForecastDetailsPopup");
	popups[5] = main.findName("SettingsScreen");
	
	navDots[0] = main.findName("NavDot0");
	navDots[1] = main.findName("NavDot1");
	navDots[2] = main.findName("NavDot2");
	navDots[3] = main.findName("NavDot3");
	
	navLabels[0] = "Live Conditions";
	navLabels[1] = "Local Radar";
	navLabels[2] = "Extended Forecast";
	navLabels[3] = "Hourly Forecast";
	
	
//	alert(navDots[0]);
	
	hideOtherScreens();
	hidePopups();
    currentScreen = screens[currentIdx];
	otherScreen = screens[currentIdx + 1];
	resetScreen(screens[currentIdx]);
	updateNavDots(currentIdx);
	
	// Setup animation parameters.
	//setCloudParams(0.0, 0.0);
	//setSunParams(0.0);
	//setRainParams(0); // 1.0
	//setSnowParams(0); // 1.0
	//setLightningParams(0);
	setFogParams(0); // 1.0
	//doWind(currentScreen, false);
	isUS(true);
    //setTimeout(init, 10000)
    //init(s);
    loadInitialData();
}

function isUS(us)
{
    isUSLocation = us;
    if(us == true)
    {
        main.findName("RadarRadarButton").Visibility="Visible";
        main.findName("RadarSatelliteButton").Visibility="Collapsed";
        
        navDots[3].Visibility="Visible";
    }
    else
    {
        // Hide the radar button and set the satellite as active
        OnSatelliteOn(main);
        main.findName("RadarSatelliteButton").Visibility="Visible";
        main.findName("RadarRadarButton").Visibility="Collapsed";
        
        // Hide the other nav dot
        navDots[3].Visibility="Collapsed";
    }
}

function updateNavDots(current)
{
    for(var i = 0; i < navDots.length; ++i)
    {
	    var xformgroup = navDots[i].renderTransform;
	    var scaleXform = xformgroup.Children.getItem(0);
	    if(i == current)
	    {
	        scaleXform.scaleX = 2.0;
	        scaleXform.scaleY = 2.0;
	        
	        centerNavLabel(i);
	    }
	    else
	    {
	        scaleXform.scaleX = 1.0;
	        scaleXform.scaleY = 1.0;
	    }
    }
}

function centerNavLabel(idx)
{
    var label = main.findName("NavLabel");
    var shadow = main.findName("NavLabel_Shadow")
    var navArea = main.findName("NavArea");
    
    label.text = navLabels[idx];
    shadow.text = navLabels[idx];
    if (label.actualwidth > 0)
    {
        var offset = (navArea.width - label.actualwidth) / 2;
        label["Canvas.Left"] = offset;
        shadow["Canvas.Left"] = offset;
    }
    
}

function ToggleSettings(sender, args)
{
//    alert("Toggle Settings");

    // Note: settingsScreen is defined in settingsScreen.js
    if (null != dataTimer) clearTimeout(dataTimer);
            
    if (null != sender && (sender.Name == "SettingsOKButton" || sender.Name == "SettingsCancelButton"))
    {
        updateSettings(sender);
    }
    
    if(currentScreen == settingsScreen)
    {
        otherScreen = screens[currentIdx];
    }
    else
    {
        otherScreen = settingsScreen;
    }
    
//    otherScreen.opacity = 100;
//    currentScreen.opacity = 100;
    
//    doTransition(main.findName("FadeAnim"));
    doTransition(main.findName("FadeAnim"));
}

function updateSettings(sender)
{
    if (null != newLocation && null != newStation)
    {
        addRecentLocation(locat, station);
        locat = newLocation;
        station = newStation;
    }
    plugin.content.findName("CountryText").Text = "Search...";
    clearOldCityRecords();
    clearOldStationRecords();
    updateLocation(locat, station);
    
    newLocation = null;
    newStation = null;
    
    if (plugin.content.findName("SettingsCelsiusSelected").opacity == 1)
        units = unitType.metric;
    else
        units = unitType.english;
    
    init(sender);
}

function OnCardFlipCompleted(sender, args)
{
    // There's a problem when card flipping from the settings screen.
    // For some reason, the settings screen still shows a thin sliver when
    // it is scaled to 0. I think it's a bug in Silverlight.
    // To fix the issue, make sure to set the opacity of the settings screen
    // to 0. It'll get fixed up again when the animation is run again.
    if(otherScreen == settingsScreen)
    {
        otherScreen.opacity = 0;
    }
}

var animIdx = 0;
function animateDemo(sender, args)
{
    
    switch (animIdx)
    {
        
        case 0:
            // Snow
		    setCloudParams(0.5, 0.05);
	        setSunParams(0);
	        setRainParams(0); // 1.0
	        setSnowParams(1.0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, false);
	        break;
        case 1:
            // Storm
		    setCloudParams(1.0, 0.7);
	        setSunParams(0);
	        setRainParams(2.0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(5);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, true);		    
	        break;
	    case 2:
	         // Bright Sunny day
		    setCloudParams(0.1, 0.1);
	        setSunParams(0.25);
	        setRainParams(0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, false);
	        break;
        case 3:
            // Moderately windy day
		    setCloudParams(0.4, 0.4);
	        setSunParams(0);
	        setRainParams(0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, true);
	        break;
        case 4:
            // Rain Showers
		    setCloudParams(0.2, 0.2);
	        setSunParams(0);
	        setRainParams(0.5); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, false);	
	        break;
	    case 5: 
            //stop anim
		    setCloudParams(0.0, 0.0);
	        setSunParams(0);
	        setRainParams(0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, false);	
	        break;
    }
    animIdx++;
    if (animIdx > 5)
        animIdx = 0;
}

function onKeyDown(sender, args)
{
    writeLine("args.key: " + args.key);
    writeLine("args.platformKeyCode:" + args.platformKeyCode);
    if(currentScreen == settingsScreen)
    {
        OnSettingsKeyDown(args);
    }
    else
    {
	    if(args.key == 21)
	    {
	        // Bright Sunny day
		    setCloudParams(0.1, 0.1);
	        setSunParams(0.25);
	        setRainParams(0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, false);		    
	    }
	    else if(args.key == 22)
	    {
	        // Moderately windy day
		    setCloudParams(0.4, 0.4);
	        setSunParams(0);
	        setRainParams(0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, true);		    
	    }
	    else if(args.key == 23)
	    {
	        // Rain Showers
		    setCloudParams(0.2, 0.2);
	        setSunParams(0);
	        setRainParams(0.5); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, false);		    
	    }
	    else if(args.key == 24)
	    {
	        // Storm
		    setCloudParams(1.0, 0.7);
	        setSunParams(0);
	        setRainParams(2.0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(5);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, true);		    
	    }
	    else if(args.key == 25)
	    {
	        // Snow
		    setCloudParams(0.5, 0.05);
	        setSunParams(0);
	        setRainParams(0); // 1.0
	        setSnowParams(1.0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, false);		    
	    }
	    else if(args.key == 26)
	    {
	        // Foggy
		    setCloudParams(0.5, 0.05);
	        setSunParams(0);
	        setRainParams(0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(1.0); // 1.0
	        doWind(currentScreen, false);		    
	    }
	     else if(args.key == 20)
	    {
	        // Clear
		    setCloudParams(0.0, 0.0);
	        setSunParams(0);
	        setRainParams(0); // 1.0
	        setSnowParams(0); // 1.0
	        setLightningParams(0);
	        setFogParams(0); // 1.0
	        doWind(currentScreen, false);		    
	    }
    }
}

function resetScreen(screen)
{
	screen.opacity = 1.0;
	var xformgroup = screen.renderTransform;
	var scaleXform = xformgroup.Children.getItem(0);
	scaleXform.scaleX = 1.0;
	scaleXform.scaleY = 1.0;
	var translateXform = xformgroup.Children.getItem(3);
	translateXform.X = 0;
	
	screen.IsHitTestVisible = true;
}

function OnTransitionFade(sender, args)
{
	doTransition(main.findName("FadeAnim"));
}

function OnTransitionLeft(sender, args)
{
    var otherIdx = (currentIdx + (screens.length - 1)) % screens.length;
    
    if(isUSLocation == false && otherIdx == 3)
    {
        otherIdx = 2;
    }
    
    currentScreen = screens[currentIdx];
    otherScreen = screens[otherIdx];
    
    currentIdx = otherIdx;
	doTransition(main.findName("FadeAnim"));
}

function OnTransitionRight(sender, args)
{
    var otherIdx = (currentIdx + 1) % screens.length
    
    if(!isUSLocation && otherIdx == 3)
    {
        otherIdx = 0;
    }
    
    currentScreen = screens[currentIdx];
    otherScreen = screens[otherIdx];
    currentIdx = otherIdx;
	doTransition(main.findName("FadeAnim"));
}

function hideOtherScreens()
{
    for(var i = 0; i < screens.length; ++i)
    {
        screens[i].opacity = 0;
        screens[i].IsHitTestVisible = false;
    }
}

function hidePopups()
{
    for(var i = 0; i < popups.length; ++i)
    {
        popups[i].opacity = 0;
        popups[i].IsHitTestVisible=false;
    }
}

function doTransition(anim)
{
    window.status = (screens[1].opacity);
    hideOtherScreens();
	updateNavDots(currentIdx);
	// We need to reset the screen parameters because
	// animations can affect any of the params.
	// This won't show up as a flicker because the
	// animation will kick in before the screen updates.
	resetScreen(otherScreen);
	resetScreen(currentScreen);
	
	// If the timeline is not stopped, an exception is
	// thrown when setting the name properties.
	anim.stop();
	
	// Silverlight timelines only affect on property.
	// To manage this properly, we have a convention where
	// all of the timelines pertaining to the current screen
	// are declared first. Then all of the timelines pertaining
	// to the other screen are declared second.
	var numTimelines = anim.children.count;
	var halfTimelines = numTimelines / 2;
	
	if(numTimelines % 2 == 1)
	{
		writeLine("Uneven timelines in animation " + anim.Name + ". Results may be undesired.");
	}
	
	var timeline;
	var i;
	
	// Set the values for the current screen.
	for(i = 0; i < halfTimelines; i++)
	{
		timeline = anim.children.getItem(i);
		timeline["Storyboard.Targetname"] = currentScreen.name;
	}
	
	// Set the values for the other screen.
	for(i = halfTimelines; i < numTimelines; i++)
	{
		timeline = anim.children.getItem(i);
		timeline["Storyboard.Targetname"] = otherScreen.name;
	}
	
	
	anim.begin();
	
	// Swap the screen pointers to keep the bookkeeping correct.
	var tmp = currentScreen;
	currentScreen = otherScreen;
	otherScreen = tmp;
	
	// Only the current screen should be hit test visible.
	// The other screens get their hit testing turned off in hideOtherScreens();
	// Calling Reset Screen will turn it back on.
	otherScreen.IsHitTestVisible = false;
	
	
	updateWeatherAnim();
}

function updateWeatherAnim()
{
	//doWind(currentScreen);

}

function setCloudParams(density, scale)
{
    var cloudAnim = main.FindName("CloudAnim");
    if(scale > 0)
    {
    //	alert("setCloudParams " + density + " " + scale);
	    cloudAnim.stop();
	    cloudAnim.SpeedRatio = scale;
	    cloudAnim.begin();
	}
	else
	{
	    cloudAnim.stop();
    }
	    
	
	var cloudLayer = main.FindName("CloudLayer");
	cloudLayer.Opacity = density;
}

function setSunParams(speed)
{
    var sunAnim = main.FindName("SunAnim");
    var sunLayer = main.FindName("SunLayer");
    if(speed == 0)
    {
        sunAnim.stop();
        sunLayer.opacity = 0;        
    
    }
    else
    {
        sunLayer.opacity = 100;
        sunAnim.SpeedRatio = speed;
        sunAnim.begin();
    }
}

function doWind(screen, windy)
{
//	alert("doWind " + screen.name);
	var windAnim = main.findName("WindyAnim");
//	alert(windAnim.name);
	windAnim.stop();
	
	if(windy == true)
	{

		var numChildren = windAnim.children.count;
		for(var i = 0; i < numChildren; ++i)
		{
			var timeline = windAnim.children.getItem(i);
			timeline["Storyboard.Targetname"] = screen.name;
		}

		windAnim.begin();
	}
}

function setLightningParams(delaySeconds)
{
    lightningBaseDelay = delaySeconds;
    if(delaySeconds == 0)
    {
        lightningAnim.stop();
        clearTimeout(lightningInterval);
    }
    else
    {
        lightningInterval = setTimeout(doLightning, Math.random() * lightningBaseDelay * 1000);
    }
}

function doLightning()
{
    lightningAnim.begin();
    if(lightningBaseDelay != 0)
    {
        lightningInterval = setTimeout(doLightning, Math.random() * lightningBaseDelay * 1000);
    }
}

function setFogParams(scale)
{
	var fogAnim = main.findName("FogAnim");
	var fogCanvas = main.findName("FogCanvas");
	if(scale == 0)
	{
		fogAnim.stop();
		fogCanvas.opacity = 0;	
	}
	else
	{
		fogAnim.stop();
		fogCanvas.opacity = 100;	
		fogAnim.SpeedRatio = scale;
		fogAnim.begin();
	}
}

function OnFadeCompleted(sender, args)
{
    var fadeAnim = main.findName("FadeAnim");
    fadeAnim.stop();   
    otherScreen.Opacity = 0;
}

var locTextElements = ["HeaderLocationLabel", "HeaderLocationLabel_Shadow"]
var locLeftAlignElements = ["CityText", "StationText"];
var locLeftTop = {};
var locLeftTopLeft = {};
var locFirstTime = true;

function updateLocation(locData, statData)
{
    if (null != locData && null != statData)
    {
        if (locFirstTime)
        {
            locLeftTop = captureLeftTop(locTextElements);
            locLeftTopLeft = captureLeftTop(locLeftAlignElements);
            locFirstTime = false;
        }
        
        isUS(locat.isUs);
        
        var loc = locData.city + ", ";
        if (locat.isUs) 
            loc += locData.state;
        else
            loc +=  locData.country;
            
        plugin.content.findName("CityText").Text = loc;
        plugin.content.findName("StationText").Text = station.name;
        plugin.content.findName("HeaderLocationLabel").Text = loc;
        plugin.content.findName("HeaderLocationLabel_Shadow").Text = loc;
        centerText(locTextElements, locLeftTop);
        leftAlignText(locLeftAlignElements, locLeftTopLeft);
    }
}

function captureLeftTop(textElems)
{
    var leftTop = {};
    if (null != textElems && textElems.length > 0)
    {
        for (var i = 0; i < textElems.length; i++)
        {
            var text = plugin.content.findName(textElems[i]);
            var lt = {"left": text.GetValue("Canvas.Left"), "width": text.Width, "top": text.GetValue("Canvas.Top"), "height": text.Height, "fontSize": text.FontSize};
            leftTop[textElems[i]] = lt;
        }
    }
    return leftTop;        
}

function centerText(textElems, leftTop)
{
    if (null != textElems && textElems.length > 0)
    {
        for (var i = 0; i < textElems.length; i++)
        {
            if (leftTop[textElems[i]] && plugin.content.findName(textElems[i]))
            {
                var lt = leftTop[textElems[i]];
                var text = plugin.content.findName(textElems[i]);
                text.FontSize = lt.fontSize;
                
                while(text.ActualWidth > lt.width) 
                    text.FontSize -= 0.5; 
                
                var newLeft = ((lt.width - text.ActualWidth) / 2) + lt.left; 
                text.SetValue("Canvas.Left", newLeft);

                var newTop = ((lt.height - text.ActualHeight) / 2) + lt.top; 
                text.SetValue("Canvas.Top", newTop);
            }
        }
    }
}

function leftAlignText(textElems, leftTop)
{
    if (null != textElems && textElems.length > 0)
    {
        for (var i = 0; i < textElems.length; i++)
        {
            if (leftTop[textElems[i]] && plugin.content.findName(textElems[i]))
            {
                var lt = leftTop[textElems[i]];
                var text = plugin.content.findName(textElems[i]);
                text.FontSize = lt.fontSize;
                
                while(text.ActualWidth > lt.width) 
                    text.FontSize -= 0.5; 
                
                var newTop = ((lt.height - text.ActualHeight) / 2) + lt.top; 
                text.SetValue("Canvas.Top", newTop);                    
            }
        }
    }
}


function init(sender)
{    
    writeLine("WebRoot: "  + WebRoot);
    
    //getAlertData();
    //getObsData();
    //getForecastData();
    //getForecastHourlyData();
    //getRadarData();
    getData();
    return true;
}

if (!window.MobileSilverlight)
	window.MobileSilverlight = {};

MobileSilverlight.WeatherBug = function() 
{
}

MobileSilverlight.WeatherBug.prototype =
{
	_zipCode: null,
    _cityCode: null,
	
	handleLoad: function(plugIn, userContext, rootElement) 
	{
		this.plugIn = plugIn;
		
		// Sample button event hookup: Find the button and then attach event handlers
		// this.button = rootElement.children.getItem(0);	
		
		// this.button.addEventListener("MouseDown", Silverlight.createDelegate(this, this.handleMouseDown));
	}
	
	// Sample event handler
	//handleMouseDown: function(sender, eventArgs) 
	//{
	//}
}