/* From http://javascript.crockford.com/remedial.html */
String.prototype.entityify = function () {
    return this.replace(/&/g, "&amp;").replace(/</g,
        "&lt;").replace(/>/g, "&gt;");
};

String.prototype.quote = function () {
    var c, i, l = this.length, o = '"';
    for (i = 0; i < l; i += 1) {
        c = this.charAt(i);
        if (c >= ' ') {
            if (c === '\\' || c === '"') {
                o += '\\';
            }
            o += c;
        } else {
            switch (c) {
            case '\b':
                o += '\\b';
                break;
            case '\f':
                o += '\\f';
                break;
            case '\n':
                o += '\\n';
                break;
            case '\r':
                o += '\\r';
                break;
            case '\t':
                o += '\\t';
                break;
            default:
                c = c.charCodeAt();
                o += '\\u00' + Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }
        }
    }
    return o + '"';
};

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
};

/* PRUNTI code */

PRUNTI = {};

PRUNTI.BusyIndicator = {
    centredOnElement: null,
    
    activate: function() {
        var c = PRUNTI.BusyIndicator.centredOnElement;
        
        if($('busy_indicator')) {
            $('busy_indicator').setStyle({position: 'absolute'});
            if (c) {
                var targetOffset = c.viewportOffset();
                var targetDims = c.getDimensions();
                var busyDims = $('busy_indicator').getDimensions();
                var left = targetOffset[0] - (busyDims.width / 2) + (targetDims.width / 2);
                var top = targetOffset[1] - (busyDims.height / 2) + (targetDims.height / 2);
                
                $('busy_indicator').setStyle({
                        top: top + 'px',
                        left: left + 'px'
                            });
            }
            Element.show('busy_indicator');
        }
    },
    
    deactivate: function() {
        if($('busy_indicator')) {
            Element.hide('busy_indicator');
        }
    },

    centreOn: function (elementOrId) {
        PRUNTI.BusyIndicator.centredOnElement = $(elementOrId);
    }
};

PRUNTI.Effects = {
    openClose: function(id) {
        var element = $(id);
        if (element.visible()) {
            element.hide();
        }
        else {
            element.show();
        }
        return false;
    },
    toggleTruncatedText: function(blockId) {
        var truncatedElement = $('truncated-' + blockId);
        var fullElement = $('full-' + blockId);
        if (truncatedElement.visible()) {
            truncatedElement.hide();
            fullElement.show();
        }
        else {
            truncatedElement.show();
            fullElement.hide();
        }
        return false;
    },

    /**
     * eg. showSingleElementFrom(1, 'box1', 'box2')
     *   -> hides box1 and shows box2
     * @param int 0-based index of dom element to show
     * @param mixed string id or object dom element
     * @param ...
     */
    showSingleElementFrom: function() {
        var args = $A(arguments);
        var pos = args.shift();
        args.each(function(v, i) {
                if (i==pos) {
                    $(v).show();
                }
                else {
                    $(v).hide();
                }
            });
    }
};

