﻿/* 
This class is responsible for managing the panels that are displayed on the page and mapping the click events on the menus.
 
In initalize method we are creating hashtable( this.functionMap = $H(); ), where key is li#id of 
anchor and value is function name what will be call when we click on page menu anchor. By default we will call
genericMenuClick. Default funcionality is hidding all div`s and show`s first one what 
contain class name: "firstPanel". If we want to use default funcionality we don`t need to 
modify any code, just add new li#id into page menu. If we want to override existing funcionality 
or add new funcionality we need to add li#id into hashtable and add function what will be call 
when we click on anchor into initialize method.
Example: this.functionMap['new li#id'] = newjavascriptfuncion;
 
*/

var PanelManager = Class.create({

    // Creating hashtable with div id and funcion
    initialize: function() {
        this.functionMap = $H({
            'login': showLoginPanel,
            'editProfile': showEditProfilePanel,
            'redeemPoints': showRedeemPointsPanel,
            'codeEntry': showCodeEntryPanel,
            'userCodes': showUserCodesPanel,
            'createProfile': showCreateProfilePanel,
            'whereToBuy': showWhereToBuyPanel,
            'campaignLanding': showCampaignLandingPanel
        });
    },

    getMenuClickEvent: function(divID) {
        var clickEvent = this.functionMap.get(divID);
        if (clickEvent == null) {
            clickEvent = this.genericMenuClick;
        }
        return clickEvent;
    },

    genericMenuClick: function(event) {
        // get id of <li> element parent for anchor to identify the 'panel' that should be displayed
        var itemId = (event.element().ancestors()[0]).getAttribute('id');
        panelManager.switchPanel(itemId);

        event.stop();
    },

    switchPanel: function(itemId) {

        var isLoggedIn = profileManager.profile != null && profileManager.profile.isLoggedIn;

        resetFeedbackPanel(itemId + "FeedbackPanel");

        if ($(itemId + "Panel").hasClassName("loginRequired")) {
            if (!isLoggedIn) {
                itemId = "login";
            }
        }

        // update container div with class that indicates the current panel and whether the user is logged in or not
        // these class names are used by css to control presentation
        $('multiCampaignPanels').classNames().each(function(item) {
            $('multiCampaignPanels').removeClassName(item);
        });
        $('multiCampaignPanels').addClassName(itemId + "Panel");
        $('multiCampaignPanels').addClassName(isLoggedIn ? "registered" : "anonymous");


        // hide all panels and show the selected panel
        this.selectedPanel = $(itemId + "Panel");
        $$('div.pagePanel').each(function(item) {
            item.hide();
        });

        // hide all sub panels in selected panel and show the div.firstPanel subpanel
        var subPanels = this.selectedPanel.select('div.subPanel');
        if (subPanels.size() > 0) {
            subPanels.each(function(item) {
                item.hide();
            });
            this.selectedPanel.select('div.firstPanel')[0].show();
        }

        // update menu with 'menuitemselected' class
        $('pageMenu').select('li').each(function(item) {
            if (item.id == itemId) {
                item.addClassName('menuitemselected');
            } else {
                item.removeClassName('menuitemselected');
            }
        });

        this.selectedPanel.show();
        webtrendsTracker.trackActivity(itemId);
    },

    switchSubPanel: function(itemId) {

        var subPanels = this.selectedPanel.select('div.subPanel');
        subPanels.each(function(subItem) {
            if (subItem.id == itemId) {
                subItem.show();
            } else {
                subItem.hide();
            }
        });
        webtrendsTracker.trackActivity(itemId);
    },

    showPanelOverlay: function(itemId) {
        $(itemId + "Panel").addClassName('overlay');

        new Popup(itemId + "Panel", null, { modal: true }, { position: 'center' });
        $(itemId + "Panel").popup.show();

        $("popup_overlay").observe('click', function(event) {
            $(itemId + "Panel").popup.hide();
            $(itemId + "Panel").removeClassName('overlay');
            event.stop();
        });
    }
});

/* 
This class is responsible for managing the profile for the current site visitor 
*/

var ProfileManager = Class.create({

    loadProfile: function() {
        new Ajax.Request('/' + locale + '/GetProfile.json',
        {
            method: 'get',
            asynchronous: false,
            parameters: { useResponseBody: 'true', jsonSource: pointSystemKey },
            onSuccess: function(transport) {
                var json = transport.responseText.evalJSON();
                switch (json.type) {
                    case 'JsonMethodMessage':
                        profileManager.profile = json.result;
                        break;
                    case 'JsonSystemExceptionMessage':
                        profileManager.profile = null;
                        break;
                }
            },
            onFailure: function() {
                profileManager.profile = null;
            }
        });
    },

    login: function(email, password, successFunction, feedbackPanel) {

        $(feedbackPanel).update();

        var jsonParams = {
            'login': email,
            'password': password
        }

        document.body.style.cursor = 'wait';
        new Ajax.Request('/' + locale + '/Login.json',
        {
            method: 'get',
            parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(jsonParams) },
            onSuccess: function(transport) {
                var json = transport.responseText.evalJSON();
                switch (json.type) {
                    case 'JsonMethodMessage':
                        profileManager.profile = json.result;
                        successFunction();
                        break;

                    case 'JsonValidationMessage':
                        handleValidationError(feedbackPanel, json.messages);
                        break;

                    case 'JsonSystemExceptionMessage':
                        handleSystemExceptionError(feedbackPanel, json.message);
                        break;
                }
            },
            onFailure: function() {
                handleSystemExceptionError(feedbackPanel, json.message);
            },
            onComplete: function() {
                document.body.style.cursor = 'default';
            }
        });
    },

    logout: function(feedbackPanel) {

        $(feedbackPanel).update();

        document.body.style.cursor = 'wait';
        new Ajax.Request('/' + locale + '/Logout.json',
        {
            method: 'get',
            parameters: { useResponseBody: 'true', jsonSource: pointSystemKey },
            onSuccess: function(transport) {
                var json = transport.responseText.evalJSON();
                switch (json.type) {
                    case 'JsonMethodMessage':
                        profileManager.logoutSuccessFunction();
                        break;

                    case 'JsonValidationMessage':
                        handleValidationError(feedbackPanel, json.messages);
                        break;

                    case 'JsonSystemExceptionMessage':
                        handleSystemExceptionError(feedbackPanel, json.message);
                        break;
                }
            },
            onFailure: function() {
                handleSystemExceptionError(feedbackPanel, json.message);
            },
            onComplete: function() {
                document.body.style.cursor = 'default';
            }
        });
    }
});

