/* GENERIC TOOLTIP */
Tooltip = Class.create({
    TYPE: 'generic',
    effect: null,
    timer: null,
    locked: false,
    initialize: function(target, options) {
        this.target = $(target);
        this.element = new Element('div', {id:'tooltip'});
        if(this.target.rel && !this.target.rel.blank() && !Object.isArray(options)) {
            this.options = this.target.rel.replace('feed:', '').replace(' remove', '');
        } else {
            this.options = options || null;
        }
        
        this.attachEvents();
    },
    attachEvents: function() {
        this.target.observe('click', this.toggle.bindAsEventListener(this));  
    },
    show: function(event) {
        event.stop();
        
        if (this.timer != null) {
            window.clearTimeout(this.timer);
            this.timer = null;
        }
        this.timer = window.setTimeout(this.add.bind(this), 200);
    },
    hide: function(event, immediate) {
        if (this.timer) {
            window.clearTimeout(this.timer);
            this.timer = null;
        }
        if (this.element.descendantOf(document.body)) {
            if (!!immediate) {
                this.element.remove();
            } else {
                if (this.locked) {
                    return true;
                }
                this.timer = window.setTimeout(this.remove.bind(this),200);
            }
        }
    },
    add: function() {
        Tooltip.hideAll(null, this);
        $$('select').each(function(select) { select.setStyle({ visibility: 'hidden' }); });
        this.writeContent();
        document.body.appendChild(this.element);
        this.position();
    },
    remove: function(event) {
        if (event && event.stop) {
            event.stop();
        }
        $$('select').each(function(select) { select.setStyle({ visibility: 'visible' }); });
        window.clearTimeout(this.timer);
        this.timer = null;
        if (this.element.parentNode)
            this.element.remove();
    },
    toggle: function(event) {
        if (this.element.descendantOf(document.body)) {
            this.hide(event);
        } else {
            this.show(event);
        }
    },
    getTemplate: function() {
        return new Template('<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">#{content}</div></div><div class="bot"></div>');
    },
    position: function() {
        var position = this.target.cumulativeOffset();
        position.left += this.target.offsetWidth/2;
        position.top += this.target.offsetHeight;
        this.element.setStyle({left: position.left+'px', top: position.top+'px'})
    },
    writeContent: function() {
        this.element.className = this.TYPE+'_tooltip';
        this.element.update(this.getTemplate().evaluate({content:'This is a tooltip'}));
    },
    lock: function() {
        if (this.timer != null) {
            window.clearTimeout(this.timer);
            this.timer = null;
        }
        this.locked = true;
    },
    unlock: function() {
        this.locked = false;
    },
    unlockAndHide: function() {
        this.unlock();
        this.hide();
    }
});
Tooltip.tips = [];
Tooltip.hideAll = function(event, except) {
    Tooltip.tips.each(function(tip){
        if (tip!=except) { 
            tip.hide(event, true);
        }
    });
};
Tooltip.init = function() {
    // Preload tooltip images
    var images = [
        '/TooltipLib/schedule_bg-top.png',
        '/TooltipLib/schedule_bg-mid.png',
        '/TooltipLib/schedule_bg-bot.png',
        '/TooltipLib/schedule_flag.png',
        '/TooltipLib/schedule_flag_reverse.png',
        '/TooltipLib/favorite_bg-top.png',
        '/TooltipLib/favorite_bg-mid.png',
        '/TooltipLib/favorite_bg-bot.png',
        '/TooltipLib/favorite_flag.png',
        '/TooltipLib/login_bg-top.png',
        '/TooltipLib/login_bg-mid.png',
        '/TooltipLib/login_bg-bot.png',
        '/TooltipLib/login_input.png',
        '/TooltipLib/login_submit.png'
    ];
    Starz.preloadImages(images);
    
    // Add tooltip event listeners
    elements = $$('.has_tooltip');
    elements.each(function(element){
        if (element.className.match(/login/) && !element.className.match(/actor|director/)) {
            Tooltip.tips.push( new LoginTooltip(element) );
        } else {
            if (element.className.match(/schedule/)) {
                Tooltip.tips.push( new ScheduleTooltip(element) );
            }
            if (element.className.match(/actor|director/) && element.className.match(/login/)) {
                Tooltip.tips.push( new ActorLoginTooltip(element) );
            }
            if (element.className.match(/actor|director/)) {
                Tooltip.tips.push( new ActorTooltip(element) );
            }
            if (element.className.match(/genre/)) {
                Tooltip.tips.push( new GenreTooltip(element) );
            }
            if (element.className.match(/favorite/)) {
                Tooltip.tips.push( new FavoriteTooltip(element) );
            }
            if (element.className.match(/reminder/)) {
                Tooltip.tips.push( new ReminderTooltip(element) );
            }
            if (element.className.match(/rating/)) {
                Tooltip.tips.push( new RatingTooltip(element) );
            }
            if (element.className.match(/scheduleViewReminderIcon/)) {
                Tooltip.tips.push( new ReminderScheduleViewTooltip(element) );
            }
       
        }
    });
};
Tooltip.attach = function(element, type, options) {
    // don't uncomment this line please
    //$(element).addClassName('has_tooltip');
    if(options) {
        Tooltip.tips.push( new type(element, options) );
    } else {
        Tooltip.tips.push( new type(element) );
    }
}
Event.observe(window, 'load', Tooltip.init)