PRUNTI.InvitationForm = {
    openClosePreview: function() {
        var previewElement = $('preview');
        if (previewElement.visible()) {
            previewElement.hide();
        }
        else {
            previewElement.show();
        }
        return false;
    },
    onLoad: function() {
    },
    onPlaxoAddressbookComplete: function() {
        var addressList, nextEmptyRow, numberOfRowsCreated, rowsNeeded, blankRows;

        function addNewRows(numRows) {
            var template = new Template('<tr id="invitation_grid_row_#{rowNum}"><td><input id="first_name_#{rowNum}" name="first_name[#{rowNum}]" value="" /></td><td><input id="last_name_#{rowNum}" name="last_name[#{rowNum}]" value="" /></td><td><input id="email_#{rowNum}" name="email[#{rowNum}]" value="" /></td></tr>');
            var htmlToAppend = '';
            var templateVars = { rowNum: numberOfRowsCreated + 1 };
            for (var i=0; i<numRows; i++) {
                htmlToAppend += template.evaluate(templateVars);
                templateVars.rowNum++;
                numberOfRowsCreated++;
            }
            new Insertion.Bottom($('invitation_grid'), htmlToAppend);
        };
        function findFirstEmptyRow() {
            for(var i=1; i<=numberOfRowsCreated; i++) {
                if(isRowEmpty(i))
                    return i;
            }
            return numberOfRowsCreated + 1;
        };
        function isRowEmpty(row) {
            var inputs = $$('#invitation_grid #invitation_grid_row_' + row + ' td input');
            var values = inputs.map(function(v) {return v.type == 'checkbox' ? '' : v.value;});
            var isEmpty = true;
            values.each(function(v) {
                    if (v.length > 0) {
                        isEmpty = false;
                    }
                });
            return isEmpty;
        };
        function addInvitee(email) {
            $('first_name_' + nextEmptyRow).value = email.firstName;
            $('last_name_' + nextEmptyRow).value = email.lastName;
            $('email_' + nextEmptyRow).value = email.address;
            nextEmptyRow++;
        };
        function parseEmail(email) {
            var match = /^"(([^"]*) )?([^ "]*)" <([^>]*)>$/.exec(email);
            var email;
            if (match) {
                email = {};
                if (match[2]) {
                    email.firstName = match[2];
                    email.lastName = match[3];
                }
                else {
                    email.firstName = match[3];
                    email.lastName = '';
                }
                email.address = match[4];
                return email;
            }
            return null;
        };
        function extractEmailAddresses(list) {
            var emails = [], email;
            
            $('plaxo_email_list').value.split(/, ?/).each(function(v,k) {
                    email = parseEmail(v);
                    if (email) {
                        emails.push(email);
                    }
                }
                );
            return emails;
        };


        numberOfRowsCreated = 5;
        addressList = extractEmailAddresses($('plaxo_email_list').value);
        nextEmptyRow = findFirstEmptyRow();
        blankRows = numberOfRowsCreated - nextEmptyRow + 1;
        rowsNeeded = addressList.length - blankRows;
        addNewRows(rowsNeeded);
        
        addressList.each(addInvitee);
    }
    
};

PRUNTI.UpdateLoanStatusForm = {
    openCloseNotSentYet: function() {
        var previewElement = $('preview');
        if (previewElement.visible()) {
            previewElement.hide();
        }
        else {
            previewElement.show();
        }
        return false;
    }
};

PRUNTI.AddressForm = {
    openClosePermanentAddress: function() {
        var previewElement = $('permanentAddress');
        if (previewElement.visible()) {
            previewElement.hide();
            $('permanent_address_different').value='';
            PRUNTI.AddressForm.enablePermanent(false);
        }
        else {
            previewElement.show();
            PRUNTI.AddressForm.copyFromCurrent();
            PRUNTI.AddressForm.enablePermanent(true);
            $('permanent_address_different').value='1';
        }
        return false;
    },
    copyFromCurrent: function() {
        var name, fromName, toName;
        $$('#currentAddress input').each(function(elem, index) {
                toName = elem.name.replace(/current-/, 'permanent-');
                $(toName).value = elem.value;
        });
        $$('#currentAddress select').each(function(elem, index) {
                toName = elem.name.replace(/current-/, 'permanent-');
                $(toName).value = elem.value;
        });
        return false;
    },
    enablePermanent: function(enable) {
        var name, fromName, toName;
        $$('#permanentAddress input').each(function(elem, index) {
                toName = elem.disabled = !enable;
        });
        $$('#permanentAddress select').each(function(elem, index) {
                toName = elem.disabled = !enable;
        });
    },
    onLoad: function() {
        PRUNTI.AddressForm.enablePermanent($('permanent_address_different').value);
    },
    usFormCountryChanged: function(prefix) {
        return function(e) {
            var iso2 = this.options[this.selectedIndex].value;
            if (iso2 == 'US') {
                $(prefix + 'us-states').show();
                $(prefix + 'us-postcode').show();
                $(prefix + 'ca-states').hide();
                $(prefix + 'ca-postcode').hide();
            }
            else {
                $(prefix + 'us-states').hide();
                $(prefix + 'us-postcode').hide();
                $(prefix + 'ca-states').show();
                $(prefix + 'ca-postcode').show();
            }
        }
    }
};