/* 
This class is responsible to show and get the capthca image and its information on the page.
 
In 'getCaptchaImage' function we are getting two parameters; 'divId' and 'feedbackPanel'. 'divId' is the id of div which will contain 
captcha image, textbox to enter captha text and an hidden div which will get contain captcha src path. 'feedbackPanel' is the id of
the feedback where you want to use error messages. Further in this menthod we are calling a 'getCaptchaImage.json' which will create
a captcha image for us and will return its path for example; "/captcha/13d9bbc0-7b6b-409b-aadc-e18484bec68f" then in case of successful
json call we are assigning this captcha src to an image and an hidden div. 
'getHtmlCaptchaInfo' as name suggests this function is used to get html information related to captcha image. This function will return 
an object of imageUrl and text entered in the textbox.
NOTE: The order of capthaInfo div should be as below otherwise you will not get desired results.  
<div id="divId">
<div><i18n:text>CaptchaDirectionsLabel</i18n:text></div>
<div><img src="" alt="" /></div>                        
<div><input name="redeemPointsCaptchaInput" type="text" value="" /></div>
<div style="display:none"></div>
</div> 
*/


var CaptchaManager = Class.create({

    getCaptchaImage: function(divId, feedbackPanel) {

        document.body.style.cursor = 'wait';
        new Ajax.Request('/' + locale + '/GetCaptchaImage.json',
        {
            method: 'get',
            parameters: { jsonSource: pointSystemKey },
            onSuccess: function(transport, json) {
                switch (json.type) {
                    case "JsonMethodMessage":
                        $(divId).select('img')[0].src = json.result.captchaImage;
                        $(divId).select('div')[3].update(json.result.captchaImage);
                        break;
                    case "JsonSystemExceptionMessage":
                        handleSystemExceptionError(feedbackPanel, json.message);
                        break;
                }
            },
            onFailure: function() {
                handleSystemExceptionError(feedbackPanel, json.message);
            },
            onComplete: function() {
                document.body.style.cursor = 'default';
            }
        });
    },

    getHtmlCaptchaInfo: function(divId) {
        return {
            imageUrl: $(divId).select('div')[3].innerHTML,
            text: $(divId).select('input')[0].value
        };
    }
});

/*

This class is rsponsible to initiate a javascript request to where to buy section.

*/

var WhereToBuyManager = Class.create({

    initialize: function() {

        //whereToBuyPanel
        $("postalCodeFilter").observe('click', this.filterFieldClick);
        $("cityFilter").observe('click', this.filterFieldClick);
        $("regionFilter").observe('change', this.filterFieldClick);

        $("regionFilter").update($("regionsDropDownList").innerHTML);
        $("regionFilter").select('select')[0].id = "regionListId";

        $("dealersSortBy").update($("sortByDropDownList").innerHTML);
        $("dealersSortBy").select('select')[0].id = "sortBy";
        $("sortBy").observe('change', this.pageLoad);

        $('searchButton').select('a')[0].observe('click', this.pageLoad);

        this.defaultValues = $H({
            'postalCodeFilter': $('postalCodeFilter').value,
            'cityFilter': $('cityFilter').value,
            'regionFilter': $("regionFilter").select('select')[0].select('option')[0].innerHTML
        });
    },

    pageLoad: function() {
        whereToBuyManager.getDealers("whereToBuyFeedbackPanel", 1, whereToBuyManager.renderPage);
    },

    filterFieldClick: function(event) {
        $('filter').select('.filterField').each(function(item) {
            if (item.id != event.element().id) {
                if (item.type == 'select-one') {
                    $('regionFilter').select('select')[0].selectedIndex = 0;
                }
                item.value = whereToBuyManager.defaultValues.get(item.id);
            }
            else {
                item.value = "";
            }
        });

        event.stop();
    },

    getDealers: function(feedbackPanel, selectedPage, successFunction) {

        document.body.style.cursor = 'wait';
        $(feedbackPanel).update();
        new Ajax.Request('/' + locale + '/GetDealers.json',
        {
            method: 'get',
            parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(this.dealerFilterJsonString(selectedPage)) },
            onSuccess: function(transport) {
                var json = transport.responseText.evalJSON();
                switch (json.type) {
                    case 'JsonMethodMessage':
                        successFunction(json.result);
                        break;
                    case 'JsonValidationMessage':
                        handleValidationError(feedbackPanel, json.messages);
                        break;
                    case 'JsonSystemExceptionMessage':
                        handleSystemExceptionError(feedbackPanel, json.message);
                        break;
                }
            },
            onFailure: function() {
                handleSystemExceptionError(feedbackPanel, json.message);
            },
            onComplete: function() {
                document.body.style.cursor = 'default';
            }
        });
    },

    renderPage: function(googleMapContainer) {

        // update dealer list id with empty pages
        $('dealerList').update();
        for (var i = 0; i < googleMapContainer.totalPages; i++) {
            $('dealerList').insert("<div class =\"pagingItem\" id=\"page" + (i + 1) + "\" style=\"display:none\"></div>");
        }

        whereToBuyManager.displayDealers(googleMapContainer);
        whereToBuyManager.renderPaging(googleMapContainer);
        whereToBuyManager.updateSortyByControl(googleMapContainer);
        whereToBuyManager.renderGoogleMap(googleMapContainer);
    },

    pageClick: function(googleMapContainer) {

        whereToBuyManager.displayDealers(googleMapContainer);
        whereToBuyManager.renderGoogleMap(googleMapContainer);
    },

    displayDealers: function(googleMapContainer) {

        $('page' + googleMapContainer.currentPage).update();
        var googleIndex = 1;
        googleMapContainer.googleMapItems.each(function(item, index) {
            var markerDiv = new Element("div", { 'class': 'marker' });
            var titleDiv = new Element("div", { 'class': 'title' });
            titleDiv.insert(item.name);
            var addressDiv = new Element("div", { 'class': 'address' });
            addressDiv.insert(item.displayAddress);
            var phoneDiv = new Element("div", { 'class': 'phone' });
            phoneDiv.insert(item.phone);
            var emailDiv = new Element("div", { 'class': 'email' });
            emailDiv.insert(item.email);
            var faxDiv = new Element("div", { 'class': 'fax' });
            faxDiv.insert(item.fax);

            if (item.latitude != 0 && item.longitude != 0) {
                var showLink = new Element("a", { 'class': 'showOnMap', 'href': 'javascript:void(0);', 'name': 'linkShowMap', 'id': 'linkNum' + googleIndex });
                showLink.insert(i18nText.translate('mapLabel'));
                googleIndex++;
            }
            var dealerDiv = new Element("div", { 'class': 'dealer' });
            dealerDiv.insert(markerDiv);
            dealerDiv.insert(titleDiv);
            dealerDiv.insert(addressDiv);
            dealerDiv.insert(emailDiv);
            dealerDiv.insert(phoneDiv);
            dealerDiv.insert(faxDiv);
            dealerDiv.insert(showLink);

            $('page' + googleMapContainer.currentPage).insert(dealerDiv);
        });
    },

    updateSortyByControl: function(googleMapContainer) {
        var selectElement = $('dealersSortBy');
        selectElement.select('option').each(function(item, index) {
            if (item.value == 'B2B') {
                if (!Boolean(googleMapContainer.hasB2BDealers)) {
                    item.hide();
                }
                else {
                    item.show();
                }
            }
            if (item.value == 'B2C') {
                if (!Boolean(googleMapContainer.hasB2CDealers)) {
                    item.hide();
                }
                else {
                    item.show();
                }
            }
            if (item.value == 'Priority') {
                if (!Boolean(googleMapContainer.hasPriorityDealers)) {
                    item.hide();
                }
                else {
                    item.show();
                }
            }
            if (item.value == 'Distance') {
                if (whereToBuyManager.defaultValues.get("postalCodeFilter") != $('postalCodeFilter').value) {
                    item.show();
                }
                else {
                    item.hide();
                }
            }
        });
    },

    renderGoogleMap: function(googleMapContainer) {
        lats = googleMapContainer.mapDetailInfo.latitudes;
        longs = googleMapContainer.mapDetailInfo.longitudes;
        adds = googleMapContainer.mapDetailInfo.addresses;
        homeLat = 0;
        homeLong = 0;
        maxPageSize = googleMapContainer.resultsPerPage;
        pageNumber = googleMapContainer.currentPage;
        startAddressIndex = 0;
        if (googleMapContainer.currentPage == 1) {
            currentPage = googleMapContainer.currentPage
        }
        else {

            currentPage = googleMapContainer.currentPage * googleMapContainer.resultsPerPage;
        }
        isShowAll = false;

        gInit();
    },

    renderPaging: function(googleMapContainer) {
        createPaging('desato.paging', 'dealerList', 'pagingContainer', 1, 'pagingItem', 'page', whereToBuyManager.pagingFunction);
    },

    dealerFilterJsonString: function(selectedPage) {
        var dealerFilter = {
            addressString: "",
            currentPage: selectedPage,
            dealerType: 3,
            dealerListId: $("dealerListId").value,
            postalCode: "",
            regionId: "",
            resultsPerPage: 20,
            sortBy: $("sortBy").value
        };

        if (whereToBuyManager.defaultValues.get("cityFilter") != $('cityFilter').value) {
            dealerFilter.addressString = $('cityFilter').value;
        }
        if (whereToBuyManager.defaultValues.get("postalCodeFilter") != $('postalCodeFilter').value) {
            dealerFilter.postalCode = $('postalCodeFilter').value;
        }
        if (whereToBuyManager.defaultValues.get("regionFilter") != $('regionListId').value) {
            dealerFilter.regionId = $('regionListId').value;
        }

        return dealerFilter;
    },

    pagingFunction: function(state) {
        var pageItems = $('dealerList').select('[class="pagingItem"]');
        pageItems.each(function(item) {
            item.hide();
        });

        for (var i = state.records[0] + 1; i <= state.records[1] + 1; i++) {
            $('page' + i).toggle();
        }

        if ($('page' + state.page).childElements().length == 0) {
            whereToBuyManager.getDealers("whereToBuyFeedbackPanel", state.page, whereToBuyManager.pageClick);
        }

        // update the summary now
        var summary = $('pagingContainer').select('div.summary')[0];
        summary.innerHTML = Ex.formatSummary(state);
        Ex.paginator.setState(state);
    }

});

