var tutorials = null;

var cookie = {
    data: [],
    name: 'tutorials',

    path: function() {
        if (!this._path) {
            this._path = document.location.toString();
            this._path = '/'+this._path.replace(/http:\/\/[^\/]*\//, '').replace(/\/([^\/]*)\/.*/, '')+'/';
        }
        return this._path;
    },

    reset: function() {
        this.data = this.data.sort().uniq();
    },

    read: function() {
        if (this.data.length == 0) {
            // get the desired cookie and populate the internal data with it
            var cookies = document.cookie.split(';');
            cookies.each(function(cookie) {
                var cookie = cookie.toQueryParams();
                if (cookie[this.name]) {
                    var seen = cookie[this.name].split(',');
                    this.data = this.data.concat(seen);
                    this.reset();
                }
            }.bind(this));
        }

        return this.data;
    },

    set: function(id) {
        // set cookie to expire in 1 week
        var date = new Date();
        date.setDate(date.getDate()+7);
        date.toGMTString();

        // update the internal array
        this.data.push(id);
        this.reset();

        // figure out the cookie data string
        var string = this.data.join(',');
        if (!string.match(id)) {
            string = (string != '') ? string+','+id : id;
        }

        // set the cookie
        document.cookie = this.name+'='+string+'; expires='+date+'; path='+this.path()+'; domain=apple.com';
    }
}

// tracking delegate
var trackerDelegate = {
    sectionDidChange: function(tracker, view, incoming, id, properties) {
        if (typeof(properties.prop13) != 'undefined' && properties.prop13.match('V@S')) {
            properties.prop8 = 'Video View';
        }
        return properties;
    }
}

// tutorials delegate
var tutorialsDelegate = {
    url: false,

    createPosterLink: function(section) {
        // create the poster link if we're lazy
        if (!section.posterLink) {
            section.posterLink = new Element('a', { className:'posterLink', href:'http://images.apple.com/global/elements/overlay/overlay_movie_endstate_640x400_20081014.jpg' });
        }
    },

    createEndState: function(section) {
        // create the end state and replay button if we're lazy
        if (!section.endState) {
            var replay = new Element('a', { className:'replay pillbutton', href:'#'+section.id });
            replay.innerHTML = '<span>Watch again</span><b>&gt;</b>';
            if (replay) replay.observe('click', function(evt) {
                evt.stop();
                this.replayMovie();
            }.bindAsEventListener(section));

            section.endState = new Element('div', { className:'endState' });
            section.endState.appendChild(replay);
        }
    },

    createFeaturedNav: function(view, section) {
        if (!this.featuredNav) {
            this.featuredNav = view.sectionWithId(view.orderedSections[0]).content.down('#featurednav');
        }

        // add the featured nav
        section.content.appendChild(this.featuredNav);

        var active = this.featuredNav.down('a.active');
        if (active) {
            active.removeClassName('active');
        }

        var link = this.featuredNav.down('a[href*='+section.id+']');
        if (link) {
            link.addClassName('active');
        }
    },

    setVisited: function(section) {
        // set the visited class on the triggers
        section.triggers().each(function(trigger) {
            trigger.addClassName('visited');
        });
        // set a cookie to remember we visited this tutorial
        cookie.set(section.id);
    },

    didAppendContent: function(view, content) {
        var section = view.currentSection;
        if (section) {
            if (section.movieLink) {
                this.createPosterLink(section);
                this.createEndState(section);
                this.createFeaturedNav(view, section);
            }
            this.setVisited(section);
        }
   },

   didShow: function(view, outgoing, incoming) {
       if (!this.url) {
           this.url = document.location.toString().replace(/#.*/, '');
       } else if (incoming && incoming.id && !incoming.id.match('clicktoplay')) {
           document.location = this.url+'#'+incoming.id;
       }

       if (outgoing && !this.featuredNav) {
           this.featuredNav = outgoing.content.down('#featurednav');
       }
   }
}

Event.onDOMReady(function() {
    cookie.read();

    // click to play frame
    var hero = $('clicktoplay');
    hero.remove(); // for IE, ViewMaster will add it back

    var wrapper = new Element('a', { className:'controllerPanel tutorial-link', href:hero.down('a.pillbutton').href });
    hero.down('.movie').appendChild(wrapper);
    var fakeController = new AC.QuicktimeController();
    wrapper.appendChild(fakeController.render());
    fakeController = null; // for IE

    // initialize the tutorial swap view & set the delegate
    tutorials = new AC.ViewMaster.Viewer([hero], 'tutorial-container', 'tutorial-link', { shouldAnimateContentChange:false, defaultId:'clicktoplay' });
    tutorials.setDelegate(tutorialsDelegate);

    // click tracking and delegate
    tracker = new AC.ViewMaster.Tracker();
    tracker.setDelegate(trackerDelegate);

    // show the correct initial section for both swap views
    var id = document.location.hash.toString().replace('#', '');
    var section = $$('a.tutorial-link[href*='+id+']');
    tutorials.addSection(section[0]);
    tutorials.show(tutorials.sectionWithId(id));

    // set the visited links on the new content
    var visited = cookie.read();
    visited.each(function(visitedId) {
        var visitedLinks = $$('a.tutorial-link[href*='+visitedId+']');
        visitedLinks.each(function(visitedLink) {
            visitedLink.addClassName('visited');
        })
    });
});