PRUNTI.TabbedNavigation = {
    init: function () {
        var i=0, id;
        var a= $$('#tabbar li a.tab').each(function(e, i) {
             var menuSrcElem, theTab;
             if (e.parentNode.parentNode.getElementsByClassName('yuimenu').length) {
                 menuSrcElem = e.parentNode.parentNode.getElementsByClassName('yuimenu')[0];
                 var oMenu = new YAHOO.widget.Menu(menuSrcElem, { context: [e, 'tl', 'bl'], iframe: false});
                 oMenu.render();
                 id='darr'+i; i++;
                 new Insertion.After(e, '<img src="/images/darr.gif" class="darr" id="'+id+'"></img>');
                 $(id).observe('click', function() { oMenu.show()});
             }
    
             theTab = e.parentNode.parentNode;
             e.parentNode.parentNode.observe('mouseover', function(event) {
                 theTab.addClassName('hover');
             });
             e.parentNode.observe('mouseover', function(event) {
                 theTab.addClassName('hover');
             });
             e.observe('mouseover', function(event) {
                 theTab.addClassName('hover');
             });
             e.parentNode.parentNode.observe('mouseout', function(event) {
                 theTab.removeClassName('hover');
             });
             e.parentNode.observe('mouseout', function(event) {
                 theTab.removeClassName('hover');
             });
             e.observe('mouseout', function(event) {
                 theTab.removeClassName('hover');
             });
            });
    }
};

PRUNTI.TranslationBox = {
    dismiss: function() {
        $('translation-box').style.display='none';
        return false;
    },
    toggle: function() {
        if ($('translation-box').style.display == 'block') {
            $('translation-box').style.display='none';
        }
        else {
            $('translation-box').style.display='block';
        }
        return false;
    }
};

PRUNTI.RegistrationForm = {
    over18Clicked: function() {
        if ($('over18').checked) {
            $('parent-details').hide();
        }
        else {
            $('parent-details').show();
        }
    },
    
    onDOMReady: function(countryConfiguration) {
        PRUNTI.RegistrationForm.over18Clicked();

        PRUNTI.tooltip.activateAll();
        PRUNTI.RegistrationForm.countryConfiguration = countryConfiguration;
    },

    getInstanceForCountry: function(country) {
        var supportingInstance = null;
        
        $H(PRUNTI.RegistrationForm.countryConfiguration).values().each(function(instanceConfig) {
                $A(instanceConfig.countries).each(function(c) {
                        if (c == country) {
                            supportingInstance = instanceConfig;
                            throw $break;
                        }
                    });
            });
        
        return supportingInstance;
    },

    getSelectedFacebookCountry: function() {
        var selector = $('facebookCountry');
        return selector.options[selector.selectedIndex].value;
    },
    
    facebookCountryChanged: function(event) {
        var country = PRUNTI.RegistrationForm.getSelectedFacebookCountry();
        var supportingInstance = PRUNTI.RegistrationForm.getInstanceForCountry(country);
            
        if (supportingInstance) {
            document.location = supportingInstance.routes.register + '?country=' + country;
        }
        else {
            $('RES_ID_fb_login').show();
        }
    },

    wrongCountry: function(event) {
        $('setCountry').show();
        $('RES_ID_fb_login').hide();
    },
    
    countryChanged: function(event) {
        var country = this.options[this.selectedIndex].value;
        var supportingInstance = PRUNTI.RegistrationForm.getInstanceForCountry(country);

        if (supportingInstance) {
            $('registerForm').action = supportingInstance.routes.form_action;
            $('terms').href = supportingInstance.routes.terms_and_conditions;
            $('privacy').href = supportingInstance.routes.privacy_policy;
        }
    }
    
};

