﻿var HomeState = new Class({
    Implements: Options,
    options: {
        dataUrl: 'data/home.aspx',
        videoRoot: 'http://d3r33qgzufzbhd.cloudfront.net/',
        playerWidth: 358,
        playerHeight: 254,
        scrollInterval: 2500
    },

    initialize: function() {
        this.freeId = null;
        this.freePlayer = 'freeplayer';
        this.freeContainer = $(this.freePlayer);
        this.downloadBox = $('downloadBox');

        this.image_index = 0;
        this.introPlaying = false;
        this.showIntroVideo();
        
        this.currentSearch = 'bodypart';
        this.searchTitle = $('searchTitle');
        this.searchBodyParts = $('bodyparts');
        this.searchTrainers = $('trainers');
        
        this.currentResults = 'new';
        this.resultsTitle = $('resultsTitle');
        this.resultsContainer = $('resultsContainer');
        
        this.startScroll();
        
        //this.showCustomSample();
    },
    
    showIntroVideo: function() {
        var autoplay;
        if (Cookie.read('introvideo') == 'viewed')
            this.startRotatingImages();
        else {
            var flashvars = { file:'http://d3vuq4ow0v2loa.cloudfront.net/introduction.flv', autostart:'true', wmode:'transparent', screencolor:'FFFFFF', icons:false, controlbar:'over' }
            var params = { allowfullscreen:'true',  allowscriptaccess:'always', wmode:'transparent' }
            var attributes = { id:'intro_player', name:'intro_player' }
            swfobject.embedSWF('swf/player-licensed.swf', 'right-player', '460', '276', '9', false, flashvars, params, attributes);

            this.introPlaying = true;
            Cookie.write('introvideo', 'viewed', { 'path': '/', 'duration': 365 });
        }
    },
    
    startRotatingImages: function() {
        var container = $('right-rotator');
        if (container) {
            this.introPlaying = false;
            container.empty();
            
            // start rotating image content
            new Element('img', { 'id': 'topimage', 'src': 'images/home/women2.gif' }).inject(container);
            this.rotateImage.periodical(15000, this);
        }
    },

    rotateImage: function() {
        //var collection = ['women2.gif', 'rotate_custom_workout.gif', 'itunes.gif', 'rotate_image.gif', 'sexypack.gif', 'specialpacks.gif'];
        var collection = ['women2.gif', 'allmax.gif', 'virginmobile.gif', 'rotate_custom_workout.gif', 'itunes.gif', 'sexypack.gif', 'specialpacks.gif'];
        this.image_index++;
        if (this.image_index >= collection.length) this.image_index = 0;
        $('topimage').src = 'images/home/' + collection[this.image_index];
        if (this.image_index == 1) {
            $('topimage').setStyle('cursor', 'pointer');
            $('topimage').addEvent('click', function() { window.open('http://www.ALLMAXNutrition.com/', '', ''); });
        }
        else if (this.image_index == 3) {
            $('topimage').setStyle('cursor', 'pointer');
            $('topimage').addEvent('click', function() { window.location.href = 'custom-sample.aspx'; });
        }
        else {
            $('topimage').setStyle('cursor', 'default');
            $('topimage').removeEvents();
        }
    },
    
    // free video options
    showFreeVideo: function(id, url, autoplay) {
        this.freeId = id;
        $(this.freeContainer).empty();
        //$(this.freeContainer).removeEvents();
        
        if (this.introPlaying)
            this.startRotatingImages();
        
        var s1 = new SWFObject('swf/player-licensed.swf','player',this.options.playerWidth,this.options.playerHeight,'9');
        s1.addParam('allowfullscreen','true');
        s1.addParam('allowscriptaccess','always');
        s1.addParam('wmode', 'transparent');
        s1.addParam('autostart', (autoplay ? 'true' : 'false'));
        
        if (id)
            s1.addParam('flashvars','autostart=' + (autoplay ? 'true' : 'false') + '&file=' + url + '&image=photo.aspx%3Ft=vt%26id=' + id);
        else
            s1.addParam('flashvars','autostart=' + (autoplay ? 'true' : 'false') + '&file=' + url + '&image=images/player_bg.jpg');
        s1.write(this.freePlayer);
        
        this.downloadBox.empty();
        if (id) {
            new Element('a', { 'events': { 'click': function() { this.downloadFreeVideo(); }.bind(this) }}).set('text', '► DOWNLOAD THIS VIDEO').inject(this.downloadBox);
        }
    },
    
    downloadFreeVideo: function() {
        if (this.freeId) {
            var url = 'download.aspx?id=' + this.freeId;
            window.location.href = url;
        }
    },
    
    // search options
    toggleSearch: function(type) {
        if (type)
            this.currentSearch = type;
        else
            this.currentSearch = this.currentSearch == 'bodypart' ? 'trainer' : 'bodypart';
        
        this.searchTitle.src = this.currentSearch == 'bodypart' ? 'images/title_bodypart_trainer.jpg' : 'images/title_bodypart_trainer2.jpg';
        this.searchBodyParts.setStyle('display', this.currentSearch == 'bodypart' ? 'block' : 'none');
        this.searchTrainers.setStyle('display', this.currentSearch == 'trainer' ? 'block' : 'none');
    },
    
    // result options
    toggleResults: function(type) {
        if (type)
            this.currentResults = type;
        else
            this.currentResults = this.currentResults == 'new' ? 'search' : 'new';
        
        this.resultsTitle.src = this.currentResults == 'search' ? 'images/title_news_search.jpg' : 'images/title_news_search2.jpg';
    },
    
    search: function(type, option) {
        // send ajax request for data
        var url = this.options.dataUrl + '?type=' + escape(type) + '&id=' + escape(option);
        new Request.JSON({ 'url': url, 'method': 'get',
            'onSuccess': function(result) {
                if (result) {
                    this.results = result;
                    this.toggleResults(type == 'new' ? 'new' : 'search');
                    this.resultsContainer.empty();

                    result.each(function(item) {
                        var wrapper = new Element('div', { 'class': 'homeresult' }).inject(this.resultsContainer);
                        new Element('img', { 'class': 'thumb-large', 'src': 'photo.aspx?t=vc&id=' + item.ID }).inject(wrapper);
                        var detail = new Element('div', { 'class': 'detail' }).inject(wrapper);
                        new Element('div', { 'class': 'news_search' }).set('text', item.Name).inject(detail);
                        new Element('div', { 'class': 'news_search_text' }).set('text', item.CategoryName).inject(detail);
                        new Element('img', { 'src': 'images/results/button_preview.png', 'class': 'rollover', 'events': {
                            'click': function() { new PreviewWindow(item); }.bind(this)
                        }}).inject(detail);
                        /*
                        if (is_member) {
                            new Element('img', { 'src': 'images/button_addtoaccount.jpg', 'class': 'rollover' }).inject(
                                new Element('a', { 'href': 'add.aspx?id=' + item.ID + '&from=' + escape(window.location.pathname + window.location.search) }).inject(detail));
                        }
                        else {
                            new Element('img', { 'src': 'images/results/button_add.png', 'class': 'rollover', 'events': {
                                'click': function() { VideoCart.current.addAndViewCart(item.ID); }
                            }}).inject(detail);
                            new Element('img', { 'src': 'images/results/button_buynow.png', 'class': 'rollover', 'events': {
                                'click': function() { VideoCart.current.add(item.ID); window.location.href = './checkout/'; }
                            }}).inject(detail);
                        }
                        */
                    }.bind(this));
                    
                    new Element('div', { 'class': 'clear' }).inject(this.resultsContainer);
                    new Element('img', { 'src': 'images/exerciseprograms.jpg', 'class': 'rollover' }).inject(
                        new Element('a', { 'href': 'videos.aspx' }).inject(
                            new Element('div', { 'styles': { 'text-align': 'right' }}).inject(this.resultsContainer)));
                        
                    if (rollovers) rollovers.update();
                }
            }.bind(this), 'onFailure': function(result) {
        }.bind(this)}).send();
    },
    
    startScroll: function() {
        this.scroller = $('scroller').getElement('div.content');
        if (this.scroller) {
            this.scrollIndex = 0;
            this.scroller.getElements('img').each(function(img) {
                img.addEvent('click', function() { window.location.href = 'programs.aspx'; });
            });
            this.scroll = this.doScroll.periodical(this.options.scrollInterval, this);
        }
    },
    
    doScroll: function(stop) {
        var images = this.scroller.getElements('img');
        if (images <= 1) return;
        
        var first = images[0];
        var width = first.getSize().x;
        first.get('tween', { 'property': 'margin-left', 'duration': 'long' }).start(-width).chain(function() {
            this.scroller.grab(first);
            first.setStyle('margin-left', '0');
            
            //if (!stop) this.doScroll(true);
        }.bind(this));
    }
});