/*===========================================================================*/

/* ACTOR FAVORITES TOOLTIP */
ActorTooltip = Class.create(Tooltip, {
    TYPE: 'actor',
    attachEvents: function() {
        this.target.observe('click', this.show.bindAsEventListener(this));
    },
    getTemplate: function() {
        return new Template('<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">'+
            '#{content}'+'<p class="manage"><a href="/mystarz/myfavorites/">&raquo; Manage all favorites</a></p>'+
            '</div></div><div class="bot"></div>');        
    },
    getName: function() {
        return this.target.innerHTML;
    },
    getKind: function() {
        return this.target.hasClassName('actor') ? "actors" : "directors";
    },
    writeContent: function() {
        var template = new Template('<a href="#" class="cancel">&raquo; Cancel</a><p class="favorite">#{favorite}</p><p class="more">#{more}</p>');
        
        var favorite_content, more_content;
        var kind = this.getKind();
        var list_type = kind=="actors" ? "starring" : "directed by";
        
        if (this.target.rel=="add") {
            favorite_content = '<a href="#">Add '+this.getName()+'</a> to your favorite '+kind+' list';
        } else {
            favorite_content = '<a href="#">Remove '+this.getName()+'</a> from your favorite '+kind+' list';
        }
        more_content = '<a href="/search/starz/'+this.target.innerHTML+'">View more movies</a> '+list_type+' '+this.getName();
        
        var output = template.evaluate({favorite:favorite_content, more:more_content});
        output = this.getTemplate().evaluate({content: output});
        this.element.update(output);
        $(this.element.getElementsByTagName('a')[0]).observe('click', this.remove.bindAsEventListener(this));
        $(this.element.getElementsByTagName('a')[1]).observe('click', this.performRequest.bindAsEventListener(this));
    },
    position: function() {
        this.element.className = this.TYPE+'_tooltip';            

        var position   = this.target.cumulativeOffset();

        position.left += this.target.offsetWidth/2;
        position.top  += this.target.offsetHeight/2;
        this.element.setStyle({left: position.left+'px', top: position.top+'px'});
    },
    updateHref: function(request) {
        this.target.href = request.responseText;
    },
    performRequest: function(event, reload) {
        if(event) { event.stop(); }

        if (!/#$/.test(this.target.href)) {
            new Ajax.Request(this.target.href, {
                method: 'post',
                onComplete: function(transaction) {
                    if(reload) { window.location.reload(); } else { this.updateHref(transaction); }
                }.bind(this)
            });
        
            var output = '<p class="favorite"><strong>'+
                this.target.innerHTML+' '+(this.target.rel=="add" ? "added to" : "removed from")+
                ' your favorite '+this.getKind()+' list</strong></p>';
            output = this.getTemplate().evaluate({content: output});
            this.element.update(output);

            this.target.rel = this.target.rel=="add" ? "remove" : "add";
            
            // adding Omiture tracking
            new Tracking().Favorite(this.getKind().toUpperCase() + ' : ' + this.target.innerHTML);

            window.setTimeout(this.remove.bind(this), 2000);
        }
    }
});