PRUNTI.PrepareWrapper = {
    init: function() {
        $('success').disable();
        if ($('wrapperPrintFail')) {
            $('wrapperPrintFail').disable();
        }
        $('printWrapper').observe('click', PRUNTI.PrepareWrapper.printWrapperClicked);
    },
    printWrapperClicked: function() {
        window.setTimeout(function() {
                $('success').enable();
                if ($('wrapperPrintFail')) {
                    $('wrapperPrintFail').enable();
                }
            }, 5000);
    }
};


PRUNTI.MyDvdsPage = {
    currentTab: null,
    
    init: function(defaultTab) {
        var name;
        var that = this;

        this.selectTab(defaultTab);
        PRUNTI.BusyIndicator.centreOn('bordered');
    },

    tabClicked: function(event, tab) {
        this.selectTab(tab.id);
        
        Event.stop(event);
    },
    
    selectTab: function(tabName) {
        var current, content, tab;

        tab = $(tabName);
        tab.addClassName('selected');

        if (this.currentTab != null) {
            this.deselectTab(this.currentTab);
        }

        this.currentTab = tabName;
        DH_RATING_PLUGIN.init();
    },
    
    deselectTab: function(tabName) {
        var current, content, tab;

        tab = $(tabName);
        tab.removeClassName('selected');

//         var content = $(tabName + '-content');
//         if (content != null) {
//             content.hide();
//             this.currentTab = null;
//         }
    }
};

// suggested at http://www.joestelmach.com/blog/ajax_busy_indicators
Ajax.Responders.register({
  onCreate: function() {
    if(Ajax.activeRequestCount>0)
        PRUNTI.BusyIndicator.activate();
  },
  onComplete: function() {
    if(Ajax.activeRequestCount==0)
        PRUNTI.BusyIndicator.deactivate();
  }
});

// From http://www.leigeber.com/2008/06/javascript-tooltip/
PRUNTI.tooltip = function(){
	var id = 'tt';
	var top = 3;
	var left = 3;
	var maxw = 300;
	var speed = 10;
	var timer = 20;
	var endalpha = 95;
	var alpha = 0;
	var tt,t,c,b,h;
	var ie = document.all ? true : false;
	return{
		show:function(tooltipContent,w){
			if(tt == null){
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t);
				tt.appendChild(c);
				tt.appendChild(b);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				document.onmousemove = this.pos;
			}
			tt.style.display = 'block';
			c.innerHTML = tooltipContent;
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie){
				t.style.display = 'none';
				b.style.display = 'none';
				tt.style.width = tt.offsetWidth;
				t.style.display = 'block';
				b.style.display = 'block';
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){PRUNTI.tooltip.fade(1)},timer);
		},
		pos:function(e){
			var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
			tt.style.top = (u - h) + 'px';
			tt.style.left = (l + left) + 'px';
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function(){
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){PRUNTI.tooltip.fade(-1)},timer);
		},
        apply:function(elemOrList, tooltipContent) {
            var list;
            if (!elemOrList.length) {
                list = [elemOrList];
            }
            else {
                list = elemOrList;
            }
            list.each(function(e) {
                    e.observe('mouseover', function() {PRUNTI.tooltip.show(tooltipContent)});
                    e.observe('mouseout', PRUNTI.tooltip.hide);
                });
        },
        activateAll: function() {
            $$('.tooltip').each(function(elem) {
                    PRUNTI.tooltip.activateTooltip(elem);
                });
        },
        activateTooltip: function(elem) {
            var content = elem;
            var hotspot = $(elem.id + '-hotspot');
            
            hotspot.observe('click', function(e) {Event.stop(e)});
            PRUNTI.tooltip.apply(hotspot, content.innerHTML);
        }
	};
}();

