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

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

	Y.namespace('NowPlaying');

	Y.NowPlaying = (function() {

		var _this = null;

		var _Y = null;
		var $U = null;

		var _currentRegion = null;
		var _currentRegionName = '';

		var _dom = {
			radio1: null,
			radio2:  null

		};

		var _currentGenre = null;
		var _currentNetwork = null;

		var $D = _dom;

        var _isAppleMobile = navigator.userAgent.match(/iPad|iPod|iPhone/i) != null;
        var _itunesStoreUrl = 'http://itunes.apple.com/ca/app/cbc-radio/id325946767?mt=8&s=143455&ign-mpt=uo%3D4';

		return {

			init: function(Y) {

				_this = this;
				_Y = Y;

				//get the dom elements we'll need to interact with
				$D.radio1 = Y.one("#rp-nowplaying ul li.nowplaying-streams.radio1 p.nowplaying");
				$D.radio2 = Y.one("#rp-nowplaying ul li.nowplaying-streams.radio2 p.nowplaying");

				$D.selected = Y.one("#rp-nowplaying ul li.nowplaying-streams.streams div.selectgenre p.selected");
				$D.dropdown = Y.one("#rp-nowplaying ul li.nowplaying-streams.streams div.selectgenre ul");

				_this.adjustRadio3Title();

				_currentRegion = 'ottawa';
				_currentRegionName = 'Ottawa';
				if (!$U) { $U = _Y.CBC.Util(); }

				if (!_currentRegion) {
					_this.loadingErrorAll();
				} else {
					_this.loadNowPlaying();
				}

				_this.listen();

			},

			listen: function() {

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


				_Y.one('#rp-nowplaying').on('click', function(e) {

					e.preventDefault();
					var t = e.target;

					if (t.test('a.change') && t.ancestor('.nowplaying-header')) {

						CBC.APP.globalnav.personalize({tab:3});

					} else if (t.ancestor('.nowplaying-streams')) {

						if(_isAppleMobile) {

                            window.location.href = _itunesStoreUrl;

                        } else {

							var programKey;

                            if (t.test('a') && t.ancestor('.nowplaying-streams.radio1')) {

                                programKey = rpRegions[_currentRegion].radio1.player_program_key;
                                _this.listenNow('cbc_radio_one', programKey);

                            } else if (t.test('a') && t.ancestor('.nowplaying-streams.radio2')) {

                                programKey = rpRegions[_currentRegion].radio2.player_program_key;
                                _this.listenNow('cbc_radio_2', programKey);

                            } else if (t.test('a') && t.ancestor('.nowplaying-streams.radio3')) {

                                _this.listenNow('cbc_radio_3', 'radio3');

                            } else if (t.ancestor('.nowplaying-streams.streams') && t.test('p.selected')) {

								_this.toggleDropDown();

							} else if (t.ancestor('.nowplaying-streams.streams ul') && t.test('a')) {

								var selection = t.get('className');
								if (selection) {
                                    selection = selection.split("-");
                                    _currentGenre = selection[1];
                                    _currentNetwork = selection[0];
                                }

                                var name = t.get('innerHTML');
                                $D.selected.set('innerHTML', name);

                                _this.toggleDropDown('hide');

                            } else if (t.ancestor('.nowplaying-streams.streams .listenlive')) {

								if (_currentGenre && _currentNetwork) {
									_this.listenNow(_currentNetwork, _currentGenre);
	                            }

							}


                        }

					}

				});

			},
			adjustRadio3Title: function() {

				var titleDom = _Y.one(".nowplaying-streams.radio3 p.nowplaying");
				var title = titleDom.get('innerHTML');

				if (title.length > 25) {
					titleDom.set('innerHTML', _this.formatResponse(title));
				}


			},
			toggleDropDown: function(action) {

				if (!action) {

					if (!$D.dropdown.getStyle('display') || $D.dropdown.getStyle('display') == 'none') {
						$D.dropdown.setStyle('display', 'block');
					} else {
						$D.dropdown.setStyle('display', 'none');
					}
				} else if (action == 'hide') {

					$D.dropdown.setStyle('display', 'none');

				}

			},

			listenNow: function(networkKey,programKey) {

				//console.log(programKey);

				if (!programKey) {
					programKey = rpRegions[_currentRegion].pgkey;
				}

				window.open('http://www.cbc.ca/video/radio-popup.html?networkKey=' + networkKey + '&programKey=' + programKey + '', 'r2pop', 'width=800,height=420,scrollbars=0,resizable=1').focus();

			},

			loadingErrorAll: function() {

				_this.loadingError($D.radio1);
				_this.loadingError($D.radio2);
			},

			loadingError: function(dom) {
				dom.set('innerHTML', 'loading error');
			},

			loadNowPlaying: function() {
								
				if(!_Y.Cookie.get("cbclocal"))	{
					_Y.use("cbc_geoip", function(_Y){
						_currentRegion = $U.readCookieProperty("cbclocal", "radio");
						
						_this.loadRegion();
						
					})
				} else {		
					_currentRegion = $U.readCookieProperty("cbclocal","radio");
					_this.loadRegion();
				}				
			},
			
			loadRegion: function() {
			
				_currentRegionName = rpRegions[_currentRegion].name;

				_Y.one('#rp-nowplaying div ul li h3.region').set('innerHTML', _currentRegionName);

				_this.loadRadio1();
				_this.loadRadio2();			
			
			},

			loadRadio1: function() {

				//get the file name from the global variable rpRegions from radioportal.js

				var fileName = rpRegions[_currentRegion].radio1.now_playing_file;

				Y.io(fileName, {
					on: {
						success: function(tid,response) { $D.radio1.set('innerHTML',response.responseText); },
						failure: _this.loadingError($D.radio1)
					}
				});

			},

			loadRadio2: function() {

				//get the file name from the global variable rpRegions from radioportal.js
				var fileName = rpRegions[_currentRegion].radio2.now_playing_file;

				Y.io(fileName, {
					on: {
						success: function(tid,response) { $D.radio2.set('innerHTML',_this.formatResponse(response.responseText)); },
						failure: _this.loadingError($D.radio2)
					}
				});

			},

			formatResponse: function(responseText) {

				//trim whitespace
				var output = responseText.replace(/^\s+|\s+$/g,"");

				// ellipses the output when necessary
				if (output.length > 25) {
					output = output.substr(0,22) + '...';
				}

				return output;

			}
		};

	}());

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


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