/* RATINGS TOOLTIP */
RatingTooltip = Class.create(Tooltip, {
    TYPE: 'rating',
    attachEvents: function() {
        this.target.observe('click', this.show.bindAsEventListener(this));
    },
    getTemplate: function() {
        return '<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">'+
            '<a href="#" class="cancel">&raquo; Cancel</a><h4>Choose Your Rating</h4>'+
            '<p class="hearts"><a href="#"></a><a href="#"></a><a href="#"></a><a href="#"></a><a href="#"></a></p>'+
            '</div></div><div class="bot"></div>';        
    },
    writeContent: function() {
        this.element.update(this.getTemplate());
        this.hearts = this.element.select('p.hearts a');
        this.heartContainer = $(this.hearts[0].parentNode);
        this.hearts.each(function(link) {
            link.observe('mouseover', this.setRating.bindAsEventListener(this));
            link.observe('mouseout', this.clearRating.bindAsEventListener(this));
            link.observe('click', this.submitRating.bindAsEventListener(this));
        }, this);
        $(this.element.getElementsByTagName('a')[0]).observe('click', this.remove.bindAsEventListener(this));
    },
    position: function() {
        this.element.className = this.TYPE+'_tooltip';            

        var position   = this.target.cumulativeOffset();

        position.left += this.target.offsetWidth/2;
        position.top  += this.target.offsetHeight/2;
        this.element.setStyle({left: position.left+'px', top: position.top+'px'});
    },
    setRating: function(event) {
        var rating = this.hearts.indexOf(event.element());
        var ratings = $w("one two three four five");
        
        this.heartContainer.className = "hearts "+ratings[rating];
    },
    clearRating: function(event) {
        this.heartContainer.className = "hearts";
    },
    submitRating: function(event) {
        event.stop();

        // Submit Rating via Ajax
        var rating = this.hearts.indexOf(event.element())+1;
        new Ajax.Request(this.target.href, {
            method: 'post',
            parameters: {rating: rating}
        });
        
        this.remove();
    }
});

/* FAVORITE GENRE TOOLTIP */
GenreTooltip = Class.create(Tooltip, {
    TYPE: 'actor',
    attachEvents: function() {
        this.target.observe('click', this.show.bindAsEventListener(this));
    },
    getTemplate: function() {
        return new Template('<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">'+
            '#{content}'+
            '</div></div><div class="bot"></div>');        
    },
    getName: function() {
        return this.target.innerHTML;
    },
    getKind: function() {
        return this.target.hasClassName('actor') ? "actors" : "directors";
    },
    writeContent: function() {
        var favorite_content = '<a href="#" class="cancel">&raquo; Cancel</a><p class="favorite">';
        if (this.target.rel=="add") {
            favorite_content += '<a href="#">Add '+this.getName()+'</a> to your favorite genres list';
        } else {
            favorite_content += '<a href="#">Remove '+this.getName()+'</a> from your favorite genres list';
        }
        favorite_content += '</p>';
        output = this.getTemplate().evaluate({content: favorite_content});
        this.element.update(output);
        $(this.element.getElementsByTagName('a')[0]).observe('click', this.remove.bindAsEventListener(this));
        $(this.element.getElementsByTagName('a')[1]).observe('click', this.performRequest.bindAsEventListener(this));
    },
    position: function() {
        this.element.className = this.TYPE+'_tooltip';            

        var position   = this.target.cumulativeOffset();

        position.left += this.target.offsetWidth/2;
        position.top  += this.target.offsetHeight/2;
        this.element.setStyle({left: position.left+'px', top: position.top+'px'});
    },
    updateHref: function(request) {
        this.target.href = request.responseText;
    },
    performRequest: function(event) {
        event.stop();
        
        if (!/#$/.test(this.target.href)) {
            new Ajax.Request(this.target.href, {
                method: 'post',
                onComplete: this.updateHref.bind(this)
            });
        
            var output = '<p class="favorite"><strong>'+
                this.target.innerHTML+' '+(this.target.rel=="add" ? "added to" : "removed from")+
                ' your favorite genres list</strong></p>';
            output = this.getTemplate().evaluate({content: output});
            this.element.update(output);

            this.target.href = "#";
            this.target.rel = this.target.rel=="add" ? "remove" : "add";
            
            window.setTimeout(this.remove.bind(this), 2000);
        }
    }
});