PRUNTI.friendRequestForm = {
    init: function () {
        if ($('choice_confirm-superfriend')) {
            $('choice_confirm-superfriend').observe('click', function() {PRUNTI.friendRequestForm.show('superfriend-friends');});
        }
        if ($('choice_confirm-household')) {
            $('choice_confirm-household').observe('click', function() {PRUNTI.friendRequestForm.show('household-friends');});
        }
        if ($('choice_confirm')) {
            $('choice_confirm').observe('click', function() {PRUNTI.friendRequestForm.hide('superfriend-friends');});
            $('choice_confirm').observe('click', function() {PRUNTI.friendRequestForm.hide('household-friends');});
        }
        $('choice_decline').observe('click', function() {PRUNTI.friendRequestForm.hide('superfriend-friends');});
        $('choice_decline').observe('click', function() {PRUNTI.friendRequestForm.hide('household-friends');});
    },
    hide: function(elemId) {
        if ($(elemId)) {
            $(elemId).hide();
        }
    },
    show: function(elemId) {
        if ($(elemId)) {
            $(elemId).show();
        }
    },
    selectAll: function() {
        $$('input.select-inviters-friends').each(function (v) {v.checked = true});
    },
    clearAll: function() {
        $$('input.select-inviters-friends').each(function (v) {v.checked = false});
    }
};

PRUNTI.recommendDvdForm = {
    getSelectionId: function(li) {
        if (li.getAttribute('friendId') == 'new') {
            $('email').focus();
        }
        else {
            $('friend').value = li.innerHTML;
            $('email').value = li.getAttribute('friendEmail');
            $('message').focus();
        }
    }
};

PRUNTI.BorrowedDvds = {
    onActionSelectionChanged: function(e) {
        var commandName = this.options[this.selectedIndex].value;
        var actionRecord;
        
        if (PRUNTI.BorrowedDvds.actionUrlMap[commandName]) {
            actionRecord = PRUNTI.BorrowedDvds.actionUrlMap[commandName];
            if (!actionRecord[1] || confirm(actionRecord[1])) {
                window.location = actionRecord[0];
            }
        }
    },
    setActionUrlMap: function(map) {
        PRUNTI.BorrowedDvds.actionUrlMap = map;
    }
};

PRUNTI.getAutoCompleterClass = function() {
    return Class.create(Ajax.Autocompleter, {
            initialize: function($super, inputId, divId, url, options) {
                $(inputId).observe('keypress', this.inputKeypress.bindAsEventListener(this));
                $super(inputId, divId, url, options);
            },
            onComplete: function($super, request) {
                $super(request);
                if (request.responseText == '') {
                    $(this.options.warningDivId).show();
                }
            },
            onObserverEvent: function() {
                this.changed = false;   
                this.tokenBounds = null;
                if(PRUNTI.batchAddDvdPage.isValidInput(this.getToken())) {
                    this.getUpdatedChoices();
                } else {
                    this.active = false;
                    this.hide();
                }
                this.oldElementValue = this.element.value;
            },
            selectEntry: function($super) {
                var current = this.getCurrentEntry();
                if (current.hasClassName('ajaxWarning')) {
                    this.active = false;
                    this.hide();
                }
                else {
                    $super();
                }
            },
            inputKeypress: function(event) {
                if (!this.active) {
                    if ((event.keyCode == Event.KEY_TAB ||
                         event.keyCode == Event.KEY_RETURN)
                        &&
                        event.ctrlKey == false &&
                        event.shiftKey == false &&
                        event.altKey == false &&
                        event.metaKey == false
                        ) {
                        if (this.getToken().length >= this.options.minChars) {
                            this.activate();
                            clearTimeout(this.observer);
                            Event.stop(event);
                        }
                        
                    }
                }
                this.hasFocus = true;
            }
            
            });
};

