
var LITE_APP = false; // run/deploy application as lite (demo) version
var GA_ID = "UA-21890324-12";

VIEWS = {};

AMOSTV = {
    
    players: null, // storage for players and their playlists
    currView: null, // memory of current view being displayed
    preloads: [], // for storing temporary image objects in preloader
    views: VIEWS, // load views defined in separate files
    loading: false, // for the main loading screen
    abortShowView: false, // controls showView(), used for global exit and return
    
    // images to be preloaded
    images: [
        'img/menu/rise-1080.png',
        'img/menu/rise_1080.png',
        'img/menu/rally-1080.png',
		'img/menu/rally_1080.png',
		'img/menu/rest-1080.png',
        'img/menu/rest_1080.png',
		'img/menu/rebel-1080.png',
        'img/menu/rebel_1080.png',
        
        'img/descriptions/riseGoogle.png',
        'img/descriptions/rallyGoogle.png',
        'img/descriptions/restGoogle.png',
        'img/descriptions/rebelGoogle.png',
        
        'img/buttons/googleBackFocus.png',
		'img/buttons/googleBack.png',
		'img/buttons/googleMenu.png',
		'img/buttons/googleMenuHighlighted.png',
		'img/buttons/googleCheckoutNoFocus.png',
		'img/buttons/googleCheckout.png',
		'img/buttons/signup-nofocus.png',
		'img/buttons/signup.png',
		/*'img/buttons/googleCheckoutDone.png',*/
		'img/buttons/watchNow.png',
		'img/buttons/watchNow-focus.png',
		'img/buttons/backToHome.png',
		'img/buttons/backToHome-focus.png',
        'img/buttons/skipIntro.png',
        'img/buttons/skipIntroFocus.png',
        
        'img/videos/small.png',
        'img/videos/medium.png',
        'img/videos/large.png',
		
		'img/labels/rally-1080.png',
		'img/labels/rebel-1080.png',
		'img/labels/rest-1080.png',
		'img/labels/rise-1080.png',
                
        'img/bgs/amosAbout.png',
        'img/bgs/amosBGList.png',
		'img/bgs/googleCheckoutDone.png',
		'img/bgs/googleCheckout.png',
		'img/bgs/amosGoogleWelcome.png',
		'img/bgs/amosDistri.png',
		'img/bgs/googlePreviewOverlay.png',
		
		'img/osd/menuFocus.png',
		'img/osd/prevArrow-1080.png',
		'img/osd/nextArrow-1080.png',
		'img/osd/placeholder.png',
		'img/osd/aboutDownArrow.png',
		'img/osd/aboutUpArrow.png',
        'img/osd/aboutDownArrowHover.png',
        'img/osd/aboutUpArrowHover.png',
		'img/osd/playButton_fullaccess-1080.png',
		'img/osd/playButton-1080.png'
		
		
    ],
    
    init: function() {
        

        this.startLoading();
    
        this.preload();
        
        // helper object
        var Player = function(id) {
            this.id = id;
            this.player = null;
            this.playlists = null;
            this.positions = {};
        };
        
        // define categories
        this.players = {
			'rise': new Player('835199025001'),
            'rally': new Player('835199027001'),
            'rest': new Player('835199028001'),
            'rebel': new Player('834025878001'),
        };
		
 		this.hideViews();
		
        this.ajaxInit();
        
			$('AmosStartup').hide();
			DOUT(window.name);
			if(((window.name == 'amostv_notrailer' && (window.location.href.indexOf("index.html") != -1 || window.location.href.indexOf(".html") == -1)) || window.location.href.indexOf("index.html?from_microsite=true") != -1 || window.location.href.indexOf("stream.html") != -1) && window.location.href.indexOf("index.html?token=") == -1)
			{
				
				AMOSTV.loadView('Menu');
				AMOSTV.currView = null;
            
				AMOSTV.loadView('viewingOptions');
				VIEWS.viewingOptions.show();
				AMOSTV.loadView('Menu');
				
				if(window.location.href.indexOf("stream.html") != -1)
				{
					jQuery("body").attr("class","stream");
					jQuery("#StreamMenu").attr("href","https://www.amostv.com/dvd/");
					jQuery("#StreamMenu").attr("target","_blank");
					VIEWS.GoogleMenu.show(2);
					VIEWS.GoogleMenu.setFocus();
				}
				
				
			} else 
			{
				if(window.location.href.indexOf("index.html") != -1 || window.location.href.indexOf(".html") == -1)
				{
					AMOSTV.loadView('Welcome');
				}
				else
				{
					if(window.location.href.indexOf("about.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('About');
					}
					if(window.location.href.indexOf("find_us_here.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('Distribution');
					}
					if(window.location.href.indexOf("news.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('News');
					}
					if(window.location.href.indexOf("contact.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('Contact');
					}
					if(window.location.href.indexOf("rise.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('List',{player:"rise"});
					}
					if(window.location.href.indexOf("rally.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('List',{player:"rally"});
					}
					if(window.location.href.indexOf("rest.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('List',{player:"rest"});
					}
					if(window.location.href.indexOf("rebel.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('List',{player:"rebel"});
					}
					if(window.location.href.indexOf("checkout.html") != -1 || window.location.href.indexOf("checkout_sandbox.html") != -1)
					{
						AMOSTV.currView = "Menu";
						AMOSTV.loadView('List',{player:"rise",loadCheckout: true});
					}
					
				}
			}
    },
    
    exit: function() {
    },
    
    preload: function() {
        for (var i = 0; i < this.images.length; i++ ) {
            var img = new Image();
            img.src = this.images[i];
            this.preloads.push(img);
        }
    },
    
    //// loading popup
    startLoading: function() {
        if ( !this.abortShowView ) {
            this.loading = true;
            $('loading').style.display = 'block';
        }
    },
    
    stopLoading: function() {
        if ( !this.abortShowView ) {
            this.loading = false;
            $('loading').style.display = 'none';
        }
    },
    
    isLoading: function() {
        return this.loading;
    },
    
    ajaxRequests: [],
    ajaxInit: function() {
        Ajax.Responders.register({
            // when an ajax call is created
            onCreate: function(request) {
                // store request so it can be cancelled
                AMOSTV.ajaxRequests.push(request);
                
                // start timeout
                request['timeoutID'] = setTimeout(function(){
                    
                    // if request is active
                    var state = request.transport.readyState;
                    if ( state == 1 || state == 2 || state == 3 ) {
                        
                        // for all outstanding requests
                        for ( i in AMOSTV.ajaxRequests ) {
                            var req = AMOSTV.ajaxRequests[i];
                            
                            // if request has a transport
                            if ( req.transport ) {
                                // abort request
                                req.transport.abort();
                                // run onFailure
                                req.options['onFailure'](req.transport, req.json);
                            }
                        }
                    }
                }, 15000);
            },
            // when an ajax call is completed
            onComplete: function(request) {
                // clear the timeout
                clearTimeout(request['timeoutID']);
            }
        });
    },
    
    // ajax helper
    ajax: function(url, callback) {
        
        new Ajax.Request(url, { method: 'get',
            onSuccess: function(response){
                var json = response.responseText;
                var obj = eval('(' + json + ')');
                callback(obj);
            },
            onFailure: function() {
                AMOSTV.networkError('ajax');
            }
        });
    },
    
    networkError: function(type) {        
        AMOSTV.loadView('Error', {type: type});
    },
    
    //// view related global functions
    keyHandler: function(event) {
        
        var key;
        if (event && event.keyCode) {
            key = event.keyCode;
        } else if (window.event.type == "keydown") {
            key = window.event.keyCode;
        }
		//event.stopPropagation();
		//event.preventDefault();
        // block normal event handling for special keys, to avoid crash if video is playing
        var keysToBlockNav = [
            KEYS.SOURCE, KEYS.POWER, KEYS.INFOLINK, KEYS.BACK, KEYS.EXIT
        ];
        /*for ( var i = 0; i < keysToBlockNav.length; i++ ) {
            var keyToBlockNav = keysToBlockNav[i];
            
            if ( key == keyToBlockNav ) {
                if ( DEVICE == 'samsung' ) {
                    Samsung.blockNavigation(event);
                }
            }
        }*/
        
        //// handle system keys first, because user should always be able to quit the app
        if ( key == KEYS.BACK ) {
			event.preventDefault();  //TODO: Will this work in IE8? (Fredrik Wallenius 110617) 
            // http://stackoverflow.com/questions/1000597/event-preventdefault-function-not-working-in-ie-any-help
        }
		
		if( key == KEYS.UP){
			event.preventDefault();
		}
		
		if( key == KEYS.DOWN){
			event.preventDefault();
		}
                
        // if loading: dont accept any regular key input except BACK
        if ( AMOSTV.isLoading() ) {
            
            if ( key == KEYS.BACK ) {
                // call view-local key handler
				
                AMOSTV.views[AMOSTV.currView].keyHandler(key);
                AMOSTV.abortShowView = true;
            }
            
			if( AMOSTV.currView == 'Welcome' && key == KEYS.OK  ){
				AMOSTV.views[AMOSTV.currView].keyHandler(key);
				AMOSTV.stopLoading();
			}
			
			/*if(AMOSTV.currView == 'List'){
				AMOSTV.views[AMOSTV.currView].keyHandlerOnLoading(key);
			}*/
            return;
        }
        
        // call view-local key handler
		AMOSTV.views[AMOSTV.currView].keyHandler(key);
        
    },
    
    loadPreviousView: function() {
        var view;
        
        // cant go back to Play, because it requires an argument
        if ( this.oldView == 'Play' ) {
            view = 'List';
        } else if(this.oldView == 'Welcome') {
			view = 'Menu';
		} else {
            view = this.oldView;
        }
        
        this.loadView(view);
    },
    
    loadView: function(view, args) 
	{
        if(view == "Play")
		{
			jQuery(".logo1").css("display","none");
			jQuery(".logo2").css("display","none");
		}
		else
		{
			jQuery(".logo1").css("display","block");
			jQuery(".logo2").css("display","block");
		}
        if(view != "About")
		{
			jQuery("#AboutTextDiv").css("display","none");
		}
        if(view != "Distribution")
		{
			jQuery("#DistriTextDiv").css("display","none");
		}
        if(view != "News")
		{
			jQuery("#NewsTextDiv").css("display","none");
		}
        if(view != "Contact")
		{
			jQuery("#ContactTextDiv").css("display","none");
		}
		if(view == "Welcome")
		{
			pauseImages();
		}
		else
		{
		    moveImages();
		}
		//this.setShowViewAbort(false);
        this.abortShowView = false;
        // if there is a current view
        if ( this.currView ) {
            // destruct current view
            this.views[this.currView].exit();
        }
        
        this.oldView = this.currView;
        this.currView = view;
        DOUT('LoadView: ' + view);
        // construct new view
        this.views[view].init(args);
    },
    
    hideViews: function() {
        
        $('Error').hide();
        $('Menu').hide();
        $('List').hide();
        $('About').hide();
		$('Distribution').hide();
		$('News').hide();
		$('Contact').hide();
        $('Play').hide();
		$('Welcome').hide();
		$('GoogleMenu').hide();
		$('GoogleCheckoutDone').hide();
		$('previewGoogle').hide();
		$('googleCheckoutContainer').hide();
        $('viewingOptions').hide();

    },
    
    showView: function(view, hideOtherViews) {
        if ( !this.abortShowView ) {
            if ((hideOtherViews == null) || (hideOtherViews == true)) {
                this.hideViews();
            }
            $(view).show();
        }
      //  this.loadButtons();
    },
    
    // create button icons for current view
    loadButtons: function() {
        $('buttons').hide();
        // if current view has buttons defined
        if ( typeof(this.views[this.currView].buttons) != 'undefined' ) {
            $('buttons').innerHTML = '';
            // loop backwards (because float: right; inverts order)
            for ( var i = this.views[this.currView].buttons.length - 1; i >= 0; i-- ) {
                var button = this.views[this.currView].buttons[i];
                var li = document.createElement('li');
                var img = document.createElement('img');
                img.writeAttribute('src', 'img/buttons/' + button + '.png');
                li.appendChild(img);
                $('buttons').appendChild(li);
            }
            $('buttons').show();
        }
    },
    
    /*Audio: {
        init: function() {
            $('volume').hide();
        },
        
        setMute: function(mute) {
            Samsung.Audio.setMute(mute);
            this.setOSDMute(mute);
        },
        
        getMute: function() {
            return Samsung.Audio.getMute();
        },
        
        volUp: function() {
            Samsung.Audio.setMute(false);
            Samsung.Audio.adjustVolume(+1);
            this.setOSDVolume();
        },
        
        volDown: function() {
            Samsung.Audio.setMute(false);
            Samsung.Audio.adjustVolume(-1);
            this.setOSDVolume();
        },
        
        setOSDMute: function(mute) {
            this.showOSD();
            if ( mute ) {
                $('volume').className = 'mute';
            } else {
                $('volume').className = 'nomute';
            }
        },
        
        OSDtimer: null,
        showOSD: function() {
            clearTimeout(this.OSDtimer);
            $('volume').show();
            
            this.OSDtimer = setTimeout(function(){
                $('volume').hide();
            }, 1000);
        },
        
        setOSDVolume: function() {
            this.showOSD();
            
            var level = Samsung.Audio.getVolume();
            var maxLevel = 100;
            
            var maxWidth = 77;
            
            var percent = maxLevel/100 * level;
            
            var width = maxWidth/100 * percent;
            $('volumeLevel').style.width = parseInt(width) + 'px';
        }
    },
    
    Video: {
        
        // states
        BUFFERING:  1,
        PLAYING:    2,
        PAUSED:     3,
        STOPPED:    4,
        
        state: null,
        player: null,
        
        currentPlayTime: 0, // temporary storage of time spent playing video
        oldPlayTime: 0,
        
        init: function() {
            this.state = this.STOPPED;
            this.player = Samsung.Video;
            
            if ( !LITE_APP ) {
                if ( DEVICE == 'samsung' ) {
                    this.readPlayTime();
                    
                    var self = this;
                    new PeriodicalExecuter(function(pe){
                        self.writePlayTime();
                    }, 10);
                }
            }
        },
        
        play: function(url, left, top, width, height) {
            DOUT('play: ' + this.state)
            if ( DEVICE == 'samsung' ) {
                if ( this.state == this.STOPPED ) {
                    this.state = this.BUFFERING;
                    this.player.play(url, left, top, width, height);
                }
            }
        },
        
        ready: function() {
            DOUT('ready: ' + this.state)
            if ( DEVICE == 'samsung' ) {
                Samsung.Video.ready();
            }
        },
        
        stop: function() {
            DOUT('stop: ' + this.state)
            if ( DEVICE == 'samsung' ) {
                this.state = this.STOPPED;
                this.player.stop();
            }
        },
        
        pause: function() {
            DOUT('pause: ' + this.state)
            if ( this.state == this.PLAYING ) {
                this.state = this.PAUSED;
                this.player.pause();
            }
        },
        
        resume: function() {
            DOUT('resume: ' + this.state)
            if ( this.state == this.PAUSED ) {
                this.state = this.PLAYING;
                this.player.resume();
            }
        },
        
        bufferStart: function() {
            DOUT('bufferStart: ' + this.state)
            this.state = this.BUFFERING;
            if ( AMOSTV.views[AMOSTV.currView].bufferStart ) {
                AMOSTV.views[AMOSTV.currView].bufferStart();
            }
        },
        
        bufferDone: function() {
            DOUT('bufferDone: ' + this.state)
            this.state = this.PLAYING;
            if ( AMOSTV.views[AMOSTV.currView].bufferDone ) {
                AMOSTV.views[AMOSTV.currView].bufferDone();
            }
        },
        
        playTime: function(time) {
            if ( LITE_APP ) {
                return;
            }
            
            if ( AMOSTV.Video.state == AMOSTV.Video.PLAYING ) {
                this.currentPlayTime = parseInt(time);
            }
        },
        
        playTimeFileName: 'playTime_hardLimit.dat',
        
        writePlayTime: function() {
            if ( LITE_APP ) {
                return;
            }
            
            // if playback has happened
            if ( this.currentPlayTime > 0 && this.state == this.STOPPED ) {
                
                // store new value
                var file = Samsung.openFile(this.playTimeFileName, 'w', false);
                file.writeLine('' + (this.oldPlayTime + this.currentPlayTime));
                Samsung.closeFile(file);
                
                // reset values
                this.oldPlayTime += this.currentPlayTime;
                this.currentPlayTime = 0;
            }
        },
        
        readPlayTime: function() {
            if ( LITE_APP ) {
                return;
            }
            
            // read old time from file
            var file = Samsung.openFile(this.playTimeFileName, 'r');
            if ( file ) {
                var data = file.readLine();
                Samsung.closeFile(file);
                
                // if there was a value (ie not the first time running application)
                if ( data ) {
                    data = parseInt(data);
                    
                    // store the value so it can be added when saving
                    this.oldPlayTime = data;
                }
            }
        },
        
        removePlayTimeFile: function() {
            Samsung.removeFile(this.playTimeFileName);
            this.oldPlayTime = 0;
        },
        
        checkPlayTime: function() {
            if ( LITE_APP ) {
                return true;
            }
            
            this.writePlayTime();

            var seconds = 18000000; // 5 hours
            //var seconds = 600000; // 10 minutes
            //var seconds = 420000; // 7 minutes
            //var seconds = 180000 // 3 minutes
            //var seconds = 60000 // 1 minutes
            //var seconds = 25000 // 25 seconds
            //var seconds = 5000; // 5 seconds
            
            // if total playback time is less than the allowed maximum
            if ( this.oldPlayTime + this.currentPlayTime < seconds ) {
                return true;
            } else {
                AMOSTV.loadView('Error', {type: 'timeout', returnView: 'Menu'});
                return false;
            }
        },
        
        renderDone: function() {
            if ( AMOSTV.views[AMOSTV.currView].renderDone ) {
                AMOSTV.views[AMOSTV.currView].renderDone();
            }
        },
        
        renderError: function() {
            if ( AMOSTV.views[AMOSTV.currView].renderError ) {
                AMOSTV.views[AMOSTV.currView].renderError();
            }
        },
        
        networkError: function() {
            AMOSTV.networkError('video');
        }
    }*/
};