/* SCHEDULE MOVIE DETAIL TOOLTIP */
ScheduleTooltip = Class.create(Tooltip, {
    TYPE: 'schedule',
    WIDTH: 263,
    attachEvents: function() {
        this.titleContent = this.target.title;
        this.target.title = '';
        this.target.select('a')[0].observe('mouseover', this.show.bindAsEventListener(this));
        this.target.select('a')[0].observe('mouseout', this.hide.bindAsEventListener(this));
        this.element.observe('mouseover', this.lock.bindAsEventListener(this), true);
        this.element.observe('mouseout', this.unlockAndHide.bindAsEventListener(this), true);
    },
    writeContent: function() {
        this.element.className = this.TYPE+'_tooltip';
        var url = this.titleContent;

        if (ScheduleTooltip.Cache[url]) {
            var content = this.getTemplate().evaluate({content: ScheduleTooltip.Cache[url]})
            this.element.update(content);
        } else {
            new Ajax.Request(url, {
                method: 'get',
                onComplete: this.onContentLoaded.bind(this, url)
            });
        }
    },
    onContentLoaded: function(id, request) {
        ScheduleTooltip.Cache[id] = request.responseText;
        var content = this.getTemplate().evaluate({content: request.responseText})
        this.element.update(content);
    },
    position: function() {
        this.posTarget = this.target.select('a')[0];
        var position   = this.posTarget.cumulativeOffset();
        var leftOffset = this.posTarget.offsetWidth;
        var topOffset  = this.posTarget.offsetHeight-5
                
        if (position.left+leftOffset+this.WIDTH+10 > document.body.clientWidth) {
            this.element.className = this.TYPE+'_tooltip_reverse';
            leftOffset = 0;
        } else {
            this.element.className = this.TYPE+'_tooltip';            
        }
        
        position.left += leftOffset;
        position.top  += topOffset;
        this.element.setStyle({left: position.left+'px', top: position.top+'px'})
    }
});
ScheduleTooltip.Cache = {};

