/*global YUI:false,_CBC_LOADER:false*/

YUI.add('primetime', function(Y) {

	Y.namespace('Primetime');

	Y.Primetime = (function() {

		var _this = null;
	
		var _filePath = '/pgschedules/tv/cbc_television/%%location%%/primetime.html';

		var _Y = null;
		var $U = null;

		var _currentRegion = null;

		var _dom = null;
		var $D = _dom;

		var $Location = null;

		var regionNames = {
			vancouver: 'Vancouver',
			calgary: 'Calgary',
			edmonton: 'Edmonton',
			regina: 'Regina',
			winnipeg: 'Winnipeg',
			ottawa: 'Ottawa',
			toronto: 'Toronto',
			windsor: 'Windsor',
			montreal: 'Montreal',
			fredericton: 'Fredericton',
			charlottetown: 'Charlottetown',
			halifax: 'Halifax',
			labrador: 'Labrador',
			stjohns: "St. John's",
			iqaluit: 'Iqaluit',
			yellowknife: 'Yellowknife',
			whitehorse: 'Whitehorse'
		};

		return {

			init: function(Y) {

				_this = this;
				_Y = Y;

				//get the dom elements we'll need to interact with
				$D = Y.one("#primetimeLineup");
				$Location = Y.one("#schedule_location");

				if (!$U) { $U = _Y.CBC.Util(); }
			
				_this.loadPrimetime();
				_this.listen();									
									
			},



			listen: function() {

				//add the listener for modal box close
				_Y.Global.on('cbc_modalboxclose', _this.loadPrimetime, _this);

			},

			loadPrimetime: function() {
			
				var cookieRegion;
			
				if(!_Y.Cookie.get("cbclocal"))	{
					_Y.use("cbc_geoip", function(_Y){
						cookieRegion = $U.readCookieProperty("cbclocal", "tv");						
						_this.loadDom(cookieRegion);						
					})
				} else {		
				
					cookieRegion = $U.readCookieProperty("cbclocal","tv");
					
					if (!cookieRegion) {
						cookieRegion = 'ottawa';
					}
					
					_this.loadDom(cookieRegion);
				}
			
						
			},
			
			loadDom: function(region) {
			
				
				if (region != _currentRegion) {
					
					_currentRegion = region;

					if (regionNames.hasOwnProperty(region)) {
						region = regionNames[region];
					}
				
					var fileName = _filePath.replace('%%location%%', _currentRegion);

					Y.io(fileName, {
						on: {
							success: function(tid,response) { 
								$D.set('innerHTML',response.responseText);
								$Location.set('innerHTML',region+' | <span id="change_location"><a href="#" onclick="CBC.APP.globalnav.personalize({tab:4});return false;">Change</a></span>');
							},
							failure: function() { 
								$D.set('innerHTML','Sorry, there was an error loading tonights lineup'); 
							}
						}
					});				
								
				}			
			
			}
				
		};

	}());

},
	'1.0.0',
	{requires: ['io', 'node', 'cbc_core']}
);

YUI(_CBC_LOADER).use('primetime', function(Y,result) {
	if(result.success) {Y.Primetime.init(Y);}
});