CBC.namespace("CBC.APP").Weather = function () {
	var _Y, _this, $U;
	var animInt = 0;
	var currentImage = 0;
	var firstRun = true;
	var imgArr = [];
	var _locObj	= null;
	var $searchTimer = 0;
	var cookieDomain = 'cbc.ca';

	return {
		init: function(Y, params){
			_Y = Y;
			_this = this;
			_this.hideCities();
			_locObj = CBC.SETTINGS.weatherlocations;
			$U = new _Y.CBC.Util();
			_listeners = {
				weather: {
					click: {
						defaultset:this.setWeatherCookie,
						celcbtn:this.convertC,
						farenbtn:this.convertF,
						animstart:this.radarAnimStart,
						animstop:this.radarAnimStop,
						animpause:this.radarAnimPause,
						canlocations:this.cityPages,
						usalocations:this.cityPages,
						intlocations:this.cityPages
					}
				}
			};
			_this.generateImgList();
			_this.setupSearch();
			_this.listen();
		},
		/**
		* showCities(provTitle)
		* Desc: shows the cities for the provided Province or region
		*/
		showCities: function(e){
			_this.hideCities();
			var listParent = e.target.get('id');
			if (!listParent) return;
			if(_Y.one("#"+listParent+"-list")) _Y.one("#"+listParent+"-list").setStyle("display","block");
		},
		/**
		* Name: hideCities()
		* Desc: hides each of the city elements
		*/
		hideCities: function(){
			if (document.location.href.match("/weather/canada/") || document.location.href.match("/weather/usa/") || document.location.href.match("/weather/intl/")) return;
			_Y.all(".city-select").setStyle("display", "none");
		},
		/**
		* Name: citypages(e)
		* Desc: moves the user to the new weather page from their existing location
		* In: e - the html anchor object
		*/
		cityPages: function(e){
			var _loc, _id = e.target.get('id');
			if (!_id) return;
			switch(_id){
				case "canlocations":
					_loc = 'cities-canada';
				break;
				case "usalocations":
					_loc = 'cities-usa';
				break;
				case "intlocations":
					_loc = 'cities-intl';
				break;
				default:
					_loc = _id;
				break;
			}
			if(!!region) {
				window.location = "http://"+window.location.host+"/"+region+"/weather/"+_loc+".html";
			} else {
				window.location = "http://"+window.location.host+"/weather/"+_loc+".html";
			}
		},
		/**
		* Name: getLoc() //Depricated
		* Desc: gets the region from the url
		*/
		getloc: function(){
			var locArr = String(window.location.pathname).split("/");
			var locid = locArr[locArr.length-1].split(".html").join("");
			return locid;
		},
		/**
		* Name: convertC()
		* Desc: sends a call to tempSwitch to change text fields from Fahrenheit to Celsius
		*/
		convertC: function(e){
			if (e.target.ancestor('#deg-sel-c')) return;
			_this.tempSwitch(".fahrenheit",".celsius");
		},
		/**
		* Name: convertF
		* Desc: sends a call to tempSwitch to change text fields from Celsius to Fahrenheit
		*/
		convertF: function(e){
			if (e.target.ancestor('#deg-sel-f')) return;
			_this.tempSwitch(".celsius",".fahrenheit");
			
		},
		/**
		* Name: tempSwitch(tagA, tagB)
		* Desc: toggles tagA off and tagB on
		* In: tagA - the tag to set to none
		*     tagB - the tag to set to block
		*/
		tempSwitch: function(tagA, tagB){
			_Y.all(tagA).setStyle("display", "none");
			_Y.all(tagB).setStyle("display", "block");
		},
		/**
		* Name: generateImgList()
		* Desc: generates the list of images for the animation by utilizing the name of the first one
		*/
		generateImgList: function(){
			var mapElement = document.getElementById("radarMap");
			if(!!mapElement) {
				var initImg = mapElement.src;
				for(i=0;i<=5;i++){
					var newImgSrc = initImg.replace("00000", "0000"+i);
					imgArr.push(newImgSrc);
				}
				_this.radarAnimStart();
			}
		},
		/**
		* Name: radarAnimStart()
		* Desc: sets up an interval to update the current image number and then the image every second
		*/
		radarAnimStart: function(){
			clearInterval(animInt);
			animInt = setInterval('CBC.APP.Instances.get("weather").nextFrame()', 1000);
		},
		/**
		* Name: radarAnimStop
		* Desc: stops the animation, sets the current frame number to the last frame, and updates the graphic
		*/
		radarAnimStop: function(){
			clearInterval(animInt);
			currentImage = imgArr.length -1;
			_this.updateFrame();
		},
		/**
		* Name: radarAnimPause()
		* Desc: stops the interval from firing, thus stopping the animation
		*/
		radarAnimPause: function(){
			clearInterval(animInt);
		},
		/**
		* Name: nextFrame()
		* Desc: increases the currentImage number by 1, then does a check to see if it is greater than the length of the image array
		*       If it is longer, the number is set to 0
		*/
		nextFrame: function(){
			currentImage+=1;
			if(currentImage==imgArr.length){
				currentImage = 0;
			}
			_this.updateFrame();
		},
		/**
		* Name: updateFrame()
		* Desc:   updates the src tag of the image area pertaining to the radar maps to simulate animation
		*         if it is the first run through, the animation will run once then stop
		*/
		updateFrame: function(){
			var mapElement = document.getElementById("radarMap");
			if(!!mapElement) {
				mapElement.src = imgArr[currentImage];
				if(currentImage==(imgArr.length -1) && firstRun==true){
					firstRun=false;
					_this.radarAnimStop();
				}
			}
		},
		/**
		* Name: setWeatherCookie(regionValue)
		* Desc: sets the region value for the weather location in the cbclocal cookie
		* In: regionValue - the CBC region value to be set as a cookie value
		*/
		setWeatherCookie: function(e){
			var region = e.target.getAttribute("class");
			CBC.APP.Instances.get("weathermodule").changeLocation(region);
		},
		/**
		* Name: setupSearch
		* Desc: creates a local reference.  
		* 		On page load the function gotoLocationSection is called
		* 		On keyup setSearchTimer is called.  On keydown resetTimer is called.
		*
		* 		This should ensure that the search call should only occur when the user has finished typing
		*
		* 		finds out the current date and uses it to determine a new cookie expiration date.  Next it reads
		* 		any existing cookies and then creates then deletes cookies
		*/
		setupSearch : function(){	
			var fieldLoc = _Y.one("#weatherSelector").getXY();
			var fieldLocY = fieldLoc[1] + parseInt(_Y.one("#weatherSelector").getStyle("height").replace("px", ""))-5;
			var fieldLocX = fieldLoc[0] - 12;
			_Y.one('#inputResults').setStyle("top", fieldLocY + "px").setStyle("left", fieldLocX + "px");
		},
		/**
		* Name: lostfocus
		* Desc: on losing focus, the  city list is retracted
		*/
		
		lostFocus : function(e){
			var t=setTimeout('CBC.APP.Instances.get("weather").listClear()',750);
			
		},
		listClear : function(){
			_Y.one('#inputResults').set("innerHTML", '');
			_Y.one('#inputResults').setStyle("display", 'none');
		},
		/**
		* Name: locationSearch 
		* Desc: if the search string is equal to 'Enter city name...' or blank, then render the list as empty
		*		otherwise change the search query to lowercase and use it to generate a regex for a search
		*/
		locationSearch : function(){
			
			var searchQuery = document.getElementById('cityentry').value.replace(/[^a-zA-Z0-9_\-'יא\. ]/ig,'').toLowerCase();
			if(searchQuery =='Enter city name...' || searchQuery == ''){
				_this.renderLocations(' ');
				return;
			}else{
				searchQuery = searchQuery.toLowerCase();
				var searchVal = new RegExp(searchQuery,"i");
			}
			
			var loc = '';
			var locCount = 0;
			
			for(i=0;i<_locObj.length;i++){
				try{ 
					var searchStr = _locObj[i].loc.toLowerCase();
					var m = searchStr.split(searchQuery);
					var searchStrNoAccents = searchStr.replace(/[\u00e0\u00e2\u00e4]/gi,"a");
					searchStrNoAccents = searchStrNoAccents.replace(/[\u00e8\u00e9\u00ea\u00eb]/gi,"e");
					searchStrNoAccents = searchStrNoAccents.replace(/[\u00ee\u00ef]/gi,"i");
					searchStrNoAccents = searchStrNoAccents.replace(/[\u00f4]/gi,"o");
					searchStrNoAccents = searchStrNoAccents.replace(/[\u00f9\u00fb\u00fc]/gi,"u");
					searchStrNoAccents = searchStrNoAccents.replace(/[\u00ff]/gi,"y");
					var mNoAccents = searchStrNoAccents.split(searchQuery);
					
					if((m.length > 1 || mNoAccents.length > 1) && locCount < 10){
						var _l = _locObj[i].loc.replace("'","&apos;");
						loc += '<li><a href="#" onclick="CBC.APP.Instances.get(\'weather\').setLocation({locType:\'weather\',loc:\''+escape(_l)+'\',dataSet:\''+_locObj[i].stn+'\'});return false;">'+_locObj[i].loc+'</a></li>';
						locCount++;
					}
					m.length = null;
				}catch(err){ 
					//error
				}	
			}
			if(locCount > 0)
				_this.renderLocations(loc);
			else{
				_Y.one("#cityentry").removeClass("searching");
				_Y.one('#inputResults').set("innerHTML","").setStyle("display","none");
			}
		},
		/**
		* Name: renderLocations
		* Desc: renders the html node to appear on the screen
		*/
		renderLocations : function(_loc){
			_Y.one("#cityentry").removeClass("searching");
			_Y.one("#inputResults").set("innerHTML", "<ul>"+_loc+"</ul>").setStyle("display","block");
		},
		/**
		* Name: resetTimer
		* Desc: clears out the timer
		*/
		resetTimer : function(){
			clearTimeout($searchTimer);
		},
		/**
		* Name: keyCheck
		* Desc: checks to see if the key that has been pressed is the enter key
		*/
		keyCheck: function (e){
			if(e.keyCode == 13){
				_this.listSelectTip();
			}else{
				_this.resetTimer();
			}
		},
		/**
		* Name: listSelectTip
		* Desc: makes the tool tip visible that asks the user to click on a list element
		*/
		listSelectTip: function(){
			var $tip = document.getElementById("listTip");
			$tip.className= 'listTipOn';
			
		},
		/**
		* Name: setSearchTimer
		* Desc: initializes a timer from the last keystroke recorded
		*/
		setSearchTimer : function(){
			$searchTimer = setTimeout('CBC.APP.Instances.get("weather").locationSearch()',1000);
			_Y.one("#cityentry").addClass("searching");
		},
		/**
		* Name: setLocation
		* Desc: weather is the only useful section in this portion of the code, news and radio are likely to be deleted
		*/
		setLocation : function(_o){
			_this.renderLocations(' ');
			_Y.one("#inputResults").setStyle("display","none");
			if(!!region) {
				window.location = "http://"+window.location.host+"/"+region+"/weather/"+_o.dataSet+".html";
			} else {
				window.location = "http://"+window.location.host+"/weather/"+_o.dataSet+".html";
			}
			
		},
		listen: function(){
			_Y.on("weather|click", _this._defStartFn, "#content");
			_Y.on("weather|key", _this.setSearchTimer, "#cityentry", "up");
			_Y.on("weather|key", _this.keyCheck, "#cityentry", "down");
			_Y.on("weather|blur", _this.lostFocus, "#cityentry");
		},
		_defStartFn: function(e, o) {
			var t = e.target;
			if (t.test('a') && _listeners["weather"]["click"][t.get('id')]) {
				e.preventDefault();
				_listeners["weather"]["click"][t.get('id')](e);
			}else if(t.test('a') && t.ancestor("#citylist")){
				e.preventDefault();
				_this.cityPages(e);
			}else if(t.test('a') && t.ancestor("#loc-select")){
				e.preventDefault();
				_this.showCities(e);
			}
		}
	};

};