/* SCHEDULE FAVORITE MOVIE & REMINDER TOOLTIPS */
FavoriteAndReminderPrototype = {
    attachEvents: function() {
        this.target.observe('click', this.show.bindAsEventListener(this));  
    },
    show: function(event) {
        event.stop();
        if (this.timer != null) {
            window.clearTimeout(this.timer);
            this.timer = null;
        }
        this.add();
        this.timer = window.setTimeout(this.hide.bind(this), 4000);
    },
    getTemplate: function() {
        return new Template('<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">'+
            '<h4>#{headline}</h4>#{extra}<a href="/mystarz/#{prefPage}">&raquo; #{tagLine}</a>'+
            '</div></div><div class="bot"></div>');        
    },
    position: function() {
        this.element.className = this.TYPE+'_tooltip';            

        var position   = this.target.cumulativeOffset();
        var topOffset  = -(this.element.offsetHeight-10);
        var leftOffset = this.target.offsetWidth/2;

        position.left += leftOffset;
        position.top  += topOffset;
        this.element.setStyle({left: position.left+'px', top: position.top+'px'})
    },
    getMovie: function() {
        if (this.movie) {
            return this.movie;
        } else {
            this.movie = $(this.target).up('li');
            return this.movie;
        }
    },
    updateHref: function(request) {
        this.target.href = request.responseText;
        //alert("here...");
//        if(this.getMovie().className == 'reminder')
//        {
//             this.getMovie().removeClassName('reminder');
//             this.getMovie().addClassName('reminder_set');
//        }

        if(typeof this.getMovie() == 'undefined') {
            if(this.target.rel == 'add' && this.target.innerHTML == 'Add to Favorites') {
                this.target.innerHTML = 'Remove from Favorites';
                this.target.rel = 'remove';
                this.target.addClassName('favorited');
            } else if(this.target.rel == 'remove' && this.target.innerHTML == 'Remove from Favorites'){
                this.target.innerHTML = 'Add to Favorites';
                this.target.rel = 'add';
                this.target.removeClassName('favorited');
            }
        }
        this.renderUI();
    },
    renderUI: function(){
    },
    performRequest: function() {
        if (!/#$/.test(this.target.href)) {
            new Ajax.Request(this.target.href, {
                method: 'post',
                onComplete: this.updateHref.bind(this)
            });
        }
    }
};
FavoriteTooltip = Class.create(Tooltip, FavoriteAndReminderPrototype);
Object.extend(FavoriteTooltip.prototype, {
    TYPE: 'favorite',
    writeContent: function() {
        this.performRequest();
        
        var headline;
        if (this.isFavorite()) {
            if (this.getMovie()) {
                this.getMovie().removeClassName('favorite');
            }
            headline = 'Removed From Favorite Movies';       
        } else {
            try {
                var tracking = new Tracking();
                if (Object.isArray(this.options)) {
                    tracking.Favorite(this.options[1]);
                } else {
                   tracking.Favorite(window.s.pageName);
                }
            } catch(e) { }

            if (this.getMovie()) {
                this.getMovie().addClassName('favorite');
            }
            headline = 'Added to Favorite Movies';       
        }
        this.element.update(this.getTemplate().evaluate({headline: headline, prefPage: 'myfavorites', tagLine: 'Manage All Favorites'}));
    },
    isFavorite: function() {
        var movie = this.getMovie();
        if (typeof movie == "undefined") {
            return this.target.rel=="remove";
        } else {
            return movie.hasClassName('favorite');
        }
    }
});
ReminderTooltip = Class.create(Tooltip, FavoriteAndReminderPrototype);
Object.extend(ReminderTooltip.prototype, {
    TYPE: 'reminder',
    writeContent: function() {
        this.element.className = this.TYPE+'_tooltip';  
        this.performRequest();
    },
    renderUI: function(){
        var headline;
        if (this.hasReminder()) {
            if (this.getMovie()) {
                this.getMovie().removeClassName('reminder');
            }
            this.target.writeAttribute('rel', '');

            headline = 'Reminder Removed';  
            this.target.removeClassName('reminder_set');
            this.target.addClassName('reminder');
        } else {
            var canReminderBeSet = true;
            var linear = true;
            // Check whether it is OD or linear as the message varies
            var href = this.target.href;
            if (href != undefined) {
                // extract OD and exhib_dtm
                if (href.indexOf('&OD') > 0)
                    linear = false;
            }
            
            if (linear == true) {
                // Reminder for linear program
                canReminderBeSet = this.checkIfReminderCanbeSet(href, linear);
                headline = "This title will be airing in the next 12 hours and therefore a reminder can no longer be set.  Click the title name to see future air dates.";
            } 
            else {
                // Reminder for OD program
                canReminderBeSet = this.checkIfODReminderCanbeSet(href, linear);
                headline = "A reminder for this title can no longer be set. This title will be available on demand for the next 24 hours.";
            }
            
            if (canReminderBeSet == true) {
                try {
                    var tracking = new Tracking();
                    if (Object.isArray(this.options)) {
                        tracking.Reminder(this.options[1]);
                    } else {
                       tracking.Reminder(window.s.pageName);
                    }
                } catch(e) { }

//                if (this.getMovie()) {
//                    this.getMovie().addClassName('reminder');
//                }
                if(href.indexOf('reminderSet=false')==-1) 
                {
                    headline = 'Reminder Set'; 
                    this.target.writeAttribute('rel', 'remove');
                    this.target.removeClassName('reminder');
                    this.target.addClassName('reminder_set');
                }
               
                if(href.indexOf('reminderSet=false')!=-1) 
                {
                    headline = "You will not receive an email reminder. If you wish to receive email reminders in the future, you must update your user preferences.";
                    this.target.removeClassName('reminder_set');
                    this.target.addClassName('reminder');
                   
                    
                }
            } else {
                if (this.getMovie()) {
                    this.getMovie().removeClassName('reminder');
                }
               
                this.target.writeAttribute('rel', '');
                this.target.removeClassName('reminder_set');
                ///this.target.addClassName('reminder');
            }
        }
        var zonefeed = (Object.isArray(this.options)) ? this.options[0] : this.options;
        if(zonefeed && zonefeed.capitalize() != "Add" && ScheduleTooltip.TIMEZONE != "undefined") {
            feed = '<p>'+Schedule.TIMEZONE+' '+zonefeed.capitalize()+' Feed <a href="/mystarz/myschedule/">&raquo; Change</a></p>';
        } else {
            feed = '';
        }
        
        this.element.update(this.getTemplate().evaluate({headline: headline, prefPage: 'myreminders', extra: feed, tagLine: 'Manage All Reminders'}));
        this.position();
    },
    
    getExhibDate: function(href, linearFlag) {
        if (linearFlag == false) {
            var str = href.substring(href.indexOf('exhib_dtm=') + 10, href.indexOf('&OD'));
            var newStr = str.replace(/%20/g, ' ');
            var exhib_dtm = new Date(newStr);
            return exhib_dtm;
        } else if (linearFlag == true) {
            var str = href.substring(href.indexOf('exhib_dtm=') + 10, href.indexOf('&action'));
            var newStr = str.replace(/%20/g, ' ');
            var exhib_dtm = new Date(newStr);
            return exhib_dtm;
        }
    },
    
    checkIfReminderCanbeSet: function(href, linearFlag) {
        // First get the exhib_dtm which will be newDate
        var newDate = this.getExhibDate(href, linearFlag);
        var today = new Date();
        
        // Compare two dates
        var timeDiffInMin = newDate.getTime() - today.getTime();
        timeDiffInMin = Math.floor((newDate.getTime() - today.getTime())/1000/60);

        // 720 minutes represents 12 hours
        if (timeDiffInMin <= 720) {
            return false;
        } else {
            return true;
        }
    },
    checkIfODReminderCanbeSet: function(href, linearFlag) {
        // First get the exhib_dtm which will be newDate
        var newDate = this.getExhibDate(href, linearFlag);
        var today = new Date();

        // Compare two dates
        var timeDiffInMin = Math.floor((newDate.getTime() - today.getTime())/1000/60);
        
        // 1440 minutes represents 24 hours
        if (timeDiffInMin <= 1440) {
            return false;
        } else {
            return true;
        }
    },
    
    hasReminder: function() {
        var movie = this.getMovie();
        if (typeof movie == "undefined") {
            return this.target.rel == 'remove';
        } else {
            return movie.hasClassName('reminder') || this.target.hasClassName('reminder_set');
        }
    }
});

