var tab = null, tutorials = null, url = null;

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

    path: function() {
        if (!this._path) {
            this._path = document.location.toString();
            this._path = this._path.replace(/http:\/\/[^\/]*/, '');
            this._path = this._path.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';
    }
}

// didShow delegate for both the tabs (apps) and the tutorials view masters
var didShow = function(view, outgoing, incoming) {
    if (!url) {
        url = document.location.toString().replace(/#.*/, '');
    }

    if (incoming && !incoming.id.match('[^-]*-hero')) {
        document.location = url+'#'+incoming.id;
    }
}

var tabsDelegate = {
    didShow: didShow,
    didAppendContent: function(view, content) {
        var section = view.currentSection;
        if (section) {
            if (!section.initialLoad) {
                // create the hero section
                if (!tutorials.sectionWithId(section.id+'-hero')) {
                    var hero = new Element('a', { className:'tutorial-link', href:cookie.path()+section.id+'/hero.html#'+section.id+'-hero' });
                    tutorials.addSection(hero);
                }

                // set the visited links on the new content
                var visited = cookie.read();
                visited.each(function(visitedId) {
                    if (visitedId.match(section.id)) {
                        var visitedLink = section.content.down('a[href$='+visitedId+']');
                        if (visitedLink) {
                            visitedLink.addClassName('visited');
                        }
                    }
                });
            }

            // load the default tutorial for this tab (app)
            var initialSection = section.content.down('a[href$='+view.initialId+']');
            if (view.initialId && initialSection) {
                tutorials.addSection(initialSection);
                tutorials.show(tutorials.sectionWithId(view.initialId));
                view.initialId = null;
            } else if (tutorials.sectionWithId(section.id+'-hero')) {
                tutorials.show(tutorials.sectionWithId(section.id+'-hero'));
            }

            section.initialLoad = true;
        }
    }
}

var tutorialsDelegate = {
    didShow: didShow,
    didAppendContent: function(view, content) {
        var section = view.currentSection;
        if (section) {
            if (section.movieLink) {

                // 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' });
                }

                // 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);
                }
            }


            // select the featured nav items if applicable
            if (content) {
                var otherLinks = content.select('.'+view.triggerClassName);
                otherLinks.each(function(link) {
                    var id = link.href.replace(/.*#/, '');
                    if (id.match(section.id)) {
                        link.addClassName('active');
                    }
                });
            }

            // 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);
        }
    }
}

var trackerDelegate = {
    trackingNameForSection: function(tracker, name, section) {
        if (name.match('[^-]*-hero')) {
            return;
        } else {
            return name;
        }
    },    

    sectionDidChange: function(tracker, view, incoming, id, properties) {
        properties.prop8 = 'Video View';
        return properties;
    }
}

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

    // initialize the tutorial swap view & set the delegate
    tutorials = new AC.ViewMaster.Viewer(null, 'tutorial-container', 'tutorial-link');
    tutorials.setDelegate(tutorialsDelegate);

    // initialize the tab (app) swap view & set the delegate
    tabs = new AC.ViewMaster.Viewer(null, 'tutoriallist-container', 'tutoriallist-link');
    tabs.setDelegate(tabsDelegate);

    // add the sections to the tab (app) swap view later, so we don’t use the
    // inherit view master initialization that shows the first section
    var content = $$('ul.tutorialnav li a.tutoriallist-link');
    content.each(function(section) {
        tabs.addSection(section);
    });

    // click tracking and delegate
    tracker.setDelegate(trackerDelegate);

    // show the correct initial section for both swap views
    var id = document.location.hash.toString().replace('#', '');
    if (id && id.match('-')) {
        var tab = id.split('-')[0];
    }
    if (tabs.sectionWithId(id) || tabs.sectionWithId(tab)) {
        if (tabs.sectionWithId(tab)) {
            tabs.show(tabs.sectionWithId(tab));
            tabs.initialId = id;
        } else {
            tabs.show(tabs.sectionWithId(id));
        }
    } else {
        tabs.show(tabs.sectionWithId(tabs.orderedSections[0]));
    }
});