PRUNTI.batchAddDvdPage = {
    initAutoCompletion: function(id, ajaxUpdateUrl) {
        var inputId = 'ajaxSearchBox' + id;
        var divId = 'ajaxSearchDropdown' + id;
        var warningId = 'ajaxSearchWarning' + id;
        var Autocompleter = PRUNTI.getAutoCompleterClass();

        var completer = new Autocompleter(
               inputId,
               divId,
               ajaxUpdateUrl,
               {
                   frequency: 0.4,
                   afterUpdateElement: function(inputElem, li) {PRUNTI.batchAddDvdPage.selectionMade(li)},
                   minChars: 2,
                   indicator: 'spinner' + id,
                   warningDivId: warningId
               });
        
    },
    
    dvdCounter: 0,
    
    getDvdCount: function() {
        return PRUNTI.batchAddDvdPage.dvdCounter;
    },

    decrementDvdCount: function() {
        PRUNTI.batchAddDvdPage.dvdCounter--;
        if (PRUNTI.batchAddDvdPage.onDvdAddedOrRemoved) {
            PRUNTI.batchAddDvdPage.onDvdAddedOrRemoved();
        }
    },
    
    incrementDvdCount: function() {
        PRUNTI.batchAddDvdPage.dvdCounter++;
        if (PRUNTI.batchAddDvdPage.onDvdAddedOrRemoved) {
            PRUNTI.batchAddDvdPage.onDvdAddedOrRemoved();
        }
    },
    
    initPendingDvdCounter: function(divId, singleMessage, multipleMessage) {
        PRUNTI.batchAddDvdPage.onDvdAddedOrRemoved = function() {
                var message;
                var numDvds = PRUNTI.batchAddDvdPage.getDvdCount();
                var messageDomElement = $(divId);
                
                if (numDvds == 0) {
                    messageDomElement.hide();
                }
                else if (numDvds == 1) {
                    messageDomElement.innerHTML = singleMessage.supplant({'n': numDvds});
                    messageDomElement.show();
                }
                else {
                    messageDomElement.innerHTML = multipleMessage.supplant({'n': numDvds});
                    messageDomElement.show();
                }
            };
    },
    
    showWarning: function(warningDiv) {
        $(warningDiv).show();
    },
    
    isUpcLike: function(input) {
        return /^[0-9]+$/.match(input);
    },
    
    isValidUpc: function(input) {
        return /^[0-9]{12,13}$/.match(input);
    },
    
    isValidInput: function(input) {
        if (PRUNTI.batchAddDvdPage.isUpcLike(input)) {
            return PRUNTI.batchAddDvdPage.isValidUpc(input);
        }
        else {
            return input.length>2;
        }
    },

    clearRowAndDecrement: function(rowNum) {
        PRUNTI.batchAddDvdPage.clearRow(rowNum);
        PRUNTI.batchAddDvdPage.decrementDvdCount();
    },
    
    clearRow: function(rowNum) {
        $('ajaxSearchBox' + rowNum).value = '';
        $('ajaxSearchBox' + rowNum).show();
        $('ajaxSearchResult' + rowNum) . innerHTML = '';
        $('ajaxSearchBox' + rowNum).focus();
    },
    
    confirmAdd: function(rowNum, productId) {
        var result = $('ajaxSearchResult' + rowNum);
        result.down('.dupMessage').remove();
        result.innerHTML = result.innerHTML + PRUNTI.batchAddDvdPage.readyToAddHtml(rowNum, productId);
        PRUNTI.batchAddDvdPage.incrementDvdCount();
    },

    isAlreadyListed: function(productId) {
        var isAlreadyListed = false;
        $$('.auto_complete_result input').each(function (v) {
                if (v.getAttribute('value') == productId) {
                    isAlreadyListed = true
                }
            });
        return isAlreadyListed;
    },
    
    selectionMade: function(li) {
        var productId = li.getAttribute('productId');
        var result = li.up('.form-row').down('.auto_complete_result');
        var input = li.up('.form-row').down('input');
        var nextRow = li.up('.form-row').next('.form-row');
        var next;
        while (nextRow && (!next || next.style.display == 'none')) {
            next = nextRow.down('input');
            nextRow = nextRow.next('.form-row');
        }
        var rowNum = /[0-9]+$/.exec(li.up('.auto_complete').getAttribute('id'))[0];
        
        input.hide();
        var appendHtml;
        if (li.getAttribute('alreadyincollection') || PRUNTI.batchAddDvdPage.isAlreadyListed(productId)) {
            appendHtml = ' <span class="dupMessage">This DVD is already in your collection.<br />Do you really have two copies?'
                + ' <a onclick="PRUNTI.batchAddDvdPage.confirmAdd(' + rowNum + ', ' + productId + '); return false;" href="#" >Yes</a> '
                + '<a onclick="PRUNTI.batchAddDvdPage.clearRow(' + rowNum + '); return false;" href="#" >No</a>'
                + '</span>';
        }
        else if (li.getAttribute('parentalApprovalDenied')) {
            appendHtml = ' <p>Sorry, you can\'t add this DVD to your collection because you do not have permission from your parent or guardian.</p>'
        }
        else {
            appendHtml = PRUNTI.batchAddDvdPage.readyToAddHtml(rowNum, productId);
            PRUNTI.batchAddDvdPage.incrementDvdCount();
        }
        result.innerHTML = li.innerHTML + appendHtml;
        result.show();
        if (next) {
            next.focus();
        }
    },

    readyToAddHtml: function(rowNum, productId) {
        return ' Ready to add <a onclick="PRUNTI.batchAddDvdPage.clearRowAndDecrement(' + rowNum + '); return false;" href="#" >[cancel]</a>' +
        '<input type="hidden" name="selectedProductIds[]" value="' + productId + '" />';
    }
    
};