/* LOGIN TOOLTIP */
LoginTooltip = Class.create(Tooltip, {
    TYPE: 'login',
    WIDTH: 330,
    attachEvents: function() {
        this.target.observe('click', this.show.bindAsEventListener(this));
    },
    getTemplate: function() {
        // Apologies for the ugliness
        return new Template('<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">' +
            '<a href="#" id="LoginCancel">&raquo; Cancel</a>' +
            '<h4>Log In to #{title}</h4>' +
            '<div class="prompt">#{prompt}</div>' +
            '<div class="form"><form action="/ajax/ScheduleLogin.aspx" id="login-Form">' +
            '<input type="text" name="username" id="login-Username" value="Username" onfocus="if (this.value==\'Username\') this.value=\'\'" onblur="if (this.value==\'\') this.value=\'Username\'" />' +
            '<span id="fauxPassword"><input type="text" value="Password" readonly="readonly" onfocus="$(\'fauxPassword\').style.display=\'none\'; $(\'realPassword\').style.display=\'block\'; $(\'realPassword\').getElementsByTagName(\'input\')[0].focus();"></span>' +
            '<span id="realPassword" style="display: none">' +
            '<input type="password" value="" name="password" id="login-Password" onblur="if (this.value==\'\'){ $(\'realPassword\').style.display=\'none\'; $(\'fauxPassword\').style.display=\'block\'; }">' +
            '</span><span class="remember"><input type="checkbox" checked="checked" id="login-Remember" name="remember" /> <label for="remember">Remember Me</label></span>' +
            '<button id="login-Submit" type="submit">Login</button><span id="login-Progress" style="display: none"><b>Logging In&hellip;</b></span></form></div>' +
            '<br style="display: block; height: 0px; clear: left"></div></div><div class="bot"></div>');
    },
    writeContent: function() {
        var title = this.target.className == "reminder" ? "Set Reminders" : (this.target.className == "favorite" ? "Set Favorites" : "Starz.com");
        var prompt = '<p><span>Not a member yet?</span> Get reminders, rate movies and customize your schedule for free. Registered on old site? <a href="/recoverpassword">Click here for password.</a></p>' +
        '<p><a href="/register">&raquo; Register Now</a><br /><a href="/recoverpassword">&raquo; Forgot Password?</a></p>';
        this.element.update(this.getTemplate().evaluate({ title: title, prompt: prompt }));
        $(this.element.getElementsByTagName('a')[0]).observe('click', this.remove.bindAsEventListener(this));
        this.element.select('form')[0].observe('submit', this.attemptLogin.bindAsEventListener(this));
    },
    showForgotForm: function(event) {
        event.stop();
        var inputValue = ($('login-Username').value == 'Username') ? 'Email Address' : $('login-Username').value;
        var output = '<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">' +
            '<a href="#" id="LoginCancel">&raquo; Cancel</a>' +
            '<h4>Recover Your Password</h4>' +
            '<div class="prompt"><p><span>Need to recover your password?</span> Enter your email address and we\'ll email you your password.</p></div>' +
            '<div class="form"><form action="/recoverpassword" id="login-ResetPassword" method="post">' +
            '<input type="text" name="email" id="login-Email" value="' + inputValue + '" onfocus="if (this.value==\'Email Address\') this.value=\'\'" onblur="if (this.value==\'\') this.value=\'Email Address\'" />' +
            '<button id="login-Submit" type="submit">Submit</button></form></div>' +
            '<br style="display: block; height: 0px; clear: left"></div></div><div class="bot"></div>';
        this.element.update(output);
        $(this.element.getElementsByTagName('a')[0]).observe('click', this.remove.bindAsEventListener(this));
        this.position();
    },
    position: function() {
        var header = this.target.hasClassName('login_header');
        var flag = this.element.down('.flag');
        this.element.className = this.TYPE + (header ? '_header' : '') + '_tooltip';

        var position = this.target.cumulativeOffset();
        var topOffset = header ? this.target.offsetHeight : -(this.element.offsetHeight - 10);
        var leftOffset = Math.floor(this.target.offsetWidth / 2);
        var flagOffset = flag.getStyle('left').replace('px', '');

        if (document.viewport.getScrollOffsets()[1] > (position.top - this.element.offsetHeight)) {
            topOffset = this.target.offsetHeight;
            this.element.className = this.TYPE + '_header_tooltip';
        }

        if (position.left + leftOffset + this.WIDTH - flagOffset > document.body.clientWidth) {
            var positionLeft = position.left + (flagOffset - this.WIDTH + (document.body.clientWidth - position.left - leftOffset));
            var flagLeft = position.left - (positionLeft + leftOffset) - this.element.getStyle('margin-left').replace('px', '');
            if (Prototype.Browser.IE) {
                flagLeft = flagLeft - (flag.offsetWidth / 2);
            }
            position.left = positionLeft;
            flag.setStyle({ left: flagLeft + 'px' });
        }

        position.left += leftOffset;
        position.top += topOffset;
        this.element.setStyle({ left: position.left + 'px', top: position.top + 'px' });
    },
    attemptLogin: function(event) {
        event.stop();
        //debugger;
        new Ajax.Request($('login-Form').action, {
            method: 'post',
            parameters: {
                username: encodeURIComponent($('login-Username').value),
                password: encodeURIComponent($('login-Password').value),
                remember: $('login-Remember').getValue()
            },
            onFailure: this.loginFail.bind(this),
            onSuccess: this.loginSuccess.bind(this)
        });
        $('login-Submit').hide();
        $('login-Progress').show();
        this.position();
    },
    loginFail: function() {
        $('login-Submit').show();
        $('login-Progress').hide();
        $('login-Password').value = "";
        var forgot_password = '<p><span class="error">Username/Password was incorrect.</span> Please try logging in again. Registered on old site? <a href="/recoverpassword">Click here for password.</a></p>' +
            '<p><a href="/register">&raquo; Register Now</a><br /><a href="/recoverpassword">&raquo; Forgot Password?</a></p>';
        this.element.select('div.prompt')[0].update(forgot_password);
        $('login-ForgotPassword').observe('click', this.showForgotForm.bindAsEventListener(this));
        this.position();
    },
    loginSuccess: function() {
        window.location.reload();
    }
});

