/*
 * Copyright (c) 2006 AWS Convergence Technologies, Inc. 
 * All rights reserved.
 * Visit http://www.aws.com
 *
 * WBDataLocation.js
 *
 * This scripts contains the WBDataLocations resuable class. A WBDataLocations object
 * takes care of loading and holding references for the design information such as
 * data URLs, landing page URLs, and important messages for the user.
 */

// Object Definition
function WBDataLocations(loadCallback,errorCallback,errorString,shortErrorWaitTime,longErrorWaitTime,dataUrl,preferences,version)
{
	// Static data objects
	this.url = new WBUrl(dataUrl);
	this.loadErrorCallback = errorCallback;
	this.loadCallback = loadCallback;
	this.dataFetched.currentScope = this; // Used when the dataFetched function has lost scope
	this.time = new WBTime(); // New time object
	
	this.lastReload; // Last time the data was successfully updated or max allowed errors were reached
	this.updateRate = 21600*1000; // Rate at which the data should be updated in miliseconds
	this.updateAvailable = false;

	this.errorString = errorString;               // String passed to the reload timer
	this.shortErrorWaitTime = shortErrorWaitTime; // Timeout for short error
	this.longErrorWaitTime = longErrorWaitTime;   // Timeout for long error
	this.errorCount = 0;                          // Counts the number of internal loading errors
	this.dataLoadedCorrectly = false;             // BOOL to see if we have correct data in the object or not
	this.preferences = preferences;
	
	this.urlArray = new Array();
	
	// Other contructor requirements
    this.checkUrl();
		
	this.url.AddParameter(URLParameters.HitType,URLParameters.HitTypeValue);
	this.url.AddParameter(URLParameters.AppVersion,URLParameters.AppVersionValue);
	this.url.AddParameter(URLParameters.ZCode,URLParameters.ZCodeValue);
	this.url.AddParameter("rnd","^^^rnd^^^");
	this.url.AddParameter("ChangeLocation","^^^ChangeLocation^^^");
	this.url.AddParameter("UpdateAction","^^^UpdateAction^^^");
	this.url.AddParameter("SkippedVersion","^^^SkippedVersion^^^");
	this.url.AddParameter("rDate","^^^rDate^^^");
		
	this.data = new WBDataRequest(this.url,this.dataFetched,this.preferences);
}

WBDataLocations.prototype.checkUrl = function ()
{
    var i;
    var valueFound = false;
    
    for(i = 0; i < this.url.parameterArray.length; i++)
    {
        if(this.url.parameterArray[i].paramName == URLParameters.UserId)
            valueFound = true;
    }
    
    if(valueFound == false)
    {
	    if(this.preferences.IsGuidValid() == true)
            this.url.AddParameter(URLParameters.UserId,URLParameters.UserIdValue);
    }
}

// Do not call this directly, only from an initialized WBDataLocations object.
// Used to reload information in the WBDataLocations object.
WBDataLocations.prototype.load = function () {
    this.checkUrl();
	if(this.errorCount > 2)
	{
		this.errorCount = 0;
		this.loadErrorCallback(this.errorString,this.longErrorWaitTime);
		this.dataLoadedCorrectly = false;
		return;
	}

	// Check to see if we are allowed to reload the object based on the update rate.
	if(this.time.checkForUpdate(this.lastReload,this.updateRate)) { this.data.load(); }
	else if(this.dataLoadedCorrectly == true)
	{
		this.loadCallback();
	}
}

WBDataLocations.prototype.superReload = function () { this.checkUrl(); this.data.load(); }

// Do not call this directly, only from an initialized WBLiveData object.
// Used to parse the information from the WBDataRequest object into the object variables.
WBDataLocations.prototype.dataFetched = function ()
{
	// make sure 'this' is in scope, if not call it again with the correct scope
    if(this != arguments.callee.currentScope){ return arguments.callee.apply(arguments.callee.currentScope, arguments); };
	if(this.data.request.readyState == 4)
	{
	    try
	    {
		    var data = this.data.request.responseXML.firstChild.nextSibling;

		    if(this.preferences.getGUID() != data.getElementsByTagName("aws:uid")[0].firstChild.data)
		        this.preferences.setGUID( data.getElementsByTagName("aws:uid")[0].firstChild.data );		
    			
		    this.shortErrorWaitTime = parseInt(data.getElementsByTagName("aws:shortErrorWaitTime")[0].firstChild.data);
		    this.longErrorWaitTime = parseInt(data.getElementsByTagName("aws:longErrorWaitTime")[0].firstChild.data);
		    this.pid = data.getElementsByTagName("aws:pid")[0].firstChild.data;
		    this.appName = data.getElementsByTagName("aws:appName")[0].firstChild.data;
		    this.activeToInactiveSwitchRate = data.getElementsByTagName("aws:activeToInactiveSwitchRate")[0].firstChild.data;
		    this.allowedLocationLength = data.getElementsByTagName("aws:allowedLocationLength")[0].firstChild.data;
    		
		    if(data.getElementsByTagName("aws:updateAvailable")[0].firstChild.data == "1")
			    this.updateAvailable = true;
		    else
			    this.updateAvailable = false;
    		
		    this.newestVersionNumber = data.getElementsByTagName("aws:newestVersionNumber")[0].firstChild.data;
	        this.sideshowenabled = data.getElementsByTagName("aws:sideshowenabled")[0].firstChild.data;

    		if(this.urlArray != null)
    		    delete this.urlArray;
    		    
    		this.urlArray = new Array();
    		
		    // parse the datasources
		    var dataSourceArray = data.getElementsByTagName("aws:datasource");
		    
		    for(i = 0; i < dataSourceArray.length; i++)
		    {
			    for(var child = dataSourceArray[i].firstChild; child != null; child = child.nextSibling)
			    {
				    if(child.nodeName == "aws:url")
					    this.urlArray[this.urlArray.length] = new WBUrl(child.firstChild.data);
				    else if(child.nodeName == "aws:parameter")
					    this.urlArray[this.urlArray.length - 1].AddParameter(child.getAttribute("name"),child.getAttribute("value"));
			        else if(child.nodeName == "aws:updaterate")
			            this.urlArray[this.urlArray.length - 1].AddUpdateRate(child.getAttribute("normalinmiliseconds"),child.getAttribute("errorinmiliseconds"));
			    }
		    }
		    this.locationUrl = this.urlArray[0];
		    this.stationUrl = this.urlArray[1];
		    this.liveDataUrl = this.urlArray[2];
		    this.alertsDataUrl = this.urlArray[3];
		    this.forecastDataUrl = this.urlArray[4];
		    this.cameraDataUrl = this.urlArray[5];
		    this.radarDataUrl = this.urlArray[6];
		    this.moreDataUrl = this.urlArray[7];
		    this.redirectDataUrl = this.urlArray[8];
	    }
	    catch(e)
	    {
		    this.errorCount++;
		    this.loadErrorCallback(this.errorString,this.shortErrorWaitTime);
		    this.dataLoadedCorrectly = false;
		    return;
	    }
    	
	    this.lastReload = this.time.currentTime();
	    this.errorCount = 0;
	    this.dataLoadedCorrectly = true;
	    this.loadCallback();
	}
}