/*
This class is responsible to handle Generic Panels functions.
"createPaging" as the name suggests this function is used to create paging in generic panels
*/

var GenericPanelManager = Class.create({

    createPaging: function() {
        $('multiCampaignPanels').select('.genericPanel').each(function(item) {
            var genericPanelId = item.getAttribute('id');
            genericPanelId = genericPanelId.substring(0, (genericPanelId.length - 5));
            createPaging('desato.namespace.' + genericPanelId, genericPanelId + 'Pages', genericPanelId + 'Paging', 1, genericPanelId + 'PageItem', genericPanelId + 'Page', null, formLabels);
        });
    }
});


/*
* GLOBAL VARIABLES DEFINED HERE
*/

var panelManager;
var profileManager;
var captchaManager;
var whereToBuyManager;
var genericPanelManager;

/*
* INITIALIZE CAMPAIGN PAGE
*/
document.observe("dom:loaded", function() {

    try {
        // Class Initialization
        genericPanelManager = new GenericPanelManager();
        panelManager = new PanelManager();

        profileManager = new ProfileManager();
        profileManager.logoutSuccessFunction = function() {
            profileManager.loadProfile();
            showLoginPanel();
        }

        captchaManager = new CaptchaManager();
        webtrendsTracker.initialize();
        if ($('whereToBuyPanel') != null) {
            whereToBuyManager = new WhereToBuyManager();
        }

        // create generic panel paging
        genericPanelManager.createPaging();

        // load profile
        profileManager.loadProfile();

        // Populate DropdownLists
        populateDropDownLists();

        // initialize menu click events
        $('pageMenu').select('li').each(function(item) {
            var divId = item.getAttribute('id');
            item.select('a')[0].observe('click', panelManager.getMenuClickEvent(divId));
        });

        // initialize button click events
        if ($('loginPanel') != null) {
            $('loginButton').select('a')[0].observe('click', loginButtonClick);
            $('forgotPasswordButton').select('a')[0].observe('click', forgotPasswordButtonClick);
            // initialize key binding events
            $("newUserEmail").observe('focus', function(event) {
                $('existingUserForm').reset();
            });
            $("existingUserEmail").observe('focus', function(event) {
                $('newUserForm').reset();
            });
            $("existingUserPassword").observe('focus', function(event) {
                $('newUserForm').reset();
            });

            // cleaning email and password controls 
            $("existingUserEmail").value = "";
            $("existingUserPassword").value = "";
        }

        if ($('activateAccountPanel') != null) {
            $('activateAccountLoginButton').select('a')[0].observe('click', activateAccountLoginButtonClick);
        }

        if ($('createProfilePanel') != null) {
            $('createAccountButton').select('a')[0].observe('click', createAccountButtonClick);
            $('newUserButton').select('a')[0].observe('click', newUserButtonClick);

            var wherePurchasedSelect = $$('#createWherePurchasedField select')[0];
            if (wherePurchasedSelect != null) {
                wherePurchasedSelect.observe('change', wherePurchasedOnChange);
            }
        }

        if ($('editProfilePanel') != null) {
            $('updateAccountButton').select('a')[0].observe('click', updateAccountButtonClick);
        }

        if ($('redeemPointsPanel') != null) {
            $('redeemPointsButton').select('a')[0].observe('click', redeemPointsButtonClick);
        }

        if ($('codeEntryPanel') != null) {
            $('codeEntrySubmitButton').select('a')[0].observe('click', codeEntrySubmitButtonClick);
            if ($('faqPanel') != null && $('faqButton') != null) {
                $('faqButton').select('a')[0].observe('click', faqButtonClick);
            }
        }

        if ($('campaignLandingPanel') != null) {
            $('userDetailsButton').select('a')[0].observe('click', showUserCodesPanel);
            $('codeEntryButton').select('a')[0].observe('click', showCodeEntryPanel);
            if ($('editProfileButton') != null) {
                $('editProfileButton').select('a')[0].observe('click', showEditProfilePanel);
            }
        }

        if ($('redeemPointsConfirmation') != null) {
            $('showFlashButton').select('a')[0].observe('click', showFlashPanel);
            $('closeRedeemPointsButton').select('a')[0].observe('click', showCampaignLandingPanel);
        }

        if ($('globalNav') != null) {
            $('globalNav').select('a')[0].observe('click', showFlashPanel);
        }

        $('multiCampaignPanels').select('a.closeBtn').each(function(item) {
            item.observe('click', closeButtonClick);
        });

        $('sendPasswordButton').observe('click', forgotPasswordSubmitLinkClick);
        $('logoutButton').select('a')[0].observe('click', logoutButtonClick);

        $('multiCampaignPanels').select('a.closeBtn').each(function(item) {
            item.observe('click', closeButtonClick);
        });

        if ($('privacyPolicyPanel') != null) {
            $('createPrivacyPolicyField').select('a.privacyPolicyAgreement').each(function(item) {
                item.observe('click', showPrivacyPolicyPanel);
            });
        }

        if ($('termsConditionsPanel') != null) {
            $('createTermsAndConditionField').select('a.termsAndConditionAgreement').each(function(item) {
                item.observe('click', showTermsAndConditionPanel);
            });
        }

        //    setProfilerImage('profiler_1');

        // determining which panel should be displayed when first loading this page
        setInitialPanelStates();

    } catch (err) {
        alert("error: " + err);
    }
});