PRUNTI.likesDislikesPage = {
    initAutoCompletion: function(type, searchUrl, selectionMadeUrl) {
        var inputId = 'ajaxSearchBox' + type;
        var divId = 'ajaxSearchDropdown' + type;
        var warningId = 'ajaxSearchWarning' + type;
        var Autocompleter = PRUNTI.getAutoCompleterClass();
        PRUNTI.likesDislikesPage.selectionMadeUrl = selectionMadeUrl;

        var completer = new Autocompleter(
               inputId,
               divId,
               searchUrl,
               {
                   frequency: 0.4,
                   afterUpdateElement: function(inputElem, li) {PRUNTI.likesDislikesPage.selectionMade(type, li)},
                   minChars: 2,
                   indicator: 'spinner' + type,
                   warningDivId: warningId
               });
        
    },
    
    clearRowAndDecrement: function(rowNum) {
        PRUNTI.batchAddDvdPage.clearRow(rowNum);
        PRUNTI.batchAddDvdPage.decrementDvdCount();
    },
    
    clearRow: function(rowNum) {
        $('ajaxSearchBox' + rowNum).value = '';
        $('ajaxSearchBox' + rowNum).show();
        $('ajaxSearchResult' + rowNum) . innerHTML = '';
        $('ajaxSearchBox' + rowNum).focus();
    },
    
    confirmAdd: function(rowNum, productId) {
        var result = $('ajaxSearchResult' + rowNum);
        result.down('.dupMessage').remove();
        result.innerHTML = result.innerHTML + PRUNTI.batchAddDvdPage.readyToAddHtml(rowNum, productId);
        PRUNTI.batchAddDvdPage.incrementDvdCount();
    },

    selectionMade: function(type, li) {
        var productId = li.getAttribute('productId');

        $('ajaxSearchBox' + type).value = '';
        $('ajaxSearchBox' + type).focus();
        new Ajax.Updater('ajaxSearchResult' + type,
                         PRUNTI.likesDislikesPage.selectionMadeUrl + '/add' + type + '/' + productId,
{'insertion': 'top', 'onComplete': function() {PRUNTI.likesDislikesPage.selectionConfirmed(type, productId)}});
    },

    selectionConfirmed: function(type, productId) {
        $$('.dvd-productId-' + productId + ' a.remove').each(function(v) {
                v.observe('click', PRUNTI.likesDislikesPage.removeSelection.bindAsEventListener(v))});
    },

    removeSelection: function(event) {
        var li = this.up('li');
        var productId = /^dvd-productId-(.*)$/.exec(li.className)[1];
        var ul = li.up('ul');
        var type = /^ajaxSearchResult(.*)$/.exec(ul.id)[1];
        
        new Ajax.Request(PRUNTI.likesDislikesPage.selectionMadeUrl + '/remove' + type + '/' + productId,
                         {'onSuccess': function() {PRUNTI.likesDislikesPage.removeSelectionConfirmed(type, productId)}});

        Event.stop(event);
    },

    removeSelectionConfirmed: function(type, productId) {
        $$('.dvd-productId-' + productId).each(function(v) {v.remove()});
    },

    initRemoveHandlers: function() {
        $$('a.remove').each(function(v) {v.observe('click', PRUNTI.likesDislikesPage.removeSelection.bindAsEventListener(v));});
    }
};