var homeState;
window.addEvent('domready', function() {
    homeState = new HomeState();
    homeState.search('new');
});


// helper functions for intro video
var intro_player = null;
function playerReady(player) {
    if (player.id == 'intro_player') {
        intro_player = window.document[player.id];
        addListeners();
    }
}
function addListeners() {
    if (intro_player)
        intro_player.addModelListener('STATE', 'stateListener');
    else
        setTimeout('addListeners()',100);
}
function stateListener(obj) {
    if (obj.newstate == 'COMPLETED' || obj.newstate == 'IDLE') {
        homeState.startRotatingImages();
    }
}


// helper functions for get started
var modalizer;
function showGetStarted() {
    var dialog = $('get_started');
    if (dialog) {
        modalizer = new Modalizer();
        modalizer.modalShow();
        
        var top = window.getScroll().y + 30;
        var left = Math.max(0, (window.getSize().x - 506)/2);
        dialog.setStyles({ 'top': top + 'px', 'left': left + 'px', 'display': 'block' });
    }
}
function hideGetStarted() {
    if (modalizer) modalizer.modalHide();
    $('get_started').setStyle('display', 'none');
}
function toggleSection(n) {
    $('section-1').setStyle('display', n == 1 ? 'block' : 'none');
    $('section-2').setStyle('display', n == 2 ? 'block' : 'none');
    $('section-3').setStyle('display', n == 3 ? 'block' : 'none');
    $('section-4').setStyle('display', n == 4 ? 'block' : 'none');
    $('section-5').setStyle('display', n == 5 ? 'block' : 'none');
}