function setInitialPanelStates() {

    var showPanel = $('showPanel').innerHTML;
    if (showPanel != "") {
        panelManager.switchPanel(showPanel);

        var feedbackMessage = $('messageValue').innerHTML;
        if (feedbackMessage != "") {
            $(showPanel + 'FeedbackPanel').update(feedbackMessage);
        }
    } else {
        var firstPanelId = $('multiCampaignPanels').select('.pagePanel')[0].id;
        firstPanelId = firstPanelId.substring(0, (firstPanelId.length - 5));
        panelManager.switchPanel(firstPanelId);
    }
}

/*
* CUSTOM MENU CLICK EVENT METHODS
*/

function showFlashPanel(event) {
    panelManager.switchPanel("flashOverlay");
    event.stop();
}

function showLoginPanel(event) {

    $("existingUserEmail").value = "";
    $("existingUserPassword").value = "";
    $("newUserEmail").value = "";

    panelManager.switchPanel("login");

    if (event != null) {
        event.stop();
    }
}

function showEditProfilePanel(event) {

    document.body.style.cursor = 'wait';

    var prefix = $("updateClientId").innerHTML;
    populateFields(prefix);

    captchaManager.getCaptchaImage("editProfileCaptcha", "editProfileFeedbackPanel");
    $("editProfileCaptcha").select('input')[0].value = '';

    panelManager.switchPanel("editProfile");
    document.body.style.cursor = 'default';

    event.stop();
}

function showRedeemPointsPanel(event) {

    document.body.style.cursor = 'wait';

    getUserTransactions(refreshRedeemPointsPanel, "redeemPointsPointSummary", "redeemPointsFeedbackPanel");

    document.body.style.cursor = 'default';
    event.stop();
}

function showCodeEntryPanel(event) {

    document.body.style.cursor = 'wait';

    getUserTransactions(displayCodeSummary, "codeEntryCodesSummary", "codeEntryFeedbackPanel");

    captchaManager.getCaptchaImage("codeEntryCaptcha", "codeEntryFeedbackPanel");
    $("codeEntryCaptcha").select('input')[0].value = '';

    // reset code entry text boxes to one
    $("userCodeTextBoxes").select('div').each(function(item) {
        item.remove();
    });
    createCodeEntryTextBox(1);

    panelManager.switchPanel("codeEntry");

    document.body.style.cursor = 'default';
    event.stop();
}

function showUserCodesPanel(event) {
    getUserTransactions(refreshUserCodesPanel, "userCodesSummary", "userCodesFeedbackPanel");

    panelManager.switchPanel("userCodes");
    if (event != null)
        event.stop();
}

function showCreateProfilePanel(event) {

    panelManager.switchPanel("createProfile");

    captchaManager.getCaptchaImage("createProfileCaptcha", "createProfileFeedbackPanel");
    $("createProfileCaptcha").select('input')[0].value = '';

    event.stop();
}

function showWhereToBuyPanel(event) {
    if ($('whereToBuyPanel') != null) {
        whereToBuyManager.pageLoad();
        panelManager.switchPanel("whereToBuy");
    }
    event.stop();
}

function showCampaignLandingPanel(event) {

    getUserTransactions(displayCodeSummary, "campaignLandingCodeSummary", "campaignLandingFeedbackPanel");

    var result = profileManager.profile;
    if (result.salutation != null) {
        $A($("salutationDropDownList").select("select")[0].options).each(function(item) {
            if (result.salutation == item.value) {
                $('salutation').update(item.text);
            }
        });
    }
    if (result.firstName != null) {
        $('firstName').update(result.firstName);
    }
    if (result.lastName != null) {
        $('lastName').update(result.lastName);
    }
    if (result.email != null) {
        $('email').update(result.email);
    }
    if (result.address.phoneNumber != null) {
        $('phoneNumber').update(result.address.phoneNumber);
    }
    if (result.address.companyName != null) {
        $('companyName').update(result.address.companyName);
    }
    if (result.address.address1 != null) {
        $('address').update(result.address.address1);
    }
    if (result.address.city != null) {
        $('city').update(result.address.city);
    }
    if (result.address.state != null) {
        $('state').update(result.address.state);
    }
    if (result.address.country != null) {
        $('country').update(result.address.country);
    }
    if (result.address.postalCode != null) {
        $('zipCode').update(result.address.postalCode);
    }

    panelManager.switchPanel("campaignLanding");

    if (event != null) {
        event.stop();
    }
}

/*
* BUTTON CLICK EVENTS
*/

function loginButtonClick(event) {

    resetFeedbackPanel("loginFeedbackPanel");
    if ($('forgotPasswordOverlay').popup != null) {
        $('forgotPasswordOverlay').popup.hide();
    }

    profileManager.login($F('existingUserEmail'), $F('existingUserPassword'), showCampaignLandingPanel, 'loginFeedbackPanel');
    event.stop();
}