PRUNTI.ViewPassonRequestPage = {
    init: function() {
        $$('form input[type=radio]').each(function(elem) {
                elem.observe('click', PRUNTI.ViewPassonRequestPage.onClick.bindAsEventListener(elem));
            });
    },
    onClick: function(event) {
        switch(this.value) {
        case 'ok':
        case 'intermittent':
        case 'none':
        PRUNTI.ViewPassonRequestPage.revealPasson();
        break;
        
        case 'unplayable':
        case 'illegal_duplicate':
        PRUNTI.ViewPassonRequestPage.revealReturn();
        break;
        }
    },
    revealPasson: function() {
        $('passonOptions').show();
        $('returnWarning').hide();
    },
    revealReturn: function() {
        $('returnWarning').show();
        $('passonOptions').hide();
    }
};

PRUNTI.ActivityTicker = {
    updateInterval: 10,
    
    init: function(callbackUrl, initialDelay) {
        if (initialDelay === undefined) {
            initialDelay = PRUNTI.ActivityTicker.updateInterval;
        }
        setTimeout(function() {
                new Ajax.Request(callbackUrl, {'onSuccess': function(transport) {
                            PRUNTI.ActivityTicker.start(transport.responseJSON); }})},
                initialDelay * 1000);
    },
    start: function(messages) {
        var i=0;
        var activityUpdater = function() {
            $('activityTicker').innerHTML = messages[i % messages.length];
            i++;
        }
        activityUpdater();
        setInterval ( activityUpdater, PRUNTI.ActivityTicker.updateInterval * 1000 );
    }
};

PRUNTI.FaceBook = {
    ApiKey: null,
    XdReceiverPath: null,
    share: function(url) {
        window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url),'sharer','toolbar=0,status=0,width=626,height=436');
        return false;
    },
    onRegisterClicked: function(postLoginUrl, registerCallbackUrl) {
        var postRegistrationHandler = function() {
            var url = registerCallbackUrl + '?country=' + PRUNTI.RegistrationForm.getSelectedFacebookCountry();
            new Ajax.Request(url, {'onSuccess': function(transport) {window.location = transport.responseText}});
        };
        
        return function() {
            FB_RequireFeatures(["Connect"], function() {
                    FB.init(PRUNTI.FaceBook.ApiKey, PRUNTI.FaceBook.XdReceiverPath);
                    FB.Connect.requireSession(postRegistrationHandler);
                }
                );
        };
    },
    onLoginClicked: function(postLoginUrl) {
        return function() {
            FB_RequireFeatures(["Connect"], function() {
                    FB.init(PRUNTI.FaceBook.ApiKey, PRUNTI.FaceBook.XdReceiverPath);
                    FB.Connect.requireSession(function() {window.location=postLoginUrl;});
                }
                );
        };
    },
    onLogoutClicked: function(signoutUrl) {
        FB_RequireFeatures(["Connect"], function() {
                FB.init(PRUNTI.FaceBook.ApiKey, PRUNTI.FaceBook.XdReceiverPath);
                FB.Connect.logout(function() {window.location=signoutUrl});
            }
            );
    },
    requireXfbml: function() {
        FB_RequireFeatures(["XFBML"], function() {
                FB.init(PRUNTI.FaceBook.ApiKey, PRUNTI.FaceBook.XdReceiverPath);
            }
            );
    }
};