/* This module allows for radio player popups to be
 * launched from the radio portal "now playing" module */
YUI(_CBC_LOADER).use('node','event','cbc_radio_header', function(Y,result) {
    var _Y = Y;
    if (result.success) {
        Y.one('.seeAll').on('click',function(e) {

            var $RM = CBC.radio.menus;
            var $RS = CBC.radio.streams; 
            var $RH = CBC.radio.menus.uberHeader.JS;
            if (!Y.one("overlay")){
                var overlay = Y.Node.create('<div id="overlay" class="hide" style="height:100%;">&nbsp;</div>');
                _Y.one('body').append(overlay);
            }

            // overiding functions from uberplayer radioHeader.js which conflict with
            // radio portal DOM structure (nodes missing from document)
            $RH.reset = function (){};
            $RH.display = function() {};

            $RH.init = function (){
                var $RH = CBC.radio.menus.uberHeader.JS;
                $RH.elements.get();
                $RS.checkCookie();
                $RH.getDefaultStreamData();
            };
            $RH.elements.get = function(){
                var $RH = CBC.radio.menus.uberHeader.JS;
                $RH.container	= document.getElementById('radioHeader');
                $RH.radio1		= document.getElementById('listenradio1');
                $RH.radio2		= document.getElementById('listenradio2');
                $RH.radio3		= document.getElementById('listenradio3');
            };
            $RH.getDefaultStreamData = function(){
                var $RS = CBC.radio.streams;
                var $RH = CBC.radio.menus.uberHeader.JS;
                _pgCache = $RS.getPgCache();
                _networkKeys = { radio1: 'cbc_radio_one', radio2: 'cbc_radio_2', radio3: 'cbc_radio_3' };
                _defaultProgramKeys = { radio1: $RS.getDefaultProgramKey('radio1'), radio2: $RS.getDefaultProgramKey('radio2'), radio3: $RS.getDefaultProgramKey('radio3') };
                _streams = { radio1: $RS.getStream(_networkKeys['radio1'], _defaultProgramKeys['radio1']), radio2: $RS.getStream(_networkKeys['radio2'], _defaultProgramKeys['radio2']), radio3: $RS.getStream(_networkKeys['radio3'], _defaultProgramKeys['radio3']) };
                $RH.processCache();
                $RH.reset();
            };
            $RS.playStream = function(urlParams){
                var $RM = CBC.radio.menus;
                var $RS = CBC.radio.streams; 
                var $RH = CBC.radio.menus.uberHeader.JS;
                var stream;
                urlParams = $RS.parseParams(urlParams);
                if (urlParams)
                stream = $RS.getStream(urlParams.networkKey, urlParams.programKey);
                $RS.setCookie(urlParams.networkKey, urlParams.programKey);
                $RM.closeMenu();
                $RH.getDefaultStreamData();
                if (stream){
                    if ($RS.popupplyr){
                        $RS.popupplyr.close();
                    }
                    $RS.popupplyr = window.open('/video/radio-popup.html#/networkKey='+urlParams.networkKey+'&programKey='+urlParams.programKey, 'gnAudioClip','width=800,height=460,scrollbars=0,resizable=0');
                    $RS.popupplyr.focus();
                }
            };
            $RM.toggleOverlay = function(){
                YUI().use("node-base", function(Y){
                    var overlay = Y.one("#overlay");
                    if (overlay.hasClass("hide")){
                        overlay.removeClass("hide");
                        var docHeight = document.body.scrollHeight;
                        overlay._node.style.height = docHeight+"px";
                    }else
                        overlay.addClass("hide");
                });
            };
            $RH.init();
            CBC.radio.menus.openMenu('allStreams'); 
        });

    };
});