function activateAccountLoginButtonClick(event) {

    resetFeedbackPanel("activateAccountFeedbackPanel");
    profileManager.login($F('activateAccountEmail'), $F('activateAccountPassword'), showCampaignLandingPanel, 'activateAccountFeedbackPanel');
    event.stop();
}

function logoutButtonClick(event) {

    profileManager.logout('loginFeedbackPanel');
    event.stop();
}

function wherePurchasedOnChange(event) {
    if (($F('createWherePurchased')).toLowerCase() == 'other') {
        $('createWherePurchasedTextBox').value = "";
        $('createWherePurchasedTextBoxField').show();
    }
    else {
        $('createWherePurchasedTextBoxField').hide();
    }

    event.stop();
}

function newUserButtonClick(event) {

    if ($('forgotPasswordOverlay').popup != null) {
        $('forgotPasswordOverlay').popup.hide();
    }

    resetFeedbackPanel("loginFeedbackPanel");

    var prefix = $("createClientId").innerHTML;

    var jsonParams = {
        'email': $('newUserEmail').value,
        'confirmationEmail': $('newUserEmail').value
    }

    document.body.style.cursor = 'wait';
    new Ajax.Request('/' + locale + '/RegisterGuest.json',
    {
        method: 'get',
        parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(jsonParams) },
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON();
            switch (json.type) {
                case 'JsonMethodMessage':
                    $(prefix + 'Email').value = jsonParams.email;
                    cleanCreateProfileControls();
                    panelManager.switchPanel("createProfile");
                    captchaManager.getCaptchaImage("createProfileCaptcha", "createProfileFeedbackPanel");
                    $("createProfileCaptcha").select('input')[0].value = '';
                    break;
                case 'JsonValidationMessage':
                    handleValidationError('loginFeedbackPanel', json.messages);
                    break;
                case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError('loginFeedbackPanel', json.messages);
                    break;
            }
        },
        onFailure: function() {
            handleSystemExceptionError('loginFeedbackPanel', json.message);
        },
        onComplete: function() {
            document.body.style.cursor = 'default';
        }
    });

    event.stop();
}

function sendActivationEmail() {
    document.body.style.cursor = 'wait';

    var jsonParams = {
        'email': $('existingUserEmail').value
    }

    new Ajax.Request('/' + locale + '/SendActivationEmail.json',
    {
        method: 'get',
        parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(jsonParams) },
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON();
            switch (json.type) {
                case 'JsonMethodMessage':
                    $('loginFeedbackPanel').update($('resendEmailConfirmed').innerHTML);
                    break;
                case 'JsonValidationMessage':
                    handleValidationError('loginFeedbackPanel', json.messages);
                    break;
                case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError('loginFeedbackPanel', json.message);
                    break;
            }
        },
        onFailure: function() {
            handleSystemExceptionError('loginFeedbackPanel', json.message);
        },
        onComplete: function() {
            document.body.style.cursor = 'default';
        }
    });
}

function forgotPasswordButtonClick(event) {

    $("forgotPasswordFeedbackPanel").update();
    $('forgotPasswordEmail').value = "";

    new Popup('forgotPasswordOverlay', null, { modal: true }, { position: 'center' });
    $('forgotPasswordOverlay').popup.show();

    event.stop();
}

function forgotPasswordSubmitLinkClick(event) {

    $("forgotPasswordFeedbackPanel").update();

    var jsonParam = {
        'email': $('forgotPasswordEmail').value
    }

    document.body.style.cursor = 'wait';
    new Ajax.Request('/' + locale + '/ForgotPassword.json',
      {
          method: 'get',
          parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(jsonParam) },
          onSuccess: function(transport) {
              var json = transport.responseText.evalJSON();
              switch (json.type) {
                  case 'JsonMethodMessage':
                      handleDisplayText('forgotPasswordFeedbackPanel', json.userMessage);
                      break;
                  case 'JsonValidationMessage':
                      handleValidationError('forgotPasswordFeedbackPanel', json.messages);
                      break;
                  case 'JsonSystemExceptionMessage':
                      handleSystemExceptionError('forgotPasswordFeedbackPanel', json.messages || json.message );
                      break;
              }
          },
          onFailure: function() {
              handleSystemExceptionError('forgotPasswordFeedbackPanel', json.message);
          },
          onComplete: function() {
              document.body.style.cursor = 'default';
          }
      });

    event.stop();
}

function createAccountButtonClick(event) {

    resetFeedbackPanel("createProfileFeedbackPanel");

    var prefix = $("createClientId").innerHTML;

    document.body.style.cursor = 'wait';
    new Ajax.Request('/' + locale + '/CreateProfile.json',
    {
        method: 'get',
        parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(profileJsonString(prefix)), captcha: Object.toJSON(captchaManager.getHtmlCaptchaInfo("createProfileCaptcha")) },
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON();
            switch (json.type) {
                case 'JsonMethodMessage':
                    panelManager.switchSubPanel("createProfileConfirmation");
                    $("pageMenu").show();
                    $("logoutButton").show();
                    break;
                case 'JsonValidationMessage':
                    handleValidationError('createProfileFeedbackPanel', json.messages);
                    captchaManager.getCaptchaImage("createProfileCaptcha", "createProfileFeedbackPanel");
                    $("createProfileCaptcha").select('input')[0].value = '';
                    break;
                case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError('createProfileFeedbackPanel', json.message);
                    captchaManager.getCaptchaImage("createProfileCaptcha", "createProfileFeedbackPanel");
                    $("createProfileCaptcha").select('input')[0].value = '';
                    break;
            }
        },
        onFailure: function() {
            handleSystemExceptionError('createProfileFeedbackPanel', json.message);
            captchaManager.getCaptchaImage("createProfileCaptcha", "createProfileFeedbackPanel");
            $("createProfileCaptcha").select('input')[0].value = '';
        },
        onComplete: function() {
            document.body.style.cursor = 'default';
        }
    });

    event.stop();
}

function redeemPointsButtonClick(event) {

    resetFeedbackPanel("redeemPointsFeedbackPanel");

    var prizes = new Hash();
    $("prizeList").select('input.quantity').each(function(item) {
        if (item.value > 0) {
            prizes.set(item.id, item.value);
        }
    });

    var redeemPoints = {
        'systemKey': pointSystemKey,
        'prizes': prizes,
        'shippingAddress': null
    };

    document.body.style.cursor = 'wait';
    new Ajax.Request('/' + locale + '/RedeemPoints.json',
    {
        method: 'get',
        parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(redeemPoints), captcha: Object.toJSON(captchaManager.getHtmlCaptchaInfo("redeemPointsCaptcha")) },
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON();
            switch (json.type) {
                case 'JsonMethodMessage':
                    profileManager.loadProfile();
                    panelManager.switchSubPanel("redeemPointsConfirmation");
                    break;
                case 'JsonValidationMessage':
                    handleValidationError('redeemPointsFeedbackPanel', json.messages);
                    captchaManager.getCaptchaImage("redeemPointsCaptcha", "redeemPointsFeedbackPanel");
                    $("redeemPointsCaptcha").select('input')[0].value = '';
                    break;
                case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError('redeemPointsFeedbackPanel', json.message);
                    captchaManager.getCaptchaImage("redeemPointsCaptcha", "redeemPointsFeedbackPanel");
                    $("redeemPointsCaptcha").select('input')[0].value = '';
                    break;
            }
        },
        onFailure: function() {
            handleSystemExceptionError('redeemPointsFeedbackPanel', json.message);
            captchaManager.getCaptchaImage("redeemPointsCaptcha", "redeemPointsFeedbackPanel");
            $("redeemPointsCaptcha").select('input')[0].value = '';
        },
        onComplete: function() {
            document.body.style.cursor = 'default';
        }
    });

    event.stop();
}