/* ACTOR LOGIN TOOLTIP */
ActorLoginTooltip = Class.create(ActorTooltip, {
    TYPE: 'actor',
    getName: function() {
        return this.target.innerHTML;
    },
    getKind: function() {
        return this.target.hasClassName('actor') ? "actors" : "directors";
    },
    getTemplate: function() {
        return new Template('<div class="flag"></div><div class="top"></div><div class="mid"><div class="content">'+
            '<a href="#" class="cancel">&raquo; Cancel</a>'+
            '<p class="favorite"><a href="#">Log in to add #{title}</a> to your favorite #{type}</p>'+
            '<div class="loginbox" style="display: none;"><h4>Log in to add #{title} to your favorite #{type}</h4>'+
            '<div class="prompt">#{prompt}</div>'+
            '<div class="form"><form action="/ajax/ScheduleLogin.aspx" id="login-Form">'+
            '<input type="text" name="username" id="login-Username" value="Username" onfocus="if (this.value==\'Username\') this.value=\'\'" onblur="if (this.value==\'\') this.value=\'Username\'" />'+
            '<span id="fauxPassword"><input type="text" value="Password" readonly="readonly" onfocus="$(\'fauxPassword\').style.display=\'none\'; $(\'realPassword\').style.display=\'block\'; $(\'realPassword\').getElementsByTagName(\'input\')[0].focus();"></span>'+
            '<span id="realPassword" style="display: none">'+
            '<input type="password" value="" name="password" id="login-Password" onblur="if (this.value==\'\'){ $(\'realPassword\').style.display=\'none\'; $(\'fauxPassword\').style.display=\'block\'; }">'+
            '</span><span class="remember"><input type="checkbox" checked="checked" id="login-Remember" name="remember" /> <label for="remember">Remember Me</label></span>'+
            '<button id="login-Submit" type="submit">Login</button><span id="login-Progress" style="display: none"><b>Logging In&hellip;</b></span></form></div></div>'+
            '<p class="more">#{more}</p>'+
            '</div></div><div class="bot"></div>');        
    },
    writeContent: function() {
        var prompt= '<p><span>Not a member yet?</span> Get reminders, rate movies and customize your schedule for free. Registered on old site? <a href="/recoverpassword">Click here for password.</a></p>'+
        '<p><a href="/register">&raquo; Register Now</a><br /><a href="/recoverpassword">&raquo; Forgot Password?</a></p>';
        
        var list_type = (this.getKind()=="actors") ? "starring" : "directed by";
        var favorite_content = '<a href="#">Log in to add '+this.getName()+'</a> to your favorite '+this.getKind()+' list';
        var more_content = '<a href="/search/starz/'+this.target.innerHTML+'">View more movies</a> '+list_type+' '+this.getName();
        
        this.element.update(this.getTemplate().evaluate({
            type: this.getKind(),
            title: this.getName(),
            prompt: prompt, 
            content: favorite_content, 
            more: more_content 
        }));
        this.element.select('a.cancel')[0].observe('click', this.remove.bindAsEventListener(this));
        this.element.select('.favorite a')[0].observe('click', this.showLogin.bindAsEventListener(this));
    },
    showLogin: function(event) {
        event.stop();
        this.element.select('.loginbox')[0].show();
        this.element.addClassName('actorlogin_tooltip');
        this.element.select('form')[0].observe('submit', this.attemptLogin.bindAsEventListener(this));
    },
    showForgotForm: function(event) {
        event.stop();
        var inputValue = ($('login-Username').value == 'Username') ? 'Email Address' : $('login-Username').value;
        var output = '<h4>Recover Your Password</h4>'+
            '<div class="prompt"><p><span>Need to recover your password?</span> Enter your email address and we\'ll email you your password.</p></div>'+
            '<div class="form"><form action="/recoverpassword" id="login-ResetPassword" method="post">'+
            '<input type="text" name="email" id="login-Email" value="'+inputValue+'" onfocus="if (this.value==\'Email Address\') this.value=\'\'" onblur="if (this.value==\'\') this.value=\'Email Address\'" />'+
            '<button id="login-Submit" type="submit">Submit</button></form>';
        this.element.select('.loginbox')[0].update(output);
    },
    attemptLogin: function(event) {
        event.stop();
        
        new Ajax.Request($('login-Form').action, {
            method: 'post',
            parameters: {
                username: encodeURIComponent($('login-Username').value),
                password: encodeURIComponent($('login-Password').value),
                remember: $('login-Remember').getValue()
            },
            onFailure: this.loginFail.bind(this),
            onSuccess: this.loginSuccess.bind(this)
        });
        $('login-Submit').hide();
        $('login-Progress').show();
    },
    loginFail: function() {
        $('login-Submit').show();
        $('login-Progress').hide();
        
        var forgot_password = '<p><span class="error">Username/Password was incorrect.</span> Please try logging in again. Registered on old site? <a href="/recoverpassword">Click here for password.</a></p>'+
            '<p><a href="#" id="login-ForgotPassword">&raquo; Forgot Password?</a></p>';
        this.element.select('div.prompt')[0].update(forgot_password);
        $('login-Password').value = "";
        $('login-ForgotPassword').observe('click', this.showForgotForm.bindAsEventListener(this));
    },
    loginSuccess: function() {
        this.performRequest(null, true);
    }
});