function codeEntrySubmitButtonClick(event) {

    document.body.style.cursor = 'wait';
    resetFeedbackPanel("codeEntryFeedbackPanel");

    var codeEntriesArray = new Array();
    $('userCodeTextBoxes').select('.userCode').each(function(item) {
        var val = $F(item);
        if (val != '') {
            codeEntriesArray.push(val);
        }
    });

    var codeEntries = {
        systemKey: pointSystemKey,
        codes: codeEntriesArray
    };

    new Ajax.Request('/' + locale + '/CodeEntry.json',
    {
        method: 'get',
        parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(codeEntries), captcha: Object.toJSON(captchaManager.getHtmlCaptchaInfo("codeEntryCaptcha")) },
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON();
            switch (json.type) {
                case 'JsonMethodMessage':
                    if (json.result.successful) {
                        panelManager.switchSubPanel("codeEntryConfirmation");
                    } else {
                        handleSubmitCodesResponse(json.result);
                    }
                    break;
                case 'JsonValidationMessage':
                    handleValidationError('codeEntryFeedbackPanel', json.messages);
                    captchaManager.getCaptchaImage("codeEntryCaptcha", "codeEntryFeedbackPanel");
                    $("codeEntryCaptcha").select('input')[0].value = '';
                    break;
                case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError('codeEntryFeedbackPanel', json.message);
                    captchaManager.getCaptchaImage("codeEntryCaptcha", "codeEntryFeedbackPanel");
                    $("codeEntryCaptcha").select('input')[0].value = '';
                    break;
            }
        },
        onFailure: function() {
            handleSystemExceptionError('codeEntryFeedbackPanel', json.message);
            captchaManager.getCaptchaImage("codeEntryCaptcha", "codeEntryFeedbackPanel");
            $("codeEntryCaptcha").select('input')[0].value = '';
        },
        onComplete: function() {
            document.body.style.cursor = 'default';
        }
    });

    event.stop();
}

function handleSubmitCodesResponse(codeResult) {
    if (codeResult.notFound.length > 0) {
        handleSubmitCodesError('CodeNotFound');
    } else {
        handleSubmitCodesError('CodeAlreadyClaimed');
    }  
}

function handleSubmitCodesError(errorType) {
    var errorMsg = i18nText.translate(errorType);
    handleSystemExceptionError('codeEntryFeedbackPanel', errorMsg);
    captchaManager.getCaptchaImage("codeEntryCaptcha", "codeEntryFeedbackPanel");
    $("codeEntryCaptcha").select('input')[0].value = '';
}

function updateAccountButtonClick(event) {

    document.body.style.cursor = 'wait';
    resetFeedbackPanel("editProfileFeedbackPanel");

    var prefix = $("updateClientId").innerHTML;
    var profileContainerDTO = {
        actions: 1,
        profileData: profileJsonString(prefix)
    };

    new Ajax.Request('/' + locale + '/UpdateProfile.json',
    {
        method: 'get',
        parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(profileContainerDTO), captcha: Object.toJSON(captchaManager.getHtmlCaptchaInfo("editProfileCaptcha")) },
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON();
            switch (json.type) {
                case 'JsonMethodMessage':
                    profileManager.profile = json.result;
                    showCampaignLandingPanel();
                    break;
                case 'JsonValidationMessage':
                    handleValidationError('editProfileFeedbackPanel', json.messages);
                    captchaManager.getCaptchaImage("editProfileCaptcha", "editProfileFeedbackPanel");
                    $("editProfileCaptcha").select('input')[0].value = '';
                    break;
                case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError('editProfileFeedbackPanel', json.message);
                    captchaManager.getCaptchaImage("editProfileCaptcha", "editProfileFeedbackPanel");
                    $("editProfileCaptcha").select('input')[0].value = '';
                    break;
            }
        },
        onFailure: function() {
            handleSystemExceptionError('editProfileFeedbackPanel', json.message);
            captchaManager.getCaptchaImage("editProfileCaptcha", "editProfileFeedbackPanel");
            $("editProfileCaptcha").select('input')[0].value = '';
        },
        onComplete: function() {
            document.body.style.cursor = 'default';
        }
    });

    event.stop();
}

function closeButtonClick(event) {
    showCampaignLandingPanel();
    event.stop();
}

function showPrivacyPolicyPanel(event) {
    panelManager.showPanelOverlay("privacyPolicy");
    event.stop();
}

function showTermsAndConditionPanel(event) {
    panelManager.showPanelOverlay("termsConditions");
    event.stop();
}

function faqButtonClick(event) {
    panelManager.showPanelOverlay("faq");
    event.stop();
}

/*
* HELPER METHODS
*/

function profileJsonString(prefix) {

    var profile = profileManager.profile;
    var newsletters = $H(profile.newsletters);

    $(prefix + "UserForm").select('input.newsletter').each(function(item) {
        var profileNewsletter = newsletters.get(item.value);
        if (profileNewsletter != null) {
            newsletters.unset(item.value);
        }
        newsletters.set(item.value, item.checked);
    });
    profile.newsletters = newsletters;

    var addressInfo = {
        address1: $F(prefix + 'Address1'),
        address2: $F(prefix + 'Address2'),
        postalCode: $F(prefix + 'ZipCode'),
        city: $F(prefix + 'City'),
        state: $F(prefix + 'State'),
        country: $F(prefix + 'Country'),
        phoneNumber: $F(prefix + 'PhoneNumber'),
        companyName: $F(prefix + 'CompanyName')
    };

    var profileInfo = {
        salutation: $F(prefix + 'Salutation'),
        firstName: $F(prefix + 'FirstName'),
        lastName: $F(prefix + 'LastName'),
        address: addressInfo,
        email: $F(prefix + 'Email'),
        login: $F(prefix + 'Email'),
        password: $F(prefix + 'Password'),
        confirmpassword: $F(prefix + 'ConfirmPassword'),
        newsletters: newsletters
    };

    if ($(prefix + "PrivacyPolicyField") != null) {
        profileInfo.privacyPolicyAgreement = $(prefix + "PrivacyPolicyField").select('input')[0].checked;
    }

    if ($(prefix + "TermsAndConditionField") != null) {
        profileInfo.termsAndConditionAgreement = $(prefix + "TermsAndConditionField").select('input')[0].checked;
    }

    var wherePurchasedSelect = $$("#" + prefix + "WherePurchasedField select")[0];
    if (wherePurchasedSelect != null) {
        if (($F(wherePurchasedSelect)).toLowerCase() != 'other') {
            profileInfo.wherePurchased = $F(prefix + 'WherePurchased');
        } else {
            profileInfo.wherePurchased = $(prefix + 'WherePurchasedTextBox').value;
        }
    }

    return profileInfo;
}

function populateDropDownLists() {

    if ($('createProfilePanel') != null) {
        var createClientId = $("createClientId").innerHTML;
        populateCountryField(createClientId);
        populateSalutation(createClientId);
        populateWherePurchased(createClientId);
        populateState(createClientId);
    }

    if ($('editProfilePanel') != null) {
        var updateClientId = $("updateClientId").innerHTML;
        populateCountryField(updateClientId);
        populateSalutation(updateClientId);
        populateState(updateClientId);
    }
}


function populateCountryField(prefix) {

    $(prefix + "CountryField").select("div")[1].update($("countryControl").select("div")[0].select("div")[1].innerHTML);

    var selectElement = $(prefix + "CountryField").select('select')[0];
    var inputElement = $(prefix + "CountryField").select('input')[0];
    if (inputElement != null) {
        $(prefix + "CountryField").select('input')[0].id = prefix + "Country";
    } else {
        $(prefix + "CountryField").select('select')[0].id = prefix + "Country";
    }
}

function populateSalutation(prefix) {

    $(prefix + "SalutationField").select("div")[1].update($("salutationDropDownList").select("div")[0].select("div")[1].innerHTML);
    $(prefix + "SalutationField").select("select")[0].id = prefix + "Salutation";
}

function populateWherePurchased(prefix) {

    var wherePurchasedList = $$("#wherePurchasedDropDownList select")[0];
    if (wherePurchasedList.select("option").size() > 0) {
        $(prefix + "WherePurchasedField").select("div")[1].update(wherePurchasedList);
        $(prefix + "WherePurchasedField").select("select")[0].id = prefix + "WherePurchased";
    } else {
        $(prefix + "WherePurchasedField").hide();
    }
}


function populateState(prefix) {

    $(prefix + "StateField").select("div")[1].update($("stateControl").select("div")[0].select("div")[1].innerHTML);

    var selectElement = $(prefix + "StateField").select('select')[0];
    var inputElement = $(prefix + "StateField").select('input')[0];
    if (inputElement != null) {
        $(prefix + "StateField").select('input')[0].id = prefix + "State";
    } else {
        $(prefix + "StateField").select('select')[0].id = prefix + "State";
    }
}

function getPointSystem() {

    document.body.style.cursor = 'wait';
    resetFeedbackPanel("redeemPointsFeedbackPanel");

    var jsonParam = {
        'systemKey': pointSystemKey
    }

    new Ajax.Request('/' + locale + '/GetPointSystem.json',
    {
        method: 'get',
        parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(jsonParam) },
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON();
            switch (json.type) {
                case 'JsonMethodMessage':
                    displayPrizes(json.result);
                    panelManager.switchPanel("redeemPoints");
                    break;
                case 'JsonValidationMessage':
                    handleValidationError('redeemPointsFeedbackPanel', json.messages);
                    break;
                case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError('redeemPointsFeedbackPanel', json.message);
                    break;
            }
        },
        onFailure: function() {
            handleSystemExceptionError('redeemPointsFeedbackPanel', json.message);
        },
        onComplete: function() {
            document.body.style.cursor = 'default';
        }
    });
}


function getUserTransactions(successFunction, codeSummaryInfoDiv, feedbackPanel) {

    document.body.style.cursor = 'wait';

    var jsonParam = {
        'systemKey': pointSystemKey
    }

    new Ajax.Request('/' + locale + '/GetUserTransactions.json',
    {
        method: 'get',
        parameters: { useResponseBody: 'true', jsonSource: pointSystemKey, jsonString: Object.toJSON(jsonParam) },
        onSuccess: function(transport) {
            var json = transport.responseText.evalJSON();
            switch (json.type) {
                case 'JsonMethodMessage':
                    successFunction(json.result, codeSummaryInfoDiv);
                    break;
                case 'JsonValidationMessage':
                    handleValidationError(feedbackPanel, json.messages);
                    break;
                case 'JsonSystemExceptionMessage':
                    handleSystemExceptionError(feedbackPanel, json.message);
                    break;
            }
        },
        onFailure: function() {
            handleSystemExceptionError(feedbackPanel, json.message);
        },
        onComplete: function() {
            document.body.style.cursor = 'default';
        }
    });
}

/* TODO: only used by edit profile?? */
function populateFields(prefix) {

    var result = profileManager.profile;

    if (result.salutation != null) {
        $(prefix + 'Salutation').value = result.salutation;
    }
    if (result.firstName != null) {
        $(prefix + 'FirstName').value = result.firstName;
    }
    if (result.lastName != null) {
        $(prefix + 'LastName').value = result.lastName;
    }
    if (result.address.address1 != null) {
        $(prefix + 'Address1').value = result.address.address1;
    }
    if (result.address.address2 != null) {
        $(prefix + 'Address2').value = result.address.address2;
    }
    if (result.address.postalCode != null) {
        $(prefix + 'ZipCode').value = result.address.postalCode;
    }
    if (result.address.city != null) {
        $(prefix + 'City').value = result.address.city;
    }
    if (result.address.state != null) {
        $(prefix + 'State').value = result.address.state;
    }
    if (result.address.country != null) {
        $(prefix + 'Country').value = result.address.country;
    }
    if (result.address.phoneNumber != null) {
        $(prefix + 'PhoneNumber').value = result.address.phoneNumber;
    }
    if (result.address.companyName != null) {
        $(prefix + 'CompanyName').value = result.address.companyName;
    }
    if (result.email != null) {
        $(prefix + 'Email').value = result.email;
    }
    var newsletters = $H(result.newsletters);
    newsletters.each(function(item) {
    	var newsletterId = prefix + item.key;
    	if (item.value && $(newsletterId) != null) {
    		$(newsletterId).checked = "checked";
    	}
    });
}

function cleanCreateProfileControls() {

    $("createSalutationField").select("select")[0].selectedIndex = 0;

    var wherePurchasedSelect = $$("#createWherePurchasedField select")[0];
    if (wherePurchasedSelect != null) {
        wherePurchasedSelect.selectedIndex = 0;
    }

    if ($("createCountryField").select("select")[0] != null) {
        $("createCountryField").select("select")[0].selectedIndex = 0;
    }
    $('createFirstName').value = "";
    $('createLastName').value = "";
    $('createAddress1').value = "";
    $('createAddress2').value = "";
    $('createZipCode').value = "";
    $('createCity').value = "";
    $('createState').value = "";
    $('createPhoneNumber').value = "";
    $('createCompanyName').value = "";
    $('createPassword').value = "";
    $('createConfirmPassword').value = "";
}

function validateKeyPress(event, validKeys) {
    var key = event.which || event.keyCode;
    if (String.fromCharCode(key).match("[" + validKeys + "]") == null &&
           key != Event.KEY_BACKSPACE &&
           key != Event.KEY_TAB &&
           key != Event.KEY_RETURN &&
           key != Event.KEY_ESC &&
           key != Event.KEY_LEFT &&
           key != Event.KEY_UP &&
           key != Event.KEY_RIGHT &&
           key != Event.KEY_UP &&
           key != Event.KEY_DOWN &&
           key != Event.KEY_DELETE &&
           key != Event.KEY_HOME &&
           key != Event.KEY_END &&
           key != Event.KEY_PAGEUP &&
           key != Event.KEY_PAGEDOWN) {
        event.stop();
    }
}

function changeTextBox(event) {
    if (event.element().value == '') {
        event.element().stopObserving('blur', changeTextBox);
        event.element().ancestors()[1].remove();
    }
}

function createTextBox(event) {

    if ($('userCodeTextBoxes').childElements().length < 5) {
        if (event.element().value.length >= 1) {

            event.element().stopObserving('keyup', createTextBox);
            event.element().observe('blur', changeTextBox);

            createCodeEntryTextBox($('userCodeTextBoxes').childElements().length + 1);
        }
    }
}

function displayCodeSummary(userTransactions, summaryDivId) {

    var label = $(summaryDivId).select('span')[0].innerHTML;
    $(summaryDivId).select('div')[0].update('<span class="label">' + label + '</span>' + userTransactions.totalCodesEntered);
    label = $(summaryDivId).select('span')[1].innerHTML;
    $(summaryDivId).select('div')[1].update('<span class="label">' + label + '</span>' + userTransactions.totalPointsCollected);
    label = $(summaryDivId).select('span')[2].innerHTML;
    $(summaryDivId).select('div')[2].update('<span class="label">' + label + '</span>' + userTransactions.totalPointsRedeemed);
    label = $(summaryDivId).select('span')[3].innerHTML;
    $(summaryDivId).select('div')[3].update('<span class="label">' + label + '</span><span>' + (userTransactions.totalPointsCollected - userTransactions.totalPointsRedeemed) + '</span>');
}


function displayPrizes(pointSystem) {

    // Deleting existing rows in table
    var tableElem = $('prizeList').select('tbody')[0];
    tableElem.select('tr').each(function(item, index) {
        if (index > 0) {
            item.remove();
        }
    });

    var profilePoints = $('redeemPointsPointSummary').select('span')[4].innerHTML;
    prizes.each(function(item, index2) {
        if (parseInt(profilePoints) >= parseInt(item.requiredPoints)) {
            // Adding new rows in table
            var trElem = new Element("tr");
            var tdElem = new Element("td");

            var imgDivElem = new Element("div", { 'class': 'image' });
            var imgElem = new Element("img", { 'src': item.image });
            imgDivElem.insert(imgElem);
            tdElem.insert(imgDivElem);

            var titleDivElem = new Element("div", { 'class': 'title' });
            titleDivElem.insert(item.name);
            tdElem.insert(titleDivElem);

            var descriptionDivElem = new Element("div", { 'class': 'description' });
            descriptionDivElem.insert(item.description);
            tdElem.insert(descriptionDivElem);

            trElem.insert(tdElem);

            var tdQuanityElem = new Element("td");
            var txtQuantityElem = new Element("input", { 'type': 'text', 'class': 'quantity', 'id': item.uniqueID });
            txtQuantityElem.observe('keypress', function(event) {
                validateKeyPress(event, "0-9");
            });

            tdQuanityElem.insert(txtQuantityElem);
            trElem.insert(tdQuanityElem);

            tableElem.insert(trElem);
        }
    });

    if (tableElem.select('tr').size() < 2) {
        $('noPrizesFound').show();
        tableElem.select('tr')[0].hide();
    } else {
        $('noPrizesFound').hide();
        tableElem.select('tr')[0].show();
    }
}


function refreshUserCodesPanel(userTransactions, summaryPanel) {
    displayCodeSummary(userTransactions, summaryPanel);

    // Deleting existing rows in table
    var tableElem = $("transactionView").select('tbody')[0];
    tableElem.select('tr').each(function(item, index) {
        if (index > 0) {
            item.remove();
        }
    });

    if (userTransactions.userTransaction != null) {
        userTransactions.userTransaction.each(function(item, index) {

            var trElem = new Element("tr");

            var tdElem = new Element("td", { 'class': 'dateColumn' });
            tdElem.insert(item.transactionDate);
            trElem.insert(tdElem);

            tdElem = new Element("td", { 'class': 'codeColumn' });
            tdElem.insert(campaignMessages.translate(item.description));
            if (item.description == 'codesClaimed') {
                var ulElem = new Element("ul");
                item.refIds.each(function(item) {
                    var liElem = new Element("li");
                    liElem.insert(item);
                    ulElem.insert(liElem);
                });
                tdElem.insert(ulElem);
            }

            trElem.insert(tdElem);

            tdElem = new Element("td", { 'class': 'pointColumn' });
            tdElem.insert(item.points);
            trElem.insert(tdElem);

            tableElem.insert(trElem);
        });
    }
}

function refreshRedeemPointsPanel(userTransactions, pointSummaryDiv) {

    displayCodeSummary(userTransactions, pointSummaryDiv);

    displayPrizes();
    panelManager.switchPanel("redeemPoints");

    captchaManager.getCaptchaImage("redeemPointsCaptcha", "redeemPointsFeedbackPanel");
    $("redeemPointsCaptcha").select('input')[0].value = '';
}

function createCodeEntryTextBox(uniqueID) {
    var divElement = new Element("div", { 'class': 'codeEntryField' });
    $("userCodeTextBoxes").insert(divElement);

    var divFieldElement = new Element("div", { 'class': 'field' });
    var txtBoxElement = new Element("input", { 'type': 'text', 'class': 'userCode', 'id': 'userCode' + uniqueID });

    txtBoxElement.observe('keypress', function(event) {
        validateKeyPress(event, "0-9a-fA-F");
    });
    txtBoxElement.observe('keyup', createTextBox);

    divFieldElement.insert(txtBoxElement);
    divElement.insert(divFieldElement);
}
